@nice2dev/ui-audio 1.0.28 → 1.0.30

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 (69) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +52 -14
  3. package/dist/core/audioIcons.d.ts +10 -0
  4. package/dist/core/audioIcons.d.ts.map +1 -0
  5. package/dist/editor/AudioEditorPianoRoll.d.ts.map +1 -1
  6. package/dist/editor/AudioLayerDetails.d.ts.map +1 -1
  7. package/dist/editor/AudioStudio.d.ts +51 -0
  8. package/dist/editor/AudioStudio.d.ts.map +1 -0
  9. package/dist/editor/NiceSampleBrowser.d.ts.map +1 -1
  10. package/dist/editor/PianoRoll.d.ts.map +1 -1
  11. package/dist/editor/nav/AudioTimelineNav.d.ts.map +1 -1
  12. package/dist/editor/panels/AdvancedEditingPanel.d.ts.map +1 -1
  13. package/dist/editor/panels/LFOPanel.d.ts.map +1 -1
  14. package/dist/editor/panels/ProjectPanel.d.ts.map +1 -1
  15. package/dist/editor/panels/StepSequencerPanel.d.ts.map +1 -1
  16. package/dist/engine/NiceAudioEffectsRack.d.ts.map +1 -1
  17. package/dist/engine/instrumentPresets.d.ts +1 -1
  18. package/dist/engine/instrumentPresets.d.ts.map +1 -1
  19. package/dist/index.cjs +57 -66
  20. package/dist/index.d.ts +36 -0
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.mjs +24637 -19672
  23. package/dist/input/AudioInputPicker.d.ts +43 -0
  24. package/dist/input/AudioInputPicker.d.ts.map +1 -0
  25. package/dist/input/VocalEffectsRack.d.ts +15 -0
  26. package/dist/input/VocalEffectsRack.d.ts.map +1 -0
  27. package/dist/karaoke/KaraokeLyrics.d.ts.map +1 -1
  28. package/dist/karaoke/KaraokeManager.d.ts +104 -0
  29. package/dist/karaoke/KaraokeManager.d.ts.map +1 -0
  30. package/dist/karaoke/KaraokeSelectionMode.d.ts +26 -0
  31. package/dist/karaoke/KaraokeSelectionMode.d.ts.map +1 -0
  32. package/dist/karaoke/KaraokeSessionJoin.d.ts +41 -0
  33. package/dist/karaoke/KaraokeSessionJoin.d.ts.map +1 -0
  34. package/dist/karaoke/KaraokeSetupPanel.d.ts +31 -0
  35. package/dist/karaoke/KaraokeSetupPanel.d.ts.map +1 -0
  36. package/dist/karaoke/KaraokeSongBrowser.d.ts +64 -0
  37. package/dist/karaoke/KaraokeSongBrowser.d.ts.map +1 -0
  38. package/dist/karaoke/KaraokeSummaryOverlay.d.ts +9 -1
  39. package/dist/karaoke/KaraokeSummaryOverlay.d.ts.map +1 -1
  40. package/dist/karaoke/KaraokeUploader.d.ts +27 -0
  41. package/dist/karaoke/KaraokeUploader.d.ts.map +1 -0
  42. package/dist/karaoke/LatencyCalibrator.d.ts +18 -0
  43. package/dist/karaoke/LatencyCalibrator.d.ts.map +1 -0
  44. package/dist/karaoke/PadKaraokeOverlay.d.ts +16 -0
  45. package/dist/karaoke/PadKaraokeOverlay.d.ts.map +1 -0
  46. package/dist/karaoke/VocalPerformanceReport.d.ts +21 -0
  47. package/dist/karaoke/VocalPerformanceReport.d.ts.map +1 -0
  48. package/dist/karaoke/rendering/glossyBarRenderer.d.ts.map +1 -1
  49. package/dist/karaoke/useKaraokePitch.d.ts +90 -0
  50. package/dist/karaoke/useKaraokePitch.d.ts.map +1 -0
  51. package/dist/karaoke/useKaraokeScoring.d.ts +49 -0
  52. package/dist/karaoke/useKaraokeScoring.d.ts.map +1 -0
  53. package/dist/karaokeEditor/KaraokeEditorManager.d.ts.map +1 -1
  54. package/dist/library/MusicLibraryExplorer.d.ts +31 -0
  55. package/dist/library/MusicLibraryExplorer.d.ts.map +1 -0
  56. package/dist/lighting/NiceDMXTimeline.d.ts.map +1 -1
  57. package/dist/player/GenericPlayer.d.ts.map +1 -1
  58. package/dist/player/GenericPlayerControls.d.ts.map +1 -1
  59. package/dist/player/GenericPlayerTrackList.d.ts.map +1 -1
  60. package/dist/player/visualizer/StageVisualizer.d.ts +6 -0
  61. package/dist/player/visualizer/StageVisualizer.d.ts.map +1 -1
  62. package/dist/playlist/DynamicRuleEditor.d.ts.map +1 -1
  63. package/dist/playlist/GenericPlaylistItem.d.ts.map +1 -1
  64. package/dist/playlist/PlaylistImportWizard.d.ts.map +1 -1
  65. package/dist/radio/NiceRadioPlayer.d.ts.map +1 -1
  66. package/dist/ui-audio.css +1 -1
  67. package/dist/utils/vocalEffectsEngine.d.ts +1 -1
  68. package/dist/utils/vocalEffectsEngine.d.ts.map +1 -1
  69. package/package.json +8 -2
package/dist/index.cjs CHANGED
@@ -1,56 +1,73 @@
1
- "use strict";var Bl=Object.create;var Fa=Object.defineProperty;var Gl=Object.getOwnPropertyDescriptor;var Wl=Object.getOwnPropertyNames;var Ul=Object.getPrototypeOf,Vl=Object.prototype.hasOwnProperty;var ql=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Wl(t))!Vl.call(e,a)&&a!==n&&Fa(e,a,{get:()=>t[a],enumerable:!(r=Gl(t,a))||r.enumerable});return e};var wr=(e,t,n)=>(n=e!=null?Bl(Ul(e)):{},ql(t||!e||!e.__esModule?Fa(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),u=require("react"),He=require("react-bootstrap"),Nr=require("pitchy"),Hl=require("react-window"),Qr=require("react-youtube");var it=typeof document<"u"?document.currentScript:null;const Kl=(e,t)=>t??e,Ns=u.createContext(Kl),Yl=({t:e,children:t})=>s.jsx(Ns.Provider,{value:e,children:t});function we(){return{t:u.useContext(Ns)}}class Zl extends u.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){var a,o;const r=this.props.componentName?`[${this.props.componentName}]`:"[AudioErrorBoundary]";console.error(`${r} Caught error:`,t,n),(o=(a=this.props).onError)==null||o.call(a,t,n)}render(){return this.state.hasError&&this.state.error?typeof this.props.fallback=="function"?this.props.fallback(this.state.error,this.reset):this.props.fallback?this.props.fallback:s.jsx("div",{className:"nice-audio-error-boundary",role:"alert",children:s.jsxs("div",{className:"nice-audio-error-boundary__content",children:[s.jsx("h3",{className:"nice-audio-error-boundary__title",children:this.props.componentName?`${this.props.componentName} encountered an error`:"Something went wrong"}),s.jsx("p",{className:"nice-audio-error-boundary__message",children:this.state.error.message}),s.jsx("button",{className:"nice-audio-error-boundary__retry",onClick:this.reset,children:"Try Again"})]})}):this.props.children}}const Sr={},Ir={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function Xl(){const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("index.cjs",document.baseURI).href}<"u"?Sr==null?void 0:Sr.VITE_LOG_LEVEL:void 0;return e&&e in Ir?e:"WARN"}const Ql=Xl();function En(e){return Ir[e]>=Ir[Ql]}function An(e){return`[${e}]`}const nt={debug(e,t,...n){En("DEBUG")&&console.debug(An(e),t,...n)},info(e,t,...n){En("INFO")&&console.info(An(e),t,...n)},warn(e,t,...n){En("WARN")&&console.warn(An(e),t,...n)},error(e,t,...n){En("ERROR")&&console.error(An(e),t,...n)},scoped(e){return{debug:(t,...n)=>nt.debug(e,t,...n),info:(t,...n)=>nt.info(e,t,...n),warn:(t,...n)=>nt.warn(e,t,...n),error:(t,...n)=>nt.error(e,t,...n)}}},Oa=nt.scoped("Waveform"),Jl=["audio/","video/"],Is=({audioBlob:e,currentTime:t,duration:n,width:r=600,height:a=200,zoom:o=1,onSeek:i,onRegionSelect:l,markers:c=[],regions:d=[],displayMode:f="waveform",multiChannel:h=!1,waveColor:m="#007bff",progressColor:y="rgba(255,0,0,0.8)",backgroundColor:p="transparent",showRuler:v=!1,showChannelLabels:x=!0,showPeakMeter:b=!1,className:S})=>{const g=u.useRef(null),k=u.useRef(null),M=u.useRef(null),[N,j]=u.useState(0),[_,P]=u.useState(!1),[V,z]=u.useState(null),[A,I]=u.useState(null),[L,U]=u.useState(0),Y=Math.max(r,r*o),O=v?24:0;u.useEffect(()=>{if(!e||e.size===0){M.current=null;return}e.type&&!Jl.some(B=>e.type.startsWith(B))&&Oa.warn("Unexpected blob MIME type:",e.type);let G=!1;return(async()=>{let B=null;try{const w=await e.arrayBuffer();if(w.byteLength===0||G)return;B=new AudioContext;const $=await B.decodeAudioData(w);G||(M.current=$)}catch(w){Oa.error("Failed to decode audio:",w)}finally{B==null||B.close().catch(()=>{})}})(),()=>{G=!0}},[e]),u.useEffect(()=>{if(o>1&&n>0){const G=t/n*Y;(G<N||G>N+r)&&j(Math.max(0,G-r/2))}},[t,n,o,r,Y,N]),u.useEffect(()=>{const G=g.current,B=M.current;if(!G||!n||n===1/0)return;const w=G.getContext("2d");if(!w)return;const $=Y,R=a;if(G.width=$,G.height=R+O,w.clearRect(0,0,$,R+O),p!=="transparent"&&(w.fillStyle=p,w.fillRect(0,0,$,R+O)),v){w.fillStyle="rgba(128,128,128,0.15)",w.fillRect(0,0,$,O),w.fillStyle="var(--nice-text-secondary, #888)",w.font="10px monospace",w.textAlign="center";const T=Math.max(1,Math.floor(n/(Y/80)));for(let C=0;C<=n;C+=T){const E=C/n*$;w.fillText(rc(C),E,O-4),w.fillStyle="rgba(128,128,128,0.3)",w.fillRect(E,O,1,R),w.fillStyle="var(--nice-text-secondary, #888)"}}for(const T of d){const C=T.start/n*$,E=T.end/n*$;w.fillStyle=T.color??"var(--nice-accent-tint-15, rgba(99, 102, 241, 0.15))",w.fillRect(C,O,E-C,R),T.label&&(w.fillStyle=T.color??"var(--nice-info, #6366f1)",w.font="10px sans-serif",w.textAlign="left",w.fillText(T.label,C+2,O+12))}if(V!==null&&A!==null){const T=Math.min(V,A),C=Math.max(V,A);w.fillStyle="rgba(255,200,0,0.2)",w.fillRect(T,O,C-T,R)}if(B){const T=h?B.numberOfChannels:1,C=R/T;let E=0;for(let F=0;F<T;F++){const q=B.getChannelData(F),Q=O+F*C;if(f==="waveform"?ec(w,q,$,C,Q,m):f==="bars"?tc(w,q,$,C,Q,m):f==="spectrogram"&&nc(w,q,$,C,Q,B.sampleRate),b&&n>0){const J=Math.floor(t/n*q.length),ae=Math.floor(B.sampleRate*.05);let re=0;for(let D=Math.max(0,J-ae);D<Math.min(q.length,J+ae);D++)re+=q[D]*q[D];const ee=Math.sqrt(re/(ae*2));E=Math.max(E,ee)}h&&x&&T>1&&(w.fillStyle="var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))",w.font="bold 11px sans-serif",w.textAlign="left",w.fillText(F===0?"L":F===1?"R":`Ch${F+1}`,4,Q+14))}U(E)}if(n>0){const T=Math.max(0,Math.min(t/n*$,$));w.beginPath(),w.strokeStyle=y,w.lineWidth=2,w.moveTo(T,O),w.lineTo(T,R+O),w.stroke()}for(const T of c){const C=T.time/n*$;w.beginPath(),w.strokeStyle=T.color??"var(--nice-warning, #f59e0b)",w.lineWidth=2,w.setLineDash([4,4]),w.moveTo(C,O),w.lineTo(C,R+O),w.stroke(),w.setLineDash([]),T.label&&(w.fillStyle=T.color??"var(--nice-warning, #f59e0b)",w.font="bold 10px sans-serif",w.textAlign="center",w.fillText(T.label,C,O+R-4))}},[e,M.current,t,n,Y,a,o,f,h,m,y,p,v,c,d,V,A,b,x,O]);const Z=u.useCallback(G=>{var $;if(!n)return;const B=($=g.current)==null?void 0:$.getBoundingClientRect();if(!B)return;const w=G.clientX-B.left+N;P(!0),z(w),I(w)},[n,N]),H=u.useCallback(G=>{if(!_||!g.current)return;const B=g.current.getBoundingClientRect(),w=G.clientX-B.left+N;I(w)},[_,N]),te=u.useCallback(()=>{if(!_||V===null||A===null||!n){P(!1),z(null),I(null);return}const G=Math.min(V,A),B=Math.max(V,A),w=(B-G)/Y*n;if(P(!1),z(null),I(null),w<.2){const $=G/Y*n;i==null||i($)}else{const $=G/Y*n,R=B/Y*n;l==null||l({start:$,end:R})}},[_,V,A,n,Y,i,l]);return s.jsxs("div",{ref:k,className:`nice-waveform${S?` ${S}`:""}`,style:{position:"relative",width:r,overflow:o>1?"auto":"hidden",cursor:i?"crosshair":"default"},onScroll:G=>j(G.target.scrollLeft),children:[s.jsx("canvas",{ref:g,width:Y,height:a+O,style:{display:"block"},role:"img","aria-label":"Waveform canvas",onMouseDown:Z,onMouseMove:H,onMouseUp:te,onMouseLeave:te}),b&&s.jsx("div",{style:{position:"absolute",right:4,top:O+4,bottom:4,width:12,background:"var(--nice-overlay-30, rgba(0, 0, 0, 0.3))",borderRadius:4,overflow:"hidden"},children:s.jsx("div",{style:{position:"absolute",bottom:0,width:"100%",height:`${Math.min(100,L*300)}%`,background:L>.8?"var(--nice-danger, #ef4444)":L>.5?"var(--nice-warning, #f59e0b)":"var(--nice-success, #22c55e)",borderRadius:4,transition:"height 50ms"}})})]})};function ec(e,t,n,r,a,o){const i=Math.floor(t.length/n),l=a+r/2;e.beginPath(),e.strokeStyle=o,e.lineWidth=1;for(let c=0;c<n;c++){const d=c*i,f=t.subarray(d,d+i);let h=0,m=0;for(let v=0;v<f.length;v++)f[v]<h&&(h=f[v]),f[v]>m&&(m=f[v]);const y=l-m*(r/2),p=l-h*(r/2);e.moveTo(c,y),e.lineTo(c,p)}e.stroke()}function tc(e,t,n,r,a,o){const i=Math.max(2,Math.floor(n/128)),l=Math.floor(n/i),c=Math.floor(t.length/l);for(let d=0;d<l;d++){const f=d*c,h=t.subarray(f,f+c);let m=0;for(let x=0;x<h.length;x++)m+=Math.abs(h[x]);const p=m/h.length*r*.9,v=d*i;e.fillStyle=o,e.fillRect(v+1,a+r-p,i-2,p)}}function nc(e,t,n,r,a,o){const l=Math.min(n,512),c=Math.floor(t.length/l),d=n/l;for(let f=0;f<l;f++){const h=f*c,m=new Float32Array(256/2);for(let p=0;p<256/2;p++){let v=0,x=0;for(let b=0;b<256&&h+b<t.length;b++){const S=2*Math.PI*p*b/256;v+=t[h+b]*Math.cos(S),x-=t[h+b]*Math.sin(S)}m[p]=Math.sqrt(v*v+x*x)/256}const y=r/m.length;for(let p=0;p<m.length;p++){const v=Math.min(1,m[p]*10),x=Math.floor(v*255),b=Math.floor(v*100),S=Math.floor((1-v)*200);e.fillStyle=`rgb(${x},${b},${S})`,e.fillRect(f*d,a+r-(p+1)*y,d+1,y+1)}}}function rc(e){const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const _a=88,_t=16,Nn=16,ac=320;function sc(e){return e-21}function oc(e){return e+21}const Ls=({notes:e,onAddNote:t,onRemoveNote:n,selectedNoteId:r,setSelectedNoteId:a,duration:o=4,zoom:i=1})=>{const l=u.useRef(null),c=ac*i,d=_a*_t,f=u.useRef(null);u.useEffect(()=>{},[e,i,o]);const h=y=>{const p=y.target.getBoundingClientRect(),v=y.clientX-p.left,x=y.clientY-p.top,b=Math.floor(x/_t),S=oc(b),g=v/c*o;f.current={drawing:!0,startX:v,key:b},t(S,g,o/Nn)},m=(y,p)=>{p.stopPropagation(),a==null||a(y)};return s.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:h,children:[[...Array(_a)].map((y,p)=>s.jsx("rect",{x:0,y:p*_t,width:c,height:_t,fill:p%2===0?"var(--key-even, #f5f5f5)":"var(--key-odd, #e0e0e0)"},p)),[...Array(Nn+1)].map((y,p)=>s.jsx("line",{x1:p*c/Nn,y1:0,x2:p*c/Nn,y2:d,stroke:"var(--border-muted, #ccc)",strokeWidth:p%4===0?2:1},p)),e.map(y=>{const p=sc(y.pitch),v=y.start/o*c,x=y.duration/o*c;return s.jsx("rect",{x:v,y:p*_t,width:Math.max(6,x),height:_t-2,fill:y.id===r?"var(--accent, #1976d2)":"var(--accent-light, #90caf9)",stroke:"var(--accent, #1976d2)",strokeWidth:y.id===r?2:1,rx:3,onClick:b=>m(y.id,b),onDoubleClick:()=>n(y.id),style:{cursor:"pointer"}},y.id)})]})},Ds=({ccEvents:e,onAddEvent:t,onUpdateEvent:n,onRemoveEvent:r,ccType:a,duration:o,width:i,height:l=60,curveType:c})=>{const d=u.useRef(null),{t:f}=we(),[h,m]=u.useState(null),[y,p]=u.useState(null),[v,x]=u.useState(null),b=[...e].sort((I,L)=>I.time-L.time),S=I=>[I.time/o*i,(127-I.value)/127*l],g=(I,L,U)=>Math.max(L,Math.min(U,I)),k=I=>{var H;if(I.target instanceof SVGCircleElement)return;const L=(H=d.current)==null?void 0:H.getBoundingClientRect();if(!L)return;const U=I.clientX-L.left,Y=I.clientY-L.top,O=g(U/i*o,0,o),Z=g(127-Math.round(Y/l*127),0,127);t(a,Z,O)},M=(I,L)=>{var Z;L.stopPropagation(),m(I.id),x(I.id);const[U,Y]=S(I),O=(Z=d.current)==null?void 0:Z.getBoundingClientRect();O&&p({dx:L.clientX-O.left-U,dy:L.clientY-O.top-Y})},N=I=>{var H;if(h==null||!y)return;const L=(H=d.current)==null?void 0:H.getBoundingClientRect();if(!L)return;const U=g(I.clientX-L.left-y.dx,0,i),Y=g(I.clientY-L.top-y.dy,0,l),O=g(U/i*o,0,o),Z=g(127-Math.round(Y/l*127),0,127);n(h,Z,O)},j=()=>{m(null),p(null)};u.useEffect(()=>{const I=L=>{(L.key==="Delete"||L.key==="Backspace")&&v!=null&&(r(v),x(null))};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[v,r]),u.useEffect(()=>{if(h!=null)return window.addEventListener("mousemove",N),window.addEventListener("mouseup",j),()=>{window.removeEventListener("mousemove",N),window.removeEventListener("mouseup",j)}});const[_,P]=u.useState(null),V=(I,L)=>{const[U,Y]=S(I);P({x:U+10,y:Y-10,text:`Val: ${I.value}, Time: ${I.time.toFixed(2)}s`})},z=()=>P(null),A=I=>{var H;const L=(H=d.current)==null?void 0:H.getBoundingClientRect();if(!L)return;const U=I.clientX-L.left,Y=I.clientY-L.top,O=g(U/i*o,0,o),Z=g(127-Math.round(Y/l*127),0,127);t(a,Z,O)};return s.jsxs("svg",{ref:d,width:i,height:l,style:{background:"var(--surface-muted, #f3f3f3)",border:"1px solid var(--border, #bbb)",cursor:h?"grabbing":"crosshair",display:"block"},onClick:k,onDoubleClick:A,tabIndex:0,children:[[...Array(9)].map((I,L)=>s.jsx("line",{x1:0,y1:L*l/8,x2:i,y2:L*l/8,stroke:"var(--border-muted, #ddd)",strokeWidth:L===0||L===8?2:1},L)),b.length>1&&s.jsx("polyline",{fill:"none",stroke:"var(--accent, #1976d2)",strokeWidth:2,points:b.map(I=>S(I).join(",")).join(" ")}),b.map(I=>{const[L,U]=S(I);return s.jsxs("g",{children:[s.jsx("circle",{cx:L,cy:U,r:v===I.id?8:6,fill:v===I.id?"var(--accent, #1976d2)":"var(--accent-light, #90caf9)",stroke:"var(--accent, #1976d2)",strokeWidth:v===I.id?3:2,style:{cursor:"pointer"},onMouseDown:Y=>M(I,Y),onContextMenu:Y=>{Y.preventDefault(),r(I.id)},onClick:Y=>{Y.stopPropagation(),x(I.id)},onMouseOver:Y=>V(I),onMouseOut:z}),v===I.id&&s.jsx("foreignObject",{x:L+10,y:U-18,width:90,height:30,style:{pointerEvents:"auto"},children:s.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:[s.jsxs("label",{style:{marginRight:4},children:[f("ccLane.curve","Curve"),":"]}),s.jsxs("select",{value:I.handleType||c||"linear",onChange:Y=>{n(I.id,I.value,I.time,Y.target.value)},children:[s.jsx("option",{value:"linear",children:f("ccLane.linear","Linear")}),s.jsx("option",{value:"step",children:f("ccLane.step","Step")}),s.jsx("option",{value:"exp",children:f("ccLane.exponential","Exponential")})]})]})})]},I.id)}),_&&s.jsxs("g",{pointerEvents:"none",children:[s.jsx("rect",{x:_.x,y:_.y-18,width:90,height:20,fill:"var(--surface-bg, #fff)",stroke:"var(--accent, #1976d2)",rx:4}),s.jsx("text",{x:_.x+6,y:_.y-4,fontSize:13,fill:"var(--accent, #1976d2)",children:_.text})]}),s.jsxs("text",{x:6,y:16,fontSize:14,fill:"var(--accent, #1976d2)",children:["CC",a]})]})},ic=nt.scoped("audioContext");let Mn=null;function an(){if(!Mn)try{Mn=new(window.AudioContext||window.webkitAudioContext)}catch(e){ic.error("Error initializing AudioContext:",e)}return Mn}async function It(){const e=an();e&&e.state==="suspended"&&await e.resume()}function Fs(){return!!Mn&&Mn.state==="running"}function Os(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 lc(e,t){if(!t.snapEnabled)return e;const n=Os(t);return Math.round(e/n)*n}function cc(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 dc(e,t){const n=t/60,r=e*n,a=Math.floor(r/4),o=Math.floor(r%4);return`${a+1}:${o+1}`}function _s(e,t,n=!0){const r=e.getContext("2d");if(!r)return;const a=30*t.zoom*t.duration,o=Math.max(80,30*t.zoom);e.width=a,e.height=o,r.clearRect(0,0,a,o),r.fillStyle="var(--surface-bg, #f5f5f5)",r.fillRect(0,0,a,o);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,f=c%1===0;if(r.strokeStyle=f?"var(--border-secondary, #ccc)":"var(--border-muted, #eee)",r.lineWidth=f?1.5:.5,r.beginPath(),r.moveTo(d,0),r.lineTo(d,o),r.stroke(),f&&i>40){r.fillStyle="var(--muted, #666)",r.font="10px monospace",r.textAlign="center";const h=n?dc(c,t.bpm):cc(c);r.fillText(h,d,12)}}if(t.snapEnabled){const c=Os(t);r.strokeStyle="var(--accent-primary, #ffeb3b)",r.lineWidth=.5;for(let d=0;d<=t.duration;d+=c){const f=d/t.duration*a;r.beginPath(),r.moveTo(f,o-5),r.lineTo(f,o),r.stroke()}}}function uc(e,t,n,r){const a=e.getContext("2d");if(!a)return;const o=30*t.zoom*t.duration,i=Math.max(80,30*t.zoom),l=n/t.duration*o;_s(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 fc(e,t,n,r="var(--success, #4caf50)"){const a=e.getContext("2d");if(!a||!(n!=null&&n.length))return;const o=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,f)=>{const h=f/(n.length-1)*o,m=l-d*c;f===0?a.moveTo(h,m):a.lineTo(h,m)}),a.stroke(),a.restore()}const zs=({zoom:e=1,duration:t=4,isPlaying:n,isRecording:r,currentTime:a,bpm:o=120,snapEnabled:i=!1,snapMode:l="beat",waveform:c,waveformColor:d,onCurrentTimeChange:f,onZoomChange:h})=>{const m=u.useRef(null),y=u.useRef(null),p=u.useRef(null),[v,x]=u.useState(!1),b={zoom:e,duration:t,bpm:o,snapEnabled:i,snapMode:l};u.useEffect(()=>{It(),S()},[e,t,a,r,o,i,l,c]),u.useEffect(()=>{n?(p.current=performance.now(),g()):y.current&&cancelAnimationFrame(y.current)},[n]);const S=()=>{m.current&&(_s(m.current,b),c!=null&&c.length&&fc(m.current,b,c,d),uc(m.current,b,a,r))},g=()=>{if(!n)return;const P=V=>{if(p.current!==null){const z=(V-p.current)/1e3;p.current=V;const A=Math.min(a+z,t);f(A)}a<t&&(y.current=requestAnimationFrame(P))};y.current=requestAnimationFrame(P)},k=P=>{x(!0),j(P)},M=P=>{v&&j(P)},N=()=>{x(!1)},j=P=>{if(!m.current)return;const V=m.current.getBoundingClientRect();let A=(P.clientX-V.left)/V.width*t;A=lc(A,b),f(Math.min(Math.max(A,0),t))},_=P=>{if(!h)return;P.preventDefault();const V=P.deltaY>0?-.1:.1,z=Math.max(.5,Math.min(5,e+V));h(z)};return s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:s.jsx("canvas",{ref:m,style:{border:"1px solid black",backgroundColor:"white",width:`${30*e*t}px`,height:`${Math.max(80,30*e)}px`,cursor:v?"grabbing":"pointer"},onMouseDown:k,onMouseMove:M,onMouseUp:N,onMouseLeave:N,onWheel:_,role:"img","aria-label":"Audio timeline canvas"})})};let hc=Date.now();function rn(){return hc++}function pc(e,t,n=.01){if(e.length===0)return[];const r=[];let a=-1/0;for(const o of e)o.time-a>=n&&(r.push({id:rn(),cc:t,value:sn(o.value),time:o.time}),a=o.time);return r}function za(e,t,n,r=32){const a=[];for(let o=0;o<=r;o++){const i=o/r;a.push({id:rn(),cc:n,value:sn(er(e.value,t.value,i)),time:er(e.time,t.time,i)})}return a}function mc(e,t,n,r,a=48){const o=[];for(let i=0;i<=a;i++){const l=i/a,c=Ba(e.time,t.time,n.time,l),d=Ba(e.value,t.value,n.value,l);o.push({id:rn(),cc:r,value:sn(d),time:c})}return o}function yc(e,t,n,r=8){const a=[],o=(t.time-e.time)/r,i=(t.value-e.value)/r;for(let l=0;l<r;l++){const c=e.time+l*o,d=sn(e.value+l*i);a.push({id:rn(),cc:n,value:d,time:c}),a.push({id:rn(),cc:n,value:d,time:c+o-.001})}return a}function gc(e,t,n,r=2,a=32){const o=[];for(let i=0;i<=a;i++){const l=i/a,c=Math.pow(l,r);o.push({id:rn(),cc:n,value:sn(er(e.value,t.value,c)),time:er(e.time,t.time,l)})}return o}function bc(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 o=Math.max(0,a-Math.floor(t/2)),i=Math.min(n.length,o+t),l=n.slice(o,i),c=l.reduce((d,f)=>d+f.value,0)/l.length;return{...r,value:sn(Math.round(c))}})}function vc(e,t){let n;switch(e.mode){case"pencil":n=pc(t,e.cc,e.resolution);break;case"line":n=t.length>=2?za(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?n=mc(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?n=za(t[0],t[t.length-1],e.cc):n=[];break;case"step":n=t.length>=2?yc(t[0],t[t.length-1],e.cc):[];break;case"ramp":n=t.length>=2?gc(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=bc(n,r)}return n}function sn(e){return Math.max(0,Math.min(127,Math.round(e)))}function er(e,t,n){return e+(t-e)*n}function Ba(e,t,n,r){const a=1-r;return a*a*e+2*a*r*t+r*r*n}function dr(){return{waveform:"sine",rate:1,depth:.5,phase:0,center:.5,syncToBpm:!1,syncDivision:"1/4",enabled:!0}}const xc={"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 Bs(e,t){return e/60*xc[t]/4}function Gs(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 Jr(e,t,n){if(!e.enabled)return e.center;const r=e.syncToBpm&&n?Bs(n,e.syncDivision):e.rate,a=t*r+e.phase/(2*Math.PI),o=Gs(e.waveform,a),i=e.center+o*e.depth*.5;return Math.max(0,Math.min(1,i))}function ea(e,t,n){return Math.round(Jr(e,t,n)*127)}function Ws(e,t,n,r,a=30,o){const i=n-t,l=Math.max(2,Math.ceil(i*a)),c=[];for(let d=0;d<=l;d++){const f=t+d/l*i,h=ea(e,f,o);c.push({time:f,value:h,cc:r})}return c}function Us(e,t,n,r=2,a,o=200){const i=[];for(let l=0;l<=o;l++){const c=l/o*r,d=Jr(e,c,a);i.push({x:l/o*t,y:(1-d)*n})}return i}function wc(e){return JSON.stringify(e,null,2)}function Sc(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const Cr=140,on=24,Cc=[{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"}],Vs=({layerId:e=0,ccNumber:t=1,duration:n=8,zoom:r=1,automation:a,onChangeCCNumber:o,points:i,onChange:l})=>{const c=u.useRef({getEvents:()=>[],setEvents:()=>{},addEvent:()=>{},removeEvent:()=>{},updateEvent:()=>{},clearLane:()=>{},exportLane:()=>"",importLane:()=>{},undo:()=>{},redo:()=>{},canUndo:!1,canRedo:!1}).current,d=a??c,{t:f}=we(),h=u.useRef(null),[m,y]=u.useState("pencil"),[p,v]=u.useState(!1),x=u.useRef([]),[b,S]=u.useState(null),[g,k]=u.useState(!1),[M,N]=u.useState(dr()),j=u.useRef(null),_=d.getEvents(e),P=_.filter(w=>w.cc===t),V=Math.max(400,n*30*r),z=u.useCallback(w=>w/V*n,[V,n]),A=u.useCallback(w=>Math.round(Math.max(0,Math.min(127,127-(w-on)/Cr*127))),[]),I=u.useCallback(w=>w/n*V,[V,n]),L=u.useCallback(w=>on+(127-w)/127*Cr,[]),U=u.useCallback(()=>{const w=h.current;if(!w)return;const $=w.getContext("2d");if(!$)return;const R=w.width,T=w.height;$.clearRect(0,0,R,T),$.fillStyle="var(--nice-bg, #1a1a2e)",$.fillRect(0,0,R,T),$.strokeStyle="var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",$.lineWidth=1;for(let F=0;F<=127;F+=16){const q=L(F);$.beginPath(),$.moveTo(0,q),$.lineTo(R,q),$.stroke()}$.fillStyle="var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))",$.font="10px monospace",$.textBaseline="middle";for(const F of[0,32,64,96,127])$.fillText(String(F),2,L(F));$.strokeStyle="var(--nice-overlay-light-4, rgba(255, 255, 255, 0.04))";for(let F=0;F<=n;F++){const q=I(F);$.beginPath(),$.moveTo(q,0),$.lineTo(q,T),$.stroke()}const C=[...P].sort((F,q)=>F.time-q.time);if(C.length>0){$.beginPath(),$.moveTo(I(C[0].time),T-on);for(const F of C)$.lineTo(I(F.time),L(F.value));$.lineTo(I(C[C.length-1].time),T-on),$.closePath(),$.fillStyle="var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",$.fill(),$.beginPath(),$.strokeStyle="var(--nice-primary, #3b82f6)",$.lineWidth=2;for(let F=0;F<C.length;F++){const q=I(C[F].time),Q=L(C[F].value);F===0?$.moveTo(q,Q):((C[F].handleType??"linear")==="step"&&$.lineTo(q,L(C[F-1].value)),$.lineTo(q,Q))}$.stroke();for(const F of C){const q=I(F.time),Q=L(F.value),J=b===F.id;$.beginPath(),$.arc(q,Q,J?6:4,0,Math.PI*2),$.fillStyle=J?"var(--nice-primary-light, #60a5fa)":"var(--nice-primary, #3b82f6)",$.fill(),$.strokeStyle="var(--nice-bg, #fff)",$.lineWidth=1.5,$.stroke()}}$.strokeStyle="var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))",$.lineWidth=1,$.setLineDash([4,4]);const E=L(0);$.beginPath(),$.moveTo(0,E),$.lineTo(R,E),$.stroke(),$.setLineDash([])},[P,n,V,I,L,b]);u.useEffect(()=>{U()},[U]);const Y=w=>{var C;const $=(C=h.current)==null?void 0:C.getBoundingClientRect();if(!$)return;const R=w.clientX-$.left,T=w.clientY-$.top;m==="pencil"?(v(!0),x.current=[{time:z(R),value:A(T)}]):(v(!0),x.current=[{time:z(R),value:A(T)}])},O=w=>{var F;const $=(F=h.current)==null?void 0:F.getBoundingClientRect();if(!$)return;const R=w.clientX-$.left,T=w.clientY-$.top;p&&x.current.push({time:z(R),value:A(T)});const C=[...P].sort((q,Q)=>q.time-Q.time);let E=null;for(const q of C){const Q=I(q.time),J=L(q.value);if(Math.abs(R-Q)<8&&Math.abs(T-J)<8){E=q.id;break}}S(E)},Z=()=>{if(!p)return;v(!1);const w=x.current;if(w.length===0)return;const $=vc({mode:m,cc:t,resolution:.02,smoothing:m==="pencil"?.3:0},w);$.length>0&&d.setEvents(e,[..._,...$]),x.current=[]},H=w=>{var C;const $=(C=h.current)==null?void 0:C.getBoundingClientRect();if(!$)return;const R=w.clientX-$.left,T=w.clientY-$.top;for(const E of P){const F=I(E.time),q=L(E.value);if(Math.abs(R-F)<8&&Math.abs(T-q)<8){d.removeEvent(e,E.id);return}}d.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:A(T),time:z(R)})},te=()=>{const $=Ws(M,0,n,t,Math.ceil(n*20),120).map((R,T)=>({...R,id:Date.now()+T}));d.setEvents(e,[..._,...$]),k(!1)},G=()=>{const w=d.exportLane(e),$=new Blob([w],{type:"application/json"}),R=URL.createObjectURL($),T=document.createElement("a");T.href=R,T.download=`cc-lane-${t}-layer-${e}.json`,document.body.appendChild(T),T.click(),T.remove(),URL.revokeObjectURL(R)},B=w=>{var R;const $=(R=w.target.files)==null?void 0:R[0];$&&($.text().then(T=>{d.importLane(e,T)}),j.current&&(j.current.value=""))};return s.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[s.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2 flex-wrap",children:[s.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:f("ccLane.title","CC Automation Lane")}),s.jsx("select",{className:"form-select form-select-sm",style:{width:160,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:t,onChange:w=>o(Number(w.target.value)),children:Cc.map(w=>s.jsxs("option",{value:w.cc,children:[w.label," (CC",w.cc,")"]},w.cc))}),s.jsx("div",{className:"btn-group btn-group-sm",children:["pencil","line","curve","step","ramp"].map(w=>s.jsx("button",{className:`btn ${m===w?"btn-primary":"btn-outline-secondary"}`,onClick:()=>y(w),style:{fontSize:11,textTransform:"capitalize"},children:w},w))}),s.jsxs("div",{className:"btn-group btn-group-sm",children:[s.jsx("button",{className:"btn btn-outline-secondary",onClick:d.undo,disabled:!d.canUndo,title:"Undo",children:"↩"}),s.jsx("button",{className:"btn btn-outline-secondary",onClick:d.redo,disabled:!d.canRedo,title:"Redo",children:"↪"})]}),s.jsx("button",{className:"btn btn-sm btn-outline-info",onClick:()=>k(!g),title:"Apply LFO modulation",children:"LFO"}),s.jsx("button",{className:"btn btn-sm btn-outline-warning",onClick:G,title:"Export CC lane as JSON",children:"Export"}),s.jsx("button",{className:"btn btn-sm btn-outline-success",onClick:()=>{var w;return(w=j.current)==null?void 0:w.click()},title:"Import CC lane from JSON",children:"Import"}),s.jsx("input",{ref:j,type:"file",accept:".json",style:{display:"none"},onChange:B}),s.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:()=>d.setEvents(e,_.filter(w=>w.cc!==t)),title:"Clear all CC events for this lane",children:"Clear"}),s.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginLeft:"auto"},children:[P.length," ",f("ccLane.events","events")]})]}),g&&s.jsx("div",{className:"mb-2 p-2",style:{background:"var(--nice-bg-secondary, #161b22)",borderRadius:6,border:"1px solid var(--nice-border, #30363d)"},children:s.jsxs("div",{className:"d-flex gap-2 flex-wrap align-items-center mb-2",children:[s.jsxs("label",{style:{fontSize:12},children:["Wave:",s.jsx("select",{className:"form-select form-select-sm ms-1",style:{width:110,display:"inline-block",background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:M.waveform,onChange:w=>N($=>({...$,waveform:w.target.value})),children:["sine","triangle","sawtooth","square","random","sample-hold"].map(w=>s.jsx("option",{value:w,children:w},w))})]}),s.jsxs("label",{style:{fontSize:12},children:["Rate:",s.jsx("input",{type:"number",className:"form-control form-control-sm ms-1",style:{width:70,display:"inline-block",background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},min:.01,max:20,step:.1,value:M.rate,onChange:w=>N($=>({...$,rate:Number(w.target.value)}))})]}),s.jsxs("label",{style:{fontSize:12},children:["Depth:",s.jsx("input",{type:"range",min:0,max:1,step:.01,value:M.depth,onChange:w=>N($=>({...$,depth:Number(w.target.value)})),style:{width:80}}),s.jsx("span",{style:{fontSize:11,marginLeft:4},children:M.depth.toFixed(2)})]}),s.jsxs("label",{style:{fontSize:12},children:["Center:",s.jsx("input",{type:"range",min:0,max:1,step:.01,value:M.center,onChange:w=>N($=>({...$,center:Number(w.target.value)})),style:{width:80}}),s.jsx("span",{style:{fontSize:11,marginLeft:4},children:M.center.toFixed(2)})]}),s.jsx("button",{className:"btn btn-sm btn-primary",onClick:te,children:"Apply LFO"}),s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>k(!1),children:"Cancel"})]})}),s.jsx("div",{style:{overflowX:"auto",borderRadius:6},children:s.jsx("canvas",{ref:h,width:V,height:Cr+on*2,style:{cursor:p?"crosshair":b?"pointer":"crosshair",display:"block",borderRadius:6},onMouseDown:Y,onMouseMove:O,onMouseUp:Z,onMouseLeave:()=>{p&&Z()},onDoubleClick:H,role:"img","aria-label":"CC automation lane editor canvas"})}),s.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginTop:4},children:f("ccLane.hint","Click to draw. Double-click to add/remove points. Drag to draw curves.")})]})},qs={"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},Lr={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function kc(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 Hs(e,t){if(e.length===0)return[];const n=kc(e,t.octaves),r=[...n].sort((i,l)=>i.pitch-l.pitch),a=[...n].sort((i,l)=>l.pitch-i.pitch);let o;switch(t.mode){case"up":o=r;break;case"down":o=a;break;case"updown":o=[...r,...a.slice(1,-1)];break;case"downup":o=[...a,...r.slice(1,-1)];break;case"random":o=[...n].sort(()=>Math.random()-.5);break;case"as-played":o=[...n].sort((i,l)=>i.originalOrder-l.originalOrder);break;case"chord":o=n;break;default:o=r}if(t.repeats>1){const i=[];for(const l of o)for(let c=0;c<t.repeats;c++)i.push(l);o=i}return o}function Mc(e,t,n,r=0,a=1){const o=Hs(e,t);if(o.length===0)return[];const i=60/n,l=qs[t.rate]*i,c=l*t.gate,d=[],f=t.mode==="chord",h=f?a:o.length*a;for(let m=0;m<h;m++){const y=m%2===1?l*t.swing*.5:0,p=r+m*l+y;if(f)for(const v of o){const x=t.velocityPattern?t.velocityPattern[m%t.velocityPattern.length]:v.velocity;d.push({pitch:v.pitch,velocity:x,startTime:p,duration:c,step:m})}else{const v=m%o.length,x=o[v],b=t.velocityPattern?t.velocityPattern[m%t.velocityPattern.length]:x.velocity;d.push({pitch:x.pitch,velocity:b,startTime:p,duration:c,step:m})}}return d}function Ks(){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 Ys(){return Object.keys(qs)}const Zs=({config:e=Lr,onChange:t=()=>{},active:n=!1,onToggleActive:r=()=>{}})=>{const{t:a}=we(),o=Ks(),i=Ys(),l=c=>t({...e,...c});return s.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8,opacity:n?1:.6},children:[s.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[s.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:a("arp.title","Arpeggiator")}),s.jsx("button",{className:`btn btn-sm ${n?"btn-success":"btn-outline-secondary"}`,onClick:r,children:n?"ON":"OFF"}),s.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"}),s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>t(Lr),title:"Reset to defaults",children:"Reset"})]}),s.jsxs("div",{className:"row g-2",children:[s.jsxs("div",{className:"col-12",children:[s.jsx("label",{style:{fontSize:12},className:"mb-1",children:a("arp.mode","Mode")}),s.jsx("div",{className:"btn-group btn-group-sm w-100",children:o.map(c=>s.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))})]}),s.jsxs("div",{className:"col-6",children:[s.jsx("label",{style:{fontSize:12},className:"mb-1",children:a("arp.rate","Rate")}),s.jsx("select",{className:"form-select form-select-sm",style:{background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:e.rate,onChange:c=>l({rate:c.target.value}),children:i.map(c=>s.jsx("option",{value:c,children:c},c))})]}),s.jsxs("div",{className:"col-6",children:[s.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[a("arp.octaves","Octaves"),": ",e.octaves]}),s.jsx("input",{type:"range",className:"form-range",min:1,max:4,step:1,value:e.octaves,onChange:c=>l({octaves:Number(c.target.value)})})]}),s.jsxs("div",{className:"col-6",children:[s.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[a("arp.gate","Gate"),": ",Math.round(e.gate*100),"%"]}),s.jsx("input",{type:"range",className:"form-range",min:.05,max:1,step:.05,value:e.gate,onChange:c=>l({gate:Number(c.target.value)})})]}),s.jsxs("div",{className:"col-6",children:[s.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[a("arp.swing","Swing"),": ",Math.round(e.swing*100),"%"]}),s.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.swing,onChange:c=>l({swing:Number(c.target.value)})})]}),s.jsxs("div",{className:"col-6",children:[s.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[a("arp.repeats","Repeats"),": ",e.repeats]}),s.jsx("input",{type:"range",className:"form-range",min:1,max:4,step:1,value:e.repeats,onChange:c=>l({repeats:Number(c.target.value)})})]})]})]})},jc=["sine","triangle","sawtooth","square","random","sample-hold"],Rc=["1/1","1/2","1/4","1/8","1/16","1/32"],ln=200,zt=48,Xs=({config:e,onChange:t,index:n,onRemove:r})=>{const{t:a}=we(),o=u.useRef(null),i=c=>t({...e,...c}),l=u.useCallback(()=>{const c=o.current;if(!c)return;const d=c.getContext("2d");if(!d)return;d.clearRect(0,0,ln,zt),d.fillStyle="var(--nice-bg-secondary, #161b22)",d.fillRect(0,0,ln,zt),d.strokeStyle="var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",d.lineWidth=1,d.setLineDash([3,3]),d.beginPath(),d.moveTo(0,zt/2),d.lineTo(ln,zt/2),d.stroke(),d.setLineDash([]);const f=Us(e,ln,zt);if(f.length>0){d.beginPath(),d.strokeStyle=e.enabled?"var(--nice-primary, #3b82f6)":"var(--nice-text-secondary, #484f58)",d.lineWidth=1.5;for(let h=0;h<f.length;h++){const m=f[h].x,y=f[h].y;h===0?d.moveTo(m,y):d.lineTo(m,y)}d.stroke()}},[e]);return u.useEffect(()=>{l()},[l]),s.jsxs("div",{className:"card p-2 mb-2",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8,opacity:e.enabled?1:.5},children:[s.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[s.jsxs("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)",fontSize:13},children:[a("lfo.title","LFO")," ",n!==void 0?`#${n+1}`:""]}),s.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"}),s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>t(dr()),style:{fontSize:11,padding:"1px 8px"},title:"Reset to defaults",children:"Reset"}),r&&s.jsx("button",{className:"btn btn-sm btn-outline-danger ms-auto",onClick:r,style:{fontSize:11,padding:"1px 8px"},children:"✕"})]}),s.jsxs("div",{className:"d-flex gap-2 flex-wrap align-items-start",children:[s.jsx("canvas",{ref:o,width:ln,height:zt,style:{borderRadius:4,border:"1px solid var(--nice-border, #30363d)",flexShrink:0},role:"img","aria-label":"LFO waveform preview canvas"}),s.jsxs("div",{className:"flex-grow-1",children:[s.jsx("div",{className:"mb-1",children:s.jsx("div",{className:"btn-group btn-group-sm w-100",children:jc.map(c=>s.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))})}),s.jsxs("div",{className:"row g-1",children:[s.jsxs("div",{className:"col-6",children:[s.jsxs("label",{style:{fontSize:10},children:["Rate: ",e.rate.toFixed(1)," Hz"]}),s.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}})]}),s.jsxs("div",{className:"col-6",children:[s.jsxs("label",{style:{fontSize:10},children:["Depth: ",Math.round(e.depth*100),"%"]}),s.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}})]}),s.jsxs("div",{className:"col-6",children:[s.jsxs("label",{style:{fontSize:10},children:["Center: ",Math.round(e.center*100),"%"]}),s.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}})]}),s.jsxs("div",{className:"col-6",children:[s.jsxs("label",{style:{fontSize:10},children:["Phase: ",Math.round(e.phase),"°"]}),s.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}})]})]}),s.jsxs("div",{className:"d-flex align-items-center gap-2 mt-1",children:[s.jsxs("label",{style:{fontSize:10},children:[s.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&&s.jsx("select",{className:"form-select form-select-sm",style:{width:80,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)",fontSize:11},value:e.syncDivision??"1/4",onChange:c=>i({syncDivision:c.target.value}),children:Rc.map(c=>s.jsx("option",{value:c,children:c},c))}),s.jsxs("label",{style:{fontSize:10},children:["CC:",s.jsx("input",{type:"number",className:"form-control form-control-sm ms-1",style:{width:55,display:"inline-block",background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)",fontSize:11},min:0,max:127,value:e.targetCC??1,onChange:c=>i({targetCC:Number(c.target.value)})})]})]})]})]})]})},Tc=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function $c(e){const t=Math.floor(e/12)-1;return`${Tc[e%12]}${t}`}const Qs=({seq:e,steps:t,tracks:n,bpm:r,pattern:a,onChange:o})=>{const{t:i}=we();if(!e)return s.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[s.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:i("stepSeq.title","Step Sequencer")}),s.jsx("small",{style:{color:"var(--nice-text-muted, #8b949e)"},children:"Provide a `seq` prop (useStepSequencer) for live editing."})]});const{pattern:l,currentStep:c,playing:d}=e,f=u.useMemo(()=>l.steps.slice(0,l.length),[l]);return s.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[s.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2 flex-wrap",children:[s.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:i("stepSeq.title","Step Sequencer")}),s.jsx("button",{className:`btn btn-sm ${d?"btn-danger":"btn-success"}`,onClick:e.togglePlayback,style:{minWidth:60},children:d?"■ Stop":"▶ Play"}),s.jsxs("label",{style:{fontSize:12,display:"flex",alignItems:"center",gap:4},children:["BPM:",s.jsx("input",{type:"number",className:"form-control form-control-sm",style:{width:70,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},min:20,max:300,value:l.bpm,onChange:h=>e.setBpm(Number(h.target.value))})]}),s.jsxs("label",{style:{fontSize:12,display:"flex",alignItems:"center",gap:4},children:["Swing:",s.jsx("input",{type:"range",min:0,max:1,step:.01,value:l.swing,onChange:h=>e.setSwing(Number(h.target.value)),style:{width:60}}),s.jsxs("span",{style:{fontSize:11,minWidth:28},children:[Math.round(l.swing*100),"%"]})]}),s.jsx("div",{className:"btn-group btn-group-sm",children:[16,32,64].map(h=>s.jsx("button",{className:`btn ${l.length===h?"btn-primary":"btn-outline-secondary"}`,onClick:()=>e.setLength(h),style:{fontSize:11},children:h},h))})]}),s.jsxs("div",{className:"d-flex gap-1 mb-2 flex-wrap",children:[s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(1),"aria-label":"Transpose up one semitone",children:"+1"}),s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(-1),"aria-label":"Transpose down one semitone",children:"-1"}),s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(12),children:"+Oct"}),s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(-12),children:"-Oct"}),s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:e.reverse,children:"Reverse"}),s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.shift(1),children:"Shift →"}),s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.shift(-1),children:"← Shift"}),s.jsx("button",{className:"btn btn-sm btn-outline-info",onClick:()=>e.randomizeVel(),children:"Rnd Vel"}),s.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:e.clear,children:"Clear"})]}),s.jsx("div",{style:{overflowX:"auto"},children:s.jsx("div",{style:{display:"flex",gap:2,minWidth:l.length*36},children:f.map((h,m)=>{const y=h.active,p=c===m,v=m%4===0;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2,minWidth:34},children:[s.jsx("span",{style:{fontSize:9,color:v?"var(--nice-text-muted, #8b949e)":"var(--nice-border, #30363d)"},children:m+1}),s.jsx("button",{onClick:()=>e.toggle(m),style:{width:32,height:32,borderRadius:4,border:p?"2px solid var(--nice-warning, #f0c040)":"1px solid var(--nice-border, #30363d)",background:y?`hsl(${210+h.velocity/127*40}, 80%, ${35+h.velocity/127*20}%)`:v?"#21262d":"var(--nice-bg-secondary, #161b22)",cursor:"pointer",padding:0,color:y?"var(--nice-bg, #fff)":"var(--nice-text-secondary, #484f58)",fontSize:8,fontWeight:600,transition:"background 0.1s"},children:y?$c(h.note):""}),s.jsx("div",{style:{width:32,height:20,background:"var(--nice-bg-secondary, #161b22)",borderRadius:2,position:"relative",overflow:"hidden"},children:s.jsx("div",{style:{position:"absolute",bottom:0,left:0,width:"100%",height:`${h.velocity/127*100}%`,background:y?"var(--nice-primary-tint-60, rgba(59, 130, 246, 0.6))":"var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",borderRadius:2,cursor:"ns-resize"},title:`Vel: ${h.velocity}`,onMouseDown:x=>{x.preventDefault();const b=x.target.parentElement.getBoundingClientRect(),S=k=>{const M=k.clientY-b.top,N=Math.round(Math.max(1,Math.min(127,(1-M/b.height)*127)));e.setVelocity(m,N)},g=()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",g)};document.addEventListener("mousemove",S),document.addEventListener("mouseup",g)}})}),y&&h.probability<1&&s.jsxs("span",{style:{fontSize:8,color:"var(--nice-warning, #f0c040)"},children:[Math.round(h.probability*100),"%"]})]},m)})})}),s.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginTop:6},children:i("stepSeq.hint","Click steps to toggle. Drag velocity bars vertically.")})]})},Pc="_panelNarrow_42xt3_3",Ec="_panelWide_42xt3_9",Ac="_smallLabel_42xt3_19",Nc="_noteText_42xt3_29",Ic="_buttonRow_42xt3_41",Lc="_noteTextMargin_42xt3_49",Dc="_rangeW100_42xt3_63",Fc="_zoomValue_42xt3_69",Oc="_selectW100_42xt3_77",_c="_inputW70_42xt3_83",zc="_masterVolGroup_42xt3_93",Bc="_rangeW140_42xt3_99",Gc="_volumeValue_42xt3_105",Wc="_selectW140_42xt3_115",Uc="_freqGroup_42xt3_121",Vc="_freqValue_42xt3_127",qc="_narrowGroup_42xt3_137",Hc="_rangeW120_42xt3_143",Kc="_smallValue_42xt3_149",Yc="_presetDivider_42xt3_159",Zc="_presetLabel_42xt3_165",Xc="_presetBtn_42xt3_175",Qc="_deletePresetSelect_42xt3_183",Jc="_presetNameInput_42xt3_191",ed="_savePresetBtn_42xt3_199",td="_countInAlert_42xt3_211",nd="_inputW80_42xt3_219",rd="_levelLabel_42xt3_225",ad="_levelMeter_42xt3_233",sd="_levelBar_42xt3_249",me={panelNarrow:Pc,panelWide:Ec,smallLabel:Ac,noteText:Nc,buttonRow:Ic,noteTextMargin:Lc,rangeW100:Dc,zoomValue:Fc,selectW100:Oc,inputW70:_c,masterVolGroup:zc,rangeW140:Bc,volumeValue:Gc,selectW140:Wc,freqGroup:Uc,freqValue:Vc,narrowGroup:qc,rangeW120:Hc,smallValue:Kc,presetDivider:Yc,presetLabel:Zc,presetBtn:Xc,deletePresetSelect:Qc,presetNameInput:Jc,savePresetBtn:ed,countInAlert:td,inputW80:nd,levelLabel:rd,levelMeter:ad,levelBar:sd},Js=({autoSaveMode:e,setAutoSaveMode:t,autoSaveInterval:n,setAutoSaveInterval:r})=>{const{t:a}=we();return s.jsxs("div",{className:`card p-3 mb-3 ${me.panelNarrow}`,children:[s.jsx("h6",{className:"mb-2",children:a("editorPanels.autoSaveTitle","Project auto-save")}),s.jsxs("div",{className:"mb-2",children:[s.jsxs("label",{className:"form-label",children:[a("editorPanels.autoSaveMode","Auto-save mode"),":"]}),s.jsxs("select",{className:"form-select",value:e,onChange:o=>t(o.target.value),children:[s.jsx("option",{value:"off",children:a("editorPanels.off","Off")}),s.jsx("option",{value:"onChange",children:a("editorPanels.onChange","On every change")}),s.jsx("option",{value:"interval",children:a("editorPanels.interval","At set interval")}),s.jsx("option",{value:"both",children:a("editorPanels.both","Both")})]})]}),(e==="interval"||e==="both")&&s.jsxs("div",{className:"mb-2",children:[s.jsxs("label",{className:"form-label",children:[a("editorPanels.autoSaveFrequency","Auto-save frequency (seconds)"),":"]}),s.jsx("input",{type:"number",className:"form-control",min:5,max:600,value:n,onChange:o=>r(Math.max(5,Math.min(600,Number(o.target.value))))})]}),s.jsxs("div",{className:me.noteText,children:[s.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.")]})]})},eo=({undoCount:e,redoCount:t,onUndo:n,onRedo:r})=>{const{t:a}=we();return s.jsxs("div",{className:`card p-3 mb-3 ${me.panelNarrow}`,children:[s.jsx("h6",{className:"mb-2",children:a("editorPanels.changeHistory","Project change history")}),s.jsxs("div",{className:me.buttonRow,children:[s.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")]}),s.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")]})]}),s.jsx("div",{className:me.noteTextMargin,children:a("editorPanels.undoRedoNote","Undo/Redo works on the entire project (all editor changes). After each change Redo is cleared.")})]})},to=({zoom:e,setZoom:t,uiZoom:n,setUiZoom:r,snapEnabled:a,onToggleSnap:o,snapMode:i,onSnapModeChange:l,bpm:c,setBpm:d})=>{const{t:f}=we();return s.jsx("div",{className:`card p-2 mb-3 ${me.panelNarrow}`,children:s.jsxs("div",{className:"d-flex align-items-center gap-3",children:[s.jsxs("div",{className:"d-flex align-items-center gap-2",children:[s.jsx("label",{className:`form-label mb-0 ${me.smallLabel}`,children:"Zoom:"}),s.jsx("input",{type:"range",min:"0.5",max:"5",step:"0.1",value:e,onChange:h=>t(Number(h.target.value)),className:me.rangeW100}),s.jsxs("span",{className:me.zoomValue,children:[e.toFixed(1),"x"]})]}),s.jsxs("div",{className:"d-flex align-items-center gap-2",children:[s.jsx("label",{className:`form-label mb-0 ${me.smallLabel}`,children:"Zoom UI:"}),s.jsx("input",{type:"range",min:"1",max:"4",step:"0.1",value:n,onChange:h=>r(Number(h.target.value)),className:me.rangeW100}),s.jsxs("span",{className:me.zoomValue,children:[n.toFixed(1),"x"]})]}),s.jsxs("div",{className:"d-flex align-items-center gap-2",children:[s.jsx("input",{id:"snap-toggle",type:"checkbox",className:"form-check-input",checked:a,onChange:o}),s.jsx("label",{htmlFor:"snap-toggle",className:`form-check-label mb-0 ${me.smallLabel}`,children:"Snap"})]}),a&&s.jsxs("select",{className:`form-select form-select-sm ${me.selectW100}`,value:i,onChange:h=>l(h.target.value),children:[s.jsx("option",{value:"bar",children:f("editorPanels.snapBar","Bar")}),s.jsx("option",{value:"beat",children:f("editorPanels.snapBeat","Beat")}),s.jsx("option",{value:"sub-beat",children:f("editorPanels.snap16","1/16")}),s.jsx("option",{value:"second",children:f("editorPanels.snapSecond","Second")})]}),s.jsxs("div",{className:"d-flex align-items-center gap-2",children:[s.jsx("label",{className:`form-label mb-0 ${me.smallLabel}`,children:"BPM:"}),s.jsx("input",{type:"number",className:`form-control form-control-sm ${me.inputW70}`,value:c,onChange:h=>d(Number(h.target.value)),min:"20",max:"300"})]})]})})},no=({masterVolume:e,onMasterVolumeChange:t,filterType:n,filterFreq:r,filterQ:a,filterGain:o,onFilterChange:i,masterEQPresets:l,customPresets:c,onLoadPreset:d,onSavePreset:f,onDeletePreset:h})=>{const{t:m}=we();return s.jsxs("div",{className:`card p-2 mb-3 ${me.panelWide}`,children:[s.jsxs("div",{className:"d-flex align-items-center flex-wrap gap-3",children:[s.jsxs("div",{className:`d-flex align-items-center gap-2 ${me.masterVolGroup}`,children:[s.jsx("label",{className:`form-label mb-0 ${me.smallLabel}`,children:"Master Vol"}),s.jsx("input",{type:"range",min:"0",max:"1",step:"0.01",value:e,onChange:y=>t(Number(y.target.value)),className:me.rangeW140}),s.jsxs("span",{className:me.volumeValue,children:[Math.round(e*100),"%"]})]}),s.jsxs("div",{className:"d-flex align-items-center gap-2",children:[s.jsx("label",{className:`form-label mb-0 ${me.smallLabel}`,children:"Filter"}),s.jsx("select",{className:`form-select form-select-sm ${me.selectW140}`,value:n,onChange:y=>i({type:y.target.value}),children:["peaking","lowpass","highpass","lowshelf","highshelf","notch","bandpass"].map(y=>s.jsx("option",{value:y,children:y},y))})]}),s.jsxs("div",{className:`d-flex align-items-center gap-2 ${me.freqGroup}`,children:[s.jsx("span",{className:me.smallLabel,children:"Freq"}),s.jsx("input",{type:"range",min:"40",max:"12000",step:"10",value:r,onChange:y=>i({frequency:Number(y.target.value)}),className:me.rangeW140}),s.jsxs("span",{className:me.freqValue,children:[Math.round(r)," Hz"]})]}),s.jsxs("div",{className:`d-flex align-items-center gap-2 ${me.narrowGroup}`,children:[s.jsx("span",{className:me.smallLabel,children:"Q"}),s.jsx("input",{type:"range",min:"0.1",max:"12",step:"0.1",value:a,onChange:y=>i({q:Number(y.target.value)}),className:me.rangeW120}),s.jsx("span",{className:me.smallValue,children:a.toFixed(1)})]}),(n==="peaking"||n==="lowshelf"||n==="highshelf")&&s.jsxs("div",{className:`d-flex align-items-center gap-2 ${me.narrowGroup}`,children:[s.jsx("span",{className:me.smallLabel,children:"Gain"}),s.jsx("input",{type:"range",min:"-18",max:"18",step:"0.5",value:o,onChange:y=>i({gain:Number(y.target.value)}),className:me.rangeW120}),s.jsxs("span",{className:me.smallValue,children:[o.toFixed(1)," dB"]})]})]}),s.jsxs("div",{className:`mt-2 pt-2 ${me.presetDivider}`,children:[s.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[s.jsxs("span",{className:me.presetLabel,children:[m("editorPanels.eqPresets","EQ Presets"),":"]}),[...l,...c].map(y=>s.jsx("button",{className:`btn btn-sm btn-outline-secondary ${me.presetBtn}`,onClick:()=>d(y),children:y.name},y.name)),c.length>0&&s.jsxs("select",{className:`form-select form-select-sm ${me.deletePresetSelect}`,onChange:y=>{y.target.value&&(h(y.target.value),y.target.value="")},defaultValue:"",children:[s.jsx("option",{value:"",children:m("editorPanels.deletePreset","Delete preset...")}),c.map(y=>s.jsx("option",{value:y.name,children:y.name},y.name))]})]}),s.jsxs("div",{className:"d-flex align-items-center gap-2",children:[s.jsx("input",{type:"text",className:`form-control form-control-sm ${me.presetNameInput}`,placeholder:m("editorPanels.presetName","Preset name..."),id:"presetNameInput"}),s.jsx("button",{className:`btn btn-sm btn-success ${me.savePresetBtn}`,onClick:()=>{const y=document.getElementById("presetNameInput");y!=null&&y.value.trim()&&(f(y.value.trim()),y.value="")},children:m("editorPanels.saveCurrent","Save Current")})]})]})]})},ro=({countInBars:e,setCountInBars:t,isCountIn:n,countInRemaining:r,overdubEnabled:a,setOverdubEnabled:o,punchIn:i,setPunchIn:l,punchOut:c,setPunchOut:d,monitorLevel:f})=>{const{t:h}=we();return s.jsx("div",{className:`card p-2 mb-3 ${me.panelWide}`,children:s.jsxs("div",{className:"d-flex align-items-center flex-wrap gap-3",children:[s.jsxs("div",{className:"d-flex align-items-center gap-2",children:[s.jsxs("label",{className:`form-label mb-0 ${me.smallLabel}`,children:[h("editorPanels.countIn","Count-in (bars)"),":"]}),s.jsx("input",{type:"number",min:"0",max:"8",step:"1",className:`form-control form-control-sm ${me.inputW70}`,value:e,onChange:m=>t(Number(m.target.value))}),n&&s.jsxs("span",{className:me.countInAlert,children:["Count-in: ",r.toFixed(1),"s"]})]}),s.jsxs("div",{className:"form-check d-flex align-items-center gap-2",children:[s.jsx("input",{id:"overdub-toggle",className:"form-check-input",type:"checkbox",checked:a,onChange:m=>o(m.target.checked)}),s.jsx("label",{htmlFor:"overdub-toggle",className:`form-check-label ${me.smallLabel}`,children:h("editorPanels.overdub","Overdub (play background)")})]}),s.jsxs("div",{className:"d-flex align-items-center gap-1",children:[s.jsx("span",{className:me.smallLabel,children:"Punch In"}),s.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${me.inputW80}`,value:i??"",onChange:m=>l(m.target.value===""?null:Number(m.target.value))}),s.jsx("span",{className:me.smallLabel,children:"s"})]}),s.jsxs("div",{className:"d-flex align-items-center gap-1",children:[s.jsx("span",{className:me.smallLabel,children:"Punch Out"}),s.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${me.inputW80}`,value:c??"",onChange:m=>d(m.target.value===""?null:Number(m.target.value))}),s.jsx("span",{className:me.smallLabel,children:"s"})]}),s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>{l(null),d(null)},children:h("editorPanels.clearPunch","Clear punch")}),s.jsx("div",{className:me.levelLabel,children:"Level"}),s.jsx("div",{className:me.levelMeter,children:s.jsx("div",{className:me.levelBar,style:{width:`${Math.min(1,f*2)*100}%`,background:f>.7?"var(--nice-danger, #f44336)":"var(--nice-success, #4caf50)"}})})]})})};function od(e,t,n){const[r,a]=u.useState("interval"),[o,i]=u.useState(30),l=u.useRef(null),c=u.useCallback(()=>{if(e)try{localStorage.setItem("audioEditor.autoSave",JSON.stringify(e)),t("Project auto-saved locally"),n("success"),setTimeout(()=>t(""),2e3)}catch(d){t("Auto-save error: "+d.message),n("error")}},[e,t,n]);return u.useEffect(()=>{(r==="onChange"||r==="both")&&c()},[e,r,c]),u.useEffect(()=>(l.current&&(clearInterval(l.current),l.current=null),(r==="interval"||r==="both")&&o>0&&(l.current=window.setInterval(c,o*1e3)),()=>{l.current&&(clearInterval(l.current),l.current=null)}),[r,o,c]),{autoSaveMode:r,setAutoSaveMode:a,autoSaveInterval:o,setAutoSaveInterval:i}}function id(e,t,n){const r=u.useRef(null),[a,o]=u.useState(!1),[i,l]=u.useState(0),[c,d]=u.useState(10),[f,h]=u.useState(!1),[m,y]=u.useState(120),p=u.useCallback((j,_)=>`L${j}-C${_}`,[]),v=u.useCallback((j,_)=>{if(!r.current||!_.audioBuffer)return;const P=p(j,_.id),V=e[j];r.current.addClip({id:P,buffer:_.audioBuffer,startTime:_.start,offset:0,duration:_.duration,layerId:j,volume:(V==null?void 0:V.volume)??1,pan:(V==null?void 0:V.pan)??0,stretchFactor:_.stretchFactor||1,effectChain:(V==null?void 0:V.effectChain)||[]})},[e,p]),x=u.useCallback((j,_)=>{var P;(P=r.current)==null||P.removeClip(p(j,_))},[p]);u.useEffect(()=>{Object.entries(t).forEach(([j,_])=>{const P=Number(j);_==null||_.forEach(V=>v(P,V))})},[t,e,v]),u.useEffect(()=>{r.current&&Object.entries(n).forEach(([j,_])=>{const P=Number(j);r.current.setMidiCCEvents(P,_)})},[n]);const b=u.useCallback(()=>{r.current&&(a?r.current.pause():r.current.play())},[a]),S=u.useCallback(()=>{var j;(j=r.current)==null||j.stop()},[]),g=u.useCallback(j=>{var _;(_=r.current)==null||_.seek(j)},[]),k=u.useCallback(()=>{if(!r.current)return;const j=!f;h(j),r.current.setLoopRegion(0,c,j)},[f,c]),M=u.useCallback(j=>{var P;const _=Math.max(1,c+j);d(_),(P=r.current)==null||P.setLoopRegion(0,_,f)},[c,f]),N=u.useCallback(async(j,_=1024)=>{const P=await j.arrayBuffer(),V=new(window.AudioContext||window.webkitAudioContext),z=await V.decodeAudioData(P.slice(0)),A=z.getChannelData(0),I=A.length,L=Math.max(1,Math.floor(I/_)),U=[];for(let Y=0;Y<_;Y++){const O=Y*L;if(O>=I)break;U.push(A[O])}return V.close(),{waveform:U.map(Y=>Math.max(-1,Math.min(1,Y))),duration:z.duration,buffer:z}},[]);return{engineRef:r,isPlaying:a,setIsPlaying:o,currentTime:i,setCurrentTime:l,duration:c,setDuration:d,isLooping:f,setIsLooping:h,bpm:m,setBpm:y,handlePlayPause:b,handleStop:S,handleSeek:g,handleToggleLoop:k,handleAdjustDuration:M,upsertEngineClip:v,removeEngineClip:x,makeEngineClipId:p,blobToWaveform:N}}class ao{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 o=()=>{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 f=(i[d]-128)/128;l+=f*f}const c=Math.sqrt(l/i.length);this.levelCallback&&this.levelCallback(c),this.isRecording&&(this.levelRaf=requestAnimationFrame(o))};this.mediaRecorder.ondataavailable=i=>{i.data&&i.data.size>0&&this.audioChunks.push(i.data)},this.mediaRecorder.start(),this.isRecording=!0,this.levelRaf=requestAnimationFrame(o)}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 ld(e){const[t,n]=u.useState(!1),[r,a]=u.useState(!1),[o,i]=u.useState(0),[l,c]=u.useState(0),[d,f]=u.useState(null),h=u.useRef(null),m=u.useRef(null),y=u.useRef(0),p=u.useRef(null),v=u.useRef(null),x=u.useCallback(()=>{p.current&&(clearInterval(p.current),p.current=null),v.current&&(clearTimeout(v.current),v.current=null)},[]),b=u.useCallback(async()=>{if(!e.activeLayer){e.showToast("Select a layer to record.","error");return}t||(h.current||(h.current=new ao),y.current=m.current??e.currentTime,n(!0),i(0),await h.current.startRecording({onLevel:i}))},[e,t]),S=u.useCallback(async()=>{var A;if(x(),a(!1),c(0),m.current=null,!h.current){n(!1),i(0);return}const M=await h.current.stopRecording();if(n(!1),i(0),!M||!e.activeLayer)return;const{waveform:N,duration:j,buffer:_}=await e.blobToWaveform(M),P=e.activeLayer.id;e.setWaveforms(I=>({...I,[P]:N}));const V=Math.max(0,y.current||0),z={id:Date.now(),label:"Recording",start:V,duration:j,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:(A=e.layerSettings[P])==null?void 0:A.color,blob:M,blobUrl:URL.createObjectURL(M),audioBuffer:_};e.setLayerClips(I=>({...I,[P]:[...I[P]||[],z]})),e.upsertEngineClip(P,z),e.setSelectedClip({layerId:P,clipId:z.id})},[e,x]),g=u.useCallback(M=>{if(M<=0){b();return}a(!0),c(M);const N=performance.now();p.current=window.setInterval(()=>{const j=(performance.now()-N)/1e3;c(Math.max(0,M-j))},100),v.current=window.setTimeout(()=>{x(),a(!1),c(0),m.current||b()},M*1e3)},[b,x]),k=u.useCallback(async()=>{if(t||r){await S();return}if(!e.activeLayer){e.showToast("Select a layer before recording","error");return}const M=Math.max(0,e.countInBars)*4*(60/e.bpm),N=e.punchIn!=null&&e.punchIn>e.currentTime?e.punchIn:null;N&&(m.current=N),e.overdubEnabled&&!e.isPlaying&&e.playEngine(),N?M>0&&g(M):g(M)},[t,r,e,S,g]);return{isRecording:t,isCountIn:r,monitorLevel:o,countInRemaining:l,punchOut:d,setPunchOut:f,armedPunchInRef:m,recorderRef:h,clearCountInTimers:x,startRecordingNow:b,stopRecordingFlow:S,handleRecord:k}}var so=(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))(so||{});const cd={};class In{constructor(t,n,r,a={}){this.type=t,this.name=n,this.component=cd[t]??(()=>null),this.audioType=r,this.parameters=a}}new In("Recorder","Recorder","vocal",{deviceId:"",gain:1,sensitivity:"high"}),new In("Audio Clip","Audio Clip","instrumental",{clipId:null,octave:"4"}),new In("Speech Synth","Speech Synth","vocal",{text:"",voice:"default"}),new In("Keyboard/Pads","Keyboard","instrumental",{instrument:"piano",preset:"default",velocity:100});function oo(e,t,n,r,a){n(o=>t?[...o,t]:o),r([]),a(e)}function dd(e,t,n,r){t(a=>{if(a.length===0)return a;const o=a[a.length-1];return n(i=>e?[e,...i]:i),r(o),a.slice(0,-1)})}function ud(e,t,n,r){n(a=>{if(a.length===0)return a;const o=a[0];return t(i=>e?[...i,e]:i),r(o),a.slice(1)})}class fd{constructor(t={}){this.undoStack=[],this.redoStack=[],this.maxSize=t.maxSize??100,this.onChange=t.onChange}push(t,n,r,a){this.undoStack.push({label:t,category:n,timestamp:Date.now(),oldState:r,newState:a}),this.undoStack.length>this.maxSize&&this.undoStack.shift(),this.redoStack.length=0}undo(){var n;const t=this.undoStack.pop();return t?(this.redoStack.push(t),(n=this.onChange)==null||n.call(this,t,"undo"),t.oldState):null}redo(){var n;const t=this.redoStack.pop();return t?(this.undoStack.push(t),(n=this.onChange)==null||n.call(this,t,"redo"),t.newState):null}get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}get undoLabel(){return this.undoStack.length>0?this.undoStack[this.undoStack.length-1].label:null}get redoLabel(){return this.redoStack.length>0?this.redoStack[this.redoStack.length-1].label:null}get undoCount(){return this.undoStack.length}get redoCount(){return this.redoStack.length}getHistory(){return[...this.undoStack].reverse()}clear(){this.undoStack.length=0,this.redoStack.length=0}undoTo(t){const n=Math.min(t+1,this.undoStack.length);let r=null;for(let a=0;a<n;a++)r=this.undo();return r}}const hd=nt.scoped("useProjectCRUD");function pd(e){const{project:t,activeSection:n,setProject:r,setActiveSection:a,setLayers:o,setActiveLayer:i,setUndoStack:l,setRedoStack:c}=e,d=u.useCallback(x=>oo(x,t,l,c,r),[t,l,c,r]),f=u.useCallback(async()=>{var g;if(!t)return;const x=(((g=t.sections)==null?void 0:g.length)??0)+1,S={id:await e.addSection(t.id,"Section",x),projectId:t.id,name:"Section",orderNumber:x,layers:[]};d({...t,sections:[...t.sections||[],S]}),a(S)},[t,d,a]),h=u.useCallback(async x=>{var g,k,M;if(!t||!await e.confirm("Delete this section?"))return;await e.deleteSection(x);const S=(t.sections??[]).filter(N=>N.id!==x);d({...t,sections:S}),a(S[0]??null),o(((g=S[0])==null?void 0:g.layers)??[]),i(((M=(k=S[0])==null?void 0:k.layers)==null?void 0:M[0])??null)},[t,d,a,o,i,e]),m=u.useCallback(async()=>{var b;if(!n)return;const x={id:-Date.now(),name:"New Layer",sectionId:n.id,audioSource:so.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};o(S=>[...S,x]),i(x);try{const S=await e.addLayer(n.id,x.name,x.audioSource,x.audioSourceParameters);o(g=>g.map(k=>k.id===x.id?{...x,id:S}:k)),t&&d({...t,sections:((b=t.sections)==null?void 0:b.map(g=>g.id===n.id?{...g,layers:[...(g.layers??[]).filter(k=>k.id!==S),{...x,id:S}]}:g))??[]})}catch(S){o(g=>g.filter(k=>k.id!==x.id)),hd.error("Failed to add layer:",S)}},[n,t,d,o,i]),y=u.useCallback(async x=>{var S,g;if((S=e.layerSettings[x])!=null&&S.locked){e.showToast("Layer is locked. Unlock to delete.","error");return}await e.confirm("Delete this layer?")&&((e.layerClips[x]||[]).forEach(k=>e.removeEngineClip(x,k.id)),e.setLayerMidiNotes(k=>{const M={...k};return delete M[x],M}),await e.deleteLayer(x),o(k=>k.filter(M=>M.id!==x)),i(k=>(k==null?void 0:k.id)===x?null:k),t&&d({...t,sections:((g=t.sections)==null?void 0:g.map(k=>k.id===(n==null?void 0:n.id)?{...k,layers:(k.layers??[]).filter(M=>M.id!==x)}:k))??[]}))},[t,n,d,o,i,e]),p=u.useCallback(async()=>{if(!t)return;const x=e.projectVolume===""?void 0:Number(e.projectVolume);if(Number.isNaN(x)){e.setStatusType("error"),e.setStatusMessage("Volume musi byc liczba");return}if(!e.projectName.trim()){e.setStatusType("error"),e.setStatusMessage("Nazwa projektu nie moze byc pusta");return}await e.updateProject(t.id,{name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:x}),d({...t,name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:x}),e.setStatusType("success"),e.setStatusMessage("Project saved")},[t,e,d]),v=u.useCallback(async()=>{var S;if(!n)return;const x=e.sectionName||n.name,b=e.sectionOrder===""?n.orderNumber:Number(e.sectionOrder);if(!x.trim()){e.setStatusType("error"),e.setStatusMessage("Section name cannot be empty");return}if(Number.isNaN(b)){e.setStatusType("error"),e.setStatusMessage("Order musi byc liczba");return}await e.updateSection(n.id,{name:x,orderNumber:b}),a({...n,name:x,orderNumber:b}),t&&d({...t,sections:((S=t.sections)==null?void 0:S.map(g=>g.id===n.id?{...g,name:x,orderNumber:b}:g))??[]}),e.setStatusType("success"),e.setStatusMessage("Section saved")},[n,t,e,d,a]);return{handleAddSection:f,handleDeleteSection:h,handleAddLayer:m,handleDeleteLayer:y,handleSaveProject:p,handleSaveSection:v}}const io=u.createContext(null);function md(){const e=u.useContext(io);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const ta=({value:e,children:t})=>s.jsx(io.Provider,{value:e,children:t});ta.displayName="EditorTrackProvider";const Zt=(e,t)=>t&&t>0?e*15/t:e/10,na=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},yd=(e,t)=>{const n=t??na(e),r=[];let a="",o=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:o}),a=""),l=!0;else if(d.startsWith(":")||d.startsWith("*")){const f=d.indexOf(" "),h=d.indexOf(" ",f+1),m=d.indexOf(" ",h+1),y=d.indexOf(" ",m+1);if(y===-1)return;const p=Zt(parseFloat(d.substring(f+1,h)),n);a===""&&(o=p);const v=d.substring(y+1);if(v.trim()==="~")return;let x=v;x.startsWith("~")&&(x=x.substring(1)),l?(c(),i=x.trimEnd()):i+=x.trimEnd(),l=v.endsWith(" ")}}}),c(),a.trim().length>0&&r.push({text:a.trim(),timestamp:o}),r},gd=(e,t)=>{const n=t??na(e),r=[];let a=[],o="",i=0,l=!0,c=null,d="";function f(){c&&d.trim()!==""&&(c.text=d.trim(),a.push({...c}),o.length>0&&(o+=" "),o+=c.text),c=null,d=""}return e.forEach(h=>{if(!(h.startsWith("#")||h.startsWith("E"))){if(h.startsWith("-"))f(),o.trim().length>0&&(r.push({text:o.trim(),timestamp:i,words:a}),o="",a=[]),l=!0;else if(h.startsWith(":")||h.startsWith("*")){const m=h.startsWith("*"),y=h.indexOf(" "),p=h.indexOf(" ",y+1),v=h.indexOf(" ",p+1),x=h.indexOf(" ",v+1);if(x===-1)return;const b=Zt(parseFloat(h.substring(y+1,p)),n),S=Zt(parseFloat(h.substring(p+1,v)),n),g=b+S;o===""&&(i=b);const k=h.substring(x+1);if(k.trim()==="~"){c&&(c.endTime=g);return}let M=k;M.startsWith("~")&&(M=M.substring(1)),l?(f(),d=M.trimEnd(),c={text:"",startTime:b,endTime:g,isGolden:m}):c?(d+=M.trimEnd(),c.endTime=g,m&&(c.isGolden=!0)):(d=M.trimEnd(),c={text:"",startTime:b,endTime:g,isGolden:m}),l=k.endsWith(" ")}}}),f(),o.trim().length>0&&r.push({text:o.trim(),timestamp:i,words:a}),r},lo=(e,t)=>{const n=t??na(e),r=[];let a=[],o=0;function i(){a.length>0&&(r.push({timestamp:o,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)&&(o=Zt(d,n))}}else if(l.startsWith(":")||l.startsWith("*")){const c=l.startsWith("*"),d=l.indexOf(" "),f=l.indexOf(" ",d+1),h=l.indexOf(" ",f+1),m=l.indexOf(" ",h+1);if(m===-1)return;const y=parseFloat(l.substring(d+1,f)),p=parseFloat(l.substring(f+1,h)),v=Zt(y,n),x=v+Zt(p,n);a.length===0&&(o=v);const b=l.substring(m+1);if(b.trim()==="~"){a.length>0&&(a[a.length-1].endTime=x);return}let S=b;S.startsWith("~")&&(S=S.substring(1));const g=b.endsWith(" "),k=g?S.slice(0,-1):S;a.push({text:k,startTime:v,endTime:x,isGolden:c,hasTrailingSpace:g})}}}),i(),r},bd=(e,t,n=3)=>{const r=[];let a=-1;for(let o=0;o<e.length;o++){const i=e[o].timestamp,l=e[o+1]?e[o+1].timestamp:i+5;if(t>=i&&t<l){a=o;break}}if(a>=0){const o=Math.max(0,a-(n-1));for(let i=o;i<=a;i++)r.push(e[i].text)}return r},vd=(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},Ga="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",Wa="var(--karaoke-gold-glow-first, 0 0 12px #FFD700)",xd="var(--karaoke-active-glow, 0 0 10px rgba(0,229,255,0.6), 0 0 4px rgba(255,230,0,0.4))",wd="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",Sd=({song:e,currentTime:t})=>{const n=u.useMemo(()=>!e||!e.notes.length?[]:lo(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 o=a>=0?n[a]:null,i=a>=0&&a+1<n.length?n[a+1]:null;return s.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:o?s.jsxs(s.Fragment,{children:[s.jsx("p",{style:{color:"var(--karaoke-primary-text, #fff)",margin:"5px 0",lineHeight:1.4,textShadow:xd,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:o.syllables.map((l,c)=>{let d=0;r>=l.endTime?d=1:r>l.startTime&&(d=(r-l.startTime)/(l.endTime-l.startTime));const f=Math.round(d*100),h=l.text+(l.hasTrailingSpace?" ":""),m=d>0&&d<1,y=l.isGolden;return d<=0?s.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",transition:"color 0.15s ease"},children:h},c):d>=1?s.jsx("span",{style:{background:y?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Ga,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:y?`drop-shadow(${Wa})`:"none",transition:"filter 0.2s ease"},children:h},c):s.jsxs("span",{style:{position:"relative",display:"inline",filter:m?y?`drop-shadow(${Wa})`:`drop-shadow(${wd})`:"none",transition:"filter 0.15s ease"},children:[s.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",visibility:"visible"},children:h}),s.jsx("span",{style:{position:"absolute",left:0,top:0,background:y?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Ga,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",clipPath:`inset(0 ${100-f}% 0 0)`,pointerEvents:"none"},children:h})]},c)})}),i&&s.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)=>s.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?s.jsx("p",{style:{color:"var(--karaoke-waiting-text, #999)"},children:"🎵"}):s.jsx("p",{style:{color:"var(--karaoke-waiting-text, #999)"},children:"🎤 Waiting for lyrics..."})})},co=u.memo(Sd),kr={},Cd=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("index.cjs",document.baseURI).href}<"u"&&(kr==null?void 0:kr.VITE_DEBUG_KARAOKE)==="true";function Dr(e,t,...n){(Cd||typeof window<"u"&&window.DEBUG_KARAOKE)&&console.log(`%c[KARAOKE-DEBUG]%c [${e}] ${t}`,"background:var(--nice-accent-dark, #6c3483);color:var(--nice-bg, #FFF);padding: var(--nice-space-px, 1px) var(--nice-space-1, 4px);border-radius:var(--nice-radius-sm, 3px);font-weight:bold","color:var(--nice-accent-dark, #6c3483);font-weight:bold",...n)}const uo=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},Ua=(e,t)=>t&&t>0?e*15/t:e/10,ra=(e,t)=>{const n=t??uo(e),r=[];let a=[];return e.forEach(o=>{const i=o.split(" ");if(!(i.length<4))if(o.startsWith("-"))a.length>0&&(r.push(a),a=[]);else{const l=(i[0]||"").charAt(0),c=l==="*"||l==="G";a.push({startTime:Ua(parseFloat(i[1]),n),duration:Ua(parseFloat(i[2]),n),pitch:parseInt(i[3],10),isGold:c})}}),a.length>0&&r.push(a),r},fo=(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},kd=nt.scoped("karaokeScoringConfig"),aa={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}},Md="karaoke.scoringPresets";function jd(){try{const e=localStorage.getItem(Md);return e?JSON.parse(e):null}catch(e){return kd.warn("Failed to parse scoring presets overrides",e),null}}function ho(e){const t={...aa},n=jd();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=ho();const Rd=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=ho(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},po=(e="normal")=>exports.ScoringPresets[e]||aa.normal;function Fr(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():"",o=getComputedStyle(document.documentElement).getPropertyValue(r).trim();return o||a||e}return e}function Td(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 $d=3,W=$d;function Et(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} ${W}V${e-W}A${t-W} ${t-W} 0 0 1 ${W} ${t}A${t-W} ${t-W} 0 0 1 ${t} ${W}Z`}}function Xt(e){return{w:W+1,out:`M0 0H${W+1}V${e}H0Z`,inn:`M${W} ${W}H${W+1}V${e-W}H${W}Z`}}function sa(e){const t=Math.min(14,e*.22)|0,n=t+2,r=Math.max(t-W,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${W+r} ${W}H${n}V${e-W}H${W+r}Q${W} ${e-W} ${W} ${e-W-r}V${W+r}Q${W} ${W} ${W+r} ${W}Z`}}function tr(e){const t=e*.3|0,n=t+2,r=Math.max(t-W,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e-t}V${t}Z`,inn:`M${W+r} ${W}H${n}V${e-W}H${W+r}L${W} ${e-W-r}V${W+r}Z`}}function Rt(e){const t=e*.42|0,n=t+2,r=Math.max(t-(W*1.4|0),2);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e/2}Z`,inn:`M${W+r} ${W}H${n}V${e-W}H${W+r}L${W} ${e/2}Z`}}function nr(e){const t=e*.3|0,n=t+4,r=Math.max(t-W,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${W+r} ${W}H${n}V${e-W}H${W+(r*.6|0)}L${W} ${e-W-r}V${W+r}Q${W} ${W} ${W+r} ${W}Z`}}function oa(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${W+(t*1.2|0)} ${W}H${n}V${e-W}H${W+(t*1.2|0)}C${W+(t*2.2|0)} ${e*.37|0} ${W+(t*2.2|0)} ${e*.63|0} ${W+(t*1.2|0)} ${e-W}Z`}}function ia(e){const t=e*.32|0,n=t+3,r=Math.max(t-W,1);return{w:n,out:`M0 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}Z`,inn:`M${W} ${W}H${n}V${e-W}H${W+r}Q${W} ${e-W} ${W} ${e-W-r}Z`}}function rr(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${W+(t*1.8|0)} ${W}H${n}V${e-W}H${W+(t*1.8|0)}C${W+(t*.4|0)} ${e*.78|0} ${W+(t*2.8|0)} ${e*.55|0} ${W+(t*.4|0)} ${e*.37|0}S${W+(t*.9|0)} ${W} ${W+(t*1.8|0)} ${W}Z`}}function la(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${W+(t*2.5|0)} ${W}H${n}V${e-W}H${W+(t*2.5|0)}L${W+(t*.7|0)} ${e-W-(t*1.6|0)}L${W+(t*1.7|0)} ${e*.64|0}L${W} ${e/2|0}L${W+(t*1.7|0)} ${e*.36|0}L${W+(t*.7|0)} ${W+(t*1.6|0)}Z`}}function Hn(e){const t=e*.42|0,n=t+2;return{w:n,out:`M${t} 0H${n}V${e}H0Z`,inn:`M${W+t-(W*1.3|0)} ${W}H${n}V${e-W}H${W+1}Z`}}function Or(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}V${e}H${t}Z`,inn:`M${W} ${W}H${n}V${e-W}H${W+t-(W*1.3|0)+1}Z`}}function Mt(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 ${W}A${t-W} ${t-W} 0 0 1 ${t-W} ${t}A${t-W} ${t-W} 0 0 1 0 ${e-W}Z`}}function Qt(e){return{w:W+1,out:`M0 0H${W+1}V${e}H0Z`,inn:`M0 ${W}H1V${e-W}H0Z`}}function mo(e){const t=Math.min(14,e*.22)|0,n=t+2,r=Math.max(t-W,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 ${W}H${n-W-r}Q${n-W} ${W} ${n-W} ${W+r}V${e-W-r}Q${n-W} ${e-W} ${n-W-r} ${e-W}H0Z`}}function Jt(e){const t=e*.3|0,n=t+2,r=Math.max(t-W,1);return{w:n,out:`M0 0H${n-t}L${n} ${t}V${e-t}L${n-t} ${e}H0Z`,inn:`M0 ${W}H${n-W-r}L${n-W} ${W+r}V${e-W-r}L${n-W-r} ${e-W}H0Z`}}function bt(e){const t=e*.42|0,n=t+2,r=Math.max(t-(W*1.4|0),2);return{w:n,out:`M0 0H${n-t}L${n} ${e/2}L${n-t} ${e}H0Z`,inn:`M0 ${W}H${n-W-r}L${n-W} ${e/2}L${n-W-r} ${e-W}H0Z`}}function yo(e){const t=e*.3|0,n=t+4,r=Math.max(t-W,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 ${W}H${n-W-r}Q${n-W} ${W} ${n-W} ${W+r}V${e-W-r}L${n-W-(r*.6|0)} ${e-W}H0Z`}}function go(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 ${W}H${n-W-(t*1.2|0)}C${n-W-(t*2.2|0)} ${e*.37|0} ${n-W-(t*2.2|0)} ${e*.63|0} ${n-W-(t*1.2|0)} ${e-W}H0Z`}}function bo(e){const t=e*.32|0,n=t+3,r=Math.max(t-W,1);return{w:n,out:`M0 0H${n}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${W}H${n-W}V${e-W-r}Q${n-W} ${e-W} ${n-W-r} ${e-W}H0Z`}}function ca(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 ${W}H${n-W-(t*1.8|0)}C${n-W-(t*.9|0)} ${W} ${n-W+(t*.1|0)} ${e*.22|0} ${n-W-(t*.4|0)} ${e*.37|0}S${n-W-(t*.4|0)} ${e*.78|0} ${n-W-(t*1.8|0)} ${e-W}H0Z`}}function ar(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 ${W}H${n-W-(t*2.5|0)}L${n-W-(t*.7|0)} ${W+(t*1.6|0)}L${n-W-(t*1.7|0)} ${e*.36|0}L${n-W} ${e/2|0}L${n-W-(t*1.7|0)} ${e*.64|0}L${n-W-(t*.7|0)} ${e-W-(t*1.6|0)}L${n-W-(t*2.5|0)} ${e-W}H0Z`}}function _r(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}L${n-t} ${e}H0Z`,inn:`M0 ${W}H${n-W}L${n-W-t+(W*1.3|0)} ${e-W}H0Z`}}function Kn(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n-t}L${n} ${e}H0Z`,inn:`M0 ${W}H${n-W-t+(W*1.3|0)}L${n-W} ${e-W}H0Z`}}const da=[{name:"Pill",L:Et,R:Mt},{name:"Sharp",L:Xt,R:Qt},{name:"Soft",L:sa,R:mo},{name:"Chamfer",L:tr,R:Jt},{name:"Arrow",L:Rt,R:bt},{name:"Shield",L:nr,R:yo},{name:"Bracket",L:oa,R:go},{name:"Tab",L:ia,R:bo},{name:"Wave",L:rr,R:ca},{name:"Ornate",L:la,R:ar}],vo=[{name:"Pill→Arrow",L:Et,R:bt},{name:"Arrow→Pill",L:Rt,R:Mt},{name:"Pill→Sharp",L:Et,R:Qt},{name:"Sharp→Pill",L:Xt,R:Mt},{name:"Pill→Chamfer",L:Et,R:Jt},{name:"Chamfer→Pill",L:tr,R:Mt},{name:"Arrow→Sharp",L:Rt,R:Qt},{name:"Sharp→Arrow",L:Xt,R:bt},{name:"Arrow→Chamfer",L:Rt,R:Jt},{name:"Chamfer→Arrow",L:tr,R:bt},{name:"Soft→Arrow",L:sa,R:bt},{name:"Shield→Chamfer",L:nr,R:Jt},{name:"Pill→Wave",L:Et,R:ca},{name:"Wave→Arrow",L:rr,R:bt},{name:"Tab→Pill",L:ia,R:Mt},{name:"Ornate→Sharp",L:la,R:Qt},{name:"Sharp→Ornate",L:Xt,R:ar},{name:"Bracket→Arrow",L:oa,R:bt},{name:"Shield→Pill",L:nr,R:Mt},{name:"Wave→Ornate",L:rr,R:ar}],xo=[{name:"Skew ╲",L:Hn,R:_r},{name:"Skew ╱",L:Or,R:Kn},{name:"◇ Romb",L:Rt,R:bt},{name:"╲→Pill",L:Hn,R:Mt},{name:"Pill→╲",L:Et,R:_r},{name:"╱→Sharp",L:Or,R:Qt},{name:"Sharp→╱",L:Xt,R:Kn},{name:"╲→Arrow",L:Hn,R:bt},{name:"Arrow→╱",L:Rt,R:Kn},{name:"◇→Chamfer",L:Rt,R:Jt}],jn=[...da,...vo,...xo],wo=da[0];function hn(e){return jn.find(t=>t.name===e)||wo}const sr=[{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 pn(e){return sr.find(t=>t.name===e)||null}const Lt={color:null,capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,glass:0,textureUrl:null,textureScale:1},ur={...Lt,glass:85},fr={...Lt,patternName:"Stars"},hr={...Lt,patternName:"Stars"},pr={fontFamily:null,fontSize:18,fontColor:null,outlineColor:null,outlineWidth:0,shadow:null},So={filledBar:{...Lt},emptyBar:{...ur},goldFilledBar:{...hr},goldEmptyBar:{...fr},font:{...pr},disableGoldNotes:!1},en={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},Va="nice2dev-player-bar-style",qa="nice2dev-player-karaoke-settings";function tn(e){return e!=null?`${qa}-${e}`:qa}function Tn(e){return e!=null?`${Va}-${e}`:Va}function Ha(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 Ka(e){const t=So,n=(a,o)=>!o||typeof o!="object"?{...a}:{...a,...o},r=(a,o)=>!o||typeof o!="object"?{...a}:{...a,...o};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 Co(e){try{const t=localStorage.getItem(tn(e));if(t){const r=JSON.parse(t);return Ka(r)}const n=localStorage.getItem(Tn(e));if(n){const r=JSON.parse(n),a=Ha({...en,...r});return localStorage.setItem(tn(e),JSON.stringify(a)),a}if(e!=null){const r=localStorage.getItem(tn());if(r)return Ka(JSON.parse(r));const a=localStorage.getItem(Tn());if(a)return Ha({...en,...JSON.parse(a)})}}catch{}return{filledBar:{...Lt},emptyBar:{...ur},goldFilledBar:{...hr},goldEmptyBar:{...fr},font:{...pr}}}function Pd(e,t){const n=JSON.stringify(e);localStorage.setItem(tn(t),n)}let Ya=!1;async function Ed(e){if(Ya||(Ya=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(tn())||localStorage.setItem(tn(),t)}catch{}}function Ad(e){const t=new Map;for(const n of e)t.set(n,Co(n));return t}function ko(e){try{const t=localStorage.getItem(Tn(e));if(t)return{...en,...JSON.parse(t)};if(e!=null){const n=localStorage.getItem(Tn());if(n)return{...en,...JSON.parse(n)}}}catch{}return{...en}}function Nd(e,t){localStorage.setItem(Tn(t),JSON.stringify(e))}function Id(e){const t=new Map;for(const n of e)t.set(n,ko(n));return t}const Ld={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Dd=/[&<>"']/g;function Fd(e){return e.replace(Dd,t=>Ld[t])}function Od(e){const t=e.trim().toLowerCase();return!!(t.startsWith("http://")||t.startsWith("https://")||t.startsWith("blob:")||t.startsWith("data:image/")||t.startsWith("/")||t.startsWith("./")||t.startsWith("../"))}const _d=3,We=_d;function or(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),o=Math.min(t,n,r);let i=0,l=0;const c=(a+o)/2;if(a!==o){const d=a-o;switch(l=c>.5?d/(2-a-o):d/(a+o),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 ir(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 et(e,t){return e.replace(/([MLHVCSQTAZ])/gi,`
1
+ "use strict";var Bc=Object.create;var Ss=Object.defineProperty;var Gc=Object.getOwnPropertyDescriptor;var Wc=Object.getOwnPropertyNames;var Uc=Object.getPrototypeOf,qc=Object.prototype.hasOwnProperty;var Vc=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Wc(t))!qc.call(e,s)&&s!==n&&Ss(e,s,{get:()=>t[s],enumerable:!(a=Gc(t,s))||a.enumerable});return e};var Vn=(e,t,n)=>(n=e!=null?Bc(Uc(e)):{},Vc(t||!e||!e.__esModule?Ss(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),d=require("react"),we=require("@nice2dev/ui"),se=require("@nice2dev/icons"),rt=require("react-bootstrap"),ra=require("pitchy"),Ma=require("react-youtube"),Ne=require("recharts"),aa=require("@nice2dev/ui-core"),Hc=require("react-window");var xt=typeof document<"u"?document.currentScript:null;const Kc=(e,t)=>t??e,Mi=d.createContext(Kc),Yc=({t:e,children:t})=>r.jsx(Mi.Provider,{value:e,children:t});function Te(){return{t:d.useContext(Mi)}}class Zc extends d.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){var s,i;const a=this.props.componentName?`[${this.props.componentName}]`:"[AudioErrorBoundary]";console.error(`${a} Caught error:`,t,n),(i=(s=this.props).onError)==null||i.call(s,t,n)}render(){return this.state.hasError&&this.state.error?typeof this.props.fallback=="function"?this.props.fallback(this.state.error,this.reset):this.props.fallback?this.props.fallback:r.jsx("div",{className:"nice-audio-error-boundary",role:"alert",children:r.jsxs("div",{className:"nice-audio-error-boundary__content",children:[r.jsx("h3",{className:"nice-audio-error-boundary__title",children:this.props.componentName?`${this.props.componentName} encountered an error`:"Something went wrong"}),r.jsx("p",{className:"nice-audio-error-boundary__message",children:this.state.error.message}),r.jsx("button",{className:"nice-audio-error-boundary__retry",onClick:this.reset,children:"Try Again"})]})}):this.props.children}}const Ur={},sa={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function Xc(){const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:xt&&xt.tagName.toUpperCase()==="SCRIPT"&&xt.src||new URL("index.cjs",document.baseURI).href}<"u"?Ur==null?void 0:Ur.VITE_LOG_LEVEL:void 0;return e&&e in sa?e:"WARN"}const Qc=Xc();function Hn(e){return sa[e]>=sa[Qc]}function Kn(e){return`[${e}]`}const it={debug(e,t,...n){Hn("DEBUG")&&console.debug(Kn(e),t,...n)},info(e,t,...n){Hn("INFO")&&console.info(Kn(e),t,...n)},warn(e,t,...n){Hn("WARN")&&console.warn(Kn(e),t,...n)},error(e,t,...n){Hn("ERROR")&&console.error(Kn(e),t,...n)},scoped(e){return{debug:(t,...n)=>it.debug(e,t,...n),info:(t,...n)=>it.info(e,t,...n),warn:(t,...n)=>it.warn(e,t,...n),error:(t,...n)=>it.error(e,t,...n)}}},ks=it.scoped("Waveform"),Jc=["audio/","video/"],Ra=({audioBlob:e,currentTime:t,duration:n,width:a=600,height:s=200,zoom:i=1,onSeek:o,onRegionSelect:l,markers:c=[],regions:u=[],displayMode:h="waveform",multiChannel:p=!1,waveColor:f="#007bff",progressColor:y="rgba(255,0,0,0.8)",backgroundColor:m="transparent",showRuler:g=!1,showChannelLabels:b=!0,showPeakMeter:x=!1,className:k})=>{const v=d.useRef(null),w=d.useRef(null),M=d.useRef(null),[S,R]=d.useState(0),[T,j]=d.useState(!1),[O,$]=d.useState(null),[E,D]=d.useState(null),[L,W]=d.useState(0),Z=Math.max(a,a*i),A=g?24:0;d.useEffect(()=>{if(!e||e.size===0){M.current=null;return}e.type&&!Jc.some(q=>e.type.startsWith(q))&&ks.warn("Unexpected blob MIME type:",e.type);let V=!1;return(async()=>{let q=null;try{const C=await e.arrayBuffer();if(C.byteLength===0||V)return;q=new AudioContext;const F=await q.decodeAudioData(C);V||(M.current=F)}catch(C){ks.error("Failed to decode audio:",C)}finally{q==null||q.close().catch(()=>{})}})(),()=>{V=!0}},[e]),d.useEffect(()=>{if(i>1&&n>0){const V=t/n*Z;(V<S||V>S+a)&&R(Math.max(0,V-a/2))}},[t,n,i,a,Z,S]),d.useEffect(()=>{const V=v.current,q=M.current;if(!V||!n||n===1/0)return;const C=V.getContext("2d");if(!C)return;const F=Z,I=s;if(V.width=F,V.height=I+A,C.clearRect(0,0,F,I+A),m!=="transparent"&&(C.fillStyle=m,C.fillRect(0,0,F,I+A)),g){C.fillStyle="rgba(128,128,128,0.15)",C.fillRect(0,0,F,A),C.fillStyle="var(--nice-text-secondary, #888)",C.font="10px monospace",C.textAlign="center";const P=Math.max(1,Math.floor(n/(Z/80)));for(let N=0;N<=n;N+=P){const z=N/n*F;C.fillText(rd(N),z,A-4),C.fillStyle="rgba(128,128,128,0.3)",C.fillRect(z,A,1,I),C.fillStyle="var(--nice-text-secondary, #888)"}}for(const P of u){const N=P.start/n*F,z=P.end/n*F;C.fillStyle=P.color??"var(--nice-accent-tint-15, rgba(99, 102, 241, 0.15))",C.fillRect(N,A,z-N,I),P.label&&(C.fillStyle=P.color??"var(--nice-info, #6366f1)",C.font="10px sans-serif",C.textAlign="left",C.fillText(P.label,N+2,A+12))}if(O!==null&&E!==null){const P=Math.min(O,E),N=Math.max(O,E);C.fillStyle="rgba(255,200,0,0.2)",C.fillRect(P,A,N-P,I)}if(q){const P=p?q.numberOfChannels:1,N=I/P;let z=0;for(let B=0;B<P;B++){const G=q.getChannelData(B),Y=A+B*N;if(h==="waveform"?ed(C,G,F,N,Y,f):h==="bars"?td(C,G,F,N,Y,f):h==="spectrogram"&&nd(C,G,F,N,Y,q.sampleRate),x&&n>0){const X=Math.floor(t/n*G.length),ie=Math.floor(q.sampleRate*.05);let le=0;for(let H=Math.max(0,X-ie);H<Math.min(G.length,X+ie);H++)le+=G[H]*G[H];const te=Math.sqrt(le/(ie*2));z=Math.max(z,te)}p&&b&&P>1&&(C.fillStyle="var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))",C.font="bold 11px sans-serif",C.textAlign="left",C.fillText(B===0?"L":B===1?"R":`Ch${B+1}`,4,Y+14))}W(z)}if(n>0){const P=Math.max(0,Math.min(t/n*F,F));C.beginPath(),C.strokeStyle=y,C.lineWidth=2,C.moveTo(P,A),C.lineTo(P,I+A),C.stroke()}for(const P of c){const N=P.time/n*F;C.beginPath(),C.strokeStyle=P.color??"var(--nice-warning, #f59e0b)",C.lineWidth=2,C.setLineDash([4,4]),C.moveTo(N,A),C.lineTo(N,I+A),C.stroke(),C.setLineDash([]),P.label&&(C.fillStyle=P.color??"var(--nice-warning, #f59e0b)",C.font="bold 10px sans-serif",C.textAlign="center",C.fillText(P.label,N,A+I-4))}},[e,M.current,t,n,Z,s,i,h,p,f,y,m,g,c,u,O,E,x,b,A]);const _=d.useCallback(V=>{var F;if(!n)return;const q=(F=v.current)==null?void 0:F.getBoundingClientRect();if(!q)return;const C=V.clientX-q.left+S;j(!0),$(C),D(C)},[n,S]),U=d.useCallback(V=>{if(!T||!v.current)return;const q=v.current.getBoundingClientRect(),C=V.clientX-q.left+S;D(C)},[T,S]),ne=d.useCallback(()=>{if(!T||O===null||E===null||!n){j(!1),$(null),D(null);return}const V=Math.min(O,E),q=Math.max(O,E),C=(q-V)/Z*n;if(j(!1),$(null),D(null),C<.2){const F=V/Z*n;o==null||o(F)}else{const F=V/Z*n,I=q/Z*n;l==null||l({start:F,end:I})}},[T,O,E,n,Z,o,l]);return r.jsxs("div",{ref:w,className:`nice-waveform${k?` ${k}`:""}`,style:{position:"relative",width:a,overflow:i>1?"auto":"hidden",cursor:o?"crosshair":"default"},onScroll:V=>R(V.target.scrollLeft),children:[r.jsx("canvas",{ref:v,width:Z,height:s+A,style:{display:"block"},role:"img","aria-label":"Waveform canvas",onMouseDown:_,onMouseMove:U,onMouseUp:ne,onMouseLeave:ne}),x&&r.jsx("div",{style:{position:"absolute",right:4,top:A+4,bottom:4,width:12,background:"var(--nice-overlay-30, rgba(0, 0, 0, 0.3))",borderRadius:4,overflow:"hidden"},children:r.jsx("div",{style:{position:"absolute",bottom:0,width:"100%",height:`${Math.min(100,L*300)}%`,background:L>.8?"var(--nice-danger, #ef4444)":L>.5?"var(--nice-warning, #f59e0b)":"var(--nice-success, #22c55e)",borderRadius:4,transition:"height 50ms"}})})]})};function ed(e,t,n,a,s,i){const o=Math.floor(t.length/n),l=s+a/2;e.beginPath(),e.strokeStyle=i,e.lineWidth=1;for(let c=0;c<n;c++){const u=c*o,h=t.subarray(u,u+o);let p=0,f=0;for(let g=0;g<h.length;g++)h[g]<p&&(p=h[g]),h[g]>f&&(f=h[g]);const y=l-f*(a/2),m=l-p*(a/2);e.moveTo(c,y),e.lineTo(c,m)}e.stroke()}function td(e,t,n,a,s,i){const o=Math.max(2,Math.floor(n/128)),l=Math.floor(n/o),c=Math.floor(t.length/l);for(let u=0;u<l;u++){const h=u*c,p=t.subarray(h,h+c);let f=0;for(let b=0;b<p.length;b++)f+=Math.abs(p[b]);const m=f/p.length*a*.9,g=u*o;e.fillStyle=i,e.fillRect(g+1,s+a-m,o-2,m)}}function nd(e,t,n,a,s,i){const l=Math.min(n,512),c=Math.floor(t.length/l),u=n/l;for(let h=0;h<l;h++){const p=h*c,f=new Float32Array(256/2);for(let m=0;m<256/2;m++){let g=0,b=0;for(let x=0;x<256&&p+x<t.length;x++){const k=2*Math.PI*m*x/256;g+=t[p+x]*Math.cos(k),b-=t[p+x]*Math.sin(k)}f[m]=Math.sqrt(g*g+b*b)/256}const y=a/f.length;for(let m=0;m<f.length;m++){const g=Math.min(1,f[m]*10),b=Math.floor(g*255),x=Math.floor(g*100),k=Math.floor((1-g)*200);e.fillStyle=`rgb(${b},${x},${k})`,e.fillRect(h*u,s+a-(m+1)*y,u+1,y+1)}}}function rd(e){const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const ws=88,Yt=16,Yn=16,ad=320;function sd(e){return e-21}function id(e){return e+21}const Na=({notes:e,onAddNote:t,onRemoveNote:n,selectedNoteId:a,setSelectedNoteId:s,duration:i=4,zoom:o=1})=>{const l=d.useRef(null),c=ad*o,u=ws*Yt,h=d.useRef(null);d.useEffect(()=>{},[e,o,i]);const p=y=>{const m=l.current;if(!m)return;const g=m.getBoundingClientRect(),b=y.clientX-g.left,x=y.clientY-g.top,k=Math.floor(x/Yt),v=id(k),w=b/c*i;h.current={drawing:!0,startX:b,key:k},t(v,w,i/Yn)},f=(y,m)=>{m.stopPropagation(),s==null||s(y)};return r.jsxs("svg",{ref:l,width:c,height:u,style:{background:"var(--bg-secondary, #f8fafc)",border:"1px solid var(--border-color, #cbd5e1)",userSelect:"none",display:"block"},onMouseDown:p,children:[[...Array(ws)].map((y,m)=>r.jsx("rect",{x:0,y:m*Yt,width:c,height:Yt,fill:m%2===0?"var(--bg-secondary, #f8fafc)":"var(--bg-tertiary, #f1f5f9)"},m)),[...Array(Yn+1)].map((y,m)=>r.jsx("line",{x1:m*c/Yn,y1:0,x2:m*c/Yn,y2:u,stroke:"var(--border-muted, #ccc)",strokeWidth:m%4===0?2:1},m)),e.map(y=>{const m=sd(y.pitch),g=y.start/i*c,b=y.duration/i*c;return r.jsx("rect",{x:g,y:m*Yt,width:Math.max(6,b),height:Yt-2,fill:y.id===a?"var(--color-primary, #6366f1)":"color-mix(in srgb, var(--color-primary, #6366f1) 55%, var(--bg-primary, #ffffff))",stroke:"var(--color-primary, #6366f1)",strokeWidth:y.id===a?2:1,rx:3,onClick:x=>f(y.id,x),onDoubleClick:()=>n(y.id),style:{cursor:"pointer"}},y.id)})]})},Ri=({ccEvents:e,onAddEvent:t,onUpdateEvent:n,onRemoveEvent:a,ccType:s,duration:i,width:o,height:l=60,curveType:c})=>{const u=d.useRef(null),{t:h}=Te(),[p,f]=d.useState(null),[y,m]=d.useState(null),[g,b]=d.useState(null),x=[...e].sort((D,L)=>D.time-L.time),k=D=>[D.time/i*o,(127-D.value)/127*l],v=(D,L,W)=>Math.max(L,Math.min(W,D)),w=D=>{var U;if(D.target instanceof SVGCircleElement)return;const L=(U=u.current)==null?void 0:U.getBoundingClientRect();if(!L)return;const W=D.clientX-L.left,Z=D.clientY-L.top,A=v(W/o*i,0,i),_=v(127-Math.round(Z/l*127),0,127);t(s,_,A)},M=(D,L)=>{var _;L.stopPropagation(),f(D.id),b(D.id);const[W,Z]=k(D),A=(_=u.current)==null?void 0:_.getBoundingClientRect();A&&m({dx:L.clientX-A.left-W,dy:L.clientY-A.top-Z})},S=D=>{var U;if(p==null||!y)return;const L=(U=u.current)==null?void 0:U.getBoundingClientRect();if(!L)return;const W=v(D.clientX-L.left-y.dx,0,o),Z=v(D.clientY-L.top-y.dy,0,l),A=v(W/o*i,0,i),_=v(127-Math.round(Z/l*127),0,127);n(p,_,A)},R=()=>{f(null),m(null)};d.useEffect(()=>{const D=L=>{(L.key==="Delete"||L.key==="Backspace")&&g!=null&&(a(g),b(null))};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[g,a]),d.useEffect(()=>{if(p!=null)return window.addEventListener("mousemove",S),window.addEventListener("mouseup",R),()=>{window.removeEventListener("mousemove",S),window.removeEventListener("mouseup",R)}});const[T,j]=d.useState(null),O=(D,L)=>{const[W,Z]=k(D);j({x:W+10,y:Z-10,text:`Val: ${D.value}, Time: ${D.time.toFixed(2)}s`})},$=()=>j(null),E=D=>{var U;const L=(U=u.current)==null?void 0:U.getBoundingClientRect();if(!L)return;const W=D.clientX-L.left,Z=D.clientY-L.top,A=v(W/o*i,0,i),_=v(127-Math.round(Z/l*127),0,127);t(s,_,A)};return r.jsxs("svg",{ref:u,width:o,height:l,style:{background:"var(--surface-muted, #f3f3f3)",border:"1px solid var(--border, #bbb)",cursor:p?"grabbing":"crosshair",display:"block"},onClick:w,onDoubleClick:E,tabIndex:0,children:[[...Array(9)].map((D,L)=>r.jsx("line",{x1:0,y1:L*l/8,x2:o,y2:L*l/8,stroke:"var(--border-muted, #ddd)",strokeWidth:L===0||L===8?2:1},L)),x.length>1&&r.jsx("polyline",{fill:"none",stroke:"var(--accent, #1976d2)",strokeWidth:2,points:x.map(D=>k(D).join(",")).join(" ")}),x.map(D=>{const[L,W]=k(D);return r.jsxs("g",{children:[r.jsx("circle",{cx:L,cy:W,r:g===D.id?8:6,fill:g===D.id?"var(--accent, #1976d2)":"var(--accent-light, #90caf9)",stroke:"var(--accent, #1976d2)",strokeWidth:g===D.id?3:2,style:{cursor:"pointer"},onMouseDown:Z=>M(D,Z),onContextMenu:Z=>{Z.preventDefault(),a(D.id)},onClick:Z=>{Z.stopPropagation(),b(D.id)},onMouseOver:Z=>O(D),onMouseOut:$}),g===D.id&&r.jsx("foreignObject",{x:L+10,y:W-18,width:90,height:30,style:{pointerEvents:"auto"},children:r.jsxs("div",{style:{fontSize:12,background:"var(--surface-bg, #fff)",border:"1px solid var(--border, #bbb)",borderRadius:4,padding:"2px 6px",display:"inline-block"},children:[r.jsxs("label",{style:{marginRight:4},children:[h("ccLane.curve","Curve"),":"]}),r.jsxs("select",{value:D.handleType||c||"linear",onChange:Z=>{n(D.id,D.value,D.time,Z.target.value)},children:[r.jsx("option",{value:"linear",children:h("ccLane.linear","Linear")}),r.jsx("option",{value:"step",children:h("ccLane.step","Step")}),r.jsx("option",{value:"exp",children:h("ccLane.exponential","Exponential")})]})]})})]},D.id)}),T&&r.jsxs("g",{pointerEvents:"none",children:[r.jsx("rect",{x:T.x,y:T.y-18,width:90,height:20,fill:"var(--surface-bg, #fff)",stroke:"var(--accent, #1976d2)",rx:4}),r.jsx("text",{x:T.x+6,y:T.y-4,fontSize:13,fill:"var(--accent, #1976d2)",children:T.text})]}),r.jsxs("text",{x:6,y:16,fontSize:14,fill:"var(--accent, #1976d2)",children:["CC",s]})]})},od=it.scoped("audioContext");let On=null;function mn(){if(!On)try{On=new(window.AudioContext||window.webkitAudioContext)}catch(e){od.error("Error initializing AudioContext:",e)}return On}async function Bt(){const e=mn();e&&e.state==="suspended"&&await e.resume()}function Ni(){return!!On&&On.state==="running"}function Ti(e){const t=e.bpm/60;switch(e.snapMode){case"bar":return 4/t;case"beat":return 1/t;case"sub-beat":return 1/(t*4);case"second":default:return 1}}function ld(e,t){if(!t.snapEnabled)return e;const n=Ti(t);return Math.round(e/n)*n}function cd(e,t=!1){const n=Math.floor(e/60),a=Math.floor(e%60),s=Math.floor(e%1*1e3);return t?`${n}:${a.toString().padStart(2,"0")}.${s.toString().padStart(3,"0")}`:`${n}:${a.toString().padStart(2,"0")}`}function dd(e,t){const n=t/60,a=e*n,s=Math.floor(a/4),i=Math.floor(a%4);return`${s+1}:${i+1}`}function $i(e,t,n=!0){const a=e.getContext("2d");if(!a)return;const s=30*t.zoom*t.duration,i=Math.max(80,30*t.zoom);e.width=s,e.height=i,a.clearRect(0,0,s,i),a.fillStyle="var(--surface-bg, #f5f5f5)",a.fillRect(0,0,s,i);const o=s/t.duration;let l=1;o<30?l=5:o<60?l=2:o>150&&(l=.5),a.strokeStyle="var(--border-secondary, #ddd)",a.lineWidth=1;for(let c=0;c<=t.duration;c+=l){const u=c/t.duration*s,h=c%1===0;if(a.strokeStyle=h?"var(--border-secondary, #ccc)":"var(--border-muted, #eee)",a.lineWidth=h?1.5:.5,a.beginPath(),a.moveTo(u,0),a.lineTo(u,i),a.stroke(),h&&o>40){a.fillStyle="var(--muted, #666)",a.font="10px monospace",a.textAlign="center";const p=n?dd(c,t.bpm):cd(c);a.fillText(p,u,12)}}if(t.snapEnabled){const c=Ti(t);a.strokeStyle="var(--accent-primary, #ffeb3b)",a.lineWidth=.5;for(let u=0;u<=t.duration;u+=c){const h=u/t.duration*s;a.beginPath(),a.moveTo(h,i-5),a.lineTo(h,i),a.stroke()}}}function ud(e,t,n,a){const s=e.getContext("2d");if(!s)return;const i=30*t.zoom*t.duration,o=Math.max(80,30*t.zoom),l=n/t.duration*i;$i(e,t),s.strokeStyle=a?"var(--danger, #f44336)":"var(--accent-primary, #2196f3)",s.lineWidth=2,s.beginPath(),s.moveTo(l,0),s.lineTo(l,o),s.stroke(),s.fillStyle=a?"var(--danger, #f44336)":"var(--accent-primary, #2196f3)",s.beginPath(),s.moveTo(l,0),s.lineTo(l-5,-8),s.lineTo(l+5,-8),s.closePath(),s.fill()}function hd(e,t,n,a="var(--success, #4caf50)"){const s=e.getContext("2d");if(!s||!(n!=null&&n.length))return;const i=30*t.zoom*t.duration,l=e.height/2,c=Math.max(10,l-6);s.save(),s.strokeStyle=a,s.lineWidth=1,s.beginPath(),n.forEach((u,h)=>{const p=h/(n.length-1)*i,f=l-u*c;h===0?s.moveTo(p,f):s.lineTo(p,f)}),s.stroke(),s.restore()}const Ta=({zoom:e=1,duration:t=4,isPlaying:n,isRecording:a,currentTime:s,bpm:i=120,snapEnabled:o=!1,snapMode:l="beat",waveform:c,waveformColor:u,onCurrentTimeChange:h,onZoomChange:p})=>{const f=d.useRef(null),y=d.useRef(null),m=d.useRef(null),[g,b]=d.useState(!1),x={zoom:e,duration:t,bpm:i,snapEnabled:o,snapMode:l};d.useEffect(()=>{Bt(),k()},[e,t,s,a,i,o,l,c]),d.useEffect(()=>{n?(m.current=performance.now(),v()):y.current&&cancelAnimationFrame(y.current)},[n]);const k=()=>{f.current&&($i(f.current,x),c!=null&&c.length&&hd(f.current,x,c,u),ud(f.current,x,s,a))},v=()=>{if(!n)return;const j=O=>{if(m.current!==null){const $=(O-m.current)/1e3;m.current=O;const E=Math.min(s+$,t);h(E)}s<t&&(y.current=requestAnimationFrame(j))};y.current=requestAnimationFrame(j)},w=j=>{b(!0),R(j)},M=j=>{g&&R(j)},S=()=>{b(!1)},R=j=>{if(!f.current)return;const O=f.current.getBoundingClientRect();let E=(j.clientX-O.left)/O.width*t;E=ld(E,x),h(Math.min(Math.max(E,0),t))},T=j=>{if(!p)return;j.preventDefault();const O=j.deltaY>0?-.1:.1,$=Math.max(.5,Math.min(5,e+O));p($)};return r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:r.jsx("canvas",{ref:f,style:{border:"1px solid black",backgroundColor:"white",width:`${30*e*t}px`,height:`${Math.max(80,30*e)}px`,cursor:g?"grabbing":"pointer"},onMouseDown:w,onMouseMove:M,onMouseUp:S,onMouseLeave:S,onWheel:T,role:"img","aria-label":"Audio timeline canvas"})})},Je=["var(--nice-primary, #2196f3)","var(--nice-danger, #e53935)","var(--nice-warning, #ffeb3b)","var(--nice-success, #43a047)","var(--nice-warning, #ff9800)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-warning, #ffc107)","var(--nice-success, #8bc34a)","var(--nice-danger, #f44336)","var(--nice-accent, #3f51b5)","var(--nice-text-secondary, #607d8b)","var(--nice-warning-dark, #795548)","var(--nice-warning, #cddc39)","var(--nice-accent, #673ab7)","var(--nice-success, #009688)"];function pd(e){for(const t of Je)if(!e.includes(t))return t;return Je[Math.floor(Math.random()*Je.length)]}const cr=Je.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function fd(e){for(let t=0;t<Je.length;t++){const n=Je[t],a=cr[t];if(!e.includes(n)&&!e.includes(a))return a}return cr[Math.floor(Math.random()*cr.length)]}const md="_panelNarrow_19isp_3",gd="_panelWide_19isp_9",yd="_smallLabel_19isp_19",bd="_noteText_19isp_29",xd="_buttonRow_19isp_41",vd="_noteTextMargin_19isp_49",Sd="_rangeW100_19isp_63",kd="_zoomValue_19isp_69",wd="_selectW100_19isp_77",jd="_inputW70_19isp_83",Cd="_masterVolGroup_19isp_93",Md="_rangeW140_19isp_99",Rd="_volumeValue_19isp_105",Nd="_selectW140_19isp_115",Td="_freqGroup_19isp_121",$d="_freqValue_19isp_127",Pd="_narrowGroup_19isp_137",Ad="_rangeW120_19isp_143",Ed="_smallValue_19isp_149",Id="_presetDivider_19isp_159",Ld="_presetLabel_19isp_165",Dd="_presetBtn_19isp_175",_d="_deletePresetSelect_19isp_183",Fd="_presetNameInput_19isp_191",zd="_savePresetBtn_19isp_199",Od="_countInAlert_19isp_211",Bd="_inputW80_19isp_219",Gd="_levelLabel_19isp_225",Wd="_levelMeter_19isp_233",Ud="_levelBar_19isp_249",ke={panelNarrow:md,panelWide:gd,smallLabel:yd,noteText:bd,buttonRow:xd,noteTextMargin:vd,rangeW100:Sd,zoomValue:kd,selectW100:wd,inputW70:jd,masterVolGroup:Cd,rangeW140:Md,volumeValue:Rd,selectW140:Nd,freqGroup:Td,freqValue:$d,narrowGroup:Pd,rangeW120:Ad,smallValue:Ed,presetDivider:Id,presetLabel:Ld,presetBtn:Dd,deletePresetSelect:_d,presetNameInput:Fd,savePresetBtn:zd,countInAlert:Od,inputW80:Bd,levelLabel:Gd,levelMeter:Wd,levelBar:Ud},Pi=({autoSaveMode:e,setAutoSaveMode:t,autoSaveInterval:n,setAutoSaveInterval:a})=>{const{t:s}=Te();return r.jsxs("div",{className:`card p-3 mb-3 ${ke.panelNarrow}`,children:[r.jsx("h6",{className:"mb-2",children:s("editorPanels.autoSaveTitle","Project auto-save")}),r.jsxs("div",{className:"mb-2",children:[r.jsxs("label",{className:"form-label",children:[s("editorPanels.autoSaveMode","Auto-save mode"),":"]}),r.jsxs("select",{className:"form-select",value:e,onChange:i=>t(i.target.value),children:[r.jsx("option",{value:"off",children:s("editorPanels.off","Off")}),r.jsx("option",{value:"onChange",children:s("editorPanels.onChange","On every change")}),r.jsx("option",{value:"interval",children:s("editorPanels.interval","At set interval")}),r.jsx("option",{value:"both",children:s("editorPanels.both","Both")})]})]}),(e==="interval"||e==="both")&&r.jsxs("div",{className:"mb-2",children:[r.jsxs("label",{className:"form-label",children:[s("editorPanels.autoSaveFrequency","Auto-save frequency (seconds)"),":"]}),r.jsx("input",{type:"number",className:"form-control",min:5,max:600,value:n,onChange:i=>a(Math.max(5,Math.min(600,Number(i.target.value))))})]}),r.jsxs("div",{className:ke.noteText,children:[r.jsxs("b",{children:[s("editorPanels.noteLabel","Note"),":"]})," ",s("editorPanels.autoSaveNote","Auto-save works locally (localStorage/browser). Manual save (PUT) always overwrites the project on the server.")]})]})},Ai=({undoCount:e,redoCount:t,onUndo:n,onRedo:a})=>{const{t:s}=Te();return r.jsxs("div",{className:`card p-3 mb-3 ${ke.panelNarrow}`,children:[r.jsx("h6",{className:"mb-2",children:s("editorPanels.changeHistory","Project change history")}),r.jsxs("div",{className:ke.buttonRow,children:[r.jsxs("button",{className:"btn btn-secondary",onClick:n,disabled:e===0,title:s("editorPanels.undoTitle","Undo last change (Ctrl+Z)"),children:["↩️ ",s("editorPanels.undo","Undo")]}),r.jsxs("button",{className:"btn btn-secondary",onClick:a,disabled:t===0,title:s("editorPanels.redoTitle","Redo change (Ctrl+Y or Ctrl+Shift+Z)"),children:["↪️ ",s("editorPanels.redo","Redo")]})]}),r.jsx("div",{className:ke.noteTextMargin,children:s("editorPanels.undoRedoNote","Undo/Redo works on the entire project (all editor changes). After each change Redo is cleared.")})]})},$a=({zoom:e,setZoom:t,uiZoom:n,setUiZoom:a,snapEnabled:s,onToggleSnap:i,snapMode:o,onSnapModeChange:l,bpm:c,setBpm:u})=>{const{t:h}=Te();return r.jsx("div",{className:`card p-2 mb-3 ${ke.panelNarrow}`,children:r.jsxs("div",{className:"d-flex align-items-center gap-3",children:[r.jsxs("div",{className:"d-flex align-items-center gap-2",children:[r.jsx("label",{className:`form-label mb-0 ${ke.smallLabel}`,children:"Zoom:"}),r.jsx("input",{type:"range",min:"0.5",max:"5",step:"0.1",value:e,onChange:p=>t(Number(p.target.value)),className:ke.rangeW100}),r.jsxs("span",{className:ke.zoomValue,children:[e.toFixed(1),"x"]})]}),r.jsxs("div",{className:"d-flex align-items-center gap-2",children:[r.jsx("label",{className:`form-label mb-0 ${ke.smallLabel}`,children:"Zoom UI:"}),r.jsx("input",{type:"range",min:"1",max:"4",step:"0.1",value:n,onChange:p=>a(Number(p.target.value)),className:ke.rangeW100}),r.jsxs("span",{className:ke.zoomValue,children:[n.toFixed(1),"x"]})]}),r.jsxs("div",{className:"d-flex align-items-center gap-2",children:[r.jsx("input",{id:"snap-toggle",type:"checkbox",className:"form-check-input",checked:s,onChange:i}),r.jsx("label",{htmlFor:"snap-toggle",className:`form-check-label mb-0 ${ke.smallLabel}`,children:"Snap"})]}),s&&r.jsxs("select",{className:`form-select form-select-sm ${ke.selectW100}`,value:o,onChange:p=>l(p.target.value),children:[r.jsx("option",{value:"bar",children:h("editorPanels.snapBar","Bar")}),r.jsx("option",{value:"beat",children:h("editorPanels.snapBeat","Beat")}),r.jsx("option",{value:"sub-beat",children:h("editorPanels.snap16","1/16")}),r.jsx("option",{value:"second",children:h("editorPanels.snapSecond","Second")})]}),r.jsxs("div",{className:"d-flex align-items-center gap-2",children:[r.jsx("label",{className:`form-label mb-0 ${ke.smallLabel}`,children:"BPM:"}),r.jsx("input",{type:"number",className:`form-control form-control-sm ${ke.inputW70}`,value:c,onChange:p=>u(Number(p.target.value)),min:"20",max:"300"})]})]})})},Ei=({masterVolume:e,onMasterVolumeChange:t,filterType:n,filterFreq:a,filterQ:s,filterGain:i,onFilterChange:o,masterEQPresets:l,customPresets:c,onLoadPreset:u,onSavePreset:h,onDeletePreset:p})=>{const{t:f}=Te();return r.jsxs("div",{className:`card p-2 mb-3 ${ke.panelWide}`,children:[r.jsxs("div",{className:"d-flex align-items-center flex-wrap gap-3",children:[r.jsxs("div",{className:`d-flex align-items-center gap-2 ${ke.masterVolGroup}`,children:[r.jsx("label",{className:`form-label mb-0 ${ke.smallLabel}`,children:"Master Vol"}),r.jsx("input",{type:"range",min:"0",max:"1",step:"0.01",value:e,onChange:y=>t(Number(y.target.value)),className:ke.rangeW140}),r.jsxs("span",{className:ke.volumeValue,children:[Math.round(e*100),"%"]})]}),r.jsxs("div",{className:"d-flex align-items-center gap-2",children:[r.jsx("label",{className:`form-label mb-0 ${ke.smallLabel}`,children:"Filter"}),r.jsx("select",{className:`form-select form-select-sm ${ke.selectW140}`,value:n,onChange:y=>o({type:y.target.value}),children:["peaking","lowpass","highpass","lowshelf","highshelf","notch","bandpass"].map(y=>r.jsx("option",{value:y,children:y},y))})]}),r.jsxs("div",{className:`d-flex align-items-center gap-2 ${ke.freqGroup}`,children:[r.jsx("span",{className:ke.smallLabel,children:"Freq"}),r.jsx("input",{type:"range",min:"40",max:"12000",step:"10",value:a,onChange:y=>o({frequency:Number(y.target.value)}),className:ke.rangeW140}),r.jsxs("span",{className:ke.freqValue,children:[Math.round(a)," Hz"]})]}),r.jsxs("div",{className:`d-flex align-items-center gap-2 ${ke.narrowGroup}`,children:[r.jsx("span",{className:ke.smallLabel,children:"Q"}),r.jsx("input",{type:"range",min:"0.1",max:"12",step:"0.1",value:s,onChange:y=>o({q:Number(y.target.value)}),className:ke.rangeW120}),r.jsx("span",{className:ke.smallValue,children:s.toFixed(1)})]}),(n==="peaking"||n==="lowshelf"||n==="highshelf")&&r.jsxs("div",{className:`d-flex align-items-center gap-2 ${ke.narrowGroup}`,children:[r.jsx("span",{className:ke.smallLabel,children:"Gain"}),r.jsx("input",{type:"range",min:"-18",max:"18",step:"0.5",value:i,onChange:y=>o({gain:Number(y.target.value)}),className:ke.rangeW120}),r.jsxs("span",{className:ke.smallValue,children:[i.toFixed(1)," dB"]})]})]}),r.jsxs("div",{className:`mt-2 pt-2 ${ke.presetDivider}`,children:[r.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[r.jsxs("span",{className:ke.presetLabel,children:[f("editorPanels.eqPresets","EQ Presets"),":"]}),[...l,...c].map(y=>r.jsx("button",{className:`btn btn-sm btn-outline-secondary ${ke.presetBtn}`,onClick:()=>u(y),children:y.name},y.name)),c.length>0&&r.jsxs("select",{className:`form-select form-select-sm ${ke.deletePresetSelect}`,onChange:y=>{y.target.value&&(p(y.target.value),y.target.value="")},defaultValue:"",children:[r.jsx("option",{value:"",children:f("editorPanels.deletePreset","Delete preset...")}),c.map(y=>r.jsx("option",{value:y.name,children:y.name},y.name))]})]}),r.jsxs("div",{className:"d-flex align-items-center gap-2",children:[r.jsx("input",{type:"text",className:`form-control form-control-sm ${ke.presetNameInput}`,placeholder:f("editorPanels.presetName","Preset name..."),id:"presetNameInput"}),r.jsx("button",{className:`btn btn-sm btn-success ${ke.savePresetBtn}`,onClick:()=>{const y=document.getElementById("presetNameInput");y!=null&&y.value.trim()&&(h(y.value.trim()),y.value="")},children:f("editorPanels.saveCurrent","Save Current")})]})]})]})},Ii=({countInBars:e,setCountInBars:t,isCountIn:n,countInRemaining:a,overdubEnabled:s,setOverdubEnabled:i,punchIn:o,setPunchIn:l,punchOut:c,setPunchOut:u,monitorLevel:h})=>{const{t:p}=Te();return r.jsx("div",{className:`card p-2 mb-3 ${ke.panelWide}`,children:r.jsxs("div",{className:"d-flex align-items-center flex-wrap gap-3",children:[r.jsxs("div",{className:"d-flex align-items-center gap-2",children:[r.jsxs("label",{className:`form-label mb-0 ${ke.smallLabel}`,children:[p("editorPanels.countIn","Count-in (bars)"),":"]}),r.jsx("input",{type:"number",min:"0",max:"8",step:"1",className:`form-control form-control-sm ${ke.inputW70}`,value:e,onChange:f=>t(Number(f.target.value))}),n&&r.jsxs("span",{className:ke.countInAlert,children:["Count-in: ",a.toFixed(1),"s"]})]}),r.jsxs("div",{className:"form-check d-flex align-items-center gap-2",children:[r.jsx("input",{id:"overdub-toggle",className:"form-check-input",type:"checkbox",checked:s,onChange:f=>i(f.target.checked)}),r.jsx("label",{htmlFor:"overdub-toggle",className:`form-check-label ${ke.smallLabel}`,children:p("editorPanels.overdub","Overdub (play background)")})]}),r.jsxs("div",{className:"d-flex align-items-center gap-1",children:[r.jsx("span",{className:ke.smallLabel,children:"Punch In"}),r.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${ke.inputW80}`,value:o??"",onChange:f=>l(f.target.value===""?null:Number(f.target.value))}),r.jsx("span",{className:ke.smallLabel,children:"s"})]}),r.jsxs("div",{className:"d-flex align-items-center gap-1",children:[r.jsx("span",{className:ke.smallLabel,children:"Punch Out"}),r.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${ke.inputW80}`,value:c??"",onChange:f=>u(f.target.value===""?null:Number(f.target.value))}),r.jsx("span",{className:ke.smallLabel,children:"s"})]}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>{l(null),u(null)},children:p("editorPanels.clearPunch","Clear punch")}),r.jsx("div",{className:ke.levelLabel,children:"Level"}),r.jsx("div",{className:ke.levelMeter,children:r.jsx("div",{className:ke.levelBar,style:{width:`${Math.min(1,h*2)*100}%`,background:h>.7?"var(--nice-danger, #f44336)":"var(--nice-success, #4caf50)"}})})]})})},qd=[{id:1,name:"Audio 1",type:"audio",color:Je[0],volume:.8,audioBlob:null},{id:2,name:"MIDI 1",type:"midi",color:Je[1],volume:.8,notes:[]}],Vd=({initialTracks:e,tracks:t,onTracksChange:n,initialBpm:a=120,duration:s=30,height:i=480,title:o="Untitled project",displayMode:l="standard",onNew:c,onOpen:u,onSave:h,onExport:p,t:f})=>{var K,oe;const{t:y}=Te(),m=f??y,[g,b]=d.useState(l),x=g==="advanced",k=g!=="basic",[v,w]=d.useState(e??qd),M=t??v,S=d.useCallback(re=>{t===void 0&&w(re),n==null||n(re)},[t,n]),[R,T]=d.useState(!1),[j,O]=d.useState(0),[$,E]=d.useState(1),[D,L]=d.useState(2),[W,Z]=d.useState(!0),[A,_]=d.useState("beat"),[U,ne]=d.useState(a),[V,q]=d.useState(80),[C,F]=d.useState(((K=M[0])==null?void 0:K.id)??null),I=d.useRef(0),P=d.useRef(0);d.useEffect(()=>{if(!R)return;P.current=performance.now();const re=he=>{const Q=(he-P.current)/1e3;P.current=he,O(de=>{const me=de+Q;return me>=s?(T(!1),s):me}),I.current=requestAnimationFrame(re)};return I.current=requestAnimationFrame(re),()=>cancelAnimationFrame(I.current)},[R,s]);const N=d.useCallback((re,he)=>S(M.map(Q=>Q.id===re?{...Q,...he}:Q)),[M,S]),z=d.useCallback(re=>{const he=M.reduce((de,me)=>Math.max(de,me.id),0)+1,Q=M.filter(de=>de.type===re).length+1;S([...M,{id:he,name:`${re==="audio"?"Audio":"MIDI"} ${Q}`,type:re,color:Je[M.length%Je.length],volume:.8,...re==="audio"?{audioBlob:null}:{notes:[]}}]),F(he)},[M,S]),B=d.useCallback(re=>S(M.filter(he=>he.id!==re)),[M,S]),G=d.useCallback(()=>{if(c){c();return}S([]),O(0),T(!1)},[c,S]),Y=d.useCallback((re,he,Q,de)=>{const me=M.find(ye=>ye.id===re),xe=(me==null?void 0:me.notes)??[],ce=xe.reduce((ye,Se)=>Math.max(ye,Se.id),0)+1;N(re,{notes:[...xe,{id:ce,pitch:he,start:Q,duration:de,velocity:100}]})},[M,N]),X=d.useCallback((re,he)=>{const Q=M.find(de=>de.id===re);N(re,{notes:((Q==null?void 0:Q.notes)??[]).filter(de=>de.id!==he)})},[M,N]),ie=d.useMemo(()=>{const re=Math.floor(j/60),he=Math.floor(j%60),Q=Math.floor(j%1*100);return`${re}:${he.toString().padStart(2,"0")}.${Q.toString().padStart(2,"0")}`},[j]),le=d.useMemo(()=>{const re=(Q,de)=>({id:`mode-${Q}`,label:`${g===Q?"• ":" "}${de}`,onClick:()=>b(Q)}),he=[{id:"file",label:m("studio.menu.file","File"),children:[{id:"new",label:m("studio.menu.new","New"),onClick:G},...u?[{id:"open",label:m("studio.menu.open","Open…"),onClick:u}]:[],{id:"save",label:m("studio.menu.save","Save"),onClick:()=>h==null?void 0:h(M)},{id:"export",label:m("studio.menu.export","Export…"),onClick:()=>p==null?void 0:p(M)}]}];return k&&he.push({id:"edit",label:m("studio.menu.edit","Edit"),children:[{id:"add-audio",label:m("studio.addAudio","Add audio track"),onClick:()=>z("audio")},{id:"add-midi",label:m("studio.addMidi","Add MIDI track"),onClick:()=>z("midi")}]}),he.push({id:"view",label:m("studio.menu.view","View"),children:[{id:"modes",label:m("studio.menu.modes","Display mode"),divider:!1,disabled:!0},re("basic",m("studio.mode.basic","Basic")),re("standard",m("studio.mode.standard","Standard")),re("advanced",m("studio.mode.advanced","Advanced")),{id:"d1",divider:!0},{id:"snap",label:`${W?"• ":" "}${m("studio.snap","Snap to grid")}`,onClick:()=>Z(Q=>!Q)}]}),he.push({id:"help",label:m("studio.menu.help","Help"),children:[{id:"about",label:m("studio.menu.about","About NiceAudioStudio"),disabled:!0}]}),he},[m,g,k,W,G,u,h,p,M,z]),te=r.jsxs(r.Fragment,{children:[r.jsxs(we.NiceButton,{variant:"primary",size:"sm",onClick:()=>T(re=>!re),children:[R?r.jsx(se.NtdPause,{size:14}):r.jsx(se.NtdPlay,{size:14})," ",R?m("studio.pause","Pause"):m("studio.play","Play")]}),r.jsxs(we.NiceButton,{variant:"secondary",size:"sm",onClick:()=>{T(!1),O(0)},children:[r.jsx(se.NtdStop,{size:14})," ",m("studio.stop","Stop")]}),r.jsx("span",{style:{fontVariantNumeric:"tabular-nums",fontWeight:700,minWidth:80},children:ie}),r.jsx("span",{style:{flex:1}}),r.jsxs(we.NiceButton,{variant:"outline",size:"sm",onClick:()=>z("audio"),children:[r.jsx(se.NtdPlus,{size:14})," ",m("studio.addAudio","Audio")]}),k&&r.jsxs(we.NiceButton,{variant:"outline",size:"sm",onClick:()=>z("midi"),children:[r.jsx(se.NtdPlus,{size:14})," ",m("studio.addMidi","MIDI")]}),r.jsx("span",{style:{fontSize:12,color:"var(--text-muted, #94a3b8)"},children:m("studio.master","Master")}),r.jsx("div",{style:{width:90},children:r.jsx(we.NiceSlider,{value:V,onChange:q,min:0,max:100})})]}),H=r.jsxs(r.Fragment,{children:[r.jsxs("span",{children:[U," BPM"]}),r.jsx("span",{children:"·"}),r.jsx("span",{style:{fontVariantNumeric:"tabular-nums"},children:ie}),r.jsx("span",{children:"·"}),r.jsxs("span",{children:[M.length," ",m("studio.tracks","tracks")]}),x&&C!=null&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"·"}),r.jsxs("span",{children:[m("studio.active","Active"),": ",((oe=M.find(re=>re.id===C))==null?void 0:oe.name)??"—"]})]}),r.jsx("span",{style:{flex:1}}),r.jsx("span",{style:{textTransform:"capitalize"},children:g})]});return r.jsxs(we.NiceAppShell,{className:"nice-audio-studio",height:i,menubar:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[r.jsx(we.NiceMenu,{items:le,orientation:"horizontal"}),r.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13},children:o})]}),toolbar:te,statusBar:H,children:[k&&r.jsx("div",{style:{padding:"6px 12px",borderBottom:"1px solid var(--border-color)"},children:r.jsx($a,{zoom:$,setZoom:E,uiZoom:D,setUiZoom:L,snapEnabled:W,onToggleSnap:()=>Z(re=>!re),snapMode:A,onSnapModeChange:_,bpm:U,setBpm:ne})}),r.jsx("div",{style:{padding:8},children:r.jsx(Ta,{zoom:$,duration:s,isPlaying:R,isRecording:!1,currentTime:j,bpm:U,snapEnabled:W,snapMode:A,onCurrentTimeChange:O,onZoomChange:E})}),M.length===0?r.jsx("div",{style:{padding:32,textAlign:"center",color:"var(--text-muted, #94a3b8)"},children:m("studio.empty","No tracks — add an audio or MIDI track to start.")}):M.map(re=>r.jsxs("div",{style:{display:"flex",gap:8,padding:8,borderTop:"1px solid var(--border-color)",background:C===re.id?"color-mix(in srgb, var(--color-primary) 8%, transparent)":"transparent"},onClick:()=>F(re.id),children:[r.jsxs("div",{style:{flex:"0 0 180px",display:"flex",flexDirection:"column",gap:6},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:re.color||Je[0],flex:"0 0 auto"}}),r.jsx("div",{style:{flex:1},children:r.jsx(we.NiceTextInput,{value:re.name,onChange:he=>N(re.id,{name:he}),size:"sm"})})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[r.jsx(we.NiceButton,{variant:re.muted?"danger":"ghost",size:"sm",onClick:()=>N(re.id,{muted:!re.muted}),children:"M"}),k&&r.jsx(we.NiceButton,{variant:re.solo?"warning":"ghost",size:"sm",onClick:()=>N(re.id,{solo:!re.solo}),children:"S"}),r.jsx("div",{style:{flex:1},children:r.jsx(we.NiceSlider,{value:Math.round((re.volume??.8)*100),onChange:he=>N(re.id,{volume:he/100}),min:0,max:100})}),r.jsx(we.NiceButton,{variant:"ghost",size:"sm",onClick:()=>B(re.id),children:r.jsx(se.NtdClose,{size:14})})]})]}),r.jsx("div",{style:{flex:1,minWidth:0,opacity:re.muted?.5:1},children:re.type==="audio"?r.jsx(Ra,{audioBlob:re.audioBlob??null,currentTime:j,duration:s,zoom:$,height:80,waveColor:re.color,onSeek:O}):r.jsx(Na,{notes:re.notes??[],onAddNote:(he,Q,de)=>Y(re.id,he,Q,de),onRemoveNote:he=>X(re.id,he),duration:s,zoom:$})})]},re.id))]})};let Hd=Date.now();function fn(){return Hd++}function Kd(e,t,n=.01){if(e.length===0)return[];const a=[];let s=-1/0;for(const i of e)i.time-s>=n&&(a.push({id:fn(),cc:t,value:gn(i.value),time:i.time}),s=i.time);return a}function js(e,t,n,a=32){const s=[];for(let i=0;i<=a;i++){const o=i/a;s.push({id:fn(),cc:n,value:gn(wr(e.value,t.value,o)),time:wr(e.time,t.time,o)})}return s}function Yd(e,t,n,a,s=48){const i=[];for(let o=0;o<=s;o++){const l=o/s,c=Cs(e.time,t.time,n.time,l),u=Cs(e.value,t.value,n.value,l);i.push({id:fn(),cc:a,value:gn(u),time:c})}return i}function Zd(e,t,n,a=8){const s=[],i=(t.time-e.time)/a,o=(t.value-e.value)/a;for(let l=0;l<a;l++){const c=e.time+l*i,u=gn(e.value+l*o);s.push({id:fn(),cc:n,value:u,time:c}),s.push({id:fn(),cc:n,value:u,time:c+i-.001})}return s}function Xd(e,t,n,a=2,s=32){const i=[];for(let o=0;o<=s;o++){const l=o/s,c=Math.pow(l,a);i.push({id:fn(),cc:n,value:gn(wr(e.value,t.value,c)),time:wr(e.time,t.time,l)})}return i}function Qd(e,t=3){if(e.length<t)return e;const n=[...e].sort((a,s)=>a.time-s.time);return n.map((a,s)=>{const i=Math.max(0,s-Math.floor(t/2)),o=Math.min(n.length,i+t),l=n.slice(i,o),c=l.reduce((u,h)=>u+h.value,0)/l.length;return{...a,value:gn(Math.round(c))}})}function Jd(e,t){let n;switch(e.mode){case"pencil":n=Kd(t,e.cc,e.resolution);break;case"line":n=t.length>=2?js(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?n=Yd(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?n=js(t[0],t[t.length-1],e.cc):n=[];break;case"step":n=t.length>=2?Zd(t[0],t[t.length-1],e.cc):[];break;case"ramp":n=t.length>=2?Xd(t[0],t[t.length-1],e.cc):[];break;default:n=[]}if(e.smoothing>0){const a=Math.max(2,Math.round(e.smoothing*8));n=Qd(n,a)}return n}function gn(e){return Math.max(0,Math.min(127,Math.round(e)))}function wr(e,t,n){return e+(t-e)*n}function Cs(e,t,n,a){const s=1-a;return s*s*e+2*s*a*t+a*a*n}function Er(){return{waveform:"sine",rate:1,depth:.5,phase:0,center:.5,syncToBpm:!1,syncDivision:"1/4",enabled:!0}}const eu={"4/1":.25,"2/1":.5,"1/1":1,"1/2":2,"1/4":4,"1/8":8,"1/16":16,"1/32":32,"1/2t":3,"1/4t":6,"1/8t":12,"1/16t":24};function Li(e,t){return e/60*eu[t]/4}function Di(e,t){const n=(t%1+1)%1;switch(e){case"sine":return Math.sin(n*2*Math.PI);case"triangle":return n<.5?4*n-1:3-4*n;case"sawtooth":return 2*n-1;case"square":return n<.5?1:-1;case"random":return Math.sin(n*127.1)*Math.cos(n*311.7)*2;case"sample-hold":return Math.sin(Math.floor(n*4)*2.399+.5)*2-1;default:return 0}}function Pa(e,t,n){if(!e.enabled)return e.center;const a=e.syncToBpm&&n?Li(n,e.syncDivision):e.rate,s=t*a+e.phase/(2*Math.PI),i=Di(e.waveform,s),o=e.center+i*e.depth*.5;return Math.max(0,Math.min(1,o))}function Aa(e,t,n){return Math.round(Pa(e,t,n)*127)}function _i(e,t,n,a,s=30,i){const o=n-t,l=Math.max(2,Math.ceil(o*s)),c=[];for(let u=0;u<=l;u++){const h=t+u/l*o,p=Aa(e,h,i);c.push({time:h,value:p,cc:a})}return c}function Fi(e,t,n,a=2,s,i=200){const o=[];for(let l=0;l<=i;l++){const c=l/i*a,u=Pa(e,c,s);o.push({x:l/i*t,y:(1-u)*n})}return o}function tu(e){return JSON.stringify(e,null,2)}function nu(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const qr=140,yn=24,ru=[{cc:1,label:"Mod Wheel"},{cc:7,label:"Volume"},{cc:10,label:"Pan"},{cc:11,label:"Expression"},{cc:64,label:"Sustain"},{cc:74,label:"Brightness"}],zi=({layerId:e=0,ccNumber:t=1,duration:n=8,zoom:a=1,automation:s,onChangeCCNumber:i,points:o,onChange:l})=>{const c=d.useRef({getEvents:()=>[],setEvents:()=>{},addEvent:()=>{},removeEvent:()=>{},updateEvent:()=>{},clearLane:()=>{},exportLane:()=>"",importLane:()=>{},undo:()=>{},redo:()=>{},canUndo:!1,canRedo:!1}).current,u=s??c,{t:h}=Te(),p=d.useRef(null),[f,y]=d.useState("pencil"),[m,g]=d.useState(!1),b=d.useRef([]),[x,k]=d.useState(null),[v,w]=d.useState(!1),[M,S]=d.useState(Er()),R=d.useRef(null),T=u.getEvents(e),j=T.filter(C=>C.cc===t),O=Math.max(400,n*30*a),$=d.useCallback(C=>C/O*n,[O,n]),E=d.useCallback(C=>Math.round(Math.max(0,Math.min(127,127-(C-yn)/qr*127))),[]),D=d.useCallback(C=>C/n*O,[O,n]),L=d.useCallback(C=>yn+(127-C)/127*qr,[]),W=d.useCallback(()=>{const C=p.current;if(!C)return;const F=C.getContext("2d");if(!F)return;const I=C.width,P=C.height;F.clearRect(0,0,I,P),F.fillStyle="var(--nice-bg, #1a1a2e)",F.fillRect(0,0,I,P),F.strokeStyle="var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",F.lineWidth=1;for(let B=0;B<=127;B+=16){const G=L(B);F.beginPath(),F.moveTo(0,G),F.lineTo(I,G),F.stroke()}F.fillStyle="var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))",F.font="10px monospace",F.textBaseline="middle";for(const B of[0,32,64,96,127])F.fillText(String(B),2,L(B));F.strokeStyle="var(--nice-overlay-light-4, rgba(255, 255, 255, 0.04))";for(let B=0;B<=n;B++){const G=D(B);F.beginPath(),F.moveTo(G,0),F.lineTo(G,P),F.stroke()}const N=[...j].sort((B,G)=>B.time-G.time);if(N.length>0){F.beginPath(),F.moveTo(D(N[0].time),P-yn);for(const B of N)F.lineTo(D(B.time),L(B.value));F.lineTo(D(N[N.length-1].time),P-yn),F.closePath(),F.fillStyle="var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",F.fill(),F.beginPath(),F.strokeStyle="var(--nice-primary, #3b82f6)",F.lineWidth=2;for(let B=0;B<N.length;B++){const G=D(N[B].time),Y=L(N[B].value);B===0?F.moveTo(G,Y):((N[B].handleType??"linear")==="step"&&F.lineTo(G,L(N[B-1].value)),F.lineTo(G,Y))}F.stroke();for(const B of N){const G=D(B.time),Y=L(B.value),X=x===B.id;F.beginPath(),F.arc(G,Y,X?6:4,0,Math.PI*2),F.fillStyle=X?"var(--nice-primary-light, #60a5fa)":"var(--nice-primary, #3b82f6)",F.fill(),F.strokeStyle="var(--nice-bg, #fff)",F.lineWidth=1.5,F.stroke()}}F.strokeStyle="var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))",F.lineWidth=1,F.setLineDash([4,4]);const z=L(0);F.beginPath(),F.moveTo(0,z),F.lineTo(I,z),F.stroke(),F.setLineDash([])},[j,n,O,D,L,x]);d.useEffect(()=>{W()},[W]);const Z=C=>{var N;const F=(N=p.current)==null?void 0:N.getBoundingClientRect();if(!F)return;const I=C.clientX-F.left,P=C.clientY-F.top;f==="pencil"?(g(!0),b.current=[{time:$(I),value:E(P)}]):(g(!0),b.current=[{time:$(I),value:E(P)}])},A=C=>{var B;const F=(B=p.current)==null?void 0:B.getBoundingClientRect();if(!F)return;const I=C.clientX-F.left,P=C.clientY-F.top;m&&b.current.push({time:$(I),value:E(P)});const N=[...j].sort((G,Y)=>G.time-Y.time);let z=null;for(const G of N){const Y=D(G.time),X=L(G.value);if(Math.abs(I-Y)<8&&Math.abs(P-X)<8){z=G.id;break}}k(z)},_=()=>{if(!m)return;g(!1);const C=b.current;if(C.length===0)return;const F=Jd({mode:f,cc:t,resolution:.02,smoothing:f==="pencil"?.3:0},C);F.length>0&&u.setEvents(e,[...T,...F]),b.current=[]},U=C=>{var N;const F=(N=p.current)==null?void 0:N.getBoundingClientRect();if(!F)return;const I=C.clientX-F.left,P=C.clientY-F.top;for(const z of j){const B=D(z.time),G=L(z.value);if(Math.abs(I-B)<8&&Math.abs(P-G)<8){u.removeEvent(e,z.id);return}}u.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:E(P),time:$(I)})},ne=()=>{const F=_i(M,0,n,t,Math.ceil(n*20),120).map((I,P)=>({...I,id:Date.now()+P}));u.setEvents(e,[...T,...F]),w(!1)},V=()=>{const C=u.exportLane(e),F=new Blob([C],{type:"application/json"}),I=URL.createObjectURL(F),P=document.createElement("a");P.href=I,P.download=`cc-lane-${t}-layer-${e}.json`,document.body.appendChild(P),P.click(),P.remove(),URL.revokeObjectURL(I)},q=C=>{var I;const F=(I=C.target.files)==null?void 0:I[0];F&&(F.text().then(P=>{u.importLane(e,P)}),R.current&&(R.current.value=""))};return r.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[r.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2 flex-wrap",children:[r.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:h("ccLane.title","CC Automation Lane")}),r.jsx("select",{className:"form-select form-select-sm",style:{width:160,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:t,onChange:C=>i(Number(C.target.value)),children:ru.map(C=>r.jsxs("option",{value:C.cc,children:[C.label," (CC",C.cc,")"]},C.cc))}),r.jsx("div",{className:"btn-group btn-group-sm",children:["pencil","line","curve","step","ramp"].map(C=>r.jsx("button",{className:`btn ${f===C?"btn-primary":"btn-outline-secondary"}`,onClick:()=>y(C),style:{fontSize:11,textTransform:"capitalize"},children:C},C))}),r.jsxs("div",{className:"btn-group btn-group-sm",children:[r.jsx("button",{className:"btn btn-outline-secondary",onClick:u.undo,disabled:!u.canUndo,title:"Undo",children:"↩"}),r.jsx("button",{className:"btn btn-outline-secondary",onClick:u.redo,disabled:!u.canRedo,title:"Redo",children:"↪"})]}),r.jsx("button",{className:"btn btn-sm btn-outline-info",onClick:()=>w(!v),title:"Apply LFO modulation",children:"LFO"}),r.jsx("button",{className:"btn btn-sm btn-outline-warning",onClick:V,title:"Export CC lane as JSON",children:"Export"}),r.jsx("button",{className:"btn btn-sm btn-outline-success",onClick:()=>{var C;return(C=R.current)==null?void 0:C.click()},title:"Import CC lane from JSON",children:"Import"}),r.jsx("input",{ref:R,type:"file",accept:".json",style:{display:"none"},onChange:q}),r.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:()=>u.setEvents(e,T.filter(C=>C.cc!==t)),title:"Clear all CC events for this lane",children:"Clear"}),r.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginLeft:"auto"},children:[j.length," ",h("ccLane.events","events")]})]}),v&&r.jsx("div",{className:"mb-2 p-2",style:{background:"var(--nice-bg-secondary, #161b22)",borderRadius:6,border:"1px solid var(--nice-border, #30363d)"},children:r.jsxs("div",{className:"d-flex gap-2 flex-wrap align-items-center mb-2",children:[r.jsxs("label",{style:{fontSize:12},children:["Wave:",r.jsx("select",{className:"form-select form-select-sm ms-1",style:{width:110,display:"inline-block",background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:M.waveform,onChange:C=>S(F=>({...F,waveform:C.target.value})),children:["sine","triangle","sawtooth","square","random","sample-hold"].map(C=>r.jsx("option",{value:C,children:C},C))})]}),r.jsxs("label",{style:{fontSize:12},children:["Rate:",r.jsx("input",{type:"number",className:"form-control form-control-sm ms-1",style:{width:70,display:"inline-block",background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},min:.01,max:20,step:.1,value:M.rate,onChange:C=>S(F=>({...F,rate:Number(C.target.value)}))})]}),r.jsxs("label",{style:{fontSize:12},children:["Depth:",r.jsx("input",{type:"range",min:0,max:1,step:.01,value:M.depth,onChange:C=>S(F=>({...F,depth:Number(C.target.value)})),style:{width:80}}),r.jsx("span",{style:{fontSize:11,marginLeft:4},children:M.depth.toFixed(2)})]}),r.jsxs("label",{style:{fontSize:12},children:["Center:",r.jsx("input",{type:"range",min:0,max:1,step:.01,value:M.center,onChange:C=>S(F=>({...F,center:Number(C.target.value)})),style:{width:80}}),r.jsx("span",{style:{fontSize:11,marginLeft:4},children:M.center.toFixed(2)})]}),r.jsx("button",{className:"btn btn-sm btn-primary",onClick:ne,children:"Apply LFO"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>w(!1),children:"Cancel"})]})}),r.jsx("div",{style:{overflowX:"auto",borderRadius:6},children:r.jsx("canvas",{ref:p,width:O,height:qr+yn*2,style:{cursor:m?"crosshair":x?"pointer":"crosshair",display:"block",borderRadius:6},onMouseDown:Z,onMouseMove:A,onMouseUp:_,onMouseLeave:()=>{m&&_()},onDoubleClick:U,role:"img","aria-label":"CC automation lane editor canvas"})}),r.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginTop:4},children:h("ccLane.hint","Click to draw. Double-click to add/remove points. Drag to draw curves.")})]})},Oi={"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":1/1.5,"1/8T":.5/1.5,"1/16T":.25/1.5},ia={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function au(e,t){const n=[];for(let a=0;a<t;a++)for(const s of e)n.push({...s,pitch:s.pitch+a*12});return n}function Bi(e,t){if(e.length===0)return[];const n=au(e,t.octaves),a=[...n].sort((o,l)=>o.pitch-l.pitch),s=[...n].sort((o,l)=>l.pitch-o.pitch);let i;switch(t.mode){case"up":i=a;break;case"down":i=s;break;case"updown":i=[...a,...s.slice(1,-1)];break;case"downup":i=[...s,...a.slice(1,-1)];break;case"random":i=[...n].sort(()=>Math.random()-.5);break;case"as-played":i=[...n].sort((o,l)=>o.originalOrder-l.originalOrder);break;case"chord":i=n;break;default:i=a}if(t.repeats>1){const o=[];for(const l of i)for(let c=0;c<t.repeats;c++)o.push(l);i=o}return i}function su(e,t,n,a=0,s=1){const i=Bi(e,t);if(i.length===0)return[];const o=60/n,l=Oi[t.rate]*o,c=l*t.gate,u=[],h=t.mode==="chord",p=h?s:i.length*s;for(let f=0;f<p;f++){const y=f%2===1?l*t.swing*.5:0,m=a+f*l+y;if(h)for(const g of i){const b=t.velocityPattern?t.velocityPattern[f%t.velocityPattern.length]:g.velocity;u.push({pitch:g.pitch,velocity:b,startTime:m,duration:c,step:f})}else{const g=f%i.length,b=i[g],x=t.velocityPattern?t.velocityPattern[f%t.velocityPattern.length]:b.velocity;u.push({pitch:b.pitch,velocity:x,startTime:m,duration:c,step:f})}}return u}function Gi(){return[{mode:"up",label:"Up",description:"Notes played low to high"},{mode:"down",label:"Down",description:"Notes played high to low"},{mode:"updown",label:"Up/Down",description:"Alternates up then down"},{mode:"downup",label:"Down/Up",description:"Alternates down then up"},{mode:"random",label:"Random",description:"Random note order"},{mode:"as-played",label:"As Played",description:"Order in which notes were pressed"},{mode:"chord",label:"Chord",description:"All notes played simultaneously"}]}function Wi(){return Object.keys(Oi)}const Ui=({config:e=ia,onChange:t=()=>{},active:n=!1,onToggleActive:a=()=>{}})=>{const{t:s}=Te(),i=Gi(),o=Wi(),l=c=>t({...e,...c});return r.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8,opacity:n?1:.6},children:[r.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[r.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:s("arp.title","Arpeggiator")}),r.jsx("button",{className:`btn btn-sm ${n?"btn-success":"btn-outline-secondary"}`,onClick:a,children:n?"ON":"OFF"}),r.jsx("button",{className:`btn btn-sm ${e.latch?"btn-warning":"btn-outline-secondary"}`,onClick:()=>l({latch:!e.latch}),title:"Latch — keep arp running after releasing keys",children:"Latch"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>t(ia),title:"Reset to defaults",children:"Reset"})]}),r.jsxs("div",{className:"row g-2",children:[r.jsxs("div",{className:"col-12",children:[r.jsx("label",{style:{fontSize:12},className:"mb-1",children:s("arp.mode","Mode")}),r.jsx("div",{className:"btn-group btn-group-sm w-100",children:i.map(c=>r.jsx("button",{className:`btn ${e.mode===c.mode?"btn-primary":"btn-outline-secondary"}`,onClick:()=>l({mode:c.mode}),title:c.description,style:{fontSize:11},children:c.label},c.mode))})]}),r.jsxs("div",{className:"col-6",children:[r.jsx("label",{style:{fontSize:12},className:"mb-1",children:s("arp.rate","Rate")}),r.jsx("select",{className:"form-select form-select-sm",style:{background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:e.rate,onChange:c=>l({rate:c.target.value}),children:o.map(c=>r.jsx("option",{value:c,children:c},c))})]}),r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.octaves","Octaves"),": ",e.octaves]}),r.jsx("input",{type:"range",className:"form-range",min:1,max:4,step:1,value:e.octaves,onChange:c=>l({octaves:Number(c.target.value)})})]}),r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.gate","Gate"),": ",Math.round(e.gate*100),"%"]}),r.jsx("input",{type:"range",className:"form-range",min:.05,max:1,step:.05,value:e.gate,onChange:c=>l({gate:Number(c.target.value)})})]}),r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.swing","Swing"),": ",Math.round(e.swing*100),"%"]}),r.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.swing,onChange:c=>l({swing:Number(c.target.value)})})]}),r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.repeats","Repeats"),": ",e.repeats]}),r.jsx("input",{type:"range",className:"form-range",min:1,max:4,step:1,value:e.repeats,onChange:c=>l({repeats:Number(c.target.value)})})]})]})]})},iu=["sine","triangle","sawtooth","square","random","sample-hold"],ou=["1/1","1/2","1/4","1/8","1/16","1/32"],bn=200,Zt=48,qi=({config:e,onChange:t,index:n,onRemove:a})=>{const{t:s}=Te(),i=d.useRef(null),o=c=>t({...e,...c}),l=d.useCallback(()=>{const c=i.current;if(!c)return;const u=c.getContext("2d");if(!u)return;u.clearRect(0,0,bn,Zt),u.fillStyle="var(--nice-bg-secondary, #161b22)",u.fillRect(0,0,bn,Zt),u.strokeStyle="var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",u.lineWidth=1,u.setLineDash([3,3]),u.beginPath(),u.moveTo(0,Zt/2),u.lineTo(bn,Zt/2),u.stroke(),u.setLineDash([]);const h=Fi(e,bn,Zt);if(h.length>0){u.beginPath(),u.strokeStyle=e.enabled?"var(--nice-primary, #3b82f6)":"var(--nice-text-secondary, #484f58)",u.lineWidth=1.5;for(let p=0;p<h.length;p++){const f=h[p].x,y=h[p].y;p===0?u.moveTo(f,y):u.lineTo(f,y)}u.stroke()}},[e]);return d.useEffect(()=>{l()},[l]),r.jsxs("div",{className:"card p-2 mb-2",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8,opacity:e.enabled?1:.5},children:[r.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[r.jsxs("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)",fontSize:13},children:[s("lfo.title","LFO")," ",n!==void 0?`#${n+1}`:""]}),r.jsx("button",{className:`btn btn-sm ${e.enabled?"btn-success":"btn-outline-secondary"}`,onClick:()=>o({enabled:!e.enabled}),style:{fontSize:11,padding:"1px 8px"},children:e.enabled?"ON":"OFF"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>t(Er()),style:{fontSize:11,padding:"1px 8px"},title:"Reset to defaults",children:"Reset"}),a&&r.jsx("button",{className:"btn btn-sm btn-outline-danger ms-auto",onClick:a,style:{fontSize:11,padding:"1px 8px"},"aria-label":s("lfo.remove","Remove LFO"),title:s("lfo.remove","Remove LFO"),children:r.jsx(se.NtdClose,{size:12})})]}),r.jsxs("div",{className:"d-flex gap-2 flex-wrap align-items-start",children:[r.jsx("canvas",{ref:i,width:bn,height:Zt,style:{borderRadius:4,border:"1px solid var(--nice-border, #30363d)",flexShrink:0},role:"img","aria-label":"LFO waveform preview canvas"}),r.jsxs("div",{className:"flex-grow-1",children:[r.jsx("div",{className:"mb-1",children:r.jsx("div",{className:"btn-group btn-group-sm w-100",children:iu.map(c=>r.jsx("button",{className:`btn ${e.waveform===c?"btn-primary":"btn-outline-secondary"}`,onClick:()=>o({waveform:c}),style:{fontSize:10,textTransform:"capitalize",padding:"1px 4px"},children:c==="sample-hold"?"S&H":c.slice(0,3)},c))})}),r.jsxs("div",{className:"row g-1",children:[r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:10},children:["Rate: ",e.rate.toFixed(1)," Hz"]}),r.jsx("input",{type:"range",className:"form-range",min:.01,max:20,step:.1,value:e.rate,onChange:c=>o({rate:Number(c.target.value)}),style:{height:16}})]}),r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:10},children:["Depth: ",Math.round(e.depth*100),"%"]}),r.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.depth,onChange:c=>o({depth:Number(c.target.value)}),style:{height:16}})]}),r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:10},children:["Center: ",Math.round(e.center*100),"%"]}),r.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.center,onChange:c=>o({center:Number(c.target.value)}),style:{height:16}})]}),r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:10},children:["Phase: ",Math.round(e.phase),"°"]}),r.jsx("input",{type:"range",className:"form-range",min:0,max:360,step:1,value:e.phase,onChange:c=>o({phase:Number(c.target.value)}),style:{height:16}})]})]}),r.jsxs("div",{className:"d-flex align-items-center gap-2 mt-1",children:[r.jsxs("label",{style:{fontSize:10},children:[r.jsx("input",{type:"checkbox",checked:e.syncToBpm,onChange:c=>o({syncToBpm:c.target.checked}),className:"form-check-input me-1",style:{marginTop:0,width:12,height:12}}),"BPM Sync"]}),e.syncToBpm&&r.jsx("select",{className:"form-select form-select-sm",style:{width:80,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)",fontSize:11},value:e.syncDivision??"1/4",onChange:c=>o({syncDivision:c.target.value}),children:ou.map(c=>r.jsx("option",{value:c,children:c},c))}),r.jsxs("label",{style:{fontSize:10},children:["CC:",r.jsx("input",{type:"number",className:"form-control form-control-sm ms-1",style:{width:55,display:"inline-block",background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)",fontSize:11},min:0,max:127,value:e.targetCC??1,onChange:c=>o({targetCC:Number(c.target.value)})})]})]})]})]})]})},lu=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function cu(e){const t=Math.floor(e/12)-1;return`${lu[e%12]}${t}`}const Vi=({seq:e,steps:t,tracks:n,bpm:a,pattern:s,onChange:i})=>{const{t:o}=Te();if(!e)return r.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[r.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:o("stepSeq.title","Step Sequencer")}),r.jsx("small",{style:{color:"var(--nice-text-muted, #8b949e)"},children:"Provide a `seq` prop (useStepSequencer) for live editing."})]});const{pattern:l,currentStep:c,playing:u}=e,h=d.useMemo(()=>l.steps.slice(0,l.length),[l]);return r.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[r.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2 flex-wrap",children:[r.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:o("stepSeq.title","Step Sequencer")}),r.jsx("button",{className:`btn btn-sm ${u?"btn-danger":"btn-success"}`,onClick:e.togglePlayback,style:{minWidth:60,display:"inline-flex",alignItems:"center",gap:4},children:u?r.jsxs(r.Fragment,{children:[r.jsx(se.NtdStop,{size:12})," Stop"]}):r.jsxs(r.Fragment,{children:[r.jsx(se.NtdPlay,{size:12})," Play"]})}),r.jsxs("label",{style:{fontSize:12,display:"flex",alignItems:"center",gap:4},children:["BPM:",r.jsx("input",{type:"number",className:"form-control form-control-sm",style:{width:70,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},min:20,max:300,value:l.bpm,onChange:p=>e.setBpm(Number(p.target.value))})]}),r.jsxs("label",{style:{fontSize:12,display:"flex",alignItems:"center",gap:4},children:["Swing:",r.jsx("input",{type:"range",min:0,max:1,step:.01,value:l.swing,onChange:p=>e.setSwing(Number(p.target.value)),style:{width:60}}),r.jsxs("span",{style:{fontSize:11,minWidth:28},children:[Math.round(l.swing*100),"%"]})]}),r.jsx("div",{className:"btn-group btn-group-sm",children:[16,32,64].map(p=>r.jsx("button",{className:`btn ${l.length===p?"btn-primary":"btn-outline-secondary"}`,onClick:()=>e.setLength(p),style:{fontSize:11},children:p},p))})]}),r.jsxs("div",{className:"d-flex gap-1 mb-2 flex-wrap",children:[r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(1),"aria-label":"Transpose up one semitone",children:"+1"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(-1),"aria-label":"Transpose down one semitone",children:"-1"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(12),children:"+Oct"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(-12),children:"-Oct"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:e.reverse,children:"Reverse"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.shift(1),children:"Shift →"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.shift(-1),children:"← Shift"}),r.jsx("button",{className:"btn btn-sm btn-outline-info",onClick:()=>e.randomizeVel(),children:"Rnd Vel"}),r.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:e.clear,children:"Clear"})]}),r.jsx("div",{style:{overflowX:"auto"},children:r.jsx("div",{style:{display:"flex",gap:2,minWidth:l.length*36},children:h.map((p,f)=>{const y=p.active,m=c===f,g=f%4===0;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2,minWidth:34},children:[r.jsx("span",{style:{fontSize:9,color:g?"var(--nice-text-muted, #8b949e)":"var(--nice-border, #30363d)"},children:f+1}),r.jsx("button",{onClick:()=>e.toggle(f),style:{width:32,height:32,borderRadius:4,border:m?"2px solid var(--nice-warning, #f0c040)":"1px solid var(--nice-border, #30363d)",background:y?`hsl(${210+p.velocity/127*40}, 80%, ${35+p.velocity/127*20}%)`:g?"var(--nice-bg-secondary, #21262d)":"var(--nice-bg-secondary, #161b22)",cursor:"pointer",padding:0,color:y?"var(--nice-bg, #fff)":"var(--nice-text-secondary, #484f58)",fontSize:8,fontWeight:600,transition:"background 0.1s"},children:y?cu(p.note):""}),r.jsx("div",{style:{width:32,height:20,background:"var(--nice-bg-secondary, #161b22)",borderRadius:2,position:"relative",overflow:"hidden"},children:r.jsx("div",{style:{position:"absolute",bottom:0,left:0,width:"100%",height:`${p.velocity/127*100}%`,background:y?"var(--nice-primary-tint-60, rgba(59, 130, 246, 0.6))":"var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",borderRadius:2,cursor:"ns-resize"},title:`Vel: ${p.velocity}`,onMouseDown:b=>{b.preventDefault();const x=b.target.parentElement.getBoundingClientRect(),k=w=>{const M=w.clientY-x.top,S=Math.round(Math.max(1,Math.min(127,(1-M/x.height)*127)));e.setVelocity(f,S)},v=()=>{document.removeEventListener("mousemove",k),document.removeEventListener("mouseup",v)};document.addEventListener("mousemove",k),document.addEventListener("mouseup",v)}})}),y&&p.probability<1&&r.jsxs("span",{style:{fontSize:8,color:"var(--nice-warning, #f0c040)"},children:[Math.round(p.probability*100),"%"]})]},f)})})}),r.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginTop:6},children:o("stepSeq.hint","Click steps to toggle. Drag velocity bars vertically.")})]})};function du(e,t,n){const[a,s]=d.useState("interval"),[i,o]=d.useState(30),l=d.useRef(null),c=d.useCallback(()=>{if(e)try{localStorage.setItem("audioEditor.autoSave",JSON.stringify(e)),t("Project auto-saved locally"),n("success"),setTimeout(()=>t(""),2e3)}catch(u){t("Auto-save error: "+u.message),n("error")}},[e,t,n]);return d.useEffect(()=>{(a==="onChange"||a==="both")&&c()},[e,a,c]),d.useEffect(()=>(l.current&&(clearInterval(l.current),l.current=null),(a==="interval"||a==="both")&&i>0&&(l.current=window.setInterval(c,i*1e3)),()=>{l.current&&(clearInterval(l.current),l.current=null)}),[a,i,c]),{autoSaveMode:a,setAutoSaveMode:s,autoSaveInterval:i,setAutoSaveInterval:o}}function uu(e,t,n){const a=d.useRef(null),[s,i]=d.useState(!1),[o,l]=d.useState(0),[c,u]=d.useState(10),[h,p]=d.useState(!1),[f,y]=d.useState(120),m=d.useCallback((R,T)=>`L${R}-C${T}`,[]),g=d.useCallback((R,T)=>{if(!a.current||!T.audioBuffer)return;const j=m(R,T.id),O=e[R];a.current.addClip({id:j,buffer:T.audioBuffer,startTime:T.start,offset:0,duration:T.duration,layerId:R,volume:(O==null?void 0:O.volume)??1,pan:(O==null?void 0:O.pan)??0,stretchFactor:T.stretchFactor||1,effectChain:(O==null?void 0:O.effectChain)||[]})},[e,m]),b=d.useCallback((R,T)=>{var j;(j=a.current)==null||j.removeClip(m(R,T))},[m]);d.useEffect(()=>{Object.entries(t).forEach(([R,T])=>{const j=Number(R);T==null||T.forEach(O=>g(j,O))})},[t,e,g]),d.useEffect(()=>{a.current&&Object.entries(n).forEach(([R,T])=>{const j=Number(R);a.current.setMidiCCEvents(j,T)})},[n]);const x=d.useCallback(()=>{a.current&&(s?a.current.pause():a.current.play())},[s]),k=d.useCallback(()=>{var R;(R=a.current)==null||R.stop()},[]),v=d.useCallback(R=>{var T;(T=a.current)==null||T.seek(R)},[]),w=d.useCallback(()=>{if(!a.current)return;const R=!h;p(R),a.current.setLoopRegion(0,c,R)},[h,c]),M=d.useCallback(R=>{var j;const T=Math.max(1,c+R);u(T),(j=a.current)==null||j.setLoopRegion(0,T,h)},[c,h]),S=d.useCallback(async(R,T=1024)=>{const j=await R.arrayBuffer(),O=new(window.AudioContext||window.webkitAudioContext),$=await O.decodeAudioData(j.slice(0)),E=$.getChannelData(0),D=E.length,L=Math.max(1,Math.floor(D/T)),W=[];for(let Z=0;Z<T;Z++){const A=Z*L;if(A>=D)break;W.push(E[A])}return O.close(),{waveform:W.map(Z=>Math.max(-1,Math.min(1,Z))),duration:$.duration,buffer:$}},[]);return{engineRef:a,isPlaying:s,setIsPlaying:i,currentTime:o,setCurrentTime:l,duration:c,setDuration:u,isLooping:h,setIsLooping:p,bpm:f,setBpm:y,handlePlayPause:x,handleStop:k,handleSeek:v,handleToggleLoop:w,handleAdjustDuration:M,upsertEngineClip:g,removeEngineClip:b,makeEngineClipId:m,blobToWaveform:S}}class Ea{constructor(){this.stream=null,this.mediaRecorder=null,this.audioChunks=[],this.isRecording=!1,this.audioContext=null,this.analyser=null,this.gainNode=null,this.monitorGain=null,this.levelRaf=null}async startRecording(t={}){if(this.isRecording)return;this.levelCallback=t.onLevel,this.stream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t.deviceId||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}});const n=t.mimeType||"audio/webm";this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:n}),this.audioChunks=[],this.audioContext=new(window.AudioContext||window.webkitAudioContext);let s=this.audioContext.createMediaStreamSource(this.stream);t.gain!==void 0&&t.gain>0&&(this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=t.gain,s.connect(this.gainNode),s=this.gainNode),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,s.connect(this.analyser),t.monitorEnabled&&(this.monitorGain=this.audioContext.createGain(),this.monitorGain.gain.value=(t.monitorVolume??100)/100,s.connect(this.monitorGain),this.monitorGain.connect(this.audioContext.destination));const i=()=>{if(!this.analyser)return;const o=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(o);let l=0;for(let u=0;u<o.length;u++){const h=(o[u]-128)/128;l+=h*h}const c=Math.sqrt(l/o.length);this.levelCallback&&this.levelCallback(c),this.isRecording&&(this.levelRaf=requestAnimationFrame(i))};this.mediaRecorder.ondataavailable=o=>{o.data&&o.data.size>0&&this.audioChunks.push(o.data)},this.mediaRecorder.start(),this.isRecording=!0,this.levelRaf=requestAnimationFrame(i)}getStream(){return this.stream}async stopRecording(){return!this.isRecording||!this.mediaRecorder?null:new Promise(t=>{const n=this.mediaRecorder;n.onstop=()=>{const a=new Blob(this.audioChunks,{type:n.mimeType});this.cleanup(),t(a)},n.stop(),this.isRecording=!1})}cleanup(){this.levelRaf&&(cancelAnimationFrame(this.levelRaf),this.levelRaf=null),this.levelCallback=void 0,this.monitorGain&&(this.monitorGain.disconnect(),this.monitorGain=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.analyser&&(this.analyser.disconnect(),this.analyser=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.stream&&(this.stream.getTracks().forEach(t=>t.stop()),this.stream=null),this.mediaRecorder=null,this.audioChunks=[]}}function hu(e){const[t,n]=d.useState(!1),[a,s]=d.useState(!1),[i,o]=d.useState(0),[l,c]=d.useState(0),[u,h]=d.useState(null),p=d.useRef(null),f=d.useRef(null),y=d.useRef(0),m=d.useRef(null),g=d.useRef(null),b=d.useCallback(()=>{m.current&&(clearInterval(m.current),m.current=null),g.current&&(clearTimeout(g.current),g.current=null)},[]),x=d.useCallback(async()=>{if(!e.activeLayer){e.showToast("Select a layer to record.","error");return}t||(p.current||(p.current=new Ea),y.current=f.current??e.currentTime,n(!0),o(0),await p.current.startRecording({onLevel:o}))},[e,t]),k=d.useCallback(async()=>{var E;if(b(),s(!1),c(0),f.current=null,!p.current){n(!1),o(0);return}const M=await p.current.stopRecording();if(n(!1),o(0),!M||!e.activeLayer)return;const{waveform:S,duration:R,buffer:T}=await e.blobToWaveform(M),j=e.activeLayer.id;e.setWaveforms(D=>({...D,[j]:S}));const O=Math.max(0,y.current||0),$={id:Date.now(),label:"Recording",start:O,duration:R,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:(E=e.layerSettings[j])==null?void 0:E.color,blob:M,blobUrl:URL.createObjectURL(M),audioBuffer:T};e.setLayerClips(D=>({...D,[j]:[...D[j]||[],$]})),e.upsertEngineClip(j,$),e.setSelectedClip({layerId:j,clipId:$.id})},[e,b]),v=d.useCallback(M=>{if(M<=0){x();return}s(!0),c(M);const S=performance.now();m.current=window.setInterval(()=>{const R=(performance.now()-S)/1e3;c(Math.max(0,M-R))},100),g.current=window.setTimeout(()=>{b(),s(!1),c(0),f.current||x()},M*1e3)},[x,b]),w=d.useCallback(async()=>{if(t||a){await k();return}if(!e.activeLayer){e.showToast("Select a layer before recording","error");return}const M=Math.max(0,e.countInBars)*4*(60/e.bpm),S=e.punchIn!=null&&e.punchIn>e.currentTime?e.punchIn:null;S&&(f.current=S),e.overdubEnabled&&!e.isPlaying&&e.playEngine(),S?M>0&&v(M):v(M)},[t,a,e,k,v]);return{isRecording:t,isCountIn:a,monitorLevel:i,countInRemaining:l,punchOut:u,setPunchOut:h,armedPunchInRef:f,recorderRef:p,clearCountInTimers:b,startRecordingNow:x,stopRecordingFlow:k,handleRecord:w}}var Hi=(e=>(e.Recorder="Recorder",e.AudioClip="Audio Clip",e.SpeechSynth="Speech Synth",e.Stream="Stream",e.KeyboardPad="Keyboard/Pads",e.Keyboard="Keyboard",e.AudioClipCompact="AudioClip",e))(Hi||{});const pu={};class Zn{constructor(t,n,a,s={}){this.type=t,this.name=n,this.component=pu[t]??(()=>null),this.audioType=a,this.parameters=s}}new Zn("Recorder","Recorder","vocal",{deviceId:"",gain:1,sensitivity:"high"}),new Zn("Audio Clip","Audio Clip","instrumental",{clipId:null,octave:"4"}),new Zn("Speech Synth","Speech Synth","vocal",{text:"",voice:"default"}),new Zn("Keyboard/Pads","Keyboard","instrumental",{instrument:"piano",preset:"default",velocity:100});function Ki(e,t,n,a,s){n(i=>t?[...i,t]:i),a([]),s(e)}function fu(e,t,n,a){t(s=>{if(s.length===0)return s;const i=s[s.length-1];return n(o=>e?[e,...o]:o),a(i),s.slice(0,-1)})}function mu(e,t,n,a){n(s=>{if(s.length===0)return s;const i=s[0];return t(o=>e?[...o,e]:o),a(i),s.slice(1)})}class gu{constructor(t={}){this.undoStack=[],this.redoStack=[],this.maxSize=t.maxSize??100,this.onChange=t.onChange}push(t,n,a,s){this.undoStack.push({label:t,category:n,timestamp:Date.now(),oldState:a,newState:s}),this.undoStack.length>this.maxSize&&this.undoStack.shift(),this.redoStack.length=0}undo(){var n;const t=this.undoStack.pop();return t?(this.redoStack.push(t),(n=this.onChange)==null||n.call(this,t,"undo"),t.oldState):null}redo(){var n;const t=this.redoStack.pop();return t?(this.undoStack.push(t),(n=this.onChange)==null||n.call(this,t,"redo"),t.newState):null}get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}get undoLabel(){return this.undoStack.length>0?this.undoStack[this.undoStack.length-1].label:null}get redoLabel(){return this.redoStack.length>0?this.redoStack[this.redoStack.length-1].label:null}get undoCount(){return this.undoStack.length}get redoCount(){return this.redoStack.length}getHistory(){return[...this.undoStack].reverse()}clear(){this.undoStack.length=0,this.redoStack.length=0}undoTo(t){const n=Math.min(t+1,this.undoStack.length);let a=null;for(let s=0;s<n;s++)a=this.undo();return a}}const yu=it.scoped("useProjectCRUD");function bu(e){const{project:t,activeSection:n,setProject:a,setActiveSection:s,setLayers:i,setActiveLayer:o,setUndoStack:l,setRedoStack:c}=e,u=d.useCallback(b=>Ki(b,t,l,c,a),[t,l,c,a]),h=d.useCallback(async()=>{var v;if(!t)return;const b=(((v=t.sections)==null?void 0:v.length)??0)+1,k={id:await e.addSection(t.id,"Section",b),projectId:t.id,name:"Section",orderNumber:b,layers:[]};u({...t,sections:[...t.sections||[],k]}),s(k)},[t,u,s]),p=d.useCallback(async b=>{var v,w,M;if(!t||!await e.confirm("Delete this section?"))return;await e.deleteSection(b);const k=(t.sections??[]).filter(S=>S.id!==b);u({...t,sections:k}),s(k[0]??null),i(((v=k[0])==null?void 0:v.layers)??[]),o(((M=(w=k[0])==null?void 0:w.layers)==null?void 0:M[0])??null)},[t,u,s,i,o,e]),f=d.useCallback(async()=>{var x;if(!n)return;const b={id:-Date.now(),name:"New Layer",sectionId:n.id,audioSource:Hi.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};i(k=>[...k,b]),o(b);try{const k=await e.addLayer(n.id,b.name,b.audioSource,b.audioSourceParameters);i(v=>v.map(w=>w.id===b.id?{...b,id:k}:w)),t&&u({...t,sections:((x=t.sections)==null?void 0:x.map(v=>v.id===n.id?{...v,layers:[...(v.layers??[]).filter(w=>w.id!==k),{...b,id:k}]}:v))??[]})}catch(k){i(v=>v.filter(w=>w.id!==b.id)),yu.error("Failed to add layer:",k)}},[n,t,u,i,o]),y=d.useCallback(async b=>{var k,v;if((k=e.layerSettings[b])!=null&&k.locked){e.showToast("Layer is locked. Unlock to delete.","error");return}await e.confirm("Delete this layer?")&&((e.layerClips[b]||[]).forEach(w=>e.removeEngineClip(b,w.id)),e.setLayerMidiNotes(w=>{const M={...w};return delete M[b],M}),await e.deleteLayer(b),i(w=>w.filter(M=>M.id!==b)),o(w=>(w==null?void 0:w.id)===b?null:w),t&&u({...t,sections:((v=t.sections)==null?void 0:v.map(w=>w.id===(n==null?void 0:n.id)?{...w,layers:(w.layers??[]).filter(M=>M.id!==b)}:w))??[]}))},[t,n,u,i,o,e]),m=d.useCallback(async()=>{if(!t)return;const b=e.projectVolume===""?void 0:Number(e.projectVolume);if(Number.isNaN(b)){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:b}),u({...t,name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:b}),e.setStatusType("success"),e.setStatusMessage("Project saved")},[t,e,u]),g=d.useCallback(async()=>{var k;if(!n)return;const b=e.sectionName||n.name,x=e.sectionOrder===""?n.orderNumber:Number(e.sectionOrder);if(!b.trim()){e.setStatusType("error"),e.setStatusMessage("Section name cannot be empty");return}if(Number.isNaN(x)){e.setStatusType("error"),e.setStatusMessage("Order musi byc liczba");return}await e.updateSection(n.id,{name:b,orderNumber:x}),s({...n,name:b,orderNumber:x}),t&&u({...t,sections:((k=t.sections)==null?void 0:k.map(v=>v.id===n.id?{...v,name:b,orderNumber:x}:v))??[]}),e.setStatusType("success"),e.setStatusMessage("Section saved")},[n,t,e,u,s]);return{handleAddSection:h,handleDeleteSection:p,handleAddLayer:f,handleDeleteLayer:y,handleSaveProject:m,handleSaveSection:g}}const Yi=d.createContext(null);function xu(){const e=d.useContext(Yi);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const Ia=({value:e,children:t})=>r.jsx(Yi.Provider,{value:e,children:t});Ia.displayName="EditorTrackProvider";const on=(e,t)=>t&&t>0?e*15/t:e/10,La=e=>{for(const t of e){const n=t.trim();if(n.toUpperCase().startsWith("#BPM:")){const a=parseFloat(n.substring(5).replace(",","."));if(isFinite(a)&&a>0)return a}}return null},vu=(e,t)=>{const n=t??La(e),a=[];let s="",i=0,o="",l=!0;function c(){o.trim()!==""&&(s.length>0&&(s+=" "),s+=o.trim()),o=""}return e.forEach(u=>{if(!(u.startsWith("#")||u.startsWith("E"))){if(u.startsWith("-"))c(),s.trim().length>0&&(a.push({text:s.trim(),timestamp:i}),s=""),l=!0;else if(u.startsWith(":")||u.startsWith("*")){const h=u.indexOf(" "),p=u.indexOf(" ",h+1),f=u.indexOf(" ",p+1),y=u.indexOf(" ",f+1);if(y===-1)return;const m=on(parseFloat(u.substring(h+1,p)),n);s===""&&(i=m);const g=u.substring(y+1);if(g.trim()==="~")return;let b=g;b.startsWith("~")&&(b=b.substring(1)),l?(c(),o=b.trimEnd()):o+=b.trimEnd(),l=g.endsWith(" ")}}}),c(),s.trim().length>0&&a.push({text:s.trim(),timestamp:i}),a},Su=(e,t)=>{const n=t??La(e),a=[];let s=[],i="",o=0,l=!0,c=null,u="";function h(){c&&u.trim()!==""&&(c.text=u.trim(),s.push({...c}),i.length>0&&(i+=" "),i+=c.text),c=null,u=""}return e.forEach(p=>{if(!(p.startsWith("#")||p.startsWith("E"))){if(p.startsWith("-"))h(),i.trim().length>0&&(a.push({text:i.trim(),timestamp:o,words:s}),i="",s=[]),l=!0;else if(p.startsWith(":")||p.startsWith("*")){const f=p.startsWith("*"),y=p.indexOf(" "),m=p.indexOf(" ",y+1),g=p.indexOf(" ",m+1),b=p.indexOf(" ",g+1);if(b===-1)return;const x=on(parseFloat(p.substring(y+1,m)),n),k=on(parseFloat(p.substring(m+1,g)),n),v=x+k;i===""&&(o=x);const w=p.substring(b+1);if(w.trim()==="~"){c&&(c.endTime=v);return}let M=w;M.startsWith("~")&&(M=M.substring(1)),l?(h(),u=M.trimEnd(),c={text:"",startTime:x,endTime:v,isGolden:f}):c?(u+=M.trimEnd(),c.endTime=v,f&&(c.isGolden=!0)):(u=M.trimEnd(),c={text:"",startTime:x,endTime:v,isGolden:f}),l=w.endsWith(" ")}}}),h(),i.trim().length>0&&a.push({text:i.trim(),timestamp:o,words:s}),a},Zi=(e,t)=>{const n=t??La(e),a=[];let s=[],i=0;function o(){s.length>0&&(a.push({timestamp:i,syllables:[...s]}),s=[])}return e.forEach(l=>{if(!(l.startsWith("#")||l.startsWith("E"))){if(l.startsWith("-")){o();const c=l.trim().split(/\s+/);if(c.length>=2){const u=parseFloat(c[1]);isFinite(u)&&(i=on(u,n))}}else if(l.startsWith(":")||l.startsWith("*")){const c=l.startsWith("*"),u=l.indexOf(" "),h=l.indexOf(" ",u+1),p=l.indexOf(" ",h+1),f=l.indexOf(" ",p+1);if(f===-1)return;const y=parseFloat(l.substring(u+1,h)),m=parseFloat(l.substring(h+1,p)),g=on(y,n),b=g+on(m,n);s.length===0&&(i=g);const x=l.substring(f+1);if(x.trim()==="~"){s.length>0&&(s[s.length-1].endTime=b);return}let k=x;k.startsWith("~")&&(k=k.substring(1));const v=x.endsWith(" "),w=v?k.slice(0,-1):k;s.push({text:w,startTime:g,endTime:b,isGolden:c,hasTrailingSpace:v})}}}),o(),a},ku=(e,t,n=3)=>{const a=[];let s=-1;for(let i=0;i<e.length;i++){const o=e[i].timestamp,l=e[i+1]?e[i+1].timestamp:o+5;if(t>=o&&t<l){s=i;break}}if(s>=0){const i=Math.max(0,s-(n-1));for(let o=i;o<=s;o++)a.push(e[o].text)}return a},wu=(e,t)=>{const n=[];for(const a of e)for(const s of a.words)t>=s.startTime&&t<=s.endTime&&n.push(s);return n},Ms="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",Rs="var(--karaoke-gold-glow-first, 0 0 12px #FFD700)",ju="var(--karaoke-active-glow, 0 0 10px rgba(0,229,255,0.6), 0 0 4px rgba(255,230,0,0.4))",Cu="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",Mu=({song:e,currentTime:t})=>{const n=d.useMemo(()=>!e||!e.notes.length?[]:Zi(e.notes.map(l=>l.noteLine),e.bpm??void 0),[e]),a=t-(e.gap??0)/1e3;let s=-1;for(let l=0;l<n.length;l++){const c=n[l].timestamp,u=l+1<n.length?n[l+1].timestamp:c+30;if(a>=c&&a<u){s=l;break}}const i=s>=0?n[s]:null,o=s>=0&&s+1<n.length?n[s+1]:null;return r.jsx("div",{className:"karaoke-lyrics",style:{textAlign:"center",fontSize:"28px",marginTop:"20px",minHeight:"80px",textShadow:"var(--karaoke-outline, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000)",fontWeight:700,fontStyle:"italic",fontFamily:"var(--karaoke-font-family, Arial)"},children:i?r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"var(--karaoke-primary-text, #fff)",margin:"5px 0",lineHeight:1.4,textShadow:ju,background:"var(--karaoke-active-bg, linear-gradient(90deg, transparent 0%, rgba(0,229,255,0.08) 20%, rgba(255,230,0,0.06) 80%, transparent 100%))",borderRadius:8,padding:"2px 10px",transition:"text-shadow 0.3s ease, background 0.3s ease"},children:i.syllables.map((l,c)=>{let u=0;a>=l.endTime?u=1:a>l.startTime&&(u=(a-l.startTime)/(l.endTime-l.startTime));const h=Math.round(u*100),p=l.text+(l.hasTrailingSpace?" ":""),f=u>0&&u<1,y=l.isGolden;return u<=0?r.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",transition:"color 0.15s ease"},children:p},c):u>=1?r.jsx("span",{style:{background:y?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Ms,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:y?`drop-shadow(${Rs})`:"none",transition:"filter 0.2s ease"},children:p},c):r.jsxs("span",{style:{position:"relative",display:"inline",filter:f?y?`drop-shadow(${Rs})`:`drop-shadow(${Cu})`:"none",transition:"filter 0.15s ease"},children:[r.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",visibility:"visible"},children:p}),r.jsx("span",{style:{position:"absolute",left:0,top:0,background:y?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Ms,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",clipPath:`inset(0 ${100-h}% 0 0)`,pointerEvents:"none"},children:p})]},c)})}),o&&r.jsx("p",{style:{color:"var(--karaoke-next-text, #666)",margin:"5px 0",lineHeight:1.4,fontSize:"22px",transition:"opacity 0.3s ease"},children:o.syllables.map((l,c)=>r.jsx("span",{style:{color:l.isGolden?"var(--karaoke-golden-next, rgba(255,215,0,0.5))":"var(--karaoke-next-dim, #777)"},children:l.text+(l.hasTrailingSpace?" ":"")},c))})]}):n.length>0?r.jsx("p",{style:{color:"var(--karaoke-waiting-text, #999)"},children:r.jsx(se.NtdMusic,{size:20})}):r.jsxs("p",{style:{color:"var(--karaoke-waiting-text, #999)",display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(se.NtdMicrophone,{size:18})," Waiting for lyrics..."]})})},Da=d.memo(Mu),Vr={},Ru=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:xt&&xt.tagName.toUpperCase()==="SCRIPT"&&xt.src||new URL("index.cjs",document.baseURI).href}<"u"&&(Vr==null?void 0:Vr.VITE_DEBUG_KARAOKE)==="true";function oa(e,t,...n){(Ru||typeof window<"u"&&window.DEBUG_KARAOKE)&&console.log(`%c[KARAOKE-DEBUG]%c [${e}] ${t}`,"background:var(--nice-accent-dark, #6c3483);color:var(--nice-bg, #FFF);padding: var(--nice-space-px, 1px) var(--nice-space-1, 4px);border-radius:var(--nice-radius-sm, 3px);font-weight:bold","color:var(--nice-accent-dark, #6c3483);font-weight:bold",...n)}const Xi=e=>{for(const t of e){const n=t.trim();if(n.toUpperCase().startsWith("#BPM:")){const a=parseFloat(n.substring(5).replace(",","."));if(isFinite(a)&&a>0)return a}}return null},Ns=(e,t)=>t&&t>0?e*15/t:e/10,qn=(e,t)=>{const n=t??Xi(e),a=[];let s=[];return e.forEach(i=>{const o=i.split(" ");if(!(o.length<4))if(i.startsWith("-"))s.length>0&&(a.push(s),s=[]);else{const l=(o[0]||"").charAt(0),c=l==="*"||l==="G";s.push({startTime:Ns(parseFloat(o[1]),n),duration:Ns(parseFloat(o[2]),n),pitch:parseInt(o[3],10),isGold:c})}}),s.length>0&&a.push(s),a},Qi=(e,t)=>{let a=(Math.round(12*Math.log2(e/440)+69)%12+12)%12;if(t!==null){for(;a-t>6;)a-=12;for(;a-t<-6;)a+=12}return a},Nu=it.scoped("karaokeScoringConfig"),_a={easy:{semitoneTolerance:2,preWindow:.25,postExtra:.3,difficultyMult:.9},normal:{semitoneTolerance:1,preWindow:.15,postExtra:.2,difficultyMult:1},hard:{semitoneTolerance:0,preWindow:.08,postExtra:.12,difficultyMult:1.05}},Tu="karaoke.scoringPresets";function $u(){try{const e=localStorage.getItem(Tu);return e?JSON.parse(e):null}catch(e){return Nu.warn("Failed to parse scoring presets overrides",e),null}}function Ji(e){const t={..._a},n=$u();return n&&Object.keys(n).forEach(a=>{const s=n[a];s&&(t[a]={...t[a],...s})}),e&&Object.keys(e).forEach(a=>{const s=e[a];s&&(t[a]={...t[a],...s})}),t}exports.ScoringPresets=Ji();const Pu=async e=>{try{let t=null;if(e?t=await e.getKaraokeScoringConfig():(console.debug("[karaokeScoringConfig] No fetcher provided, using defaults"),t=null),t&&t.presets)return exports.ScoringPresets=Ji(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},Ir=(e="normal")=>exports.ScoringPresets[e]||_a.normal;function la(e){if(typeof document>"u")return e;const t=/var\(\s*([^,\s)]+)\s*(?:,\s*([^)]+))?\)/,n=e.match(t);if(n){const a=n[1],s=n[2]?n[2].trim():"",i=getComputedStyle(document.documentElement).getPropertyValue(a).trim();return i||s||e}return e}function Au(e){if(!e)return[128,128,128];const t=e.match(/^#([0-9a-f]{3,8})$/i);if(t){let a=t[1];if(a.length===3&&(a=a[0]+a[0]+a[1]+a[1]+a[2]+a[2]),a.length>=6)return[parseInt(a.slice(0,2),16),parseInt(a.slice(2,4),16),parseInt(a.slice(4,6),16)]}const n=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);return n?[+n[1],+n[2],+n[3]]:[128,128,128]}const Eu=3,ee=Eu;function Ut(e){const t=e/2|0;return{w:t,out:`M${t} 0H${t}V${e}H${t}A${t} ${t} 0 0 1 0 ${t}A${t} ${t} 0 0 1 ${t} 0Z`,inn:`M${t} ${ee}V${e-ee}A${t-ee} ${t-ee} 0 0 1 ${ee} ${t}A${t-ee} ${t-ee} 0 0 1 ${t} ${ee}Z`}}function ln(e){return{w:ee+1,out:`M0 0H${ee+1}V${e}H0Z`,inn:`M${ee} ${ee}H${ee+1}V${e-ee}H${ee}Z`}}function Fa(e){const t=Math.min(14,e*.22)|0,n=t+2,a=Math.max(t-ee,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}V${t}Q0 0 ${t} 0Z`,inn:`M${ee+a} ${ee}H${n}V${e-ee}H${ee+a}Q${ee} ${e-ee} ${ee} ${e-ee-a}V${ee+a}Q${ee} ${ee} ${ee+a} ${ee}Z`}}function jr(e){const t=e*.3|0,n=t+2,a=Math.max(t-ee,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e-t}V${t}Z`,inn:`M${ee+a} ${ee}H${n}V${e-ee}H${ee+a}L${ee} ${e-ee-a}V${ee+a}Z`}}function zt(e){const t=e*.42|0,n=t+2,a=Math.max(t-(ee*1.4|0),2);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e/2}Z`,inn:`M${ee+a} ${ee}H${n}V${e-ee}H${ee+a}L${ee} ${e/2}Z`}}function Cr(e){const t=e*.3|0,n=t+4,a=Math.max(t-ee,1);return{w:n,out:`M${t} 0H${n}V${e}H${t*.6|0}L0 ${e-t}V${t}Q0 0 ${t} 0Z`,inn:`M${ee+a} ${ee}H${n}V${e-ee}H${ee+(a*.6|0)}L${ee} ${e-ee-a}V${ee+a}Q${ee} ${ee} ${ee+a} ${ee}Z`}}function za(e){const t=e*.16|0,n=t*2+4;return{w:n,out:`M${t*1.5|0} 0H${n}V${e}H${t*1.5|0}C${t*2.5|0} ${e*.35|0} ${t*2.5|0} ${e*.65|0} ${t*1.5|0} ${e}Z`,inn:`M${ee+(t*1.2|0)} ${ee}H${n}V${e-ee}H${ee+(t*1.2|0)}C${ee+(t*2.2|0)} ${e*.37|0} ${ee+(t*2.2|0)} ${e*.63|0} ${ee+(t*1.2|0)} ${e-ee}Z`}}function Oa(e){const t=e*.32|0,n=t+3,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}Z`,inn:`M${ee} ${ee}H${n}V${e-ee}H${ee+a}Q${ee} ${e-ee} ${ee} ${e-ee-a}Z`}}function Mr(e){const t=e*.14|0,n=t*3+2;return{w:n,out:`M${t*2} 0H${n}V${e}H${t*2}C${t*.5|0} ${e*.8|0} ${t*3} ${e*.55|0} ${t*.5|0} ${e*.35|0}S${t} 0 ${t*2} 0Z`,inn:`M${ee+(t*1.8|0)} ${ee}H${n}V${e-ee}H${ee+(t*1.8|0)}C${ee+(t*.4|0)} ${e*.78|0} ${ee+(t*2.8|0)} ${e*.55|0} ${ee+(t*.4|0)} ${e*.37|0}S${ee+(t*.9|0)} ${ee} ${ee+(t*1.8|0)} ${ee}Z`}}function Ba(e){const t=e*.09|0,n=e*.35|0;return{w:n,out:`M${t*3} 0H${n}V${e}H${t*3}L${t} ${e-t*2}L${t*2} ${e*.65|0}L0 ${e/2|0}L${t*2} ${e*.35|0}L${t} ${t*2}Z`,inn:`M${ee+(t*2.5|0)} ${ee}H${n}V${e-ee}H${ee+(t*2.5|0)}L${ee+(t*.7|0)} ${e-ee-(t*1.6|0)}L${ee+(t*1.7|0)} ${e*.64|0}L${ee} ${e/2|0}L${ee+(t*1.7|0)} ${e*.36|0}L${ee+(t*.7|0)} ${ee+(t*1.6|0)}Z`}}function dr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M${t} 0H${n}V${e}H0Z`,inn:`M${ee+t-(ee*1.3|0)} ${ee}H${n}V${e-ee}H${ee+1}Z`}}function ca(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}V${e}H${t}Z`,inn:`M${ee} ${ee}H${n}V${e-ee}H${ee+t-(ee*1.3|0)+1}Z`}}function _t(e){const t=e/2|0;return{w:t,out:`M0 0A${t} ${t} 0 0 1 ${t} ${t}A${t} ${t} 0 0 1 0 ${e}Z`,inn:`M0 ${ee}A${t-ee} ${t-ee} 0 0 1 ${t-ee} ${t}A${t-ee} ${t-ee} 0 0 1 0 ${e-ee}Z`}}function cn(e){return{w:ee+1,out:`M0 0H${ee+1}V${e}H0Z`,inn:`M0 ${ee}H1V${e-ee}H0Z`}}function eo(e){const t=Math.min(14,e*.22)|0,n=t+2,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n-t}Q${n} 0 ${n} ${t}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-a}Q${n-ee} ${ee} ${n-ee} ${ee+a}V${e-ee-a}Q${n-ee} ${e-ee} ${n-ee-a} ${e-ee}H0Z`}}function dn(e){const t=e*.3|0,n=t+2,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n-t}L${n} ${t}V${e-t}L${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-a}L${n-ee} ${ee+a}V${e-ee-a}L${n-ee-a} ${e-ee}H0Z`}}function Tt(e){const t=e*.42|0,n=t+2,a=Math.max(t-(ee*1.4|0),2);return{w:n,out:`M0 0H${n-t}L${n} ${e/2}L${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-a}L${n-ee} ${e/2}L${n-ee-a} ${e-ee}H0Z`}}function to(e){const t=e*.3|0,n=t+4,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n-t}Q${n} 0 ${n} ${t}V${e-t}L${n-(t*.6|0)} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-a}Q${n-ee} ${ee} ${n-ee} ${ee+a}V${e-ee-a}L${n-ee-(a*.6|0)} ${e-ee}H0Z`}}function no(e){const t=e*.16|0,n=t*2+4;return{w:n,out:`M0 0H${n-(t*1.5|0)}C${n-(t*2.5|0)} ${e*.35|0} ${n-(t*2.5|0)} ${e*.65|0} ${n-(t*1.5|0)} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-(t*1.2|0)}C${n-ee-(t*2.2|0)} ${e*.37|0} ${n-ee-(t*2.2|0)} ${e*.63|0} ${n-ee-(t*1.2|0)} ${e-ee}H0Z`}}function ro(e){const t=e*.32|0,n=t+3,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee}V${e-ee-a}Q${n-ee} ${e-ee} ${n-ee-a} ${e-ee}H0Z`}}function Ga(e){const t=e*.14|0,n=t*3+2;return{w:n,out:`M0 0H${n-t*2}C${n-t} 0 ${n+(t*.3|0)} ${e*.2|0} ${n-(t*.5|0)} ${e*.35|0}S${n-(t*.5|0)} ${e*.8|0} ${n-t*2} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-(t*1.8|0)}C${n-ee-(t*.9|0)} ${ee} ${n-ee+(t*.1|0)} ${e*.22|0} ${n-ee-(t*.4|0)} ${e*.37|0}S${n-ee-(t*.4|0)} ${e*.78|0} ${n-ee-(t*1.8|0)} ${e-ee}H0Z`}}function Rr(e){const t=e*.09|0,n=e*.35|0;return{w:n,out:`M0 0H${n-t*3}L${n-t} ${t*2}L${n-t*2} ${e*.35|0}L${n} ${e/2|0}L${n-t*2} ${e*.65|0}L${n-t} ${e-t*2}L${n-t*3} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-(t*2.5|0)}L${n-ee-(t*.7|0)} ${ee+(t*1.6|0)}L${n-ee-(t*1.7|0)} ${e*.36|0}L${n-ee} ${e/2|0}L${n-ee-(t*1.7|0)} ${e*.64|0}L${n-ee-(t*.7|0)} ${e-ee-(t*1.6|0)}L${n-ee-(t*2.5|0)} ${e-ee}H0Z`}}function da(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}L${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee}L${n-ee-t+(ee*1.3|0)} ${e-ee}H0Z`}}function ur(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n-t}L${n} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-t+(ee*1.3|0)}L${n-ee} ${e-ee}H0Z`}}const Wa=[{name:"Pill",L:Ut,R:_t},{name:"Sharp",L:ln,R:cn},{name:"Soft",L:Fa,R:eo},{name:"Chamfer",L:jr,R:dn},{name:"Arrow",L:zt,R:Tt},{name:"Shield",L:Cr,R:to},{name:"Bracket",L:za,R:no},{name:"Tab",L:Oa,R:ro},{name:"Wave",L:Mr,R:Ga},{name:"Ornate",L:Ba,R:Rr}],ao=[{name:"Pill→Arrow",L:Ut,R:Tt},{name:"Arrow→Pill",L:zt,R:_t},{name:"Pill→Sharp",L:Ut,R:cn},{name:"Sharp→Pill",L:ln,R:_t},{name:"Pill→Chamfer",L:Ut,R:dn},{name:"Chamfer→Pill",L:jr,R:_t},{name:"Arrow→Sharp",L:zt,R:cn},{name:"Sharp→Arrow",L:ln,R:Tt},{name:"Arrow→Chamfer",L:zt,R:dn},{name:"Chamfer→Arrow",L:jr,R:Tt},{name:"Soft→Arrow",L:Fa,R:Tt},{name:"Shield→Chamfer",L:Cr,R:dn},{name:"Pill→Wave",L:Ut,R:Ga},{name:"Wave→Arrow",L:Mr,R:Tt},{name:"Tab→Pill",L:Oa,R:_t},{name:"Ornate→Sharp",L:Ba,R:cn},{name:"Sharp→Ornate",L:ln,R:Rr},{name:"Bracket→Arrow",L:za,R:Tt},{name:"Shield→Pill",L:Cr,R:_t},{name:"Wave→Ornate",L:Mr,R:Rr}],so=[{name:"Skew ╲",L:dr,R:da},{name:"Skew ╱",L:ca,R:ur},{name:"◇ Romb",L:zt,R:Tt},{name:"╲→Pill",L:dr,R:_t},{name:"Pill→╲",L:Ut,R:da},{name:"╱→Sharp",L:ca,R:cn},{name:"Sharp→╱",L:ln,R:ur},{name:"╲→Arrow",L:dr,R:Tt},{name:"Arrow→╱",L:zt,R:ur},{name:"◇→Chamfer",L:zt,R:dn}],Bn=[...Wa,...ao,...so],io=Wa[0];function Cn(e){return Bn.find(t=>t.name===e)||io}const Nr=[{name:"Flames",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="12" height="16" patternUnits="userSpaceOnUse"><path d="M6 0C8 3 10 5 9 9C8 12 6 14 6 16C6 14 4 12 3 9C2 5 4 3 6 0Z" fill="${t}" opacity=".5"/><path d="M3 6C4 8 5 10 3 14C1 10 2 8 3 6Z" fill="${a}" opacity=".3"/><path d="M9 6C10 8 11 10 9 14C7 10 8 8 9 6Z" fill="${a}" opacity=".3"/></pattern>`}},{name:"Zigzag",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M0 5L5 0L10 5L5 10Z" fill="${n||t}" fill-opacity=".15" stroke="${t}" stroke-width="1.2" opacity=".55"/></pattern>`},{name:"Scales",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="12" height="8" patternUnits="userSpaceOnUse"><ellipse cx="6" cy="8" rx="6" ry="4.5" fill="none" stroke="${t}" stroke-width="1" opacity=".5"/><ellipse cx="0" cy="4" rx="6" ry="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".3"/><ellipse cx="12" cy="4" rx="6" ry="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".3"/></pattern>`}},{name:"Hex",mk:(e,t,n)=>`<pattern id="${e}" width="18" height="20" patternUnits="userSpaceOnUse"><path d="M9 2L16 6V14L9 18L2 14V6Z" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M9 12L13.5 14.5V19L9 21.5L4.5 19V14.5Z" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Dots",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="8" height="8" patternUnits="userSpaceOnUse"><circle cx="4" cy="4" r="2" fill="${t}" opacity=".5"/><circle cx="0" cy="0" r="1" fill="${a}" opacity=".3"/><circle cx="8" cy="8" r="1" fill="${a}" opacity=".3"/></pattern>`}},{name:"Stars",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M7 1L8.8 5.2L13.2 5.2L9.7 7.8L11 12.2L7 9.4L3 12.2L4.3 7.8L.8 5.2L5.2 5.2Z" fill="${t}" opacity=".45" stroke="${n||t}" stroke-width=".4" stroke-opacity=".3"/></pattern>`},{name:"Diamonds",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M5 .5L9.5 5L5 9.5L.5 5Z" fill="${n||"none"}" fill-opacity=".15" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Waves",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="8" patternUnits="userSpaceOnUse"><path d="M0 4Q4 0 8 4Q12 8 16 4" fill="none" stroke="${t}" stroke-width="1.3" opacity=".5"/><path d="M0 6Q4 2 8 6Q12 10 16 6" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Crosses",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M5 2V8" stroke="${t}" stroke-width="1.3" stroke-linecap="round" opacity=".5"/><path d="M2 5H8" stroke="${n||t}" stroke-width="1.3" stroke-linecap="round" opacity=".5"/></pattern>`},{name:"Triangles",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M6 1L11 9H1Z" fill="${n||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Chevrons",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M0 7L6 1.5L12 7" fill="none" stroke="${t}" stroke-width="1.2" opacity=".55"/><path d="M0 10L6 4.5L12 10" fill="none" stroke="${n||t}" stroke-width=".7" opacity=".25"/></pattern>`},{name:"Hatch ╲",mk:(e,t,n)=>`<pattern id="${e}" width="6" height="6" patternUnits="userSpaceOnUse"><path d="M0 6L6 0" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M-1 1L1 -1M5 7L7 5" stroke="${n||t}" stroke-width=".8" opacity=".3"/></pattern>`},{name:"Hatch ╳",mk:(e,t,n)=>`<pattern id="${e}" width="7" height="7" patternUnits="userSpaceOnUse"><path d="M0 7L7 0" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M0 0L7 7" stroke="${n||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Grid",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M10 0V10" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M0 10H10" fill="none" stroke="${n||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Bricks",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="8" patternUnits="userSpaceOnUse"><rect width="14" height="8" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><line x1="7" y1="0" x2="7" y2="4" stroke="${n||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Hearts",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="12" patternUnits="userSpaceOnUse"><path d="M6 10C4 8 1 6.5 1 4C1 2.3 2.8 1 4.5 2.2L6 4L7.5 2.2C9.2 1 11 2.3 11 4C11 6.5 8 8 6 10Z" fill="${t}" opacity=".4" stroke="${n||t}" stroke-width=".5" stroke-opacity=".3"/></pattern>`},{name:"Arrows",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M3 2L9 5L3 8" fill="${n||"none"}" fill-opacity=".15" stroke="${t}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity=".5"/></pattern>`},{name:"Bolts",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="16" patternUnits="userSpaceOnUse"><path d="M7 1L4 7H8L3 15" fill="none" stroke="${t}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity=".5"/><circle cx="5" cy="11" r="1" fill="${n||t}" opacity=".3"/></pattern>`},{name:"Leaves",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M7 2C10 4 12 7 10 11C8 13 5 12 4 10C3 7 4 4 7 2Z" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M7 3L6 10" stroke="${a}" stroke-width=".6" opacity=".3"/><path d="M5 5L7 6M5 8L7 7.5" stroke="${a}" stroke-width=".4" opacity=".25"/></pattern>`}},{name:"Spirals",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="16" patternUnits="userSpaceOnUse"><path d="M8 4A4 4 0 0 1 12 8A3.5 3.5 0 0 1 8.5 11.5A2.5 2.5 0 0 1 6 9A1.5 1.5 0 0 1 7.5 7.5" fill="none" stroke="${t}" stroke-width="1.2" stroke-linecap="round" opacity=".45"/><circle cx="8" cy="8" r="1" fill="${n||t}" opacity=".25"/></pattern>`},{name:"Moons",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M9 2A5 5 0 1 0 9 12" fill="none" stroke="${t}" stroke-width="1" opacity=".4"/><path d="M9 2A3.5 3.5 0 0 1 9 12" fill="none" stroke="${n||t}" stroke-width="1" opacity=".3"/></pattern>`},{name:"Rings",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="12" patternUnits="userSpaceOnUse"><circle cx="6" cy="6" r="4" fill="none" stroke="${t}" stroke-width="1.2" opacity=".5"/><circle cx="6" cy="6" r="2" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Teeth",mk:(e,t,n)=>`<pattern id="${e}" width="8" height="10" patternUnits="userSpaceOnUse"><path d="M0 10V4L4 0L8 4V10" fill="${n||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Swirl",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="10" patternUnits="userSpaceOnUse"><path d="M0 5C3 0 6 0 8 5C10 10 13 10 16 5" fill="none" stroke="${t}" stroke-width="1.3" opacity=".5"/><path d="M0 7C3 2 6 2 8 7C10 12 13 12 16 7" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".2"/></pattern>`},{name:"Chain",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="16" patternUnits="userSpaceOnUse"><ellipse cx="5" cy="4" rx="3.5" ry="4" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><ellipse cx="5" cy="12" rx="3.5" ry="4" fill="none" stroke="${n||t}" stroke-width="1" opacity=".45"/></pattern>`},{name:"Feathers",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="18" patternUnits="userSpaceOnUse"><path d="M6 1C9 5 10 9 6 17" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M6 1C3 5 2 9 6 17" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M4 5L6 4L8 5M4 9L6 8L8 9M4 13L6 12L8 13" stroke="${n||t}" stroke-width=".5" opacity=".3"/></pattern>`},{name:"DNA",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="18" patternUnits="userSpaceOnUse"><path d="M3 0C3 4.5 11 4.5 11 9S3 13.5 3 18" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M11 0C11 4.5 3 4.5 3 9S11 13.5 11 18" fill="none" stroke="${n||t}" stroke-width="1" opacity=".45"/></pattern>`},{name:"Bubbles",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="18" height="18" patternUnits="userSpaceOnUse"><circle cx="5" cy="5" r="3.5" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><circle cx="14" cy="12" r="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".35"/><circle cx="11" cy="3" r="1.8" fill="${a}" opacity=".25"/></pattern>`}},{name:"Celtic",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="16" patternUnits="userSpaceOnUse"><path d="M8 2C12 2 14 4 14 8C14 12 12 14 8 14C4 14 2 12 2 8C2 4 4 2 8 2Z" fill="none" stroke="${t}" stroke-width=".8" opacity=".35"/><path d="M4 4L12 12M12 4L4 12" stroke="${n||t}" stroke-width=".6" opacity=".2"/></pattern>`},{name:"Squares",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><rect x="1.5" y="1.5" width="7" height="7" rx="1" fill="${n||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`}];function Mn(e){return Nr.find(t=>t.name===e)||null}const Vt={color:null,capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,glass:0,textureUrl:null,textureScale:1},Lr={...Vt,glass:85},Dr={...Vt,patternName:"Stars"},_r={...Vt,patternName:"Stars"},Fr={fontFamily:null,fontSize:18,fontColor:null,outlineColor:null,outlineWidth:0,shadow:null},oo={filledBar:{...Vt},emptyBar:{...Lr},goldFilledBar:{..._r},goldEmptyBar:{...Dr},font:{...Fr},disableGoldNotes:!1},un={capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,emptyGlass:85,filledTextureUrl:null,emptyTextureUrl:null,textureScale:1,emptyPreset:"custom",goldPatternName:"Stars",goldPatternColor:null,goldHitPatternName:"Stars",goldHitPatternColor:null,goldEmptyTextureUrl:null,goldFilledTextureUrl:null,fontFamily:null,fontSize:18,fontColor:null,fontOutlineColor:null,fontOutlineWidth:0,fontShadow:null},Ts="nice2dev-player-bar-style",$s="nice2dev-player-karaoke-settings";function hn(e){return e!=null?`${$s}-${e}`:$s}function Wn(e){return e!=null?`${Ts}-${e}`:Ts}function Ps(e){return{filledBar:{color:null,capStyleName:e.capStyleName,patternName:e.patternName,patternColor:e.patternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.filledTextureUrl,textureScale:e.textureScale},emptyBar:{color:null,capStyleName:e.capStyleName,patternName:e.patternName,patternColor:e.patternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:e.emptyGlass,textureUrl:e.emptyTextureUrl,textureScale:e.textureScale},goldFilledBar:{color:null,capStyleName:e.capStyleName,patternName:e.goldHitPatternName,patternColor:e.goldHitPatternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.goldFilledTextureUrl,textureScale:e.textureScale},goldEmptyBar:{color:null,capStyleName:e.capStyleName,patternName:e.goldPatternName,patternColor:e.goldPatternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.goldEmptyTextureUrl,textureScale:e.textureScale},font:{fontFamily:e.fontFamily,fontSize:e.fontSize,fontColor:e.fontColor,outlineColor:e.fontOutlineColor,outlineWidth:e.fontOutlineWidth,shadow:e.fontShadow}}}function As(e){const t=oo,n=(s,i)=>!i||typeof i!="object"?{...s}:{...s,...i},a=(s,i)=>!i||typeof i!="object"?{...s}:{...s,...i};return{filledBar:n(t.filledBar,e.filledBar),emptyBar:n(t.emptyBar,e.emptyBar),goldFilledBar:n(t.goldFilledBar,e.goldFilledBar),goldEmptyBar:n(t.goldEmptyBar,e.goldEmptyBar),font:a(t.font,e.font),disableGoldNotes:typeof e.disableGoldNotes=="boolean"?e.disableGoldNotes:t.disableGoldNotes}}function Ua(e){try{const t=localStorage.getItem(hn(e));if(t){const a=JSON.parse(t);return As(a)}const n=localStorage.getItem(Wn(e));if(n){const a=JSON.parse(n),s=Ps({...un,...a});return localStorage.setItem(hn(e),JSON.stringify(s)),s}if(e!=null){const a=localStorage.getItem(hn());if(a)return As(JSON.parse(a));const s=localStorage.getItem(Wn());if(s)return Ps({...un,...JSON.parse(s)})}}catch{}return{filledBar:{...Vt},emptyBar:{...Lr},goldFilledBar:{..._r},goldEmptyBar:{...Dr},font:{...Fr}}}function Iu(e,t){const n=JSON.stringify(e);localStorage.setItem(hn(t),n)}let Es=!1;async function Lu(e){if(Es||(Es=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(hn())||localStorage.setItem(hn(),t)}catch{}}function Du(e){const t=new Map;for(const n of e)t.set(n,Ua(n));return t}function lo(e){try{const t=localStorage.getItem(Wn(e));if(t)return{...un,...JSON.parse(t)};if(e!=null){const n=localStorage.getItem(Wn());if(n)return{...un,...JSON.parse(n)}}}catch{}return{...un}}function _u(e,t){localStorage.setItem(Wn(t),JSON.stringify(e))}function Fu(e){const t=new Map;for(const n of e)t.set(n,lo(n));return t}const zu={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Ou=/[&<>"']/g;function Bu(e){return e.replace(Ou,t=>zu[t])}function Gu(e){const t=e.trim().toLowerCase();return!!(t.startsWith("http://")||t.startsWith("https://")||t.startsWith("blob:")||t.startsWith("data:image/")||t.startsWith("/")||t.startsWith("./")||t.startsWith("../"))}const Wu=3,Xe=Wu;function Tr(e){const t=parseInt(e.slice(1,3),16)/255,n=parseInt(e.slice(3,5),16)/255,a=parseInt(e.slice(5,7),16)/255,s=Math.max(t,n,a),i=Math.min(t,n,a);let o=0,l=0;const c=(s+i)/2;if(s!==i){const u=s-i;switch(l=c>.5?u/(2-s-i):u/(s+i),s){case t:o=((n-a)/u+(n<a?6:0))/6;break;case n:o=((a-t)/u+2)/6;break;case a:o=((t-n)/u+4)/6;break}}return[Math.round(o*360),Math.round(l*100),Math.round(c*100)]}function $r(e){let t=e.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),"#"+t.toLowerCase()}function dt(e,t){return e.replace(/([MLHVCSQTAZ])/gi,`
2
2
  $1`).split(`
3
- `).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 o=0;o<a.length;o+=2)a[o]+=t;return r+a.join(" ")}return r==="A"&&a.length>=7?(a[5]+=t,r+a.join(" ")):n}).join("")}function Mo(e){const{width:t,height:n,capStyle:r,color:a,highlight:o=70,glow:i=55,glass:l=0,pattern:c=null,patternColor:d=null,patternOnly:f=!1,textureUrl:h=null,textureScale:m=1}=e,y=h&&Od(h)?Fd(h):null,[p,v,x]=or(ir(a)),b="c"+Math.random().toString(36).slice(2,7),S=r.L(n),g=r.R(n),k=t-S.w-g.w;if(k<4)return"";if(f&&c){const J=`hsl(${p},${v}%,${x}%)`,ae=`hsl(${p},${Math.max(v-20,0)}%,${Math.min(x+30,95)}%)`,re=d||ae,ee=S.w,D=S.w+k,K=S.inn,se=`M${ee} ${We}H${D}V${n-We}H${ee}Z`,ce=et(g.inn,D),pe=S.out,X=`M${ee} 0H${D}V${n}H${ee}Z`,fe=et(g.out,D),be=c.mk(b+"pat",re,d||void 0),Re=Math.round(256*m),Fe=Math.round(256*m),Te=y?`<pattern id="${b}tex" patternUnits="userSpaceOnUse" width="${Re}" height="${Fe}"><image href="${y}" width="${Re}" height="${Fe}" preserveAspectRatio="none"/></pattern>`:"",Se=y?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${b}tex)" opacity=".85" clip-path="url(#${b}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
4
- ${be}
5
- ${Te}
6
- <clipPath id="${b}c"><path d="${K}"/><path d="${se}"/><path d="${ce}"/></clipPath>
3
+ `).filter(Boolean).map(n=>{const a=n[0],s=n.slice(1).trim().split(/[\s,]+/).map(Number);if(a==="H")return`H${s[0]+t}`;if(a==="V"||a==="Z")return n;if("MLCSQT".includes(a.toUpperCase())){for(let i=0;i<s.length;i+=2)s[i]+=t;return a+s.join(" ")}return a==="A"&&s.length>=7?(s[5]+=t,a+s.join(" ")):n}).join("")}function co(e){const{width:t,height:n,capStyle:a,color:s,highlight:i=70,glow:o=55,glass:l=0,pattern:c=null,patternColor:u=null,patternOnly:h=!1,textureUrl:p=null,textureScale:f=1}=e,y=p&&Gu(p)?Bu(p):null,[m,g,b]=Tr($r(s)),x="c"+Math.random().toString(36).slice(2,7),k=a.L(n),v=a.R(n),w=t-k.w-v.w;if(w<4)return"";if(h&&c){const X=`hsl(${m},${g}%,${b}%)`,ie=`hsl(${m},${Math.max(g-20,0)}%,${Math.min(b+30,95)}%)`,le=u||ie,te=k.w,H=k.w+w,K=k.inn,oe=`M${te} ${Xe}H${H}V${n-Xe}H${te}Z`,re=dt(v.inn,H),he=k.out,Q=`M${te} 0H${H}V${n}H${te}Z`,de=dt(v.out,H),me=c.mk(x+"pat",le,u||void 0),xe=Math.round(256*f),ce=Math.round(256*f),ye=y?`<pattern id="${x}tex" patternUnits="userSpaceOnUse" width="${xe}" height="${ce}"><image href="${y}" width="${xe}" height="${ce}" preserveAspectRatio="none"/></pattern>`:"",Se=y?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${x}tex)" opacity=".85" clip-path="url(#${x}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
4
+ ${me}
5
+ ${ye}
6
+ <clipPath id="${x}c"><path d="${K}"/><path d="${oe}"/><path d="${re}"/></clipPath>
7
7
  </defs>
8
- <path d="${pe}" fill="rgba(255,255,255,.18)"/><path d="${X}" fill="rgba(255,255,255,.18)"/><path d="${fe}" fill="rgba(255,255,255,.18)"/>
9
- <path d="${K}" fill="${J}" opacity=".22"/><path d="${se}" fill="${J}" opacity=".22"/><path d="${ce}" fill="${J}" opacity=".22"/>
8
+ <path d="${he}" fill="rgba(255,255,255,.18)"/><path d="${Q}" fill="rgba(255,255,255,.18)"/><path d="${de}" fill="rgba(255,255,255,.18)"/>
9
+ <path d="${K}" fill="${X}" opacity=".22"/><path d="${oe}" fill="${X}" opacity=".22"/><path d="${re}" fill="${X}" opacity=".22"/>
10
10
  ${Se}
11
- <rect x="0" y="0" width="${t}" height="${n}" fill="url(#${b}pat)" clip-path="url(#${b}c)"/>
12
- </svg>`}const M=`hsl(${p},${Math.min(v+10,100)}%,${Math.max(x-22,4)}%)`,N=`hsl(${p},${v}%,${x}%)`,j=`hsl(${p},${Math.max(v-12,0)}%,${Math.min(x+18,88)}%)`,_=`hsl(${p},${Math.min(v+20,100)}%,${Math.min(x+30,93)}%)`,P=`hsl(${p},${Math.max(v-20,0)}%,${Math.min(x+30,95)}%)`,V=d||P,z=o/100*.78,A=i/100*.65,I=1-l/100*.87,L=We,U=n-We,Y=L+(U-L)*.44,O=L+(U-L)*.58,Z=S.w,H=S.w+k,te=S.out,G=`M${Z} 0H${H}V${n}H${Z}Z`,B=et(g.out,H),w=S.inn,$=`M${Z} ${We}H${H}V${n-We}H${Z}Z`,R=et(g.inn,H),T=c?c.mk(b+"pat",V,d||void 0):"",C=c?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${b}pat)" clip-path="url(#${b}c)"/>`:"",E=Math.round(256*m),F=Math.round(256*m),q=y?`<pattern id="${b}tex" patternUnits="userSpaceOnUse" width="${E}" height="${F}"><image href="${y}" width="${E}" height="${F}" preserveAspectRatio="none"/></pattern>`:"",Q=y?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${b}tex)" opacity="${I*.9}" clip-path="url(#${b}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
13
- ${T}
14
- ${q}
15
- <linearGradient id="${b}b" x1="0" y1="0" x2="0" y2="${n}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="rgba(255,255,255,.55)"/><stop offset=".3" stop-color="rgba(255,255,255,.35)"/><stop offset="1" stop-color="rgba(255,255,255,.08)"/></linearGradient>
16
- <linearGradient id="${b}f" x1="0" y1="${L}" x2="0" y2="${U}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${j}"/><stop offset=".5" stop-color="${N}"/><stop offset="1" stop-color="${M}"/></linearGradient>
17
- <linearGradient id="${b}h" x1="0" y1="${L}" x2="0" y2="${Y}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="var(--nice-bg, #fff)" stop-opacity="${z}"/><stop offset=".5" stop-color="var(--nice-bg, #fff)" stop-opacity="${z*.25}"/><stop offset="1" stop-color="var(--nice-bg, #fff)" stop-opacity="0"/></linearGradient>
18
- <linearGradient id="${b}g" x1="0" y1="${O}" x2="0" y2="${U}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${_}" stop-opacity="0"/><stop offset=".6" stop-color="${_}" stop-opacity="${A*.6}"/><stop offset="1" stop-color="${_}" stop-opacity="${A}"/></linearGradient>
19
- <clipPath id="${b}c"><path d="${w}"/><path d="${$}"/><path d="${R}"/></clipPath>
11
+ <rect x="0" y="0" width="${t}" height="${n}" fill="url(#${x}pat)" clip-path="url(#${x}c)"/>
12
+ </svg>`}const M=`hsl(${m},${Math.min(g+10,100)}%,${Math.max(b-22,4)}%)`,S=`hsl(${m},${g}%,${b}%)`,R=`hsl(${m},${Math.max(g-12,0)}%,${Math.min(b+18,88)}%)`,T=`hsl(${m},${Math.min(g+20,100)}%,${Math.min(b+30,93)}%)`,j=`hsl(${m},${Math.max(g-20,0)}%,${Math.min(b+30,95)}%)`,O=u||j,$=i/100*.78,E=o/100*.65,D=1-l/100*.87,L=Xe,W=n-Xe,Z=L+(W-L)*.44,A=L+(W-L)*.58,_=k.w,U=k.w+w,ne=k.out,V=`M${_} 0H${U}V${n}H${_}Z`,q=dt(v.out,U),C=k.inn,F=`M${_} ${Xe}H${U}V${n-Xe}H${_}Z`,I=dt(v.inn,U),P=c?c.mk(x+"pat",O,u||void 0):"",N=c?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${x}pat)" clip-path="url(#${x}c)"/>`:"",z=Math.round(256*f),B=Math.round(256*f),G=y?`<pattern id="${x}tex" patternUnits="userSpaceOnUse" width="${z}" height="${B}"><image href="${y}" width="${z}" height="${B}" preserveAspectRatio="none"/></pattern>`:"",Y=y?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${x}tex)" opacity="${D*.9}" clip-path="url(#${x}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
13
+ ${P}
14
+ ${G}
15
+ <linearGradient id="${x}b" x1="0" y1="0" x2="0" y2="${n}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="rgba(255,255,255,.55)"/><stop offset=".3" stop-color="rgba(255,255,255,.35)"/><stop offset="1" stop-color="rgba(255,255,255,.08)"/></linearGradient>
16
+ <linearGradient id="${x}f" x1="0" y1="${L}" x2="0" y2="${W}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${R}"/><stop offset=".5" stop-color="${S}"/><stop offset="1" stop-color="${M}"/></linearGradient>
17
+ <linearGradient id="${x}h" x1="0" y1="${L}" x2="0" y2="${Z}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="var(--nice-bg, #fff)" stop-opacity="${$}"/><stop offset=".5" stop-color="var(--nice-bg, #fff)" stop-opacity="${$*.25}"/><stop offset="1" stop-color="var(--nice-bg, #fff)" stop-opacity="0"/></linearGradient>
18
+ <linearGradient id="${x}g" x1="0" y1="${A}" x2="0" y2="${W}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${T}" stop-opacity="0"/><stop offset=".6" stop-color="${T}" stop-opacity="${E*.6}"/><stop offset="1" stop-color="${T}" stop-opacity="${E}"/></linearGradient>
19
+ <clipPath id="${x}c"><path d="${C}"/><path d="${F}"/><path d="${I}"/></clipPath>
20
20
  </defs>
21
- <path d="${te}" fill="url(#${b}b)"/><path d="${G}" fill="url(#${b}b)"/><path d="${B}" fill="url(#${b}b)"/>
22
- <path d="${w}" fill="url(#${b}f)" opacity="${I}"/><path d="${$}" fill="url(#${b}f)" opacity="${I}"/><path d="${R}" fill="url(#${b}f)" opacity="${I}"/>
23
- ${Q}
24
- ${C}
25
- <rect x="0" y="${O}" width="${t}" height="${U-O}" fill="url(#${b}g)" clip-path="url(#${b}c)"/>
26
- <rect x="0" y="${L}" width="${t}" height="${Y-L}" fill="url(#${b}h)" clip-path="url(#${b}c)"/>
27
- </svg>`}function qe(e,t){const n=t.match(/[MLHVCSQTAZmlhvcsqtaz][^MLHVCSQTAZmlhvcsqtaz]*/g);if(!n)return;let r=0,a=0;for(const o of n){const i=o[0],l=o.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]),f=l[3]!==0,h=l[4]!==0,m=l[5],y=l[6],p=r,v=a;if(Math.abs(p-m)<.001&&Math.abs(v-y)<.001||c<.001||d<.001){e.lineTo(m,y),r=m,a=y;break}const x=(c+d)/2,b=(p-m)/2,S=(v-y)/2,g=b*b+S*S,k=g>x*x?Math.sqrt(g):x,M=k*k,N=Math.sqrt(Math.max(0,(M-g)/g)),j=f!==h?1:-1,_=(p+m)/2+j*N*S,P=(v+y)/2-j*N*b,V=Math.atan2(v-P,p-_),z=Math.atan2(y-P,m-_);e.arc(_,P,k,V,z,!h),r=m,a=y;break}case"Z":e.closePath();break}}}function mn(e,t,n,r,a,o,i,l=70,c=55,d=0,f,h,m=!1,y,p){const[v,x,b]=or(ir(i)),S=o.L(a),g=o.R(a),k=r-S.w-g.w;if(k<0){const[w,,$]=or(ir(i));e.save(),e.translate(t,n),e.globalAlpha=1-d/100*.87,e.fillStyle=`hsl(${w},50%,${Math.min($+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 M=S.w,N=S.w+k;if(m){const w=`hsla(${v},${x}%,${b}%,0.22)`;e.save(),e.translate(t,n),e.fillStyle="rgba(255,255,255,0.18)",e.beginPath(),qe(e,S.out),e.fill(),e.fillRect(M,0,k,a),e.beginPath(),qe(e,et(g.out,N)),e.fill(),e.fillStyle=w,e.beginPath(),qe(e,S.inn),e.fill(),e.fillRect(M,We,k,a-2*We),e.beginPath(),qe(e,et(g.inn,N)),e.fill(),y&&(e.save(),e.beginPath(),qe(e,S.inn),e.rect(M,We,k,a-2*We),qe(e,et(g.inn,N)),e.clip(),e.globalAlpha=.85,e.fillStyle=y,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),p&&(e.save(),e.beginPath(),qe(e,S.inn),e.rect(M,We,k,a-2*We),qe(e,et(g.inn,N)),e.clip(),e.globalAlpha=.85,e.fillStyle=p,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),e.restore();return}const j=`hsl(${v},${Math.min(x+10,100)}%,${Math.max(b-22,4)}%)`,_=`hsl(${v},${x}%,${b}%)`,P=`hsl(${v},${Math.max(x-12,0)}%,${Math.min(b+18,88)}%)`,V=`hsl(${v},${Math.min(x+20,100)}%,${Math.min(b+30,93)}%)`,z=l/100*.78,A=c/100*.65,I=1-d/100*.87,L=We,U=a-We,Y=U-L,O=L+Y*.44,Z=L+Y*.58;e.save(),e.translate(t,n);const H=e.createLinearGradient(0,0,0,a);H.addColorStop(0,"rgba(255,255,255,0.55)"),H.addColorStop(.3,"rgba(255,255,255,0.35)"),H.addColorStop(1,"var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))"),e.fillStyle=H,e.beginPath(),qe(e,S.out),e.fill(),e.fillRect(M,0,k,a),e.beginPath(),qe(e,et(g.out,N)),e.fill();const te=e.createLinearGradient(0,L,0,U);te.addColorStop(0,P),te.addColorStop(.5,_),te.addColorStop(1,j),e.globalAlpha=I,e.fillStyle=te,e.beginPath(),qe(e,S.inn),e.fill(),e.fillRect(M,We,k,a-2*We),e.beginPath(),qe(e,et(g.inn,N)),e.fill(),e.globalAlpha=1,y&&(e.save(),e.beginPath(),qe(e,S.inn),e.rect(M,We,k,a-2*We),qe(e,et(g.inn,N)),e.clip(),e.globalAlpha=I*.9,e.fillStyle=y,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),p&&(e.save(),e.beginPath(),qe(e,S.inn),e.rect(M,We,k,a-2*We),qe(e,et(g.inn,N)),e.clip(),e.globalAlpha=I*.85,e.fillStyle=p,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),e.save(),e.beginPath(),qe(e,S.inn),e.rect(M,We,k,a-2*We),qe(e,et(g.inn,N)),e.clip();const G=e.createLinearGradient(0,Z,0,U);G.addColorStop(0,"transparent"),G.addColorStop(.6,V.replace(")",`, ${A*.6})`).replace("hsl","hsla")),G.addColorStop(1,V.replace(")",`, ${A})`).replace("hsl","hsla")),e.fillStyle=G,e.fillRect(0,Z,r,U-Z);const B=e.createLinearGradient(0,L,0,O);B.addColorStop(0,`rgba(255,255,255,${z})`),B.addColorStop(.5,`rgba(255,255,255,${z*.25})`),B.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=B,e.fillRect(0,L,r,O-L),e.restore(),e.restore()}function zd(e){const{ctx:t,ballX:n,height:r,playerColor:a,currentTime:o}=e;t.save(),t.globalCompositeOperation="source-over";const i=t.createLinearGradient(Math.max(0,n-60),0,n,0);i.addColorStop(0,"transparent"),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(o*6)*2;t.fillStyle=e.ballIsGold?"var(--nice-warning, #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?"var(--nice-warning, #FFD700)":a,t.fillRect(c.x,c.y,c.w,c.h));t.restore()}function Bd(e){const{ctx:t,ballX:n,ballY:r,ballRadius:a,playerColor:o,ballIsGold:i,currentTime:l}=e,c=3,d=a*1.5,f=l*4;t.save();for(let m=0;m<c;m++){const y=(f+m*2.1)%(Math.PI*2),p=Math.sin(y)*.5+.5,v=d+p*a*3,x=(1-p)*.5;t.globalAlpha=x,t.strokeStyle=i?"var(--nice-warning, #FFD700)":o,t.lineWidth=2-p,t.beginPath(),t.arc(n,r,v,0,Math.PI*2),t.stroke()}t.globalAlpha=.8,t.shadowColor=i?"var(--nice-warning, #FFD700)":o,t.shadowBlur=16+Math.sin(l*8)*4,t.fillStyle=i?"var(--nice-warning-bg, #fff0a8)":o;const h=a*(.8+Math.sin(l*10)*.2);t.beginPath(),t.arc(n,r,h,0,Math.PI*2),t.fill();for(const m of e.visibleNotes){if(!m.isSung)continue;const y=(l*6+m.x*.01)%(Math.PI*2),p=.15+Math.sin(y)*.1;t.globalAlpha=p,t.fillStyle=m.isGold?"var(--nice-warning, #FFD700)":o,t.fillRect(m.x,m.y,m.w,m.h)}t.restore()}function Gd(e){const{ctx:t,ballX:n,ballY:r,ballRadius:a,playerColor:o,ballIsGold:i,currentTime:l}=e,c=20+Math.abs(Math.sin(l*3))*15,d=l*5%(Math.PI*2),f=-Math.abs(Math.sin(d))*c,h=r+f;t.save(),t.globalAlpha=.3,t.fillStyle="var(--nice-overlay-50, rgba(0, 0, 0, 0.5))";const m=1-Math.abs(f)/(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 y=5;for(let x=0;x<y;x++){const b=(x+1)*.04,S=(l-b)*5%(Math.PI*2),g=r+-Math.abs(Math.sin(S))*c,k=.15*(1-x/y),M=a*(.6-x*.08);t.globalAlpha=k,t.fillStyle=o,t.beginPath(),t.arc(n-x*3,g,Math.max(2,M),0,Math.PI*2),t.fill()}t.restore(),t.save();const p=1+Math.abs(Math.sin(d))*.15,v=1/p;if(t.translate(n,h),t.scale(v,p),t.shadowColor=i?"var(--nice-warning, #FFD700)":o,t.shadowBlur=12,t.fillStyle=i?"var(--nice-warning-bg, #fff0a8)":o,t.beginPath(),t.arc(0,0,a,0,Math.PI*2),t.fill(),t.lineWidth=1.5,t.strokeStyle="var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",t.stroke(),t.restore(),Math.abs(Math.sin(d))<.1){t.save(),t.globalAlpha=.6,t.fillStyle=i?"var(--nice-warning, #FFD700)":o;for(let x=0;x<4;x++){const b=x/4*Math.PI*2+l,S=n+Math.cos(b)*(a+4),g=r+Math.sin(b)*2;t.beginPath(),t.arc(S,g,2,0,Math.PI*2),t.fill()}t.restore()}}function Wd(e,t){switch(e){case"wipe":return zd(t),!0;case"pulse":return Bd(t),!0;case"bounce":return Gd(t),!0;case"ball":default:return!1}}const Ud=1e3,Vd=20,qd=70,Hd=5,Za=26,Xa="rgba(255,215,70,0.98)",Qa=new Map,Kd=(e,t,n,r,a)=>{const o=`g${a}`,i=`<?xml version="1.0" encoding="UTF-8"?>
28
- <svg xmlns='http://www.w3.org/2000/svg' width='${r}' height='${r}' viewBox='0 0 ${r} ${r}'>
21
+ <path d="${ne}" fill="url(#${x}b)"/><path d="${V}" fill="url(#${x}b)"/><path d="${q}" fill="url(#${x}b)"/>
22
+ <path d="${C}" fill="url(#${x}f)" opacity="${D}"/><path d="${F}" fill="url(#${x}f)" opacity="${D}"/><path d="${I}" fill="url(#${x}f)" opacity="${D}"/>
23
+ ${Y}
24
+ ${N}
25
+ <rect x="0" y="${A}" width="${t}" height="${W-A}" fill="url(#${x}g)" clip-path="url(#${x}c)"/>
26
+ <rect x="0" y="${L}" width="${t}" height="${Z-L}" fill="url(#${x}h)" clip-path="url(#${x}c)"/>
27
+ </svg>`}function tt(e,t){const n=t.match(/[MLHVCSQTAZmlhvcsqtaz][^MLHVCSQTAZmlhvcsqtaz]*/g);if(!n)return;let a=0,s=0;for(const i of n){const o=i[0],l=i.slice(1).trim().split(/[\s,]+/).filter(Boolean).map(Number);switch(o){case"M":a=l[0],s=l[1],e.moveTo(a,s);break;case"L":a=l[0],s=l[1],e.lineTo(a,s);break;case"H":a=l[0],e.lineTo(a,s);break;case"V":s=l[0],e.lineTo(a,s);break;case"C":e.bezierCurveTo(l[0],l[1],l[2],l[3],l[4],l[5]),a=l[4],s=l[5];break;case"Q":e.quadraticCurveTo(l[0],l[1],l[2],l[3]),a=l[2],s=l[3];break;case"S":{e.bezierCurveTo(a,s,l[0],l[1],l[2],l[3]),a=l[2],s=l[3];break}case"A":{const c=Math.abs(l[0]),u=Math.abs(l[1]),h=l[3]!==0,p=l[4]!==0,f=l[5],y=l[6],m=a,g=s;if(Math.abs(m-f)<.001&&Math.abs(g-y)<.001||c<.001||u<.001){e.lineTo(f,y),a=f,s=y;break}const b=(c+u)/2,x=(m-f)/2,k=(g-y)/2,v=x*x+k*k,w=v>b*b?Math.sqrt(v):b,M=w*w,S=Math.sqrt(Math.max(0,(M-v)/v)),R=h!==p?1:-1,T=(m+f)/2+R*S*k,j=(g+y)/2-R*S*x,O=Math.atan2(g-j,m-T),$=Math.atan2(y-j,f-T);e.arc(T,j,w,O,$,!p),a=f,s=y;break}case"Z":e.closePath();break}}}function Rn(e,t,n,a,s,i,o,l=70,c=55,u=0,h,p,f=!1,y,m){const[g,b,x]=Tr($r(o)),k=i.L(s),v=i.R(s),w=a-k.w-v.w;if(w<0){const[C,,F]=Tr($r(o));e.save(),e.translate(t,n),e.globalAlpha=1-u/100*.87,e.fillStyle=`hsl(${C},50%,${Math.min(F+10,80)}%)`;const I=Math.min(a/2,s/2);e.beginPath(),e.moveTo(I,0),e.lineTo(a-I,0),e.quadraticCurveTo(a,0,a,I),e.lineTo(a,s-I),e.quadraticCurveTo(a,s,a-I,s),e.lineTo(I,s),e.quadraticCurveTo(0,s,0,s-I),e.lineTo(0,I),e.quadraticCurveTo(0,0,I,0),e.closePath(),e.fill(),e.restore();return}const M=k.w,S=k.w+w;if(f){const C=`hsla(${g},${b}%,${x}%,0.22)`;e.save(),e.translate(t,n),e.fillStyle="rgba(255,255,255,0.18)",e.beginPath(),tt(e,k.out),e.fill(),e.fillRect(M,0,w,s),e.beginPath(),tt(e,dt(v.out,S)),e.fill(),e.fillStyle=C,e.beginPath(),tt(e,k.inn),e.fill(),e.fillRect(M,Xe,w,s-2*Xe),e.beginPath(),tt(e,dt(v.inn,S)),e.fill(),y&&(e.save(),e.beginPath(),tt(e,k.inn),e.rect(M,Xe,w,s-2*Xe),tt(e,dt(v.inn,S)),e.clip(),e.globalAlpha=.85,e.fillStyle=y,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),m&&(e.save(),e.beginPath(),tt(e,k.inn),e.rect(M,Xe,w,s-2*Xe),tt(e,dt(v.inn,S)),e.clip(),e.globalAlpha=.85,e.fillStyle=m,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),e.restore();return}const R=`hsl(${g},${Math.min(b+10,100)}%,${Math.max(x-22,4)}%)`,T=`hsl(${g},${b}%,${x}%)`,j=`hsl(${g},${Math.max(b-12,0)}%,${Math.min(x+18,88)}%)`,O=`hsl(${g},${Math.min(b+20,100)}%,${Math.min(x+30,93)}%)`,$=l/100*.78,E=c/100*.65,D=1-u/100*.87,L=Xe,W=s-Xe,Z=W-L,A=L+Z*.44,_=L+Z*.58;e.save(),e.translate(t,n);const U=e.createLinearGradient(0,0,0,s);U.addColorStop(0,"rgba(255,255,255,0.55)"),U.addColorStop(.3,"rgba(255,255,255,0.35)"),U.addColorStop(1,"rgba(255, 255, 255, 0.08)"),e.fillStyle=U,e.beginPath(),tt(e,k.out),e.fill(),e.fillRect(M,0,w,s),e.beginPath(),tt(e,dt(v.out,S)),e.fill();const ne=e.createLinearGradient(0,L,0,W);ne.addColorStop(0,j),ne.addColorStop(.5,T),ne.addColorStop(1,R),e.globalAlpha=D,e.fillStyle=ne,e.beginPath(),tt(e,k.inn),e.fill(),e.fillRect(M,Xe,w,s-2*Xe),e.beginPath(),tt(e,dt(v.inn,S)),e.fill(),e.globalAlpha=1,y&&(e.save(),e.beginPath(),tt(e,k.inn),e.rect(M,Xe,w,s-2*Xe),tt(e,dt(v.inn,S)),e.clip(),e.globalAlpha=D*.9,e.fillStyle=y,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),m&&(e.save(),e.beginPath(),tt(e,k.inn),e.rect(M,Xe,w,s-2*Xe),tt(e,dt(v.inn,S)),e.clip(),e.globalAlpha=D*.85,e.fillStyle=m,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),e.save(),e.beginPath(),tt(e,k.inn),e.rect(M,Xe,w,s-2*Xe),tt(e,dt(v.inn,S)),e.clip();const V=e.createLinearGradient(0,_,0,W);V.addColorStop(0,"transparent"),V.addColorStop(.6,O.replace(")",`, ${E*.6})`).replace("hsl","hsla")),V.addColorStop(1,O.replace(")",`, ${E})`).replace("hsl","hsla")),e.fillStyle=V,e.fillRect(0,_,a,W-_);const q=e.createLinearGradient(0,L,0,A);q.addColorStop(0,`rgba(255,255,255,${$})`),q.addColorStop(.5,`rgba(255,255,255,${$*.25})`),q.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=q,e.fillRect(0,L,a,A-L),e.restore(),e.restore()}function Uu(e){const{ctx:t,ballX:n,height:a,playerColor:s,currentTime:i}=e;t.save(),t.globalCompositeOperation="source-over";const o=t.createLinearGradient(Math.max(0,n-60),0,n,0);o.addColorStop(0,"transparent"),o.addColorStop(1,s),t.globalAlpha=.18,t.fillStyle=o,t.fillRect(Math.max(0,n-60),0,60,a),t.globalAlpha=.9,t.strokeStyle=s,t.lineWidth=3,t.shadowColor=s,t.shadowBlur=12,t.beginPath(),t.moveTo(n,0),t.lineTo(n,a),t.stroke();const l=6+Math.sin(i*6)*2;t.fillStyle=e.ballIsGold?"var(--nice-warning, #FFD700)":s,t.beginPath(),t.moveTo(n,e.ballY-l),t.lineTo(n+l*.7,e.ballY),t.lineTo(n,e.ballY+l),t.lineTo(n-l*.7,e.ballY),t.closePath(),t.fill(),t.restore(),t.save(),t.globalCompositeOperation="source-atop",t.globalAlpha=.35;for(const c of e.visibleNotes)c.isSung&&(t.fillStyle=c.isGold?"var(--nice-warning, #FFD700)":s,t.fillRect(c.x,c.y,c.w,c.h));t.restore()}function qu(e){const{ctx:t,ballX:n,ballY:a,ballRadius:s,playerColor:i,ballIsGold:o,currentTime:l}=e,c=3,u=s*1.5,h=l*4;t.save();for(let f=0;f<c;f++){const y=(h+f*2.1)%(Math.PI*2),m=Math.sin(y)*.5+.5,g=u+m*s*3,b=(1-m)*.5;t.globalAlpha=b,t.strokeStyle=o?"var(--nice-warning, #FFD700)":i,t.lineWidth=2-m,t.beginPath(),t.arc(n,a,g,0,Math.PI*2),t.stroke()}t.globalAlpha=.8,t.shadowColor=o?"var(--nice-warning, #FFD700)":i,t.shadowBlur=16+Math.sin(l*8)*4,t.fillStyle=o?"var(--nice-warning-bg, #fff0a8)":i;const p=s*(.8+Math.sin(l*10)*.2);t.beginPath(),t.arc(n,a,p,0,Math.PI*2),t.fill();for(const f of e.visibleNotes){if(!f.isSung)continue;const y=(l*6+f.x*.01)%(Math.PI*2),m=.15+Math.sin(y)*.1;t.globalAlpha=m,t.fillStyle=f.isGold?"var(--nice-warning, #FFD700)":i,t.fillRect(f.x,f.y,f.w,f.h)}t.restore()}function Vu(e){const{ctx:t,ballX:n,ballY:a,ballRadius:s,playerColor:i,ballIsGold:o,currentTime:l}=e,c=20+Math.abs(Math.sin(l*3))*15,u=l*5%(Math.PI*2),h=-Math.abs(Math.sin(u))*c,p=a+h;t.save(),t.globalAlpha=.3,t.fillStyle="var(--nice-overlay-50, rgba(0, 0, 0, 0.5))";const f=1-Math.abs(h)/(c+20);t.beginPath(),t.ellipse(n,a+s*.5,s*f*1.5,s*.3*f,0,0,Math.PI*2),t.fill(),t.restore(),t.save();const y=5;for(let b=0;b<y;b++){const x=(b+1)*.04,k=(l-x)*5%(Math.PI*2),v=a+-Math.abs(Math.sin(k))*c,w=.15*(1-b/y),M=s*(.6-b*.08);t.globalAlpha=w,t.fillStyle=i,t.beginPath(),t.arc(n-b*3,v,Math.max(2,M),0,Math.PI*2),t.fill()}t.restore(),t.save();const m=1+Math.abs(Math.sin(u))*.15,g=1/m;if(t.translate(n,p),t.scale(g,m),t.shadowColor=o?"var(--nice-warning, #FFD700)":i,t.shadowBlur=12,t.fillStyle=o?"var(--nice-warning-bg, #fff0a8)":i,t.beginPath(),t.arc(0,0,s,0,Math.PI*2),t.fill(),t.lineWidth=1.5,t.strokeStyle="var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",t.stroke(),t.restore(),Math.abs(Math.sin(u))<.1){t.save(),t.globalAlpha=.6,t.fillStyle=o?"var(--nice-warning, #FFD700)":i;for(let b=0;b<4;b++){const x=b/4*Math.PI*2+l,k=n+Math.cos(x)*(s+4),v=a+Math.sin(x)*2;t.beginPath(),t.arc(k,v,2,0,Math.PI*2),t.fill()}t.restore()}}function Hu(e,t){switch(e){case"wipe":return Uu(t),!0;case"pulse":return qu(t),!0;case"bounce":return Vu(t),!0;case"ball":default:return!1}}const Ku=1e3,Yu=20,Zu=70,Xu=5,Is=26,Ls="rgba(255,215,70,0.98)",Ds=new Map,Qu=(e,t,n,a,s)=>{const i=`g${s}`,o=`<?xml version="1.0" encoding="UTF-8"?>
28
+ <svg xmlns='http://www.w3.org/2000/svg' width='${a}' height='${a}' viewBox='0 0 ${a} ${a}'>
29
29
  <defs>
30
- <radialGradient id='g${o}' cx='50%' cy='40%' r='60%'>
30
+ <radialGradient id='g${i}' cx='50%' cy='40%' r='60%'>
31
31
  <stop offset='0%' stop-color='hsl(${e} ${t}% ${n}%)' stop-opacity='1'/>
32
32
  <stop offset='60%' stop-color='hsl(${e} ${Math.max(10,t-30)}% ${Math.min(90,n+10)}%)' stop-opacity='0.9'/>
33
33
  <stop offset='100%' stop-color='transparent' stop-opacity='0'/>
34
34
  </radialGradient>
35
35
  </defs>
36
- <g transform='translate(${r/2}, ${r/2})'>
37
- <circle cx='0' cy='0' r='${r*.45}' fill='url(#g${o})' />
36
+ <g transform='translate(${a/2}, ${a/2})'>
37
+ <circle cx='0' cy='0' r='${a*.45}' fill='url(#g${i})' />
38
38
  </g>
39
- </svg>`;return`data:image/svg+xml;utf8,${encodeURIComponent(i)}`},Yd=(e,t,n,r,a)=>{const o=`${e}-${t}-${n}-${Math.round(r)}-${a}`;let i=Qa.get(o);return i||(i=new Image,i.src=Kd(e,t,n,r,a),Qa.set(o,i),i)},Zd=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,o=Math.max(n,r,a),i=Math.min(n,r,a);let l=0,c=0;const d=(o+i)/2;if(o!==i){const f=o-i;switch(c=d>.5?f/(2-o-i):f/(o+i),o){case n:l=(r-a)/f+(r<a?6:0);break;case r:l=(a-n)/f+2;break;case a:l=(n-r)/f+4;break}l/=6}return{h:Math.round(l*360),s:Math.round(c*100),l:Math.round(d*100)}},Xd=(e,t,n,r=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(n)}%, ${r})`;function Ln(e){try{const t=Fr(e),[n,r,a]=Td(t),o=i=>i.toString(16).padStart(2,"0");return`#${o(n)}${o(r)}${o(a)}`.toLowerCase()}catch{return"var(--nice-warning, #ffcc00)"}}function Qd(e,t,n,r,a,o){const i=Math.min(o,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()}const Kt=new Map,yn=new Set,Yn=new Set;function ua(e){const t=Kt.get(e);return t?Promise.resolve(t):Yn.has(e)?Promise.reject(new Error(`Texture failed: ${e}`)):yn.has(e)?new Promise((n,r)=>{const a=()=>{Kt.has(e)?n(Kt.get(e)):Yn.has(e)?r(new Error(`Texture failed: ${e}`)):requestAnimationFrame(a)};a()}):(yn.add(e),new Promise((n,r)=>{const a=new Image;a.crossOrigin="anonymous",a.onload=()=>{Kt.set(e,a),yn.delete(e),n(a)},a.onerror=()=>{yn.delete(e),Yn.add(e),r(new Error(`Failed to load texture: ${e}`))},a.src=e}))}function Jd(e){return Kt.get(e)??null}function gn(e,t,n=1){const r=Kt.get(t);if(!r)return!yn.has(t)&&!Yn.has(t)&&ua(t).catch(()=>{}),null;const a=e.createPattern(r,"repeat");if(!a)return null;if(n!==1){const o=new DOMMatrix;o.scaleSelf(n,n),a.setTransform(o)}return a}function eu(e){for(const t of e)t&&ua(t).catch(()=>{})}const bn=new Map,Vt=new Set;function jo(e,t,n){return`${e}|${t}|${n??""}`}function tu(e,t,n){const r=jo(e.name,t,n),a=bn.get(r);if(a)return Promise.resolve(a);if(Vt.has(r))return new Promise((p,v)=>{const x=()=>{bn.has(r)?p(bn.get(r)):Vt.has(r)?requestAnimationFrame(x):v(new Error(`Pattern render failed: ${r}`))};x()});Vt.add(r);const o="p",i=e.mk(o,t,n??void 0),l=i.match(/width="(\d+)"/),c=i.match(/height="(\d+)"/),d=l?parseInt(l[1],10):16,f=c?parseInt(c[1],10):16,h=`<svg xmlns="http://www.w3.org/2000/svg" width="${d}" height="${f}"><defs>${i}</defs><rect width="${d}" height="${f}" fill="url(#${o})"/></svg>`,m=new Blob([h],{type:"image/svg+xml;charset=utf-8"}),y=URL.createObjectURL(m);return new Promise((p,v)=>{const x=new Image;x.onload=()=>{bn.set(r,x),Vt.delete(r),URL.revokeObjectURL(y),p(x)},x.onerror=()=>{Vt.delete(r),URL.revokeObjectURL(y),v(new Error(`Failed to render pattern tile: ${e.name}`))},x.src=y})}function vn(e,t,n,r){const a=jo(t.name,n,r),o=bn.get(a);return o?e.createPattern(o,"repeat"):(Vt.has(a)||tu(t,n,r).catch(()=>{}),null)}let mt=null,Ke=null,at=null,Ct=null,ct=null,Ne=null,Ja="",es=0,ts="";const zr=(e,t,n,r,a,o,i,l,c,d,f,h,m,y,p,v,x,b,S,g,k,M,N,j)=>{e.clearRect(0,0,t,n);const _=j??null,P=(_==null?void 0:_.filledBar)??Lt,V=(_==null?void 0:_.emptyBar)??ur,z=(_==null?void 0:_.goldFilledBar)??hr,A=(_==null?void 0:_.goldEmptyBar)??fr,I=(_==null?void 0:_.font)??pr,L=hn(P.capStyleName),U=hn(V.capStyleName),Y=hn(z.capStyleName),O=hn(A.capStyleName),Z=P.patternName?pn(P.patternName):null,H=V.patternName?pn(V.patternName):null,te=z.patternName?pn(z.patternName):null,G=A.patternName?pn(A.patternName):null,B=Z?vn(e,Z,P.patternColor??P.color??"var(--nice-bg, #fff)",P.patternColor):null,w=H?vn(e,H,V.patternColor??V.color??"var(--nice-border, #d1d5db)",V.patternColor):null,$=te?vn(e,te,z.patternColor??"var(--nice-warning, #FFD700)",z.patternColor):null,R=G?vn(e,G,A.patternColor??"var(--nice-warning, #FFD700)",A.patternColor):null;ts!==o&&(ts=o,Dr("RENDER",`?? Renderer using settings for "${o}" � filled: cap=${P.capStyleName}, glass=${P.glass} | empty: cap=${V.capStyleName}, glass=${V.glass} | goldFilled: cap=${z.capStyleName}, pattern=${z.patternName??"none"} | goldEmpty: cap=${A.capStyleName}, pattern=${A.patternName??"none"} | hasSettings=${!!_}`,{filledBar:P,emptyBar:V,goldFilledBar:z,goldEmptyBar:A,filledOverlay:!!B,emptyOverlay:!!w,goldFilledOverlay:!!$,goldEmptyOverlay:!!R}));const T=P.textureUrl?gn(e,P.textureUrl,P.textureScale):null,C=V.textureUrl?gn(e,V.textureUrl,V.textureScale):null,E=z.textureUrl?gn(e,z.textureUrl,z.textureScale):null,F=A.textureUrl?gn(e,A.textureUrl,A.textureScale):null,q=typeof document<"u"?Fr(l||"var(--accent-primary, #ffcc00)"):l||"var(--accent-primary, #ffcc00)",Q=Ln(q||"var(--nice-warning, #ffcc00)"),J=ie=>Fr(ie),ae=I.fontFamily||"Arial",re=I.fontSize||18,ee=J(I.fontColor||"var(--btn-text, #fff)"),D=I.outlineColor?J(I.outlineColor):null,K=typeof I.outlineWidth=="number"?I.outlineWidth:0,se=I.shadow||null;typeof document<"u"&&((!mt||mt.width!==t||mt.height!==n)&&(mt=document.createElement("canvas"),mt.width=t,mt.height=n,Ke=mt.getContext("2d")),Ke&&Ke.clearRect(0,0,t,n),(!at||at.width!==t||at.height!==n)&&(at=document.createElement("canvas"),at.width=t,at.height=n,Ct=at.getContext("2d")),Ct&&Ct.clearRect(0,0,t,n),(!ct||ct.width!==t||ct.height!==n)&&(ct=document.createElement("canvas"),ct.width=t,ct.height=n,Ne=ct.getContext("2d")),Ne&&Ne.clearRect(0,0,t,n));const ce=S?-S:0,pe=g||t;e.fillStyle=q,e.font=`bold ${re}px ${ae}`;const fe=e.measureText(o).width+20;if(e.fillRect(ce+10,5,fe,25),e.save(),e.fillStyle=ee,se){const ie=se.match(/(-?\d+)px\s+(-?\d+)px\s+(\d+)px\s+(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\)|[a-zA-Z]+)/);ie&&(e.shadowOffsetX=parseInt(ie[1],10),e.shadowOffsetY=parseInt(ie[2],10),e.shadowBlur=parseInt(ie[3],10),e.shadowColor=ie[4])}if(e.fillText(o,ce+20,22),D&&K>0&&(e.lineWidth=K,e.strokeStyle=D,e.strokeText(o,ce+20,22)),e.restore(),x){const ie=J(b||"var(--text-secondary, #6b7280)");e.font=`bold 12px ${ae}`;const he=e.measureText(x).width,_e=8,xe=ce+10+fe+6,ye=20,ge=7,Me=he+_e*2,$e=4;e.beginPath(),e.moveTo(xe+$e,ge),e.lineTo(xe+Me-$e,ge),e.quadraticCurveTo(xe+Me,ge,xe+Me,ge+$e),e.lineTo(xe+Me,ge+ye-$e),e.quadraticCurveTo(xe+Me,ge+ye,xe+Me-$e,ge+ye),e.lineTo(xe+$e,ge+ye),e.quadraticCurveTo(xe,ge+ye,xe,ge+ye-$e),e.lineTo(xe,ge+$e),e.quadraticCurveTo(xe,ge,xe+$e,ge),e.closePath(),e.fillStyle=ie,e.fill(),e.fillStyle=ee,e.fillText(x,xe+_e,ge+14),e.font=`bold ${re}px ${ae}`}const be=120;if(e.fillStyle=q,e.fillRect(ce+pe-be-10,5,be,25),e.fillStyle=ee,e.fillText(`${i} pts`,ce+pe-be+15,22),k&&k.currentCombo>=5){const ie=k.currentCombo>=50?"3x":k.currentCombo>=30?"2.5x":k.currentCombo>=20?"2x":k.currentCombo>=10?"1.5x":"",he=`${k.currentCombo} combo${ie?" "+ie:""}`;e.font=`bold 12px ${ae}`;const xe=e.measureText(he).width+16,ye=ce+pe-be-10-xe-6;e.fillStyle=J(k.currentCombo>=20?"var(--success, #FFD700)":"var(--warning, #ff9800)"),e.globalAlpha=.9,Qd(e,ye,7,xe,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=J(k.currentCombo>=20?"var(--text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(he,ye+8,22),e.font=`bold 14px ${ae}`}if(M&&M.length>0){const ie=M[M.length-1];if(ie.label){const he=`${M.length}-${ie.label}`;he!==Ja&&(Ja=he,es=Date.now());const _e=Date.now()-es;if(_e<2500){const xe=_e<2e3?1:1-(_e-2e3)/500,ye={Perfect:J("var(--success, #00e676)"),Great:J("var(--success, #66bb6a)"),Good:J("var(--accent-primary, #ffeb3b)"),OK:J("var(--warning, #ff9800)"),Bad:J("var(--error, #ef5350)"),Awful:J("var(--error, #b71c1c)")};e.save(),e.globalAlpha=xe,e.font=`bold ${Math.round(re*1.2)}px ${ae}`;const ge=ie.label,Me=e.measureText(ge).width,$e=ce+pe/2-Me/2;e.fillStyle=ye[ge]||ee,e.shadowColor="var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",e.shadowBlur=6,e.fillText(ge,$e,58),D&&K>0&&(e.lineWidth=K,e.strokeStyle=D,e.strokeText(ge,$e,58)),e.restore()}}}const Re=a-2,Fe=a+5,Te=40;let Se=1/0,ne=-1/0;if(r.forEach(ie=>{ie.forEach(he=>{he.pitch<Se&&(Se=he.pitch),he.pitch>ne&&(ne=he.pitch)})}),c&&Array.isArray(c)&&c.length>0){let ie=null;isFinite(Se)&&isFinite(ne)&&(ie=Math.round((Se+ne)/2));let he=1/0,_e=-1/0;c.forEach(({t:xe,hz:ye})=>{if(!ye||ye<=0)return;let ge=ie;for(const $e of r)for(const Ve of $e)xe>=Ve.startTime&&xe<=Ve.startTime+Ve.duration&&(ge=Ve.pitch);const Me=fo(ye,ge);Me<he&&(he=Me),Me>_e&&(_e=Me)}),he!==1/0&&_e!==-1/0&&(he<Se&&(Se=Math.floor(he-2)),_e>ne&&(ne=Math.ceil(_e+2)))}(!isFinite(Se)||!isFinite(ne))&&(Se=40,ne=80),Se===ne&&(Se=Math.max(0,Se-6),ne=ne+6);const oe=ie=>{const he=n-Te-10;return Te+he-(ie-Se)/(ne-Se)*he},Oe=po(m||"normal"),rt=(n-Te-10)/Math.max(1,ne-Se),Ce=Math.max(10,Math.round(rt*(1+2*Oe.semitoneTolerance)*.3)),ft=Math.max(5,Math.round(Ce*.45));((ie,he,_e,xe,ye,ge)=>{ie.lineWidth=1;for(let Me=Math.ceil(ye);Me<=Math.floor(ge);Me++){const $e=oe(Me);ie.strokeStyle=J(Me%2===0?"var(--guide-line-strong, rgba(255, 255, 255, 0.12))":"var(--guide-line-weak, rgba(255, 255, 255, 0.06))"),ie.beginPath(),ie.moveTo(0,Math.round($e)+.5),ie.lineTo(he,Math.round($e)+.5),ie.stroke()}})(e,t,n-Te,Te,Se,ne),Ct&&Ct.clearRect(0,0,t,n);const Je=(a-Re)/(Fe-Re)*t;let Ue=n*.5,Ft=!1,vt=!1;const br=(ie,he,_e,xe,ye,ge,Me=0)=>{const $e=(ve,je,Pe,ze,Ge,Ze)=>{const Le=Math.min(Ze,ze/2,Ge/2);ve.beginPath(),ve.moveTo(je+Le,Pe),ve.lineTo(je+ze-Le,Pe),ve.quadraticCurveTo(je+ze,Pe,je+ze,Pe+Le),ve.lineTo(je+ze,Pe+Ge-Le),ve.quadraticCurveTo(je+ze,Pe+Ge,je+ze-Le,Pe+Ge),ve.lineTo(je+Le,Pe+Ge),ve.quadraticCurveTo(je,Pe+Ge,je,Pe+Ge-Le),ve.lineTo(je,Pe+Le),ve.quadraticCurveTo(je,Pe,je+Le,Pe),ve.closePath()},Ve=Math.max(2,Ce/2);xe.forEach(ve=>{if(ve.startTime+ve.duration<ye||ve.startTime>ge)return;const je=(ve.startTime-ye)/(ge-ye)*he,Pe=ve.duration/(ge-ye)*he,ze=oe(ve.pitch)-Ce/2,Ge=[];if(Array.isArray(h)){const Ze=ve.startTime+ve.duration;h.forEach(Le=>{if(Le.pitch!==ve.pitch||Le.noteStart!=null&&Le.noteEnd!=null&&(Math.abs(Le.noteStart-ve.startTime)>.01||Math.abs(Le.noteEnd-Ze)>.01))return;const lt=Math.max(Le.start,ve.startTime),xt=Math.min(Le.end,Ze);if(lt>=xt)return;const $t=(lt-ye)/(ge-ye)*he,Ot=(xt-ye)/(ge-ye)*he;Ge.push({x1:$t,x2:Ot,frac:Le.frac})})}if(ve.isGold){ie.save();const Ze=p&&p.shadowColor?p.shadowColor:Xa,Le=p&&typeof p.glowBlur=="number"?p.glowBlur:Za;ie.shadowColor=Ze,ie.shadowBlur=Math.max(4,Le-12),ie.fillStyle=J("var(--gold-overlay, rgba(255, 215, 0, 0.15))"),$e(ie,je-1,ze-1,Pe+2,Ce+2,Ve),ie.fill(),ie.restore();const lt=Ln("var(--gold-base, #b4af9f)");mn(ie,je,ze,Pe,Ce,O,A.color??lt,A.highlight,A.glow,A.glass,G,A.patternColor,A.patternOnly,F,R),ie.save(),$e(ie,je,ze,Pe,Ce,Ve),ie.clip(),ie.globalAlpha=.18,ie.fillStyle=J("var(--success, #FFD700)"),ie.fillRect(je,ze,Pe,Math.max(1,Ce*.25)),ie.globalAlpha=1,ie.restore(),Ge.length>0&&(ie.save(),$e(ie,je,ze,Pe,Ce,Ve),ie.clip(),Ge.forEach(xt=>{const $t=Math.max(1,xt.x2-xt.x1);mn(ie,xt.x1,ze,$t,Ce,Y,z.color??"var(--nice-warning, #FFD700)",z.highlight,z.glow,z.glass,te,z.patternColor,z.patternOnly,E,$)}),ie.restore()),Ge.length===0&&(ie.lineWidth=1,ie.strokeStyle=J("var(--gold-outline, rgba(255, 215, 0, 0.35))"),$e(ie,je+.5,ze+.5,Pe-1,Math.max(1,Ce-1),Ve),ie.stroke())}else{const Ze=Ln("var(--note-base, #d1d5db)");mn(ie,je,ze,Pe,Ce,U,V.color??Ze,V.highlight,V.glow,V.glass,H,V.patternColor,V.patternOnly,C,w),Ge.length>0&&(ie.save(),$e(ie,je,ze,Pe,Ce,Ve),ie.clip(),Ge.forEach(Le=>{const lt=Math.max(1,Le.x2-Le.x1);mn(ie,Le.x1,ze,lt,Ce,L,P.color??Q,P.highlight,P.glow,P.glass,Z,P.patternColor,P.patternOnly,T,B)}),ie.restore())}Ct&&(Ct.fillStyle="var(--nice-bg, #fff)",Ct.fillRect(je,ze,Pe,Ce))})};if(r.forEach(ie=>{br(e,t,n-Te,ie,Re,Fe,Te);for(const he of ie)if(a>=he.startTime&&a<=he.startTime+he.duration){Ue=oe(he.pitch),Ft=!0,vt=!!he.isGold;break}}),!Ft){let ie=null,he=null;for(const _e of r)for(const xe of _e)xe.startTime>a&&(!ie||xe.startTime<ie.startTime)&&(ie=xe),xe.startTime<=a&&(!he||xe.startTime>he.startTime)&&(he=xe);ie?(Ue=oe(ie.pitch),vt=!!ie.isGold):he?(Ue=oe(he.pitch),vt=!!he.isGold):Ue=n*.5}const ht=q||J("var(--accent-primary, #ffcc00)"),le=1+Math.sin((a||0)*8)*.06,ue=ft*le,ke=[];for(const ie of r)for(const he of ie){if(he.startTime+he.duration<Re||he.startTime>Fe)continue;const _e=(he.startTime-Re)/(Fe-Re)*t,xe=he.duration/(Fe-Re)*t,ye=oe(he.pitch)-Ce/2,ge=he.startTime+he.duration<=a;ke.push({x:_e,y:ye,w:xe,h:Ce,isGold:he.isGold,isSung:ge})}if(!Wd(N||"ball",{ctx:e,ballX:Je,ballY:Ue,ballRadius:ue,playerColor:ht,ballIsGold:vt,currentTime:a,height:n,visibleNotes:ke})){mt&&e.drawImage(mt,0,0),ct&&e.drawImage(ct,0,0),e.save(),e.globalCompositeOperation="source-over",e.globalAlpha=.28;const ie=Math.max(18,ue*5),he=e.createRadialGradient(Je,Ue,0,Je,Ue,ie);if(he.addColorStop(0,ht),he.addColorStop(1,"transparent"),e.fillStyle=he,e.beginPath(),e.arc(Je,Ue,ie,0,Math.PI*2),e.fill(),e.restore(),y&&Ke&&at&&(Ke.save(),Ke.globalCompositeOperation="source-over",Ke.globalAlpha=.95,Ke.fillStyle=ht,Ke.beginPath(),Ke.arc(Je,Ue,ue+4,0,Math.PI*2),Ke.fill(),Ke.restore(),Ke.save(),Ke.globalCompositeOperation="destination-in",Ke.drawImage(at,0,0),Ke.restore(),e.drawImage(mt,0,0)),y&&Ne&&at)try{const ye=Ln(ht),{h:ge,s:Me,l:$e}=Zd(ye),ve=Xd(ge,Math.max(10,Math.round(Me*(typeof f=="number"?f:.25))),$e,.85);Ne.save(),Ne.globalCompositeOperation="multiply",Ne.globalAlpha=.65,Ne.fillStyle=ve,Ne.beginPath(),Ne.arc(Je,Ue,Math.max(8,ue+6),0,Math.PI*2),Ne.fill(),Ne.restore(),Ne.save(),Ne.globalCompositeOperation="destination-out",Ne.drawImage(at,0,0),Ne.restore(),e.drawImage(ct,0,0)}catch{Ne.save(),Ne.globalCompositeOperation="source-over",Ne.globalAlpha=.6,Ne.fillStyle=ht,Ne.beginPath(),Ne.arc(Je,Ue,Math.max(8,ue+6),0,Math.PI*2),Ne.fill(),Ne.restore(),Ne.save(),Ne.globalCompositeOperation="destination-out",Ne.drawImage(at,0,0),Ne.restore(),e.drawImage(ct,0,0)}const _e=p&&p.shadowColor?p.shadowColor:Xa,xe=p&&typeof p.glowBlur=="number"?p.glowBlur:Za;e.save(),vt?(e.shadowColor=_e,e.shadowBlur=xe,e.fillStyle=J("var(--gold-light, #FFF0A8)")):(e.shadowColor=ht,e.shadowBlur=10,e.fillStyle=ht),e.globalCompositeOperation="source-over",e.globalAlpha=1,e.beginPath(),e.arc(Je,Ue,ue,0,Math.PI*2),e.fill(),e.lineWidth=1.5,e.strokeStyle=J("var(--shadow, rgba(0,0,0,0.35))"),e.stroke(),e.restore()}try{if(Array.isArray(v)&&v.length>0){const ie=Date.now(),he=p&&typeof p.lifeMs=="number"?p.lifeMs:Ud,_e=(ye,ge,Me,$e=5)=>{const Ve=Me,ve=Me*.45;e.beginPath();let je=Math.PI/2*3,Pe=ye,ze=ge;const Ge=Math.PI/$e;e.moveTo(ye,ge-Ve);for(let Ze=0;Ze<$e;Ze++)Pe=ye+Math.cos(je)*Ve,ze=ge+Math.sin(je)*Ve,e.lineTo(Pe,ze),je+=Ge,Pe=ye+Math.cos(je)*ve,ze=ge+Math.sin(je)*ve,e.lineTo(Pe,ze),je+=Ge;e.lineTo(ye,ge-Ve),e.closePath()},xe=ye=>{let ge=ye>>>0;return()=>(ge=ge*1664525+1013904223>>>0,(ge&2147483647)/2147483647)};v.forEach(ye=>{const ge=ie-ye.createdAt;if(ge<0||ge>he)return;const Me=ge/he,$e=(ye.noteStart-(a-2))/7*t,Ve=oe(ye.notePitch),ve=xe(ye.seed||Math.floor(ye.createdAt%1e5)),je=p&&typeof p.count=="number"?p.count:Vd,Pe=p&&typeof p.baseSpeed=="number"?p.baseSpeed:qd,ze=p&&typeof p.baseSize=="number"?p.baseSize:Hd;for(let Ge=0;Ge<je;Ge++){const Ze=ve(),Le=ve(),lt=Ge/je*Math.PI*2+Ze*Math.PI*.6+Me*1.5,xt=6+Pe*(1-Me)*(.5+Le*.8),$t=$e+Math.cos(lt)*xt,Ot=Ve+Math.sin(lt)*xt*(.8+Ze*.6),pt=Math.max(1,ze*(1-Me)*(.5+Le)),La=40+Math.round(20*ve()),Da=70+Math.round(20*ve()),vr=Math.max(0,1-Me)*(.9-ve()*.3),zl=Math.max(6,pt*2.6),xr=Yd(La,Da,60,Math.round(zl),(ye.seed||0)+Ge);xr&&xr.complete?(e.save(),e.translate($t,Ot+4),e.rotate(lt+Me*4+(ve()-.5)*1.2),e.globalAlpha=vr,e.drawImage(xr,-pt/2,-pt/2,pt,pt),e.restore()):(e.save(),e.translate($t,Ot+4),e.rotate(lt+Me*4),e.fillStyle=`hsla(${La}, ${Da}%, 60%, ${vr})`,e.fillRect(-pt/2,-pt/2,pt,pt),e.restore()),ve()>.85&&(e.save(),e.globalAlpha=Math.max(.35,1-Me),e.fillStyle=`hsla(${30+Math.round(10*ve())}, ${60+Math.round(30*ve())}%, ${70+Math.round(10*ve())}%, ${vr})`,e.strokeStyle=`rgba(0,0,0,${.12*(1-Me)})`,e.lineWidth=.8,_e($t,Ot+4,pt*(1.4+ve())),e.fill(),e.stroke(),e.restore())}})}}catch{}return{ballX:Je,ballY:Ue,ballIsGold:vt}},Ro=({song:e,currentTime:t,playerRef:n,config:r={},userPitch:a,segmentScores:o,goldBursts:i,combo:l,verseRatings:c})=>{const{isPlaying:d=!1,playerName:f="Ziom",score:h=1e4,playerBgColor:m="var(--karaoke-player-bg, #2196f3)",playerCount:y=2,gapDesaturation:p,goldSettings:v,difficultyLevel:x,algorithmLabel:b,algorithmColor:S,latencyMs:g=null,top:k,animationMode:M,karaokeSettings:N=null}=r,j=u.useRef(null),_=u.useRef(null),[P,V]=u.useState({width:600,height:150,top:250,visibleWidth:600}),[z,A]=u.useState(0),I=u.useRef(0),L=u.useRef(null),U=u.useRef(null),Y=u.useRef(null),O=u.useRef(t),Z=u.useRef(performance.now()),H=u.useRef(e),te=u.useRef(P),G=u.useRef(a),B=u.useRef(d),w=u.useRef(0),$=u.useRef(!1),R=u.useRef(null),T=u.useRef(null),C=()=>{const E=(e==null?void 0:e.id)??null;if(E!==T.current||!R.current){T.current=E;const F=e.notes.map(ee=>ee.noteLine);R.current=ra(F,e.bpm??void 0);const q=R.current.reduce((ee,D)=>ee+D.length,0),Q=R.current.reduce((ee,D)=>ee+D.filter(K=>K.isGold).length,0),J=R.current.flat().map(ee=>ee.pitch),ae=J.length?Math.min(...J):0,re=J.length?Math.max(...J):0;Dr("BARS",`?? Parsed notes for "${e.title}" — ${R.current.length} verses, ${q} notes (including ${Q} golden), pitch range: ${ae}–${re}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:F.length,verseCount:R.current.length,totalNotes:q,goldCount:Q,minPitch:ae,maxPitch:re})}return R.current};return u.useEffect(()=>{const E=(q,Q,J)=>q+(Q-q)*J,F=q=>{U.current===null&&(U.current=q);const Q=Math.min(.1,(q-(U.current||q))/1e3);U.current=q;const J=w.current,ae=I.current,re=1-Math.exp(-12*Q),ee=Math.abs(ae-J)<.25?ae:E(J,ae,re);Math.abs(ee-J)>1e-4&&(A(ee),w.current=ee,j.current&&(j.current.style.transform=`translateX(${ee}px)`)),L.current=requestAnimationFrame(F)};return L.current=requestAnimationFrame(F),()=>{L.current&&cancelAnimationFrame(L.current),L.current=null,U.current=null}},[]),u.useEffect(()=>{const E=()=>{if(!n.current)return;const F=n.current.getBoundingClientRect(),q=2/Math.max(1,y),Q=Math.round(F.width*q),J=Math.round(F.width),ae=Q*(150/600);V({width:Q,height:ae,top:30,visibleWidth:J})};return E(),window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[n,y]),u.useEffect(()=>{var J;if(d||!j.current)return;const E=j.current.getContext("2d");if(!E)return;const F=C(),q=t-(e.gap??0)/1e3,Q=zr(E,P.width,P.height,F,q,f,h,m,a,e.id,p??void 0,o,x??void 0,d,v??void 0,i,b,S,w.current,P.visibleWidth,l,c,M,N);if(Q&&j.current){const ae=P.visibleWidth||(((J=_.current)==null?void 0:J.getBoundingClientRect().width)??P.width),re=P.width;let ee=Math.round(ae/2-Q.ballX);const D=ae-re;ee=Math.max(D,Math.min(0,ee)),I.current=ee}},[t,e,P,a,d,o,i,M,N]),u.useEffect(()=>{O.current=t,Z.current=performance.now()},[t]),u.useEffect(()=>{H.current=e},[e]),u.useEffect(()=>{te.current=P},[P]),u.useEffect(()=>{G.current=a},[a]),u.useEffect(()=>{B.current=d},[d]),u.useEffect(()=>{const E=()=>{var se;const F=j.current,q=H.current,Q=te.current;if(!F||!q||!Q)return;const J=F.getContext("2d");if(!J)return;const ae=C(),re=Math.min(.5,(performance.now()-Z.current)/1e3),D=(B.current?O.current+re:O.current)-(q.gap??0)/1e3,K=zr(J,Q.width,Q.height,ae,D,f,h,m,G.current,q.id,p??void 0,o,x??void 0,B.current,v??void 0,i,b,S,w.current,Q.visibleWidth,l,c,M,N);if(K){const ce=Q.visibleWidth||(((se=_.current)==null?void 0:se.getBoundingClientRect().width)??Q.width),pe=Q.width;let X=Math.round(ce/2-K.ballX);const fe=ce-pe;X=Math.max(fe,Math.min(0,X)),I.current=X}};if(d){$.current||($.current=!0,Dr("BARS",`? Drawing bars in RAF loop � canvas: ${te.current.width}�${te.current.height}px, player: ${f}`,{canvasSize:te.current}));const F=()=>{E(),Y.current=requestAnimationFrame(F)};return Y.current=requestAnimationFrame(F),()=>{Y.current&&cancelAnimationFrame(Y.current),Y.current=null}}$.current=!1},[d,f,h,m,p,o,x,v,i,M,N]),s.jsxs("div",{ref:_,style:{position:"absolute",left:"50%",top:`${k??P.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:P.visibleWidth,height:P.height,overflow:"hidden"},children:[s.jsx("style",{children:"@keyframes av-latency-pulse {0% { transform: scale(1); box-shadow: 0 4px 10px var(--nice-overlay-20, rgba(0, 0, 0, 0.2));} 50% { transform: scale(1.08); box-shadow: 0 8px 18px rgba(0,0,0,0.32);} 100% { transform: scale(1); box-shadow: 0 4px 10px var(--nice-overlay-20, rgba(0, 0, 0, 0.2));} } .av-latency-pulse { animation: av-latency-pulse 1s ease-in-out infinite; }"}),s.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 g<"u"&&g!==null?(()=>{const E=g,F=E<=120?"var(--latency-good, #10b981)":E<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",q=`${E}ms`;return s.jsxs("div",{className:E>250?"av-latency-pulse":"",style:{background:F,padding:"6px 10px",borderRadius:12,boxShadow:"0 4px 10px var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",fontWeight:700,minWidth:56,textAlign:"center",display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{style:{display:"inline-block",transform:"translateY(-1px)"},children:"??"}),s.jsx("span",{children:q})]})})():s.jsx("div",{style:{background:"var(--latency-none-bg, rgba(75,85,99,0.9))",padding:"6px 8px",borderRadius:12,boxShadow:"0 4px 10px var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",minWidth:44,textAlign:"center"},children:"�"})}),s.jsx("canvas",{ref:j,width:P.width,height:P.height,role:"img","aria-label":`Pitch timeline for ${f??"player"}. Score: ${h??0}`,style:{position:"absolute",left:0,top:0,transform:`translateX(${z}px)`,willChange:"transform"}})]})},To="/textures/seamless/256x256";function wt(e,t,n){return{name:e,icon:n,entries:Array.from({length:t},(r,a)=>{const o=String(a+1).padStart(2,"0");return{label:`${e} ${o}`,url:`${To}/${e}/Photoreal_${e}_${o}-512x512.png`}})}}function kt(e,t,n){return{name:e,icon:n,entries:Array.from({length:t},(r,a)=>{const o=String(a+1).padStart(2,"0");return{label:`${e} ${o}`,url:`${To}/${e}/${e}_${o}-256x256.png`}})}}const fa=[wt("Fire",8,"🔥"),wt("Metal",8,"⚙️"),wt("Ice",8,"❄️"),wt("Stone",8,"🪨"),wt("Wood",8,"🪵"),wt("Tile",8,"🧱"),wt("Concrete",8,"🏗️"),wt("Trees",8,"🌲"),wt("Grass",8,"🌿"),kt("Wall",24,"🏠"),kt("Rust",24,"🟤"),kt("Woven",24,"🧵"),kt("Ground",24,"🟫"),kt("Pebbles",24,"🫧"),kt("Plant",24,"🌱"),kt("Roof",24,"🏛️"),kt("Misc",24,"🎨")],$o=fa.flatMap(e=>e.entries);function nu(e){return $o.find(t=>t.url===e)}const ru={color:"var(--nice-primary, #2196f3)",highlight:"var(--nice-bg, #fff)",glow:0,capStyle:"flat",pattern:null,texture:null},Po=({fill:e=ru,onChange:t=()=>{},previewColor:n="var(--nice-primary, #2196f3)",accentColor:r="var(--nice-primary, #0d6efd)",width:a,height:o})=>{const{t:i}=we(),[l,c]=u.useState(null),d=(b,S)=>{t({...e,[b]:S})},f=u.useMemo(()=>{const b=e.color||n||"var(--nice-primary, #2196f3)";return(S,g,k)=>{const M=jn.find(j=>j.name===S)||jn[0],N=g?sr.find(j=>j.name===g)??null:null;return Mo({width:80,height:22,capStyle:M,color:b,highlight:e.highlight,glow:e.glow,glass:e.glass,pattern:N,patternColor:e.patternColor,patternOnly:e.patternOnly,textureUrl:k??null,textureScale:e.textureScale})}},[e,n]),h=`2px solid ${r}`,m=r==="var(--nice-warning-dark, #d4a017)"?"var(--nice-warning-bg, #fff8e1)":"#e7f1ff",y=u.useRef(null),p=u.useRef(null),v=u.useCallback((b,S)=>{b.current&&b.current.scrollBy({left:S*180,behavior:"smooth"})},[]),x={position:"absolute",top:0,width:28,height:"100%",border:"none",cursor:"pointer",zIndex:2,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,fontWeight:700,color:"var(--nice-border, #ccc)",background:"linear-gradient(90deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"};return s.jsxs("div",{style:{padding:"4px 0"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[s.jsx(He.Form.Label,{className:"mb-0",style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:i("playerForm.barColor","Color")}),s.jsx(He.Form.Check,{type:"checkbox",id:`bar-color-auto-${r}`,label:i("playerForm.auto","Auto"),checked:!e.color,onChange:b=>d("color",b.target.checked?null:n||"var(--nice-primary, #2196f3)"),className:"mb-0"}),e.color&&s.jsx("input",{type:"color",value:e.color,onChange:b=>d("color",b.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),s.jsx(He.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:i("playerForm.capShape","Cap shape")}),s.jsxs("div",{style:{position:"relative",marginBottom:10},children:[s.jsx("button",{type:"button",style:{...x,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>v(y,-1),children:"�"}),s.jsx("button",{type:"button",style:{...x,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>v(y,1),children:"�"}),s.jsx("div",{ref:y,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:jn.map(b=>{const S=e.capStyleName===b.name;return s.jsx("div",{title:b.name,onClick:()=>d("capStyleName",b.name),style:{cursor:"pointer",flexShrink:0,border:S?h:"1px solid var(--nice-text-secondary, #555)",borderRadius:6,padding:3,background:S?m:"var(--nice-text, #222)"},dangerouslySetInnerHTML:{__html:f(b.name,null)}},b.name)})})]}),s.jsx(He.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:i("playerForm.pattern","Pattern")}),s.jsxs("div",{style:{position:"relative",marginBottom:10},children:[s.jsx("button",{type:"button",style:{...x,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>v(p,-1),children:"�"}),s.jsx("button",{type:"button",style:{...x,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>v(p,1),children:"�"}),s.jsxs("div",{ref:p,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:[s.jsx("div",{title:"None",onClick:()=>d("patternName",null),style:{cursor:"pointer",flexShrink:0,border:e.patternName?"1px solid var(--nice-text-secondary, #555)":h,borderRadius:6,padding:"3px 8px",background:e.patternName?"var(--nice-text, #222)":m,fontSize:12,lineHeight:"22px",color:"var(--nice-border, #ccc)"},children:"�"}),sr.map(b=>{const S=e.patternName===b.name;return s.jsx("div",{title:b.name,onClick:()=>d("patternName",b.name),style:{cursor:"pointer",flexShrink:0,border:S?h:"1px solid var(--nice-text-secondary, #555)",borderRadius:6,padding:3,background:S?m:"var(--nice-text, #222)"},dangerouslySetInnerHTML:{__html:f(e.capStyleName,b.name)}},b.name)})]})]}),s.jsx(He.Form.Check,{type:"switch",id:`bar-pattern-only-${r}`,label:i("playerForm.patternOnly","Pattern only (flat, no 3D)"),checked:e.patternOnly,onChange:b=>d("patternOnly",b.target.checked),className:"mb-2"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[s.jsx(He.Form.Label,{className:"mb-0",style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:i("playerForm.patternColor","Pattern color")}),s.jsx(He.Form.Check,{type:"checkbox",id:`bar-pattern-color-auto-${r}`,label:i("playerForm.auto","Auto"),checked:!e.patternColor,onChange:b=>d("patternColor",b.target.checked?null:n||"var(--nice-bg, #fff)"),className:"mb-0"}),e.patternColor&&s.jsx("input",{type:"color",value:e.patternColor,onChange:b=>d("patternColor",b.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),!e.patternOnly&&s.jsxs(s.Fragment,{children:[s.jsxs(He.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[i("playerForm.highlight","Highlight"),": ",e.highlight,"%"]}),s.jsx(He.Form.Range,{min:0,max:100,value:e.highlight,onChange:b=>d("highlight",parseInt(b.target.value)),className:"mb-2"}),s.jsxs(He.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[i("playerForm.glow","Glow"),": ",e.glow,"%"]}),s.jsx(He.Form.Range,{min:0,max:100,value:e.glow,onChange:b=>d("glow",parseInt(b.target.value)),className:"mb-2"})]}),s.jsxs(He.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[i("playerForm.glass","Transparency (glass)"),": ",e.glass,"%"]}),s.jsx(He.Form.Range,{min:0,max:100,value:e.glass,onChange:b=>d("glass",parseInt(b.target.value)),className:"mb-2"}),s.jsx(He.Form.Label,{style:{fontSize:13,fontWeight:600,marginTop:4,color:"var(--nice-border, #ccc)"},children:i("playerForm.texture","Texture")}),s.jsxs("div",{style:{marginBottom:6},children:[s.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",marginBottom:6},children:[s.jsx("button",{type:"button",className:`btn btn-sm ${e.textureUrl?"btn-outline-secondary":"btn-primary"}`,onClick:()=>{d("textureUrl",null),c(null)},children:i("playerForm.texNone","None")}),fa.map(b=>s.jsx("button",{type:"button",className:`btn btn-sm ${(l==null?void 0:l.name)===b.name?"btn-primary":"btn-outline-secondary"}`,onClick:()=>c(S=>(S==null?void 0:S.name)===b.name?null:b),title:b.name,children:b.icon},b.name))]}),l&&s.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap",maxHeight:130,overflowY:"auto",padding:4,border:"1px solid var(--nice-border, #dee2e6)",borderRadius:6,background:"var(--nice-bg-secondary, #f8f9fa)"},children:l.entries.map(b=>{const S=e.textureUrl===b.url;return s.jsx("div",{title:b.label,onClick:()=>d("textureUrl",S?null:b.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:S?`3px solid ${r}`:"1px solid var(--nice-text-muted, #bbb)",backgroundImage:`url(${b.url})`,backgroundSize:"cover",boxShadow:S?`0 0 6px ${r}`:void 0}},b.url)})}),e.textureUrl&&s.jsxs("div",{style:{marginTop:4,display:"flex",alignItems:"center",gap:8},children:[s.jsx("div",{style:{width:80,height:22,borderRadius:6,backgroundImage:`url(${e.textureUrl})`,backgroundSize:`${Math.round(256*e.textureScale)}px`,border:"1px solid var(--nice-text-muted, #aaa)"}}),s.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #666)"},children:e.textureUrl.split("/").pop()})]})]}),e.textureUrl&&s.jsxs(s.Fragment,{children:[s.jsxs(He.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[i("playerForm.textureScale","Texture scale"),": ",e.textureScale.toFixed(1),"�"]}),s.jsx(He.Form.Range,{min:10,max:200,step:10,value:Math.round(e.textureScale*100),onChange:b=>d("textureScale",parseInt(b.target.value)/100),className:"mb-2"})]})]})},Ye=nt.scoped("AudioPitchAnalyzer");function Eo({onSegments:e,defaultCompareAll:t=!1,externalFile:n=null,postPitch:r,postLibrosaPitchTrack:a}){const{t:o}=we(),[i,l]=u.useState("pitchy"),[c,d]=u.useState(null),[f,h]=u.useState(t),[m,y]=u.useState({}),[p,v]=u.useState({}),[x,b]=u.useState([]),[S,g]=u.useState([]),[k,M]=u.useState(!1),[N,j]=u.useState(null),[_]=u.useState(null),[P]=u.useState(null),[V,z]=u.useState(null),A=u.useRef(null);function I(G){try{if(G instanceof Error){let w=`${G.message}
40
- ${G.stack??""}`;const $=G;if($!=null&&$.attemptedUrls)try{w+=`
41
- Attempted URLs: ${Array.isArray($.attemptedUrls)?$.attemptedUrls.join(", "):String($.attemptedUrls)}`}catch{w+=`
42
- Attempted URLs: ${String($.attemptedUrls)}`}return w}const B=G;return B!=null&&B.attemptedUrls?`Error: ${String(B.message??B)}
43
- Attempted URLs: ${Array.isArray(B.attemptedUrls)?B.attemptedUrls.join(", "):String(B.attemptedUrls)}`:String(G)}catch{return"Unknown error"}}function L(G){if(!G||G<=0)return null;const B=12*Math.log2(G/440)+69;return Math.round(B-12)}async function U(G){var w;const B=(w=G.target.files)==null?void 0:w[0];B&&await Y(B,f)}async function Y(G,B){j(null),g([]),M(!0);try{const w=await G.arrayBuffer(),$=window.AudioContext??window.webkitAudioContext,T=await new $().decodeAudioData(w),C=T.getChannelData(0);d(C);const E=T.sampleRate,F=Math.floor(E*.1),q=F,Q=()=>{const K=[],se=Nr.PitchDetector.forFloat32Array(F);for(let ce=0;ce<C.length-F;ce+=q){const pe=C.slice(ce,ce+F),[X,fe]=se.findPitch(pe,E),be=L(X);be&&X>50&&X<2e3&&fe>.7&&K.push({start:ce/E,duration:F/E,pitch:be,freq:X})}return K},J=()=>{const K=[];for(let se=0;se<C.length-F;se+=q){const ce=C.slice(se,se+F),pe=Z(ce,E),X=L(pe);X&&pe>50&&pe<2e3&&K.push({start:se/E,duration:F/E,pitch:X,freq:pe})}return K};if(B){M(!0),j(null);const K={};try{const se={};try{K.pitchy=Q(),se.pitchy=null}catch(ce){K.pitchy=[],se.pitchy=I(ce),Ye.warn("pitchy failed",ce)}try{K["ultrastar-wp"]=J(),se["ultrastar-wp"]=null}catch(ce){K["ultrastar-wp"]=[],se["ultrastar-wp"]=I(ce),Ye.warn("ultrastar-wp failed",ce)}K.aubio=[],se.aubio="disabled";try{if(!r)throw new Error("CREPE backend not configured");const pe=(await r(G)).track??[];K.crepe=pe.map((X,fe)=>{var be;return{start:X.t,duration:(be=pe[fe+1])!=null&&be.t?pe[fe+1].t-X.t:.1,pitch:L(X.hz)??0,freq:X.hz}}),se.crepe=null}catch(ce){K.crepe=[],se.crepe=I(ce),Ye.warn("crepe failed",ce)}try{if(!a)throw new Error("Librosa backend not configured");const pe=(await a(new File([G],G.name,{type:G.type}))).track??[];K.librosa=pe.map((X,fe)=>{var be;return{start:X.t,duration:(be=pe[fe+1])!=null&&be.t?pe[fe+1].t-X.t:.1,pitch:L(X.hz)??0,freq:X.hz}}),se.librosa=null}catch(ce){K.librosa=[],se.librosa=I(ce),Ye.warn("librosa failed",ce)}v(se),y(K),g(K[i]??[])}catch(se){Ye.error("compareAll overall failed",se);const ce=se instanceof Error?se.message:String(se);j(o("audioPitch.errorComparing")+ce)}finally{M(!1)}return}const ae=[],re=[];let ee=0;if(i==="pitchy"){const K=Nr.PitchDetector.forFloat32Array(F);for(let se=0;se<C.length-F;se+=q){const ce=C.slice(se,se+F);let pe=0;for(let Re=0;Re<ce.length;Re++)pe+=ce[Re]*ce[Re];pe=Math.sqrt(pe/ce.length),re.push(pe);const[X,fe]=K.findPitch(ce,E),be=L(X);be&&X>50&&X<2e3&&fe>.7&&(ae.push({start:se/E,duration:F/E,pitch:be,freq:X}),ee++)}}else if(i==="crepe")try{if(!r)throw new Error("CREPE backend not configured");const K=await r(G);if(!K.track||K.track.length===0)j(o("audioPitch.crepeNoNotes")),Ye.warn("Crepe: No notes detected in audio file.");else{const se=K.track.map((ce,pe)=>{const X=L(ce.hz);return X&&ce.hz>50&&ce.hz<2e3?{start:ce.t,duration:pe<K.track.length-1?K.track[pe+1].t-ce.t:.1,pitch:X,freq:ce.hz}:null}).filter(ce=>ce!==null);if(g(se),e)try{e(se)}catch(ce){Ye.error("Error in onSegments:",ce)}b([]),d(null);return}}catch(K){j(o("audioPitch.crepeBackendError")),z(I(K)),Ye.error("Crepe: Error calling backend:",K)}else if(i==="librosa")try{await O(G),b([]),d(null);return}catch(K){j(o("audioPitch.librosaBackendError")),z(I(K)),Ye.error("Librosa: Error calling backend:",K)}else if(i==="ultrastar-wp")for(let K=0;K<C.length-F;K+=q){const se=C.slice(K,K+F);let ce=0;for(let fe=0;fe<se.length;fe++)ce+=se[fe]*se[fe];ce=Math.sqrt(ce/se.length),re.push(ce);const pe=Z(se,E),X=L(pe);X&&pe>50&&pe<2e3&&(ae.push({start:K/E,duration:F/E,pitch:X,freq:pe}),ee++)}b(re);const D=H(ae);if(g(D),e)try{e(D)}catch(K){Ye.error("Error in onSegments:",K)}D.length===0&&i!=="crepe"&&(j(o("audioPitch.noNotesDetected")),Ye.warn("No notes detected in audio file."))}catch(w){j(o("audioPitch.errorAnalyzing")+(w instanceof Error?w.message:String(w))),z(I(w)),Ye.error("Error analyzing audio file:",w)}finally{M(!1)}}u.useEffect(()=>{n&&Y(n,!0)},[n]);async function O(G){try{if(!a)throw new Error("Librosa backend not configured");const B=new File([G],"capture.wav",{type:"audio/wav"}),$=((await a(B)).track??[]).map(R=>({t:R.t,hz:R.hz}));if(e){const R=$.map((T,C)=>{var q;const E=((q=$[C+1])==null?void 0:q.t)??T.t+.1,F=L(T.hz)??0;return{start:T.t,duration:Math.max(.05,E-T.t),pitch:F,freq:T.hz}});e(R),g(R)}}catch(B){Ye.warn("Librosa analysis failed, falling back to local detectors",B);const $=(typeof B=="object"&&B!==null?B:{}).attemptedUrls;$&&Ye.error("Librosa attempted URLs:",$);const R=$?Array.isArray($)?$.join(", "):String($):null,T=B instanceof Error?B.message:String(B);j(o("audioPitch.librosaBackendError")+": "+T+(R?" (attempted: "+R+")":"")),z(I(B))}}function Z(G,B){const R=Math.floor(B/50),T=Math.max(2,Math.floor(B/2e3));let C=0;for(let Q=0;Q<G.length;Q++)C+=G[Q]*G[Q];if(C<=1e-8)return 0;let E=-1,F=0;const q=1e-10;for(let Q=T;Q<=Math.min(R,G.length-2);Q++){let J=0;const ae=G.length-Q;for(let ee=0;ee<ae;ee++)J+=G[ee]*G[ee+Q];const re=J/(ae+q)/(C/G.length+q);re>F&&(F=re,E=Q)}return E>0&&F>.01?B/E:0}function H(G){if(G.length===0)return[];const B=[];let w=G[0];for(let $=1;$<G.length;$++){const R=G[$];R.pitch===w.pitch&&Math.abs(R.freq-w.freq)<1?w.duration+=R.duration:(B.push(w),w=R)}return B.push(w),B}function te(){try{const G=Object.keys(m).length>0?Object.keys(m):["pitchy","ultrastar-wp","aubio","crepe","librosa"],B=(()=>{let ee=0;for(const D of G){const K=m[D]??[];for(const se of K)ee=Math.max(ee,se.start+(se.duration||0))}return ee||0})(),w=(ee,D)=>!ee||!D?1/0:1200*Math.log2(ee/D),$=(ee,D)=>{if(!ee||!D)return!1;const K=Math.round(Math.log2(D/ee)),se=ee*Math.pow(2,K),ce=Math.abs(w(se,D));return Math.abs(K)>=1&&ce<50},R=ee=>{const D={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!ee||ee.length===0)return D;D.count=ee.length,D.totalDur=ee.reduce((pe,X)=>pe+(X.duration||0),0);const K=ee.map(pe=>pe.freq).filter(Boolean);if(K.length===0)return D;const se=K.reduce((pe,X)=>pe+X,0)/K.length,ce=K.reduce((pe,X)=>pe+(X-se)*(X-se),0)/K.length;return D.meanFreq=se,D.stdFreq=Math.sqrt(ce||0),D.meanDur=D.totalDur/D.count,D.voicedFraction=B>0?D.totalDur/B:null,D},T=(ee,D)=>{let K=0,se=0;const ce=[];for(const X of ee){const fe=X.start,be=X.start+(X.duration||.05);let Re=null,Fe=0;for(const Te of D){const Se=Te.start,ne=Te.start+(Te.duration||.05),oe=Math.max(0,Math.min(be,ne)-Math.max(fe,Se));oe>Fe&&(Fe=oe,Re=Te)}if(Re&&Fe>0){const Te=Math.abs(w(X.freq,Re.freq));ce.push(Te),Te<50&&K++,$(X.freq,Re.freq)&&se++}}const pe=ce.length?ce.reduce((X,fe)=>X+fe,0)/ce.length:null;return{matches:K,compared:ee.length,meanCents:pe,octaveErrors:se}},C=[];C.push("# AudioPitchAnalyzer � Comparative Report"),C.push(`Generated: ${new Date().toISOString()}`),C.push(""),C.push("## Summary"),C.push(`- Selected algorithm in UI: **${i}**`),C.push(`- Total analyzed duration (approx): **${B.toFixed(3)} s**`),C.push(""),C.push("## Per-algorithm statistics"),C.push("| Algorithm | Segments | Total voiced (s) | Voiced fraction | Mean freq (Hz) | Std freq (Hz) | Mean dur (s) |"),C.push("|---|---:|---:|---:|---:|---:|---:|");const E={};for(const ee of G){const D=m[ee]??[],K=R(D);E[ee]=K,C.push(`| ${ee} | ${K.count||0} | ${(K.totalDur||0).toFixed(3)} | ${K.voicedFraction!==null?(K.voicedFraction*100).toFixed(1)+"%":"N/A"} | ${K.meanFreq?K.meanFreq.toFixed(1):"N/A"} | ${K.stdFreq?K.stdFreq.toFixed(1):"N/A"} | ${K.meanDur?K.meanDur.toFixed(3):"N/A"} |`)}C.push(""),C.push("## Pairwise agreement (reference -> test)");const F=G.includes("crepe")?"crepe":G.includes("librosa")?"librosa":G.includes("pitchy")?"pitchy":G[0];C.push(`Reference algorithm: **${F}**`),C.push(""),C.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),C.push("|---|---:|---:|---:|---:|---:|");for(const ee of G){if(ee===F)continue;const D=T(m[F]??[],m[ee]??[]),K=D.compared?(D.matches/D.compared*100).toFixed(1)+"%":"N/A";C.push(`| ${F} -> ${ee} | ${D.matches} | ${D.compared} | ${K} | ${D.meanCents!==null?D.meanCents.toFixed(1):"N/A"} | ${D.octaveErrors} |`)}C.push(""),C.push("## Observations and analysis"),C.push("- The table above gives an overview of voiced coverage and per-algorithm mean frequencies. High voiced fraction indicates the algorithm detected many tonal regions; low fraction indicates conservative voicing or failures in noisy/quiet sections."),C.push("- Pairwise match rate shows how often algorithms agree on the same regions (within ~50 cents). Octave error counts highlight typical autocorrelation octave mistakes."),C.push("- Mean cents difference (reference vs test) indicates systematic tuning offsets or frequency bias; values <50 cents are generally acceptable for musical content, but for scoring you may want <20 cents."),C.push("");for(const ee of G){C.push(`### ${ee}`);const D=E[ee];C.push(`- Segments: ${D.count||0}`),C.push(`- Total voiced (s): ${(D.totalDur||0).toFixed(3)}`),C.push(`- Voiced fraction: ${D.voicedFraction!==null?(D.voicedFraction*100).toFixed(1)+"%":"N/A"}`),C.push(`- Mean frequency: ${D.meanFreq?D.meanFreq.toFixed(2)+" Hz":"N/A"}`),C.push(`- Std frequency: ${D.stdFreq?D.stdFreq.toFixed(2)+" Hz":"N/A"}`),C.push("")}C.push("## Conclusions & recommendation");const q=[];for(const ee of G){if(ee===F){q.push({alg:ee,score:100});continue}const D=T(m[F]??[],m[ee]??[]),K=D.compared?D.matches/D.compared:0,se=D.compared?D.octaveErrors/D.compared:0,ce=K-se*.5;q.push({alg:ee,score:ce})}q.sort((ee,D)=>D.score-ee.score),C.push(`- Based on this recording, recommended authoritative detector: **${q[0].alg}** (best agreement with reference).`),C.push("- For live, low-latency feedback use Pitchy (YIN) with smoothing/hysteresis; use Crepe/Librosa for authoritative scoring or post-processing."),C.push("- If octave errors are frequent, consider octave-correction heuristics (prefer lower octave when ambiguity) or combine detectors via voting."),C.push(""),C.push("## Raw data (per-algorithm segments)");for(const ee of G){const D=m[ee]??[];C.push(`### ${ee} � ${D.length} segments`);for(const se of D)C.push(`- ${se.start.toFixed(3)} .. ${(se.start+(se.duration||0)).toFixed(3)} : ${se.freq.toFixed(2)} Hz (pitch ${se.pitch})`);const K=p[ee];K&&C.push(`- Error: ${K}`),C.push("")}const Q=C.join(`
44
- `),J=new Blob([Q],{type:"text/markdown;charset=utf-8"}),ae=URL.createObjectURL(J),re=document.createElement("a");re.href=ae,re.download="audiopitch_scientific_report_"+(n?n.name:"capture")+".md",document.body.appendChild(re),re.click(),re.remove(),URL.revokeObjectURL(ae)}catch(G){Ye.error("generateScientificReport error",G),Ye.warn(o("audioPitch.reportError")+String(G))}}return s.jsxs("div",{style:{marginTop:32,padding:16,border:"1px solid var(--nice-border, #ccc)",borderRadius:8},children:[s.jsx("h3",{children:o("audioPitch.title")}),s.jsxs("div",{style:{marginBottom:12},children:[s.jsx("label",{htmlFor:"pitch-algorithm-select",style:{marginRight:8},children:o("audioPitch.algorithm")}),s.jsxs("select",{id:"pitch-algorithm-select",value:i,onChange:G=>l(G.target.value),style:{marginRight:16},children:[s.jsx("option",{value:"ultrastar-wp",children:"Ultrastar WP (autokorelacja)"}),s.jsx("option",{value:"crepe",children:"crepe (AI)"}),s.jsx("option",{value:"pitchy",children:"pitchy (YIN)"}),s.jsx("option",{value:"librosa",children:"Librosa (PYIN)"})]}),s.jsxs("label",{style:{marginRight:8},children:[s.jsx("input",{type:"checkbox",checked:f,onChange:G=>h(G.target.checked)})," ",o("audioPitch.compareAll")]}),s.jsx("input",{type:"file",accept:"audio/*",ref:A,onChange:U,disabled:k})]}),k&&s.jsx("div",{children:o("audioPitch.analyzing")}),s.jsxs("div",{style:{marginTop:8},children:[s.jsx("b",{children:o("audioPitch.method")})," ",i]}),N&&s.jsxs("div",{style:{color:"red",marginTop:8},children:[s.jsxs("b",{children:[i,": "]}),s.jsx("div",{children:N}),V&&s.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap",marginTop:8},children:V})]}),_&&s.jsxs("div",{style:{marginTop:12},children:[s.jsx("b",{children:"Aubio diagnostics"}),s.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:_}),P&&s.jsxs("div",{style:{marginTop:8},children:[s.jsx("b",{children:"Probe:"})," ",P]})]}),(Object.keys(m).length>0||Object.keys(p).length>0)&&s.jsxs("div",{style:{marginTop:12},children:[s.jsx("button",{onClick:()=>te(),children:o("audioPitch.downloadReport")}),Object.entries(p).length>0&&s.jsxs("div",{style:{marginTop:8},children:[s.jsx("b",{children:"Per-algorithm errors:"}),Object.entries(p).filter(([G,B])=>B).map(([G,B])=>s.jsxs("div",{style:{marginTop:6},children:[s.jsxs("b",{children:[G,":"]}),s.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:B})]},G))]})]}),S.length>0&&s.jsxs("div",{style:{marginTop:16},children:[s.jsx("b",{children:o("audioPitch.resultUltrastar")}),s.jsxs("pre",{style:{background:"var(--nice-text, #222)",color:"var(--nice-bg, #fff)",padding:8,borderRadius:4},children:[S.map(G=>`: ${Math.round(G.start*10)} ${Math.round(G.duration*10)} ${G.pitch} [${G.freq.toFixed(1)} Hz]`).join(`
39
+ </svg>`;return`data:image/svg+xml;utf8,${encodeURIComponent(o)}`},Ju=(e,t,n,a,s)=>{const i=`${e}-${t}-${n}-${Math.round(a)}-${s}`;let o=Ds.get(i);return o||(o=new Image,o.src=Qu(e,t,n,a,s),Ds.set(i,o),o)},eh=e=>{const t=e.replace("#",""),n=parseInt(t.length===3?t[0]+t[0]:t.substring(0,2),16)/255,a=parseInt(t.length===3?t[1]+t[1]:t.substring(2,4),16)/255,s=parseInt(t.length===3?t[2]+t[2]:t.substring(4,6),16)/255,i=Math.max(n,a,s),o=Math.min(n,a,s);let l=0,c=0;const u=(i+o)/2;if(i!==o){const h=i-o;switch(c=u>.5?h/(2-i-o):h/(i+o),i){case n:l=(a-s)/h+(a<s?6:0);break;case a:l=(s-n)/h+2;break;case s:l=(n-a)/h+4;break}l/=6}return{h:Math.round(l*360),s:Math.round(c*100),l:Math.round(u*100)}},th=(e,t,n,a=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(n)}%, ${a})`;function Xn(e){try{const t=la(e),[n,a,s]=Au(t),i=o=>o.toString(16).padStart(2,"0");return`#${i(n)}${i(a)}${i(s)}`.toLowerCase()}catch{return"var(--nice-warning, #ffcc00)"}}function nh(e,t,n,a,s,i){const o=Math.min(i,a/2,s/2);e.beginPath(),e.moveTo(t+o,n),e.lineTo(t+a-o,n),e.quadraticCurveTo(t+a,n,t+a,n+o),e.lineTo(t+a,n+s-o),e.quadraticCurveTo(t+a,n+s,t+a-o,n+s),e.lineTo(t+o,n+s),e.quadraticCurveTo(t,n+s,t,n+s-o),e.lineTo(t,n+o),e.quadraticCurveTo(t,n,t+o,n),e.closePath()}const an=new Map,Nn=new Set,hr=new Set;function qa(e){const t=an.get(e);return t?Promise.resolve(t):hr.has(e)?Promise.reject(new Error(`Texture failed: ${e}`)):Nn.has(e)?new Promise((n,a)=>{const s=()=>{an.has(e)?n(an.get(e)):hr.has(e)?a(new Error(`Texture failed: ${e}`)):requestAnimationFrame(s)};s()}):(Nn.add(e),new Promise((n,a)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{an.set(e,s),Nn.delete(e),n(s)},s.onerror=()=>{Nn.delete(e),hr.add(e),a(new Error(`Failed to load texture: ${e}`))},s.src=e}))}function rh(e){return an.get(e)??null}function Tn(e,t,n=1){const a=an.get(t);if(!a)return!Nn.has(t)&&!hr.has(t)&&qa(t).catch(()=>{}),null;const s=e.createPattern(a,"repeat");if(!s)return null;if(n!==1){const i=new DOMMatrix;i.scaleSelf(n,n),s.setTransform(i)}return s}function ah(e){for(const t of e)t&&qa(t).catch(()=>{})}const $n=new Map,tn=new Set;function uo(e,t,n){return`${e}|${t}|${n??""}`}function sh(e,t,n){const a=uo(e.name,t,n),s=$n.get(a);if(s)return Promise.resolve(s);if(tn.has(a))return new Promise((m,g)=>{const b=()=>{$n.has(a)?m($n.get(a)):tn.has(a)?requestAnimationFrame(b):g(new Error(`Pattern render failed: ${a}`))};b()});tn.add(a);const i="p",o=e.mk(i,t,n??void 0),l=o.match(/width="(\d+)"/),c=o.match(/height="(\d+)"/),u=l?parseInt(l[1],10):16,h=c?parseInt(c[1],10):16,p=`<svg xmlns="http://www.w3.org/2000/svg" width="${u}" height="${h}"><defs>${o}</defs><rect width="${u}" height="${h}" fill="url(#${i})"/></svg>`,f=new Blob([p],{type:"image/svg+xml;charset=utf-8"}),y=URL.createObjectURL(f);return new Promise((m,g)=>{const b=new Image;b.onload=()=>{$n.set(a,b),tn.delete(a),URL.revokeObjectURL(y),m(b)},b.onerror=()=>{tn.delete(a),URL.revokeObjectURL(y),g(new Error(`Failed to render pattern tile: ${e.name}`))},b.src=y})}function Pn(e,t,n,a){const s=uo(t.name,n,a),i=$n.get(s);return i?e.createPattern(i,"repeat"):(tn.has(s)||sh(t,n,a).catch(()=>{}),null)}let Mt=null,at=null,ft=null,It=null,St=null,qe=null,_s="",Fs=0,zs="";const ua=(e,t,n,a,s,i,o,l,c,u,h,p,f,y,m,g,b,x,k,v,w,M,S,R)=>{e.clearRect(0,0,t,n);const T=R??null,j=(T==null?void 0:T.filledBar)??Vt,O=(T==null?void 0:T.emptyBar)??Lr,$=(T==null?void 0:T.goldFilledBar)??_r,E=(T==null?void 0:T.goldEmptyBar)??Dr,D=(T==null?void 0:T.font)??Fr,L=Cn(j.capStyleName),W=Cn(O.capStyleName),Z=Cn($.capStyleName),A=Cn(E.capStyleName),_=j.patternName?Mn(j.patternName):null,U=O.patternName?Mn(O.patternName):null,ne=$.patternName?Mn($.patternName):null,V=E.patternName?Mn(E.patternName):null,q=_?Pn(e,_,j.patternColor??j.color??"var(--nice-bg, #fff)",j.patternColor):null,C=U?Pn(e,U,O.patternColor??O.color??"var(--nice-border, #d1d5db)",O.patternColor):null,F=ne?Pn(e,ne,$.patternColor??"var(--nice-warning, #FFD700)",$.patternColor):null,I=V?Pn(e,V,E.patternColor??"var(--nice-warning, #FFD700)",E.patternColor):null;zs!==i&&(zs=i,oa("RENDER",`?? Renderer using settings for "${i}" � filled: cap=${j.capStyleName}, glass=${j.glass} | empty: cap=${O.capStyleName}, glass=${O.glass} | goldFilled: cap=${$.capStyleName}, pattern=${$.patternName??"none"} | goldEmpty: cap=${E.capStyleName}, pattern=${E.patternName??"none"} | hasSettings=${!!T}`,{filledBar:j,emptyBar:O,goldFilledBar:$,goldEmptyBar:E,filledOverlay:!!q,emptyOverlay:!!C,goldFilledOverlay:!!F,goldEmptyOverlay:!!I}));const P=j.textureUrl?Tn(e,j.textureUrl,j.textureScale):null,N=O.textureUrl?Tn(e,O.textureUrl,O.textureScale):null,z=$.textureUrl?Tn(e,$.textureUrl,$.textureScale):null,B=E.textureUrl?Tn(e,E.textureUrl,E.textureScale):null,G=typeof document<"u"?la(l||"var(--accent-primary, #ffcc00)"):l||"var(--accent-primary, #ffcc00)",Y=Xn(G||"var(--nice-warning, #ffcc00)"),X=pe=>la(pe),ie=D.fontFamily||"Arial",le=D.fontSize||18,te=X(D.fontColor||"var(--btn-text, #fff)"),H=D.outlineColor?X(D.outlineColor):null,K=typeof D.outlineWidth=="number"?D.outlineWidth:0,oe=D.shadow||null;typeof document<"u"&&((!Mt||Mt.width!==t||Mt.height!==n)&&(Mt=document.createElement("canvas"),Mt.width=t,Mt.height=n,at=Mt.getContext("2d")),at&&at.clearRect(0,0,t,n),(!ft||ft.width!==t||ft.height!==n)&&(ft=document.createElement("canvas"),ft.width=t,ft.height=n,It=ft.getContext("2d")),It&&It.clearRect(0,0,t,n),(!St||St.width!==t||St.height!==n)&&(St=document.createElement("canvas"),St.width=t,St.height=n,qe=St.getContext("2d")),qe&&qe.clearRect(0,0,t,n));const re=k?-k:0,he=v||t;e.fillStyle=G,e.font=`bold ${le}px ${ie}`;const de=e.measureText(i).width+20;if(e.fillRect(re+10,5,de,25),e.save(),e.fillStyle=te,oe){const pe=oe.match(/(-?\d+)px\s+(-?\d+)px\s+(\d+)px\s+(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\)|[a-zA-Z]+)/);pe&&(e.shadowOffsetX=parseInt(pe[1],10),e.shadowOffsetY=parseInt(pe[2],10),e.shadowBlur=parseInt(pe[3],10),e.shadowColor=pe[4])}if(e.fillText(i,re+20,22),H&&K>0&&(e.lineWidth=K,e.strokeStyle=H,e.strokeText(i,re+20,22)),e.restore(),b){const pe=X(x||"var(--text-secondary, #6b7280)");e.font=`bold 12px ${ie}`;const ve=e.measureText(b).width,Ue=8,Ee=re+10+de+6,Ce=20,Re=7,Oe=ve+Ue*2,Be=4;e.beginPath(),e.moveTo(Ee+Be,Re),e.lineTo(Ee+Oe-Be,Re),e.quadraticCurveTo(Ee+Oe,Re,Ee+Oe,Re+Be),e.lineTo(Ee+Oe,Re+Ce-Be),e.quadraticCurveTo(Ee+Oe,Re+Ce,Ee+Oe-Be,Re+Ce),e.lineTo(Ee+Be,Re+Ce),e.quadraticCurveTo(Ee,Re+Ce,Ee,Re+Ce-Be),e.lineTo(Ee,Re+Be),e.quadraticCurveTo(Ee,Re,Ee+Be,Re),e.closePath(),e.fillStyle=pe,e.fill(),e.fillStyle=te,e.fillText(b,Ee+Ue,Re+14),e.font=`bold ${le}px ${ie}`}const me=120;if(e.fillStyle=G,e.fillRect(re+he-me-10,5,me,25),e.fillStyle=te,e.fillText(`${o} pts`,re+he-me+15,22),w&&w.currentCombo>=5){const pe=w.currentCombo>=50?"3x":w.currentCombo>=30?"2.5x":w.currentCombo>=20?"2x":w.currentCombo>=10?"1.5x":"",ve=`${w.currentCombo} combo${pe?" "+pe:""}`;e.font=`bold 12px ${ie}`;const Ee=e.measureText(ve).width+16,Ce=re+he-me-10-Ee-6;e.fillStyle=X(w.currentCombo>=20?"var(--success, #FFD700)":"var(--warning, #ff9800)"),e.globalAlpha=.9,nh(e,Ce,7,Ee,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=X(w.currentCombo>=20?"var(--text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(ve,Ce+8,22),e.font=`bold 14px ${ie}`}if(M&&M.length>0){const pe=M[M.length-1];if(pe.label){const ve=`${M.length}-${pe.label}`;ve!==_s&&(_s=ve,Fs=Date.now());const Ue=Date.now()-Fs;if(Ue<2500){const Ee=Ue<2e3?1:1-(Ue-2e3)/500,Ce={Perfect:X("var(--success, #00e676)"),Great:X("var(--success, #66bb6a)"),Good:X("var(--accent-primary, #ffeb3b)"),OK:X("var(--warning, #ff9800)"),Bad:X("var(--error, #ef5350)"),Awful:X("var(--error, #b71c1c)")};e.save(),e.globalAlpha=Ee,e.font=`bold ${Math.round(le*1.2)}px ${ie}`;const Re=pe.label,Oe=e.measureText(Re).width,Be=re+he/2-Oe/2;e.fillStyle=Ce[Re]||te,e.shadowColor="var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",e.shadowBlur=6,e.fillText(Re,Be,58),H&&K>0&&(e.lineWidth=K,e.strokeStyle=H,e.strokeText(Re,Be,58)),e.restore()}}}const xe=s-2,ce=s+5,ye=40;let Se=1/0,ae=-1/0;if(a.forEach(pe=>{pe.forEach(ve=>{ve.pitch<Se&&(Se=ve.pitch),ve.pitch>ae&&(ae=ve.pitch)})}),c&&Array.isArray(c)&&c.length>0){let pe=null;isFinite(Se)&&isFinite(ae)&&(pe=Math.round((Se+ae)/2));let ve=1/0,Ue=-1/0;c.forEach(({t:Ee,hz:Ce})=>{if(!Ce||Ce<=0)return;let Re=pe;for(const Be of a)for(const Qe of Be)Ee>=Qe.startTime&&Ee<=Qe.startTime+Qe.duration&&(Re=Qe.pitch);const Oe=Qi(Ce,Re);Oe<ve&&(ve=Oe),Oe>Ue&&(Ue=Oe)}),ve!==1/0&&Ue!==-1/0&&(ve<Se&&(Se=Math.floor(ve-2)),Ue>ae&&(ae=Math.ceil(Ue+2)))}(!isFinite(Se)||!isFinite(ae))&&(Se=40,ae=80),Se===ae&&(Se=Math.max(0,Se-6),ae=ae+6);const ue=pe=>{const ve=n-ye-10;return ye+ve-(pe-Se)/(ae-Se)*ve},ze=Ir(f||"normal"),Ye=(n-ye-10)/Math.max(1,ae-Se),je=Math.max(10,Math.round(Ye*(1+2*ze.semitoneTolerance)*.3)),Ve=Math.max(5,Math.round(je*.45));((pe,ve,Ue,Ee,Ce,Re)=>{pe.lineWidth=1;for(let Oe=Math.ceil(Ce);Oe<=Math.floor(Re);Oe++){const Be=ue(Oe);pe.strokeStyle=X(Oe%2===0?"var(--guide-line-strong, rgba(255, 255, 255, 0.12))":"var(--guide-line-weak, rgba(255, 255, 255, 0.06))"),pe.beginPath(),pe.moveTo(0,Math.round(Be)+.5),pe.lineTo(ve,Math.round(Be)+.5),pe.stroke()}})(e,t,n-ye,ye,Se,ae),It&&It.clearRect(0,0,t,n);const et=(s-xe)/(ce-xe)*t;let Ze=n*.5,At=!1,pt=!1;const Et=(pe,ve,Ue,Ee,Ce,Re,Oe=0)=>{const Be=(Ae,Fe,ge,Me,Pe,Ge)=>{const De=Math.min(Ge,Me/2,Pe/2);Ae.beginPath(),Ae.moveTo(Fe+De,ge),Ae.lineTo(Fe+Me-De,ge),Ae.quadraticCurveTo(Fe+Me,ge,Fe+Me,ge+De),Ae.lineTo(Fe+Me,ge+Pe-De),Ae.quadraticCurveTo(Fe+Me,ge+Pe,Fe+Me-De,ge+Pe),Ae.lineTo(Fe+De,ge+Pe),Ae.quadraticCurveTo(Fe,ge+Pe,Fe,ge+Pe-De),Ae.lineTo(Fe,ge+De),Ae.quadraticCurveTo(Fe,ge,Fe+De,ge),Ae.closePath()},Qe=Math.max(2,je/2);Ee.forEach(Ae=>{if(Ae.startTime+Ae.duration<Ce||Ae.startTime>Re)return;const Fe=(Ae.startTime-Ce)/(Re-Ce)*ve,ge=Ae.duration/(Re-Ce)*ve,Me=ue(Ae.pitch)-je/2,Pe=[];if(Array.isArray(p)){const Ge=Ae.startTime+Ae.duration;p.forEach(De=>{if(De.pitch!==Ae.pitch||De.noteStart!=null&&De.noteEnd!=null&&(Math.abs(De.noteStart-Ae.startTime)>.01||Math.abs(De.noteEnd-Ge)>.01))return;const nt=Math.max(De.start,Ae.startTime),Ke=Math.min(De.end,Ge);if(nt>=Ke)return;const Gt=(nt-Ce)/(Re-Ce)*ve,Kt=(Ke-Ce)/(Re-Ce)*ve;Pe.push({x1:Gt,x2:Kt,frac:De.frac})})}if(Ae.isGold){pe.save();const Ge=m&&m.shadowColor?m.shadowColor:Ls,De=m&&typeof m.glowBlur=="number"?m.glowBlur:Is;pe.shadowColor=Ge,pe.shadowBlur=Math.max(4,De-12),pe.fillStyle=X("var(--gold-overlay, rgba(255, 215, 0, 0.15))"),Be(pe,Fe-1,Me-1,ge+2,je+2,Qe),pe.fill(),pe.restore();const nt=Xn("var(--gold-base, #b4af9f)");Rn(pe,Fe,Me,ge,je,A,E.color??nt,E.highlight,E.glow,E.glass,V,E.patternColor,E.patternOnly,B,I),pe.save(),Be(pe,Fe,Me,ge,je,Qe),pe.clip(),pe.globalAlpha=.18,pe.fillStyle=X("var(--success, #FFD700)"),pe.fillRect(Fe,Me,ge,Math.max(1,je*.25)),pe.globalAlpha=1,pe.restore(),Pe.length>0&&(pe.save(),Be(pe,Fe,Me,ge,je,Qe),pe.clip(),Pe.forEach(Ke=>{const Gt=Math.max(1,Ke.x2-Ke.x1);Rn(pe,Ke.x1,Me,Gt,je,Z,$.color??"var(--nice-warning, #FFD700)",$.highlight,$.glow,$.glass,ne,$.patternColor,$.patternOnly,z,F)}),pe.restore()),Pe.length===0&&(pe.lineWidth=1,pe.strokeStyle=X("var(--gold-outline, rgba(255, 215, 0, 0.35))"),Be(pe,Fe+.5,Me+.5,ge-1,Math.max(1,je-1),Qe),pe.stroke())}else{const Ge=Xn("var(--note-base, #d1d5db)");Rn(pe,Fe,Me,ge,je,W,O.color??Ge,O.highlight,O.glow,O.glass,U,O.patternColor,O.patternOnly,N,C),Pe.length>0&&(pe.save(),Be(pe,Fe,Me,ge,je,Qe),pe.clip(),Pe.forEach(De=>{const nt=Math.max(1,De.x2-De.x1);Rn(pe,De.x1,Me,nt,je,L,j.color??Y,j.highlight,j.glow,j.glass,_,j.patternColor,j.patternOnly,P,q)}),pe.restore())}It&&(It.fillStyle="var(--nice-bg, #fff)",It.fillRect(Fe,Me,ge,je))})};if(a.forEach(pe=>{Et(e,t,n-ye,pe,xe,ce,ye);for(const ve of pe)if(s>=ve.startTime&&s<=ve.startTime+ve.duration){Ze=ue(ve.pitch),At=!0,pt=!!ve.isGold;break}}),!At){let pe=null,ve=null;for(const Ue of a)for(const Ee of Ue)Ee.startTime>s&&(!pe||Ee.startTime<pe.startTime)&&(pe=Ee),Ee.startTime<=s&&(!ve||Ee.startTime>ve.startTime)&&(ve=Ee);pe?(Ze=ue(pe.pitch),pt=!!pe.isGold):ve?(Ze=ue(ve.pitch),pt=!!ve.isGold):Ze=n*.5}const ct=G||X("var(--accent-primary, #ffcc00)"),fe=1+Math.sin((s||0)*8)*.06,be=Ve*fe,_e=[];for(const pe of a)for(const ve of pe){if(ve.startTime+ve.duration<xe||ve.startTime>ce)continue;const Ue=(ve.startTime-xe)/(ce-xe)*t,Ee=ve.duration/(ce-xe)*t,Ce=ue(ve.pitch)-je/2,Re=ve.startTime+ve.duration<=s;_e.push({x:Ue,y:Ce,w:Ee,h:je,isGold:ve.isGold,isSung:Re})}if(!Hu(S||"ball",{ctx:e,ballX:et,ballY:Ze,ballRadius:be,playerColor:ct,ballIsGold:pt,currentTime:s,height:n,visibleNotes:_e})){Mt&&e.drawImage(Mt,0,0),St&&e.drawImage(St,0,0),e.save(),e.globalCompositeOperation="source-over",e.globalAlpha=.28;const pe=Math.max(18,be*5),ve=e.createRadialGradient(et,Ze,0,et,Ze,pe);if(ve.addColorStop(0,ct),ve.addColorStop(1,"transparent"),e.fillStyle=ve,e.beginPath(),e.arc(et,Ze,pe,0,Math.PI*2),e.fill(),e.restore(),y&&at&&ft&&(at.save(),at.globalCompositeOperation="source-over",at.globalAlpha=.95,at.fillStyle=ct,at.beginPath(),at.arc(et,Ze,be+4,0,Math.PI*2),at.fill(),at.restore(),at.save(),at.globalCompositeOperation="destination-in",at.drawImage(ft,0,0),at.restore(),e.drawImage(Mt,0,0)),y&&qe&&ft)try{const Ce=Xn(ct),{h:Re,s:Oe,l:Be}=eh(Ce),Ae=th(Re,Math.max(10,Math.round(Oe*(typeof h=="number"?h:.25))),Be,.85);qe.save(),qe.globalCompositeOperation="multiply",qe.globalAlpha=.65,qe.fillStyle=Ae,qe.beginPath(),qe.arc(et,Ze,Math.max(8,be+6),0,Math.PI*2),qe.fill(),qe.restore(),qe.save(),qe.globalCompositeOperation="destination-out",qe.drawImage(ft,0,0),qe.restore(),e.drawImage(St,0,0)}catch{qe.save(),qe.globalCompositeOperation="source-over",qe.globalAlpha=.6,qe.fillStyle=ct,qe.beginPath(),qe.arc(et,Ze,Math.max(8,be+6),0,Math.PI*2),qe.fill(),qe.restore(),qe.save(),qe.globalCompositeOperation="destination-out",qe.drawImage(ft,0,0),qe.restore(),e.drawImage(St,0,0)}const Ue=m&&m.shadowColor?m.shadowColor:Ls,Ee=m&&typeof m.glowBlur=="number"?m.glowBlur:Is;e.save(),pt?(e.shadowColor=Ue,e.shadowBlur=Ee,e.fillStyle=X("var(--gold-light, #FFF0A8)")):(e.shadowColor=ct,e.shadowBlur=10,e.fillStyle=ct),e.globalCompositeOperation="source-over",e.globalAlpha=1,e.beginPath(),e.arc(et,Ze,be,0,Math.PI*2),e.fill(),e.lineWidth=1.5,e.strokeStyle=X("var(--shadow, rgba(0,0,0,0.35))"),e.stroke(),e.restore()}try{if(Array.isArray(g)&&g.length>0){const pe=Date.now(),ve=m&&typeof m.lifeMs=="number"?m.lifeMs:Ku,Ue=(Ce,Re,Oe,Be=5)=>{const Qe=Oe,Ae=Oe*.45;e.beginPath();let Fe=Math.PI/2*3,ge=Ce,Me=Re;const Pe=Math.PI/Be;e.moveTo(Ce,Re-Qe);for(let Ge=0;Ge<Be;Ge++)ge=Ce+Math.cos(Fe)*Qe,Me=Re+Math.sin(Fe)*Qe,e.lineTo(ge,Me),Fe+=Pe,ge=Ce+Math.cos(Fe)*Ae,Me=Re+Math.sin(Fe)*Ae,e.lineTo(ge,Me),Fe+=Pe;e.lineTo(Ce,Re-Qe),e.closePath()},Ee=Ce=>{let Re=Ce>>>0;return()=>(Re=Re*1664525+1013904223>>>0,(Re&2147483647)/2147483647)};g.forEach(Ce=>{const Re=pe-Ce.createdAt;if(Re<0||Re>ve)return;const Oe=Re/ve,Be=(Ce.noteStart-(s-2))/7*t,Qe=ue(Ce.notePitch),Ae=Ee(Ce.seed||Math.floor(Ce.createdAt%1e5)),Fe=m&&typeof m.count=="number"?m.count:Yu,ge=m&&typeof m.baseSpeed=="number"?m.baseSpeed:Zu,Me=m&&typeof m.baseSize=="number"?m.baseSize:Xu;for(let Pe=0;Pe<Fe;Pe++){const Ge=Ae(),De=Ae(),nt=Pe/Fe*Math.PI*2+Ge*Math.PI*.6+Oe*1.5,Ke=6+ge*(1-Oe)*(.5+De*.8),Gt=Be+Math.cos(nt)*Ke,Kt=Qe+Math.sin(nt)*Ke*(.8+Ge*.6),Ct=Math.max(1,Me*(1-Oe)*(.5+De)),xs=40+Math.round(20*Ae()),vs=70+Math.round(20*Ae()),Gr=Math.max(0,1-Oe)*(.9-Ae()*.3),Oc=Math.max(6,Ct*2.6),Wr=Ju(xs,vs,60,Math.round(Oc),(Ce.seed||0)+Pe);Wr&&Wr.complete?(e.save(),e.translate(Gt,Kt+4),e.rotate(nt+Oe*4+(Ae()-.5)*1.2),e.globalAlpha=Gr,e.drawImage(Wr,-Ct/2,-Ct/2,Ct,Ct),e.restore()):(e.save(),e.translate(Gt,Kt+4),e.rotate(nt+Oe*4),e.fillStyle=`hsla(${xs}, ${vs}%, 60%, ${Gr})`,e.fillRect(-Ct/2,-Ct/2,Ct,Ct),e.restore()),Ae()>.85&&(e.save(),e.globalAlpha=Math.max(.35,1-Oe),e.fillStyle=`hsla(${30+Math.round(10*Ae())}, ${60+Math.round(30*Ae())}%, ${70+Math.round(10*Ae())}%, ${Gr})`,e.strokeStyle=`rgba(0,0,0,${.12*(1-Oe)})`,e.lineWidth=.8,Ue(Gt,Kt+4,Ct*(1.4+Ae())),e.fill(),e.stroke(),e.restore())}})}}catch{}return{ballX:et,ballY:Ze,ballIsGold:pt}},Va=({song:e,currentTime:t,playerRef:n,config:a={},userPitch:s,segmentScores:i,goldBursts:o,combo:l,verseRatings:c})=>{const{isPlaying:u=!1,playerName:h="Ziom",score:p=1e4,playerBgColor:f="var(--karaoke-player-bg, #2196f3)",playerCount:y=2,gapDesaturation:m,goldSettings:g,difficultyLevel:b,algorithmLabel:x,algorithmColor:k,latencyMs:v=null,top:w,animationMode:M,karaokeSettings:S=null}=a,R=d.useRef(null),T=d.useRef(null),[j,O]=d.useState({width:600,height:150,top:250,visibleWidth:600}),[$,E]=d.useState(0),D=d.useRef(0),L=d.useRef(null),W=d.useRef(null),Z=d.useRef(null),A=d.useRef(t),_=d.useRef(performance.now()),U=d.useRef(e),ne=d.useRef(j),V=d.useRef(s),q=d.useRef(u),C=d.useRef(0),F=d.useRef(!1),I=d.useRef(null),P=d.useRef(null),N=()=>{const z=(e==null?void 0:e.id)??null;if(z!==P.current||!I.current){P.current=z;const B=e.notes.map(te=>te.noteLine);I.current=qn(B,e.bpm??void 0);const G=I.current.reduce((te,H)=>te+H.length,0),Y=I.current.reduce((te,H)=>te+H.filter(K=>K.isGold).length,0),X=I.current.flat().map(te=>te.pitch),ie=X.length?Math.min(...X):0,le=X.length?Math.max(...X):0;oa("BARS",`?? Parsed notes for "${e.title}" — ${I.current.length} verses, ${G} notes (including ${Y} golden), pitch range: ${ie}–${le}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:B.length,verseCount:I.current.length,totalNotes:G,goldCount:Y,minPitch:ie,maxPitch:le})}return I.current};return d.useEffect(()=>{const z=(G,Y,X)=>G+(Y-G)*X,B=G=>{W.current===null&&(W.current=G);const Y=Math.min(.1,(G-(W.current||G))/1e3);W.current=G;const X=C.current,ie=D.current,le=1-Math.exp(-12*Y),te=Math.abs(ie-X)<.25?ie:z(X,ie,le);Math.abs(te-X)>1e-4&&(E(te),C.current=te,R.current&&(R.current.style.transform=`translateX(${te}px)`)),L.current=requestAnimationFrame(B)};return L.current=requestAnimationFrame(B),()=>{L.current&&cancelAnimationFrame(L.current),L.current=null,W.current=null}},[]),d.useEffect(()=>{const z=()=>{if(!n.current)return;const B=n.current.getBoundingClientRect(),G=2/Math.max(1,y),Y=Math.round(B.width*G),X=Math.round(B.width),ie=Y*(150/600);O({width:Y,height:ie,top:30,visibleWidth:X})};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[n,y]),d.useEffect(()=>{var X;if(u||!R.current)return;const z=R.current.getContext("2d");if(!z)return;const B=N(),G=t-(e.gap??0)/1e3,Y=ua(z,j.width,j.height,B,G,h,p,f,s,e.id,m??void 0,i,b??void 0,u,g??void 0,o,x,k,C.current,j.visibleWidth,l,c,M,S);if(Y&&R.current){const ie=j.visibleWidth||(((X=T.current)==null?void 0:X.getBoundingClientRect().width)??j.width),le=j.width;let te=Math.round(ie/2-Y.ballX);const H=ie-le;te=Math.max(H,Math.min(0,te)),D.current=te}},[t,e,j,s,u,i,o,M,S]),d.useEffect(()=>{A.current=t,_.current=performance.now()},[t]),d.useEffect(()=>{U.current=e},[e]),d.useEffect(()=>{ne.current=j},[j]),d.useEffect(()=>{V.current=s},[s]),d.useEffect(()=>{q.current=u},[u]),d.useEffect(()=>{const z=()=>{var oe;const B=R.current,G=U.current,Y=ne.current;if(!B||!G||!Y)return;const X=B.getContext("2d");if(!X)return;const ie=N(),le=Math.min(.5,(performance.now()-_.current)/1e3),H=(q.current?A.current+le:A.current)-(G.gap??0)/1e3,K=ua(X,Y.width,Y.height,ie,H,h,p,f,V.current,G.id,m??void 0,i,b??void 0,q.current,g??void 0,o,x,k,C.current,Y.visibleWidth,l,c,M,S);if(K){const re=Y.visibleWidth||(((oe=T.current)==null?void 0:oe.getBoundingClientRect().width)??Y.width),he=Y.width;let Q=Math.round(re/2-K.ballX);const de=re-he;Q=Math.max(de,Math.min(0,Q)),D.current=Q}};if(u){F.current||(F.current=!0,oa("BARS",`? Drawing bars in RAF loop � canvas: ${ne.current.width}�${ne.current.height}px, player: ${h}`,{canvasSize:ne.current}));const B=()=>{z(),Z.current=requestAnimationFrame(B)};return Z.current=requestAnimationFrame(B),()=>{Z.current&&cancelAnimationFrame(Z.current),Z.current=null}}F.current=!1},[u,h,p,f,m,i,b,g,o,M,S]),r.jsxs("div",{ref:T,style:{position:"absolute",left:"50%",top:`${w??j.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:j.visibleWidth,height:j.height,overflow:"hidden"},children:[r.jsx("style",{children:"@keyframes av-latency-pulse {0% { transform: scale(1); box-shadow: 0 4px 10px var(--nice-overlay-20, rgba(0, 0, 0, 0.2));} 50% { transform: scale(1.08); box-shadow: 0 8px 18px var(--nice-overlay-30, rgba(0,0,0,0.32));} 100% { transform: scale(1); box-shadow: 0 4px 10px var(--nice-overlay-20, rgba(0, 0, 0, 0.2));} } .av-latency-pulse { animation: av-latency-pulse 1s ease-in-out infinite; }"}),r.jsx("div",{style:{position:"absolute",right:8,top:6,zIndex:40,pointerEvents:"none",display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--text-on-dark, #fff)"},children:typeof v<"u"&&v!==null?(()=>{const z=v,B=z<=120?"var(--latency-good, #10b981)":z<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",G=`${z}ms`;return r.jsxs("div",{className:z>250?"av-latency-pulse":"",style:{background:B,padding:"6px 10px",borderRadius:12,boxShadow:"0 4px 10px var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",fontWeight:700,minWidth:56,textAlign:"center",display:"flex",alignItems:"center",gap:6},children:[r.jsx("span",{style:{display:"inline-block",transform:"translateY(-1px)"},children:"??"}),r.jsx("span",{children:G})]})})():r.jsx("div",{style:{background:"var(--latency-none-bg, rgba(75,85,99,0.9))",padding:"6px 8px",borderRadius:12,boxShadow:"0 4px 10px var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",minWidth:44,textAlign:"center"},children:"�"})}),r.jsx("canvas",{ref:R,width:j.width,height:j.height,role:"img","aria-label":`Pitch timeline for ${h??"player"}. Score: ${p??0}`,style:{position:"absolute",left:0,top:0,transform:`translateX(${$}px)`,willChange:"transform"}})]})},ho="/textures/seamless/256x256";function $t(e,t,n){return{name:e,icon:n,entries:Array.from({length:t},(a,s)=>{const i=String(s+1).padStart(2,"0");return{label:`${e} ${i}`,url:`${ho}/${e}/Photoreal_${e}_${i}-512x512.png`}})}}function Lt(e,t,n){return{name:e,icon:n,entries:Array.from({length:t},(a,s)=>{const i=String(s+1).padStart(2,"0");return{label:`${e} ${i}`,url:`${ho}/${e}/${e}_${i}-256x256.png`}})}}const Ha=[$t("Fire",8,"🔥"),$t("Metal",8,"⚙️"),$t("Ice",8,"❄️"),$t("Stone",8,"🪨"),$t("Wood",8,"🪵"),$t("Tile",8,"🧱"),$t("Concrete",8,"🏗️"),$t("Trees",8,"🌲"),$t("Grass",8,"🌿"),Lt("Wall",24,"🏠"),Lt("Rust",24,"🟤"),Lt("Woven",24,"🧵"),Lt("Ground",24,"🟫"),Lt("Pebbles",24,"🫧"),Lt("Plant",24,"🌱"),Lt("Roof",24,"🏛️"),Lt("Misc",24,"🎨")],po=Ha.flatMap(e=>e.entries);function ih(e){return po.find(t=>t.url===e)}const oh={color:"var(--nice-primary, #2196f3)",highlight:"var(--nice-bg, #fff)",glow:0,capStyle:"flat",pattern:null,texture:null},fo=({fill:e=oh,onChange:t=()=>{},previewColor:n="var(--nice-primary, #2196f3)",accentColor:a="var(--nice-primary, #0d6efd)",width:s,height:i})=>{const{t:o}=Te(),[l,c]=d.useState(null),u=(x,k)=>{t({...e,[x]:k})},h=d.useMemo(()=>{const x=e.color||n||"var(--nice-primary, #2196f3)";return(k,v,w)=>{const M=Bn.find(R=>R.name===k)||Bn[0],S=v?Nr.find(R=>R.name===v)??null:null;return co({width:80,height:22,capStyle:M,color:x,highlight:e.highlight,glow:e.glow,glass:e.glass,pattern:S,patternColor:e.patternColor,patternOnly:e.patternOnly,textureUrl:w??null,textureScale:e.textureScale})}},[e,n]),p=`2px solid ${a}`,f=a==="var(--nice-warning-dark, #d4a017)"?"var(--nice-warning-bg, #fff8e1)":"var(--nice-info-bg, #e7f1ff)",y=d.useRef(null),m=d.useRef(null),g=d.useCallback((x,k)=>{x.current&&x.current.scrollBy({left:k*180,behavior:"smooth"})},[]),b={position:"absolute",top:0,width:28,height:"100%",border:"none",cursor:"pointer",zIndex:2,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,fontWeight:700,color:"var(--nice-border, #ccc)",background:"linear-gradient(90deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"};return r.jsxs("div",{style:{padding:"4px 0"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[r.jsx(rt.Form.Label,{className:"mb-0",style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:o("playerForm.barColor","Color")}),r.jsx(rt.Form.Check,{type:"checkbox",id:`bar-color-auto-${a}`,label:o("playerForm.auto","Auto"),checked:!e.color,onChange:x=>u("color",x.target.checked?null:n||"var(--nice-primary, #2196f3)"),className:"mb-0"}),e.color&&r.jsx("input",{type:"color",value:e.color,onChange:x=>u("color",x.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),r.jsx(rt.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:o("playerForm.capShape","Cap shape")}),r.jsxs("div",{style:{position:"relative",marginBottom:10},children:[r.jsx("button",{type:"button",style:{...b,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>g(y,-1),children:"�"}),r.jsx("button",{type:"button",style:{...b,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>g(y,1),children:"�"}),r.jsx("div",{ref:y,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:Bn.map(x=>{const k=e.capStyleName===x.name;return r.jsx("div",{title:x.name,onClick:()=>u("capStyleName",x.name),style:{cursor:"pointer",flexShrink:0,border:k?p:"1px solid var(--nice-text-secondary, #555)",borderRadius:6,padding:3,background:k?f:"var(--nice-text, #222)"},dangerouslySetInnerHTML:{__html:h(x.name,null)}},x.name)})})]}),r.jsx(rt.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:o("playerForm.pattern","Pattern")}),r.jsxs("div",{style:{position:"relative",marginBottom:10},children:[r.jsx("button",{type:"button",style:{...b,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>g(m,-1),children:"�"}),r.jsx("button",{type:"button",style:{...b,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>g(m,1),children:"�"}),r.jsxs("div",{ref:m,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:[r.jsx("div",{title:"None",onClick:()=>u("patternName",null),style:{cursor:"pointer",flexShrink:0,border:e.patternName?"1px solid var(--nice-text-secondary, #555)":p,borderRadius:6,padding:"3px 8px",background:e.patternName?"var(--nice-text, #222)":f,fontSize:12,lineHeight:"22px",color:"var(--nice-border, #ccc)"},children:"�"}),Nr.map(x=>{const k=e.patternName===x.name;return r.jsx("div",{title:x.name,onClick:()=>u("patternName",x.name),style:{cursor:"pointer",flexShrink:0,border:k?p:"1px solid var(--nice-text-secondary, #555)",borderRadius:6,padding:3,background:k?f:"var(--nice-text, #222)"},dangerouslySetInnerHTML:{__html:h(e.capStyleName,x.name)}},x.name)})]})]}),r.jsx(rt.Form.Check,{type:"switch",id:`bar-pattern-only-${a}`,label:o("playerForm.patternOnly","Pattern only (flat, no 3D)"),checked:e.patternOnly,onChange:x=>u("patternOnly",x.target.checked),className:"mb-2"}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[r.jsx(rt.Form.Label,{className:"mb-0",style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:o("playerForm.patternColor","Pattern color")}),r.jsx(rt.Form.Check,{type:"checkbox",id:`bar-pattern-color-auto-${a}`,label:o("playerForm.auto","Auto"),checked:!e.patternColor,onChange:x=>u("patternColor",x.target.checked?null:n||"var(--nice-bg, #fff)"),className:"mb-0"}),e.patternColor&&r.jsx("input",{type:"color",value:e.patternColor,onChange:x=>u("patternColor",x.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),!e.patternOnly&&r.jsxs(r.Fragment,{children:[r.jsxs(rt.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[o("playerForm.highlight","Highlight"),": ",e.highlight,"%"]}),r.jsx(rt.Form.Range,{min:0,max:100,value:e.highlight,onChange:x=>u("highlight",parseInt(x.target.value)),className:"mb-2"}),r.jsxs(rt.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[o("playerForm.glow","Glow"),": ",e.glow,"%"]}),r.jsx(rt.Form.Range,{min:0,max:100,value:e.glow,onChange:x=>u("glow",parseInt(x.target.value)),className:"mb-2"})]}),r.jsxs(rt.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[o("playerForm.glass","Transparency (glass)"),": ",e.glass,"%"]}),r.jsx(rt.Form.Range,{min:0,max:100,value:e.glass,onChange:x=>u("glass",parseInt(x.target.value)),className:"mb-2"}),r.jsx(rt.Form.Label,{style:{fontSize:13,fontWeight:600,marginTop:4,color:"var(--nice-border, #ccc)"},children:o("playerForm.texture","Texture")}),r.jsxs("div",{style:{marginBottom:6},children:[r.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",marginBottom:6},children:[r.jsx("button",{type:"button",className:`btn btn-sm ${e.textureUrl?"btn-outline-secondary":"btn-primary"}`,onClick:()=>{u("textureUrl",null),c(null)},children:o("playerForm.texNone","None")}),Ha.map(x=>r.jsx("button",{type:"button",className:`btn btn-sm ${(l==null?void 0:l.name)===x.name?"btn-primary":"btn-outline-secondary"}`,onClick:()=>c(k=>(k==null?void 0:k.name)===x.name?null:x),title:x.name,children:x.icon},x.name))]}),l&&r.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap",maxHeight:130,overflowY:"auto",padding:4,border:"1px solid var(--nice-border, #dee2e6)",borderRadius:6,background:"var(--nice-bg-secondary, #f8f9fa)"},children:l.entries.map(x=>{const k=e.textureUrl===x.url;return r.jsx("div",{title:x.label,onClick:()=>u("textureUrl",k?null:x.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:k?`3px solid ${a}`:"1px solid var(--nice-text-muted, #bbb)",backgroundImage:`url(${x.url})`,backgroundSize:"cover",boxShadow:k?`0 0 6px ${a}`:void 0}},x.url)})}),e.textureUrl&&r.jsxs("div",{style:{marginTop:4,display:"flex",alignItems:"center",gap:8},children:[r.jsx("div",{style:{width:80,height:22,borderRadius:6,backgroundImage:`url(${e.textureUrl})`,backgroundSize:`${Math.round(256*e.textureScale)}px`,border:"1px solid var(--nice-text-muted, #aaa)"}}),r.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #666)"},children:e.textureUrl.split("/").pop()})]})]}),e.textureUrl&&r.jsxs(r.Fragment,{children:[r.jsxs(rt.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[o("playerForm.textureScale","Texture scale"),": ",e.textureScale.toFixed(1),"�"]}),r.jsx(rt.Form.Range,{min:10,max:200,step:10,value:Math.round(e.textureScale*100),onChange:x=>u("textureScale",parseInt(x.target.value)/100),className:"mb-2"})]})]})},st=it.scoped("AudioPitchAnalyzer");function mo({onSegments:e,defaultCompareAll:t=!1,externalFile:n=null,postPitch:a,postLibrosaPitchTrack:s}){const{t:i}=Te(),[o,l]=d.useState("pitchy"),[c,u]=d.useState(null),[h,p]=d.useState(t),[f,y]=d.useState({}),[m,g]=d.useState({}),[b,x]=d.useState([]),[k,v]=d.useState([]),[w,M]=d.useState(!1),[S,R]=d.useState(null),[T]=d.useState(null),[j]=d.useState(null),[O,$]=d.useState(null),E=d.useRef(null);function D(V){try{if(V instanceof Error){let C=`${V.message}
40
+ ${V.stack??""}`;const F=V;if(F!=null&&F.attemptedUrls)try{C+=`
41
+ Attempted URLs: ${Array.isArray(F.attemptedUrls)?F.attemptedUrls.join(", "):String(F.attemptedUrls)}`}catch{C+=`
42
+ Attempted URLs: ${String(F.attemptedUrls)}`}return C}const q=V;return q!=null&&q.attemptedUrls?`Error: ${String(q.message??q)}
43
+ Attempted URLs: ${Array.isArray(q.attemptedUrls)?q.attemptedUrls.join(", "):String(q.attemptedUrls)}`:String(V)}catch{return"Unknown error"}}function L(V){if(!V||V<=0)return null;const q=12*Math.log2(V/440)+69;return Math.round(q-12)}async function W(V){var C;const q=(C=V.target.files)==null?void 0:C[0];q&&await Z(q,h)}async function Z(V,q){R(null),v([]),M(!0);try{const C=await V.arrayBuffer(),F=window.AudioContext??window.webkitAudioContext,P=await new F().decodeAudioData(C),N=P.getChannelData(0);u(N);const z=P.sampleRate,B=Math.floor(z*.1),G=B,Y=()=>{const K=[],oe=ra.PitchDetector.forFloat32Array(B);for(let re=0;re<N.length-B;re+=G){const he=N.slice(re,re+B),[Q,de]=oe.findPitch(he,z),me=L(Q);me&&Q>50&&Q<2e3&&de>.7&&K.push({start:re/z,duration:B/z,pitch:me,freq:Q})}return K},X=()=>{const K=[];for(let oe=0;oe<N.length-B;oe+=G){const re=N.slice(oe,oe+B),he=_(re,z),Q=L(he);Q&&he>50&&he<2e3&&K.push({start:oe/z,duration:B/z,pitch:Q,freq:he})}return K};if(q){M(!0),R(null);const K={};try{const oe={};try{K.pitchy=Y(),oe.pitchy=null}catch(re){K.pitchy=[],oe.pitchy=D(re),st.warn("pitchy failed",re)}try{K["ultrastar-wp"]=X(),oe["ultrastar-wp"]=null}catch(re){K["ultrastar-wp"]=[],oe["ultrastar-wp"]=D(re),st.warn("ultrastar-wp failed",re)}K.aubio=[],oe.aubio="disabled";try{if(!a)throw new Error("CREPE backend not configured");const he=(await a(V)).track??[];K.crepe=he.map((Q,de)=>{var me;return{start:Q.t,duration:(me=he[de+1])!=null&&me.t?he[de+1].t-Q.t:.1,pitch:L(Q.hz)??0,freq:Q.hz}}),oe.crepe=null}catch(re){K.crepe=[],oe.crepe=D(re),st.warn("crepe failed",re)}try{if(!s)throw new Error("Librosa backend not configured");const he=(await s(new File([V],V.name,{type:V.type}))).track??[];K.librosa=he.map((Q,de)=>{var me;return{start:Q.t,duration:(me=he[de+1])!=null&&me.t?he[de+1].t-Q.t:.1,pitch:L(Q.hz)??0,freq:Q.hz}}),oe.librosa=null}catch(re){K.librosa=[],oe.librosa=D(re),st.warn("librosa failed",re)}g(oe),y(K),v(K[o]??[])}catch(oe){st.error("compareAll overall failed",oe);const re=oe instanceof Error?oe.message:String(oe);R(i("audioPitch.errorComparing")+re)}finally{M(!1)}return}const ie=[],le=[];let te=0;if(o==="pitchy"){const K=ra.PitchDetector.forFloat32Array(B);for(let oe=0;oe<N.length-B;oe+=G){const re=N.slice(oe,oe+B);let he=0;for(let xe=0;xe<re.length;xe++)he+=re[xe]*re[xe];he=Math.sqrt(he/re.length),le.push(he);const[Q,de]=K.findPitch(re,z),me=L(Q);me&&Q>50&&Q<2e3&&de>.7&&(ie.push({start:oe/z,duration:B/z,pitch:me,freq:Q}),te++)}}else if(o==="crepe")try{if(!a)throw new Error("CREPE backend not configured");const K=await a(V);if(!K.track||K.track.length===0)R(i("audioPitch.crepeNoNotes")),st.warn("Crepe: No notes detected in audio file.");else{const oe=K.track.map((re,he)=>{const Q=L(re.hz);return Q&&re.hz>50&&re.hz<2e3?{start:re.t,duration:he<K.track.length-1?K.track[he+1].t-re.t:.1,pitch:Q,freq:re.hz}:null}).filter(re=>re!==null);if(v(oe),e)try{e(oe)}catch(re){st.error("Error in onSegments:",re)}x([]),u(null);return}}catch(K){R(i("audioPitch.crepeBackendError")),$(D(K)),st.error("Crepe: Error calling backend:",K)}else if(o==="librosa")try{await A(V),x([]),u(null);return}catch(K){R(i("audioPitch.librosaBackendError")),$(D(K)),st.error("Librosa: Error calling backend:",K)}else if(o==="ultrastar-wp")for(let K=0;K<N.length-B;K+=G){const oe=N.slice(K,K+B);let re=0;for(let de=0;de<oe.length;de++)re+=oe[de]*oe[de];re=Math.sqrt(re/oe.length),le.push(re);const he=_(oe,z),Q=L(he);Q&&he>50&&he<2e3&&(ie.push({start:K/z,duration:B/z,pitch:Q,freq:he}),te++)}x(le);const H=U(ie);if(v(H),e)try{e(H)}catch(K){st.error("Error in onSegments:",K)}H.length===0&&o!=="crepe"&&(R(i("audioPitch.noNotesDetected")),st.warn("No notes detected in audio file."))}catch(C){R(i("audioPitch.errorAnalyzing")+(C instanceof Error?C.message:String(C))),$(D(C)),st.error("Error analyzing audio file:",C)}finally{M(!1)}}d.useEffect(()=>{n&&Z(n,!0)},[n]);async function A(V){try{if(!s)throw new Error("Librosa backend not configured");const q=new File([V],"capture.wav",{type:"audio/wav"}),F=((await s(q)).track??[]).map(I=>({t:I.t,hz:I.hz}));if(e){const I=F.map((P,N)=>{var G;const z=((G=F[N+1])==null?void 0:G.t)??P.t+.1,B=L(P.hz)??0;return{start:P.t,duration:Math.max(.05,z-P.t),pitch:B,freq:P.hz}});e(I),v(I)}}catch(q){st.warn("Librosa analysis failed, falling back to local detectors",q);const F=(typeof q=="object"&&q!==null?q:{}).attemptedUrls;F&&st.error("Librosa attempted URLs:",F);const I=F?Array.isArray(F)?F.join(", "):String(F):null,P=q instanceof Error?q.message:String(q);R(i("audioPitch.librosaBackendError")+": "+P+(I?" (attempted: "+I+")":"")),$(D(q))}}function _(V,q){const I=Math.floor(q/50),P=Math.max(2,Math.floor(q/2e3));let N=0;for(let Y=0;Y<V.length;Y++)N+=V[Y]*V[Y];if(N<=1e-8)return 0;let z=-1,B=0;const G=1e-10;for(let Y=P;Y<=Math.min(I,V.length-2);Y++){let X=0;const ie=V.length-Y;for(let te=0;te<ie;te++)X+=V[te]*V[te+Y];const le=X/(ie+G)/(N/V.length+G);le>B&&(B=le,z=Y)}return z>0&&B>.01?q/z:0}function U(V){if(V.length===0)return[];const q=[];let C=V[0];for(let F=1;F<V.length;F++){const I=V[F];I.pitch===C.pitch&&Math.abs(I.freq-C.freq)<1?C.duration+=I.duration:(q.push(C),C=I)}return q.push(C),q}function ne(){try{const V=Object.keys(f).length>0?Object.keys(f):["pitchy","ultrastar-wp","aubio","crepe","librosa"],q=(()=>{let te=0;for(const H of V){const K=f[H]??[];for(const oe of K)te=Math.max(te,oe.start+(oe.duration||0))}return te||0})(),C=(te,H)=>!te||!H?1/0:1200*Math.log2(te/H),F=(te,H)=>{if(!te||!H)return!1;const K=Math.round(Math.log2(H/te)),oe=te*Math.pow(2,K),re=Math.abs(C(oe,H));return Math.abs(K)>=1&&re<50},I=te=>{const H={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!te||te.length===0)return H;H.count=te.length,H.totalDur=te.reduce((he,Q)=>he+(Q.duration||0),0);const K=te.map(he=>he.freq).filter(Boolean);if(K.length===0)return H;const oe=K.reduce((he,Q)=>he+Q,0)/K.length,re=K.reduce((he,Q)=>he+(Q-oe)*(Q-oe),0)/K.length;return H.meanFreq=oe,H.stdFreq=Math.sqrt(re||0),H.meanDur=H.totalDur/H.count,H.voicedFraction=q>0?H.totalDur/q:null,H},P=(te,H)=>{let K=0,oe=0;const re=[];for(const Q of te){const de=Q.start,me=Q.start+(Q.duration||.05);let xe=null,ce=0;for(const ye of H){const Se=ye.start,ae=ye.start+(ye.duration||.05),ue=Math.max(0,Math.min(me,ae)-Math.max(de,Se));ue>ce&&(ce=ue,xe=ye)}if(xe&&ce>0){const ye=Math.abs(C(Q.freq,xe.freq));re.push(ye),ye<50&&K++,F(Q.freq,xe.freq)&&oe++}}const he=re.length?re.reduce((Q,de)=>Q+de,0)/re.length:null;return{matches:K,compared:te.length,meanCents:he,octaveErrors:oe}},N=[];N.push("# AudioPitchAnalyzer � Comparative Report"),N.push(`Generated: ${new Date().toISOString()}`),N.push(""),N.push("## Summary"),N.push(`- Selected algorithm in UI: **${o}**`),N.push(`- Total analyzed duration (approx): **${q.toFixed(3)} s**`),N.push(""),N.push("## Per-algorithm statistics"),N.push("| Algorithm | Segments | Total voiced (s) | Voiced fraction | Mean freq (Hz) | Std freq (Hz) | Mean dur (s) |"),N.push("|---|---:|---:|---:|---:|---:|---:|");const z={};for(const te of V){const H=f[te]??[],K=I(H);z[te]=K,N.push(`| ${te} | ${K.count||0} | ${(K.totalDur||0).toFixed(3)} | ${K.voicedFraction!==null?(K.voicedFraction*100).toFixed(1)+"%":"N/A"} | ${K.meanFreq?K.meanFreq.toFixed(1):"N/A"} | ${K.stdFreq?K.stdFreq.toFixed(1):"N/A"} | ${K.meanDur?K.meanDur.toFixed(3):"N/A"} |`)}N.push(""),N.push("## Pairwise agreement (reference -> test)");const B=V.includes("crepe")?"crepe":V.includes("librosa")?"librosa":V.includes("pitchy")?"pitchy":V[0];N.push(`Reference algorithm: **${B}**`),N.push(""),N.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),N.push("|---|---:|---:|---:|---:|---:|");for(const te of V){if(te===B)continue;const H=P(f[B]??[],f[te]??[]),K=H.compared?(H.matches/H.compared*100).toFixed(1)+"%":"N/A";N.push(`| ${B} -> ${te} | ${H.matches} | ${H.compared} | ${K} | ${H.meanCents!==null?H.meanCents.toFixed(1):"N/A"} | ${H.octaveErrors} |`)}N.push(""),N.push("## Observations and analysis"),N.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."),N.push("- Pairwise match rate shows how often algorithms agree on the same regions (within ~50 cents). Octave error counts highlight typical autocorrelation octave mistakes."),N.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."),N.push("");for(const te of V){N.push(`### ${te}`);const H=z[te];N.push(`- Segments: ${H.count||0}`),N.push(`- Total voiced (s): ${(H.totalDur||0).toFixed(3)}`),N.push(`- Voiced fraction: ${H.voicedFraction!==null?(H.voicedFraction*100).toFixed(1)+"%":"N/A"}`),N.push(`- Mean frequency: ${H.meanFreq?H.meanFreq.toFixed(2)+" Hz":"N/A"}`),N.push(`- Std frequency: ${H.stdFreq?H.stdFreq.toFixed(2)+" Hz":"N/A"}`),N.push("")}N.push("## Conclusions & recommendation");const G=[];for(const te of V){if(te===B){G.push({alg:te,score:100});continue}const H=P(f[B]??[],f[te]??[]),K=H.compared?H.matches/H.compared:0,oe=H.compared?H.octaveErrors/H.compared:0,re=K-oe*.5;G.push({alg:te,score:re})}G.sort((te,H)=>H.score-te.score),N.push(`- Based on this recording, recommended authoritative detector: **${G[0].alg}** (best agreement with reference).`),N.push("- For live, low-latency feedback use Pitchy (YIN) with smoothing/hysteresis; use Crepe/Librosa for authoritative scoring or post-processing."),N.push("- If octave errors are frequent, consider octave-correction heuristics (prefer lower octave when ambiguity) or combine detectors via voting."),N.push(""),N.push("## Raw data (per-algorithm segments)");for(const te of V){const H=f[te]??[];N.push(`### ${te} � ${H.length} segments`);for(const oe of H)N.push(`- ${oe.start.toFixed(3)} .. ${(oe.start+(oe.duration||0)).toFixed(3)} : ${oe.freq.toFixed(2)} Hz (pitch ${oe.pitch})`);const K=m[te];K&&N.push(`- Error: ${K}`),N.push("")}const Y=N.join(`
44
+ `),X=new Blob([Y],{type:"text/markdown;charset=utf-8"}),ie=URL.createObjectURL(X),le=document.createElement("a");le.href=ie,le.download="audiopitch_scientific_report_"+(n?n.name:"capture")+".md",document.body.appendChild(le),le.click(),le.remove(),URL.revokeObjectURL(ie)}catch(V){st.error("generateScientificReport error",V),st.warn(i("audioPitch.reportError")+String(V))}}return r.jsxs("div",{style:{marginTop:32,padding:16,border:"1px solid var(--nice-border, #ccc)",borderRadius:8},children:[r.jsx("h3",{children:i("audioPitch.title")}),r.jsxs("div",{style:{marginBottom:12},children:[r.jsx("label",{htmlFor:"pitch-algorithm-select",style:{marginRight:8},children:i("audioPitch.algorithm")}),r.jsxs("select",{id:"pitch-algorithm-select",value:o,onChange:V=>l(V.target.value),style:{marginRight:16},children:[r.jsx("option",{value:"ultrastar-wp",children:"Ultrastar WP (autokorelacja)"}),r.jsx("option",{value:"crepe",children:"crepe (AI)"}),r.jsx("option",{value:"pitchy",children:"pitchy (YIN)"}),r.jsx("option",{value:"librosa",children:"Librosa (PYIN)"})]}),r.jsxs("label",{style:{marginRight:8},children:[r.jsx("input",{type:"checkbox",checked:h,onChange:V=>p(V.target.checked)})," ",i("audioPitch.compareAll")]}),r.jsx("input",{type:"file",accept:"audio/*",ref:E,onChange:W,disabled:w})]}),w&&r.jsx("div",{children:i("audioPitch.analyzing")}),r.jsxs("div",{style:{marginTop:8},children:[r.jsx("b",{children:i("audioPitch.method")})," ",o]}),S&&r.jsxs("div",{style:{color:"red",marginTop:8},children:[r.jsxs("b",{children:[o,": "]}),r.jsx("div",{children:S}),O&&r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap",marginTop:8},children:O})]}),T&&r.jsxs("div",{style:{marginTop:12},children:[r.jsx("b",{children:"Aubio diagnostics"}),r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:T}),j&&r.jsxs("div",{style:{marginTop:8},children:[r.jsx("b",{children:"Probe:"})," ",j]})]}),(Object.keys(f).length>0||Object.keys(m).length>0)&&r.jsxs("div",{style:{marginTop:12},children:[r.jsx("button",{onClick:()=>ne(),children:i("audioPitch.downloadReport")}),Object.entries(m).length>0&&r.jsxs("div",{style:{marginTop:8},children:[r.jsx("b",{children:"Per-algorithm errors:"}),Object.entries(m).filter(([V,q])=>q).map(([V,q])=>r.jsxs("div",{style:{marginTop:6},children:[r.jsxs("b",{children:[V,":"]}),r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:q})]},V))]})]}),k.length>0&&r.jsxs("div",{style:{marginTop:16},children:[r.jsx("b",{children:i("audioPitch.resultUltrastar")}),r.jsxs("pre",{style:{background:"var(--nice-text, #222)",color:"var(--nice-bg, #fff)",padding:8,borderRadius:4},children:[k.map(V=>`: ${Math.round(V.start*10)} ${Math.round(V.duration*10)} ${V.pitch} [${V.freq.toFixed(1)} Hz]`).join(`
45
45
  `),`
46
- -`]})]}),c&&c.length>0&&s.jsxs("div",{style:{marginTop:24},children:[s.jsx("b",{children:o("audioPitch.waveformRms")}),s.jsx("canvas",{width:600,height:100,style:{background:"var(--nice-text, #222)",borderRadius:4,width:"100%",maxWidth:600,display:"block"},role:"img","aria-label":"Waveform and RMS visualization canvas",ref:G=>{if(!G)return;const B=G.getContext("2d");if(B){B.clearRect(0,0,600,100),B.strokeStyle="var(--nice-info, #0ff)",B.beginPath();for(let w=0;w<c.length;w+=Math.ceil(c.length/600)){const $=w/c.length*600,R=50-c[w]*48;w===0?B.moveTo($,R):B.lineTo($,R)}if(B.stroke(),x.length>0){B.strokeStyle="var(--nice-warning, #ff0)",B.beginPath();for(let w=0;w<x.length;w++){const $=w/x.length*600,R=100-x[w]*90;w===0?B.moveTo($,R):B.lineTo($,R)}B.stroke()}}}}),s.jsxs("div",{style:{color:"var(--nice-text-muted, #aaa)",fontSize:12,marginTop:4},children:[s.jsx("span",{style:{color:"var(--nice-info, #0ff)"},children:"Waveform"}),"  | "," ",s.jsx("span",{style:{color:"var(--nice-warning, #ff0)"},children:"RMS"})]})]}),!k&&S.length===0&&!N&&s.jsx("div",{style:{marginTop:16,color:"var(--nice-text-muted, #aaa)"},children:s.jsx("i",{children:o("audioPitch.noNotesDetected")})}),f&&Object.keys(m).length>0&&s.jsxs("div",{style:{marginTop:16},children:[s.jsx("h4",{children:o("audioPitch.algorithmComparison")}),Object.entries(m).map(([G,B])=>s.jsxs("div",{style:{marginBottom:12},children:[s.jsx("b",{children:G}),": ",o("audioPitch.detectedSegments")," ",B.length,s.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-border, #ddd)",padding:8,borderRadius:4,marginTop:8},children:B.map(w=>`: ${Math.round(w.start*10)} ${Math.round(w.duration*10)} ${w.pitch} [${w.freq.toFixed(1)} Hz]`).join(`
47
- `)})]},G))]})]})}function Ae(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 au=[Ae("Belagak","BelagakRegular-dr1zE.otf"),Ae("Big Scratch Brush","BigScratchBrush-PVY9g.ttf"),Ae("Gerhaus","Gerhaus-PK69E.ttf"),Ae("Gerhaus Italic","GerhausItalic-d96l7.ttf"),Ae("Handone Medium","HandoneMedium-nAevO.otf"),Ae("Handson Bold","HandsonBold-9MnrL.otf"),Ae("Kineks Round Bold","KineksRoundBold-7OR34.ttf"),Ae("Kineks Round Light","KineksRoundLight-m2r35.ttf"),Ae("Kineks Round Medium","KineksRoundMedium-drejZ.ttf"),Ae("Kineks Round","KineksRoundRegular-PVRl7.ttf"),Ae("Kineks Round SemiBold","KineksRoundSemiBold-LVWG3.ttf"),Ae("Lemon Jelly","LemonJellyPersonalUse-dEqR.ttf"),Ae("Lemon Milk Bold","LemonMilkBold-gx2B3.otf"),Ae("Lemon Milk Bold Italic","LemonMilkBoldItalic-PKZ3P.otf"),Ae("Lemon Milk Light","LemonMilkLight-owxMq.otf"),Ae("Lemon Milk Light Italic","LemonMilkLightItalic-7BjPE.otf"),Ae("Lemon Milk Medium","LemonMilkMedium-mLZYV.otf"),Ae("Lemon Milk Medium Italic","LemonMilkMediumItalic-d95nl.otf"),Ae("Lemon Milk","LemonMilkRegular-X3XE2.otf"),Ae("Lemon Milk Italic","LemonMilkRegularItalic-L3AEy.otf"),Ae("Pemage","PemageRegular-YqrdO.otf"),Ae("Rosmatika","RosmatikaRegular-BWA45.ttf"),Ae("Scabber","Scabber-q2Mn0.ttf"),Ae("Stylish Calligraphy","StylishCalligraphyDemo-XPZZ.ttf"),Ae("Super Adorable","SuperAdorable-MAvyp.ttf"),Ae("Super Chiby","SuperChiby-BL62V.ttf"),Ae("Super Joyful","SuperJoyful-lxwPq.ttf"),Ae("Super Kindly","SuperKindly-drE8E.ttf"),Ae("Super Meatball","SuperMeatball-Yq1Gy.ttf")],ha="nice2dev-karaoke-display",su=[{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"},...au.map(e=>({value:e.family,label:e.family}))],Ao=[{id:"default",name:"Cyan ? Yellow ? Amber",sungGradient:["#00e5ff","#ffe600","#ffab00"],goldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,229,255,0.6)"},{id:"neon-pink",name:"Neon Pink ? Violet ? Blue",sungGradient:["#ff1493","#9b59b6","var(--nice-primary, #3498db)"],goldGradient:["var(--nice-warning, #FFD700)","#FF69B4","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,20,147,0.6)"},{id:"fire",name:"Red ? Orange ? Yellow",sungGradient:["#ff1744","#ff9100","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#FF6D00","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,23,68,0.6)"},{id:"ocean",name:"Deep Blue ? Teal ? Aqua",sungGradient:["#1a237e","#00897b","#00e5ff"],goldGradient:["var(--nice-warning, #FFD700)","#00BCD4","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,137,123,0.6)"},{id:"forest",name:"Green ? Lime ? Yellow",sungGradient:["#1b5e20","#76ff03","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#76ff03","var(--nice-warning, #FFD700)"],glowColor:"rgba(118,255,3,0.6)"},{id:"retro",name:"Orange ? Pink ? Purple",sungGradient:["#ff6d00","var(--nice-accent-pink, #e91e63)","#7b1fa2"],goldGradient:["var(--nice-warning, #FFD700)","var(--nice-accent-pink, #e91e63)","var(--nice-warning, #FFD700)"],glowColor:"rgba(233,30,99,0.6)"}],nn={presetId:"default",customSungGradient:["#00e5ff","#ffe600","#ffab00"],customGoldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],customGlowColor:"rgba(0,229,255,0.6)",animationMode:"ball",fontFamily:"Arial",transitionEffect:"none",curtainPrimaryColor:"#8b0000",curtainSecondaryColor:"#1a0000",curtainDurationMs:900,immersiveMode:!1};let ns=!1;function No(){try{const e=localStorage.getItem(ha);if(e){const t=JSON.parse(e);return{...nn,...t}}}catch{}return{...nn}}async function ou(e){if(ns||(ns=!0,!e))return;const t=await e();if(t)try{const n=JSON.parse(t),r={...nn,...n};localStorage.setItem(ha,JSON.stringify(r))}catch{}}function iu(e){const t=JSON.stringify(e);localStorage.setItem(ha,t),pa(e)}function Io(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=Ao.find(n=>n.id===e.presetId);return t?{sungGradient:t.sungGradient,goldGradient:t.goldGradient,glowColor:t.glowColor}:{sungGradient:nn.customSungGradient,goldGradient:nn.customGoldGradient,glowColor:nn.customGlowColor}}function pa(e){const{sungGradient:t,goldGradient:n,glowColor:r}=Io(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 lu(){const e=No();pa(e)}const xn=["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)"],Lo={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 Br(e){return 440*Math.pow(2,(e-69)/12)}function Do(e,t){const n=Lo[t],r=n.keys.length,a=[];for(const d of e)for(const f of d)a.includes(f.pitch)||a.push(f.pitch);if(a.sort((d,f)=>d-f),a.length===0)return n.keys.map((d,f)=>({index:f,key:d,gamepadButton:n.buttons[f],label:n.labels[f],minPitch:-999,maxPitch:999,color:xn[f%xn.length]}));const o=a[0],l=a[a.length-1]-o+1,c=[];for(let d=0;d<r;d++){const f=o+Math.floor(l*d/r),h=o+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:f,maxPitch:d===r-1?999:h,color:xn[d%xn.length]})}return c}function Fo(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 o=(a.minPitch+a.maxPitch)/2,i=Math.abs(e-o);i<r&&(r=i,n=a.index)}return n}function Oo(e,t,n){const r=[];for(let a=0;a<e.length;a++)for(let o=0;o<e[a].length;o++){const i={...e[a][o]};i.startTime+=n,r.push({note:i,lane:Fo(i.pitch,t),lineIndex:a,noteIndex:o})}return r.sort((a,o)=>a.note.startTime-o.note.startTime),r}class cu{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,f,h,m,y,p,v;if(!this.running)return;const a=this.getCurrentTime();this.pollGamepad();const o=this.getActiveLanes();(d=(c=this.config).onLaneActive)==null||d.call(c,o);const i=this.findActiveNote(a);if(i!==this.lastActiveNote&&(this.lastActiveNote=i,(h=(f=this.config).onCurrentNote)==null||h.call(f,i)),o.some(Boolean)&&i){const x=i.lane,b=o.indexOf(!0);if(o[x]){const S=Br(i.note.pitch);this.config.onPitch(S),a-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=a,(y=(m=this.config).onHitFeedback)==null||y.call(m,{type:"perfect",lane:x,time:a}))}else if(b>=0){const g=Math.abs(b-x)*3,k=Br(i.note.pitch+g);this.config.onPitch(k),a-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=a,(v=(p=this.config).onHitFeedback)==null||v.call(p,{type:"miss",lane:b,time:a}))}}this.raf=requestAnimationFrame(this.loop)},this.config=t;const n=ra(t.noteLines,t.bpm),r=(t.gap??0)/1e3;switch(this.lanes=Do(n,t.difficulty),this.events=Oo(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 du(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 o=a.slice(1).trim().split(/\s+/),i=parseInt(o[0]||"0",10),l=parseInt(o[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 uu=({index:e,style:t,data:n})=>{const{lines:r,notes:a,currentIndex:o,animationConfig:i}=n,l=r[e]??"",c=a.findIndex(S=>S.lineIndex===e),d=c>=0&&c===o,f=(i==null?void 0:i.enabled)??!0,h=(i==null?void 0:i.durationMs)??300,m=(i==null?void 0:i.translateX)??8,y=(i==null?void 0:i.scale)??1.01,p=(i==null?void 0:i.easing)??"cubic-bezier(.22,1,.36,1)",v=(i==null?void 0:i.opacityInactive)??.9,x=(i==null?void 0:i.boxShadow)??"0 6px 18px rgba(3,102,214,0.08)",b={transition:f?`transform ${h}ms ${p}, opacity ${h}ms ${p}`:"none",transform:d?`translateX(${m}px) scale(${y})`:"translateX(0px) scale(1)",opacity:d?1:v,boxShadow:d?x:"none"};return s.jsx("div",{style:{...t,padding:"4px 6px",borderRadius:4},"data-note-idx":c>=0?c:void 0,children:s.jsx("div",{style:{...b,background:d?"rgba(0,130,200,0.12)":"transparent",padding:"4px 6px",borderRadius:4},children:s.jsx("code",{style:{fontFamily:"monospace",whiteSpace:"pre-wrap"},children:l})})})},_o=({ultrastarText:e,audioUrl:t,audioRef:n,animationConfig:r})=>{const{t:a}=we(),o=u.useRef(null),i=n??o,[l,c]=u.useState(!1),d=u.useMemo(()=>du(e),[e]),f=u.useRef(null),h=u.useRef(null),m=u.useRef(null),y=u.useRef(0),p=u.useRef(0),[v,x]=u.useState(-1),b=u.useMemo(()=>(e||"").split(/\r?\n/),[e]),S=28,g=b.length*S,k=u.useMemo(()=>({lines:b,notes:d,currentIndex:v,animationConfig:r}),[b,d,v,r]);return u.useEffect(()=>{const M=i.current;M&&(l?M.play().catch(()=>c(!1)):M.pause())},[l,i]),u.useEffect(()=>{const M=i.current;if(!M)return;let N=-1;const j=r??null,_=j&&typeof j.scrollSmooth=="number"?j.scrollSmooth:.18;let P=performance.now();const V=()=>{var G,B;const z=performance.now(),A=Math.max(0,Math.min(.2,(z-P)/1e3));P=z;const I=M.currentTime||0;y.current=I;let L=-1;for(let w=0;w<d.length;w++){const $=d[w];if(I>=$.start&&I<$.start+Math.max(.001,$.duration)){L=w;break}}L!==N&&(N=L,x(L));let U=0;if(N>=0){const w=((G=d[N])==null?void 0:G.lineIndex)??0,$=((B=h.current)==null?void 0:B.clientHeight)??220;U=w*S-$/2+S/2;const R=Math.max(0,g-$);(isNaN(U)||!isFinite(U))&&(U=0),U=Math.max(0,Math.min(U,R))}const Y=1-Math.pow(Math.max(0,1-_),Math.min(4,A*60)),te=(((r==null?void 0:r.scrollEasing)||"easeOutCubic")==="linear"?w=>w:w=>1-Math.pow(1-w,3))(Y);p.current=p.current+(U-p.current)*te;try{const w=h.current;w&&typeof w.scrollTop=="number"&&(w.scrollTop=Math.round(p.current))}catch{}m.current=requestAnimationFrame(V)};return m.current=requestAnimationFrame(V),()=>{m.current&&cancelAnimationFrame(m.current)}},[i,d,g,r]),s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[s.jsx("button",{onClick:()=>c(M=>!M),disabled:!t,children:l?"Pause":"Play"}),s.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-secondary, #666)"},children:[(y.current||0).toFixed(2),"s"]}),s.jsxs("div",{style:{marginLeft:"auto",fontSize:13,color:"var(--nice-text-secondary, #666)"},children:["Notes: ",d.length]})]}),s.jsx("div",{style:{border:"1px solid var(--nice-border, #ddd)",height:220,overflow:"hidden",padding:8,position:"relative"},children:e?s.jsx(Hl.FixedSizeList,{height:220,width:"100%",itemCount:b.length,itemSize:S,ref:f,outerRef:h,itemData:k,children:uu}):s.jsx("div",{style:{color:"var(--nice-text-secondary, #888)"},children:a("karaokeEditor.noText","No text")})}),!n&&s.jsx("audio",{ref:o,src:t||void 0,preload:"metadata",style:{display:"none"}})]})};function fu(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 o=a.slice(1).trim().split(/\s+/),i=parseInt(o[0]||"0",10)/10||0,l=parseInt(o[1]||"0",10)/10||.1;n.push({lineIndex:r,start:i,duration:l})}}return{lines:t,notes:n}}function zo({ultrastarText:e,audioUrl:t,audioRef:n,ytRef:r}){const a=u.useRef(null),o=u.useRef(null),i=u.useRef([]),l=u.useRef([]),c=u.useRef(null),d=u.useRef(t);return d.current=t,u.useEffect(()=>{const{lines:f,notes:h}=fu(e);i.current=f,l.current=h;const m=c.current;m&&"rebuildTexts"in m&&typeof m.rebuildTexts=="function"&&m.rebuildTexts()},[e]),u.useEffect(()=>{let f=!0;return(async()=>{var N;if(!f||!a.current)return;const h=await import("phaser"),m="default"in h?h.default:h;if(!a.current||!f)return;const y=i,p=l,v=c,x=n,b=r,S=d;class g extends m.Scene{constructor(){super({key:"preview"}),this.texts=[],this.audioEl=null}create(){if(v.current=this,this.rebuildTexts(),b!=null&&b.current)this.audioEl=null;else if(x!=null&&x.current)this.audioEl=x.current;else{const _=document.querySelector("audio");_ instanceof HTMLAudioElement?this.audioEl=_:S.current?(this.audioEl=document.createElement("audio"),this.audioEl.src=S.current,this.audioEl.preload="metadata",this.audioEl.style.display="none",document.body.appendChild(this.audioEl)):this.audioEl=null}}rebuildTexts(){for(const A of this.texts)A.destroy();this.texts=[];const _={font:"18px monospace",color:"var(--nice-bg, #fff)"},P=22;let V=20;const z=y.current;for(let A=0;A<z.length;A++){const I=this.add.text(10,V,z[A]||" ",_).setOrigin(0,0);this.texts.push(I),V+=P}}update(){let _=0;if(b!=null&&b.current&&typeof b.current.getCurrentTime=="function")try{_=b.current.getCurrentTime()||0}catch{_=0}else _=this.audioEl&&this.audioEl.currentTime||0;for(let V=0;V<this.texts.length;V++)this.texts[V].setStyle({backgroundColor:void 0,color:"var(--nice-bg, #fff)"});const P=p.current;for(const V of P)if(_>=V.start&&_<V.start+Math.max(.001,V.duration)){const z=this.texts[V.lineIndex];z&&z.setStyle({backgroundColor:"rgba(0,130,200,0.16)",color:"var(--nice-info, #00aaff)"})}}}const k=((N=a.current)==null?void 0:N.clientWidth)??640,M={type:m.AUTO,parent:a.current,width:k,height:Math.round(k/2),backgroundColor:"#101010",scene:[g]};o.current=new m.Game(M)})(),()=>{f=!1,c.current=null;try{const h=o.current;h&&typeof h.destroy=="function"&&h.destroy(!0)}catch{}}},[]),s.jsx("div",{ref:a,style:{width:"100%",height:340}})}const hu=nt.scoped("GenericPlayer"),pu=e=>/youtu(\.be|be\.com)/i.test(e),Bo=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),mu=e=>!!e&&/\.(mp3|aac|m4a|flac|wav|ogg)(\?.*)?$/i.test(e),yu=e=>{var o;if(!((o=e==null?void 0:e.sources)!=null&&o.length))return null;const t=i=>e.sources.find(l=>l.kind===i),n=e.sources.find(i=>i.kind==="youtube"&&(i.videoId||i.url&&pu(i.url)))??null;if(n)return n;const r=t("hls")||e.sources.find(i=>i.url&&Bo(i.url))||null;if(r)return r;const a=t("audio")||e.sources.find(i=>i.url&&mu(i.url))||null;return a||(e.sources[0]??null)},lr=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")}`},gu=[.25,.5,.75,1,1.25,1.5,1.75,2],Go=({tracks:e=[],initialIndex:t=0,autoPlay:n=!0,countdownSeconds:r=0,height:a=360,onIndexChange:o,onPlayingChange:i,onTimeUpdate:l,externalRef:c,uiMode:d="full",compactNextCount:f=3,progressBarPosition:h="inline",loop:m=!1,onEnded:y,enableKeyboardShortcuts:p=!0,shuffle:v=!1,repeatMode:x="none",playbackSpeed:b=1,abLoop:S=null,onRepeatModeChange:g,onShuffleChange:k,onSpeedChange:M,sleepTimer:N=0,onSleepTimerExpired:j})=>{const{t:_}=we(),[P,V]=u.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),z=e[P],A=u.useMemo(()=>yu(z),[z]),[I,L]=u.useState(!1),[U,Y]=u.useState(0),[O,Z]=u.useState(0),[H,te]=u.useState(.9),[G,B]=u.useState(null),[w,$]=u.useState(null),R=u.useRef(null),[T,C]=u.useState(v),[E,F]=u.useState(x),[q,Q]=u.useState(b),[J,ae]=u.useState(S),[re,ee]=u.useState([]),[D,K]=u.useState(N>0?N*60:null),se=u.useRef(null),[ce,pe]=u.useState(()=>Fs()),X=u.useRef(null),fe=u.useRef(null),be=u.useRef(null),Re=u.useRef(null);u.useEffect(()=>{if(T&&e.length>0){const le=e.map((ue,ke)=>ke);for(let ue=le.length-1;ue>0;ue--){const ke=Math.floor(Math.random()*(ue+1));[le[ue],le[ke]]=[le[ke],le[ue]]}ee(le)}},[T,e.length]),u.useEffect(()=>(se.current&&(window.clearInterval(se.current),se.current=null),N>0&&I&&(K(N*60),se.current=window.setInterval(()=>{K(le=>!le||le<=1?(se.current&&window.clearInterval(se.current),se.current=null,j==null||j(),null):le-1)},1e3)),()=>{se.current&&window.clearInterval(se.current)}),[N,I]);const Fe=u.useCallback(le=>{const ue=Math.min(Math.max(0,le),Math.max(0,e.length-1));V(ue),o==null||o(ue)},[e.length,o]),Te=u.useCallback(()=>{if(T&&re.length>0){const ue=re.indexOf(P)+1;return ue<re.length?re[ue]:E==="all"?re[0]:-1}return P<e.length-1?P+1:E==="all"?0:-1},[P,e.length,T,re,E]),Se=u.useCallback(()=>{if(T&&re.length>0){const le=re.indexOf(P);return le>0?re[le-1]:E==="all"?re[re.length-1]:-1}return P>0?P-1:E==="all"?e.length-1:-1},[P,e.length,T,re,E]),ne=u.useCallback(()=>{const le=Te();le>=0&&Fe(le)},[Te,Fe]),oe=u.useCallback(async()=>{var le,ue;await It(),pe(!0),(A==null?void 0:A.kind)==="youtube"?(le=X.current)==null||le.playVideo():(ue=fe.current)==null||ue.play(),L(!0),i==null||i(!0)},[A,i]),Ie=u.useCallback(()=>{var le,ue;(A==null?void 0:A.kind)==="youtube"?(le=X.current)==null||le.pauseVideo():(ue=fe.current)==null||ue.pause(),L(!1),i==null||i(!1)},[A,i]),Oe=u.useCallback(()=>I?Ie():oe(),[I,oe,Ie]),Ee=u.useCallback(le=>{var ie;const ue=(z==null?void 0:z.startOffset)??0,ke=le+ue;(A==null?void 0:A.kind)==="youtube"?(ie=X.current)==null||ie.seekTo(ke,!0):fe.current&&(fe.current.currentTime=ke);const St=Math.max(0,le);Z(St),l==null||l(St)},[A,l]),rt=u.useCallback(()=>{if(O>3){Ee(0);return}const le=Se();le>=0&&Fe(le)},[Se,Fe,O,Ee]),Ce=u.useCallback(le=>{var ue,ke;te(le),B(null),(A==null?void 0:A.kind)==="youtube"?(ke=(ue=X.current)==null?void 0:ue.setVolume)==null||ke.call(ue,Math.round(le*100)):fe.current&&(fe.current.volume=le)},[A]),ft=u.useCallback(()=>{G!==null?Ce(G):(B(H),Ce(0))},[H,G,Ce]),Pn=u.useCallback(le=>{var ue,ke;Q(le),fe.current&&(fe.current.playbackRate=le),(A==null?void 0:A.kind)==="youtube"&&((ke=(ue=X.current)==null?void 0:ue.setPlaybackRate)==null||ke.call(ue,le)),M==null||M(le)},[A,M]),Je=u.useCallback(()=>{const le=["none","all","one"],ue=le[(le.indexOf(E)+1)%le.length];F(ue),g==null||g(ue)},[E,g]),Ue=u.useCallback(()=>{const le=!T;C(le),k==null||k(le)},[T,k]),Ft=u.useCallback(le=>{ae(le)},[]);u.useImperativeHandle(c,()=>({play:oe,pause:Ie,toggle:Oe,seekTo:Ee,setVolume:Ce,setSpeed:Pn,setRepeatMode:le=>{F(le),g==null||g(le)},toggleShuffle:Ue,setABLoop:Ft,getUnderlyingPlayer:()=>(A==null?void 0:A.kind)==="youtube"?X.current:(A==null?void 0:A.kind)==="hls"||(A==null?void 0:A.kind)==="audio"?fe.current:null}),[oe,Ie,Oe,Ee,Ce,Pn,Ue,Ft,A==null?void 0:A.kind]),u.useEffect(()=>{const le=window.setInterval(()=>{let ue=0,ke=0;(A==null?void 0:A.kind)==="youtube"&&X.current?(ue=X.current.getCurrentTime()||0,ke=X.current.getDuration()||0):fe.current&&(ue=fe.current.currentTime||0,ke=fe.current.duration||0);const St=(z==null?void 0:z.startOffset)??0,ie=Math.max(0,ue-St);Z(ie),Y(ke),l==null||l(ie),J&&ie>=J.b&&Ee(J.a)},250);return()=>window.clearInterval(le)},[A==null?void 0:A.kind,l,J]),u.useEffect(()=>()=>{R.current&&(window.clearInterval(R.current),R.current=null)},[]),u.useEffect(()=>{if(be.current){try{be.current.destroy()}catch{}be.current=null}if(fe.current&&(fe.current.volume=H,fe.current.crossOrigin=A!=null&&A.withCredentials?"use-credentials":"anonymous"),(A==null?void 0:A.kind)==="hls"&&Bo(A.url)){const le=fe.current;if(!le)return;const ue=()=>{le.src=A.url,le.load();const ke=(z==null?void 0:z.startOffset)??0;try{ke&&!isNaN(ke)&&(le.currentTime=ke)}catch{}n&&le.play().catch(()=>{})};le.canPlayType("application/vnd.apple.mpegurl")?ue():(async()=>{var ke;try{const ie=(await import("hls.js")).default;if((ke=ie==null?void 0:ie.isSupported)!=null&&ke.call(ie)){const he=new ie({xhrSetup:_e=>{if(A!=null&&A.withCredentials&&(_e.withCredentials=!0),A!=null&&A.headers)for(const[xe,ye]of Object.entries(A.headers))try{_e.setRequestHeader(xe,ye)}catch{}}});be.current=he,he.loadSource(A.url),he.attachMedia(le),he.on(ie.Events.MANIFEST_PARSED,()=>{n&&le.play().catch(()=>{})})}else ue()}catch(St){hu.debug("HLS.js setup failed, falling back to native playback",St),ue()}})()}else if((A==null?void 0:A.kind)==="audio"&&A.url&&fe.current){const le=fe.current;le.src=A.url,le.load();const ue=(z==null?void 0:z.startOffset)??0;try{ue&&!isNaN(ue)&&(le.currentTime=ue)}catch{}n&&le.play().catch(()=>{})}R.current&&(window.clearInterval(R.current),R.current=null),$(null),Z(0),Y(0),n&&(A==null?void 0:A.kind)==="youtube"&&r>0?($(r),R.current=window.setInterval(()=>{$(le=>{var ue;if(!le)return null;if(le<=1){R.current&&(window.clearInterval(R.current),R.current=null);try{(ue=X.current)==null||ue.playVideo()}catch{}return L(!0),i==null||i(!0),null}return le-1})},1e3)):L(!!n)},[A==null?void 0:A.url,A==null?void 0:A.kind,A==null?void 0:A.withCredentials,JSON.stringify(A==null?void 0:A.headers),n,H]);const vt=u.useCallback(()=>{if(E==="one"){Ee(0),oe();return}const le=Te();le>=0?Fe(le):(L(!1),i==null||i(!1),Ee(0),y==null||y())},[E,Te,Fe,i,Ee,y,oe]);u.useEffect(()=>{if(!p)return;const le=ue=>{const ke=ue.target;if(!(ke.tagName==="INPUT"||ke.tagName==="TEXTAREA"||ke.isContentEditable))switch(ue.key){case" ":ue.preventDefault(),Oe();break;case"ArrowRight":ue.preventDefault(),Ee(Math.min(O+5,U));break;case"ArrowLeft":ue.preventDefault(),Ee(Math.max(0,O-5));break;case"ArrowUp":ue.preventDefault(),Ce(Math.min(1,H+.05));break;case"ArrowDown":ue.preventDefault(),Ce(Math.max(0,H-.05));break;case"m":case"M":ft();break;case"n":case"N":ne();break;case"p":case"P":rt();break;case"r":case"R":Je();break;case"s":case"S":Ue();break}};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[p,Oe,Ee,O,U,Ce,H,ft,ne,rt,Je,Ue]);const br=(A==null?void 0:A.kind)==="youtube"||d==="full"||d==="nobuttons",ht=f>0?e.slice(P+1,P+1+f):[];return s.jsxs("div",{ref:Re,className:"gp-player",style:{display:"grid",gap:12},tabIndex:-1,children:[n&&!ce&&s.jsx("div",{className:"gp-audio-activation",onClick:()=>{pe(!0),oe()},style:{position:"fixed",inset:0,zIndex:200,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",cursor:"pointer"},children:s.jsx("span",{style:{color:"var(--nice-bg, #fff)",fontSize:24},children:"Click to activate audio"})}),br&&s.jsxs("div",{className:"gp-stage",style:{width:"100%",height:a,background:(A==null?void 0:A.kind)==="youtube"?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(A==null?void 0:A.kind)==="youtube"&&s.jsx(Qr,{videoId:A.videoId??Cu(A.url),onReady:le=>{X.current=le.target,Ce(H);const ue=(z==null?void 0:z.startOffset)??0;try{ue&&le.target.seekTo(ue,!0)}catch{}if(d==="nobuttons"){try{le.target.playVideo()}catch{}L(!0)}},onEnd:vt,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%"}}),w!==null&&s.jsx("div",{style:{position:"absolute",inset:0,zIndex:120,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-70, rgba(0, 0, 0, 0.7))"},children:s.jsx("span",{style:{color:"var(--nice-bg, #fff)",fontSize:72,fontWeight:"bold"},children:w})}),d==="nobuttons"&&s.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"auto",zIndex:100,cursor:"default"}}),((A==null?void 0:A.kind)==="audio"||(A==null?void 0:A.kind)==="hls")&&s.jsxs(s.Fragment,{children:[d==="full"&&s.jsx("div",{style:{textAlign:"center",color:"var(--text, #e2e8f0)"},children:z!=null&&z.coverUrl?s.jsx("img",{alt:"cover",src:z.coverUrl,style:{height:a-24,objectFit:"contain"}}):s.jsxs("div",{style:{opacity:.8},children:[s.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[z==null?void 0:z.artist," � ",z==null?void 0:z.title]}),s.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-dim, #94a3b8)"},children:(A==null?void 0:A.label)??`${(A==null?void 0:A.codec)??""} ${(A==null?void 0:A.quality)??""}`.trim()})]})}),s.jsx("audio",{ref:fe,onEnded:vt,onLoadedMetadata:()=>{const le=fe.current;le&&Y(le.duration||0)},crossOrigin:A!=null&&A.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]})]}),(d==="minimal"||d==="compact")&&s.jsx("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600},children:(z==null?void 0:z.title)??"�"}),s.jsx("div",{style:{color:"var(--text-dim, #64748b)",fontSize:13},children:(z==null?void 0:z.artist)??"�"})]})}),d==="full"&&s.jsxs(s.Fragment,{children:[s.jsx(Wo,{currentTime:O,duration:U}),s.jsx(bu,{isPlaying:I,index:P,count:e.length,currentTime:O,duration:U,volume:H,onPrev:rt,onNext:ne,onToggle:Oe,onSeek:Ee,onVolume:Ce}),s.jsx(Su,{shuffleOn:T,repeatMode:E,speed:q,abLoop:J,currentTime:O,sleepRemaining:D,onToggleShuffle:Ue,onCycleRepeat:Je,onSpeedChange:Pn,onSetABLoop:Ft,onMuteToggle:ft,isMuted:G!==null})]}),d==="progressOnly"&&s.jsx("div",{style:h==="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:s.jsx(vu,{currentTime:O,duration:U,onSeek:Ee})}),(d==="minimal"||d==="compact")&&s.jsx(xu,{isPlaying:I,canPrev:P>0,canNext:P<e.length-1,onPrev:rt,onNext:ne,onToggle:Oe}),d==="compact"&&ht.length>0&&s.jsx(wu,{items:ht,onSelect:le=>Fe(P+1+le)}),d==="nobuttons"&&s.jsx(s.Fragment,{}),d==="full"&&e.length>0&&s.jsx("div",{className:"gp-list",style:{display:"grid",gap:4},children:e.map((le,ue)=>s.jsxs("button",{onClick:()=>Fe(ue),style:{textAlign:"left",border:"1px solid var(--border-light, #e5e7eb)",borderRadius:8,padding:"8px 10px",background:ue===P?"var(--active-bg, #eef2ff)":"var(--bg, #fff)",cursor:"pointer"},title:le.sources.map(ke=>ke.kind).join(", "),children:[s.jsx("div",{style:{fontWeight:600},children:le.title}),s.jsx("div",{style:{color:"var(--text-dim, #64748b)",fontSize:12},children:le.artist})]},le.id))})]})},ot={border:"1px solid var(--border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--bg, #fff)",cursor:"pointer"},Wo=({currentTime:e,duration:t})=>s.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[s.jsx("div",{}),s.jsxs("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:[lr(e)," / ",lr(t)]})]}),bu=({isPlaying:e,index:t,count:n,currentTime:r,duration:a,volume:o,onPrev:i,onNext:l,onToggle:c,onSeek:d,onVolume:f})=>{const{t:h}=we();return s.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("button",{onClick:i,disabled:t<=0,title:h("player.previousTrack"),"aria-label":h("player.previousTrack"),style:ot,children:"?"}),s.jsx("button",{onClick:c,title:h(e?"player.pause":"player.play"),"aria-label":h(e?"player.pause":"player.play"),style:ot,children:"?"}),s.jsx("button",{onClick:l,disabled:t>=n-1,title:h("player.nextTrack"),"aria-label":h("player.nextTrack"),style:ot,children:"?"})]}),s.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"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{children:"??"}),s.jsx("input",{type:"range",min:0,max:1,step:.01,value:o,onChange:m=>f(parseFloat(m.target.value)),"aria-label":"Volume"})]})]})},vu=({currentTime:e,duration:t,onSeek:n})=>s.jsxs(s.Fragment,{children:[s.jsx(Wo,{currentTime:e,duration:t}),s.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"})]}),xu=({isPlaying:e,canPrev:t,canNext:n,onPrev:r,onNext:a,onToggle:o})=>{const{t:i}=we();return s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[s.jsx("button",{onClick:r,disabled:!t,title:i("player.previousTrack"),"aria-label":i("player.previousTrack"),style:ot,children:"?"}),s.jsx("button",{onClick:o,title:i(e?"player.pause":"player.play"),"aria-label":i(e?"player.pause":"player.play"),style:ot,children:"?"}),s.jsx("button",{onClick:a,disabled:!n,title:i("player.nextTrack"),"aria-label":i("player.nextTrack"),style:ot,children:"?"})]})},wu=({items:e,onSelect:t})=>{const{t:n}=we();return s.jsxs("div",{style:{border:"1px solid var(--border-light, #e5e7eb)",borderRadius:8,padding:10,background:"var(--bg, #fff)"},children:[s.jsx("div",{style:{fontWeight:600,marginBottom:6},children:n("player.upNext")}),s.jsx("ol",{style:{margin:0,paddingLeft:18},children:e.map((r,a)=>s.jsx("li",{style:{marginBottom:4},children:s.jsxs("button",{type:"button",onClick:()=>t(a),style:{border:"none",padding:0,background:"transparent",cursor:"pointer",color:"var(--text, #111827)"},title:r.sources.map(o=>o.kind).join(", "),children:[s.jsx("span",{style:{fontWeight:600},children:r.artist})," � ",r.title]})},r.id))})]})},Su=({shuffleOn:e,repeatMode:t,speed:n,abLoop:r,currentTime:a,sleepRemaining:o,onToggleShuffle:i,onCycleRepeat:l,onSpeedChange:c,onSetABLoop:d,onMuteToggle:f,isMuted:h})=>{const{t:m}=we(),y={none:"➡",all:"🔁",one:"🔂"},p={none:"Off",all:"All",one:"One"};return s.jsxs("div",{className:"gp-pro-controls",style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap",fontSize:13},children:[s.jsx("button",{onClick:i,title:m("player.shuffle","Shuffle"),"aria-label":m("player.shuffle","Shuffle"),style:{...ot,opacity:e?1:.4,fontWeight:e?700:400},children:"🔀"}),s.jsx("button",{onClick:l,title:`${m("player.repeat","Repeat")}: ${p[t]}`,"aria-label":`${m("player.repeat","Repeat")}: ${p[t]}`,style:{...ot,opacity:t==="none"?.4:1},children:y[t]}),s.jsx("select",{value:n,onChange:v=>c(parseFloat(v.target.value)),title:m("player.speed","Speed"),"aria-label":m("player.speed","Speed"),style:{...ot,minWidth:56,fontSize:12},children:gu.map(v=>s.jsxs("option",{value:v,children:[v,"x"]},v))}),s.jsx("button",{onClick:f,title:m("player.mute","Mute"),"aria-label":m("player.mute","Mute"),style:{...ot,opacity:h?1:.6},children:h?"🔇":"🔊"}),r?s.jsxs("span",{style:{display:"flex",gap:4,alignItems:"center"},children:[s.jsxs("span",{style:{fontSize:11,color:"var(--text-dim, #6b7280)"},children:["A: ",lr(r.a)," — B: ",lr(r.b)]}),s.jsx("button",{onClick:()=>d(null),title:m("player.clearLoop","Clear loop"),style:{...ot,fontSize:11,padding:"2px 6px"},children:"✕"})]}):s.jsx("button",{onClick:()=>d({a,b:a+10}),title:m("player.abLoop","A-B Loop"),"aria-label":m("player.abLoop","Set A-B Loop"),style:{...ot,opacity:.4},children:"A↔B"}),o!==null&&o>0&&s.jsxs("span",{style:{marginLeft:"auto",fontSize:11,color:"var(--text-dim, #6b7280)"},children:["💤 ",Math.floor(o/60),":",(o%60).toString().padStart(2,"0")]})]})};function Cu(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 ku=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),rs=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")}`},Mr={border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg, #fff)",cursor:"pointer"},Mu=({isPlaying:e,index:t,count:n,currentTime:r,duration:a,volume:o,onPrev:i,onNext:l,onToggle:c,onSeek:d,onVolume:f})=>{const{t:h}=we();return s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[s.jsx("div",{}),s.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-secondary, #64748b)"},children:[rs(r)," / ",rs(a)]})]}),s.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("button",{onClick:i,disabled:t<=0,title:h("playerControls.prev","Prev"),"aria-label":h("playerControls.previousTrack","Previous track"),style:Mr,children:"⏮"}),s.jsx("button",{onClick:c,title:e?h("playerControls.pause","Pause"):h("playerControls.play","Play"),"aria-label":e?h("playerControls.pause","Pause"):h("playerControls.play","Play"),style:Mr,children:e?"⏸":"▶"}),s.jsx("button",{onClick:l,disabled:t>=n-1,title:h("playerControls.next","Next"),"aria-label":h("playerControls.nextTrack","Next track"),style:Mr,children:"⏭"})]}),s.jsx("input",{type:"range",min:0,max:Math.max(1,a),step:.1,value:r,"aria-label":h("playerControls.seekPosition","Seek position"),onChange:m=>d(parseFloat(m.target.value))}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{children:"🔊"}),s.jsx("input",{type:"range",min:0,max:1,step:.01,value:o,"aria-label":h("playerControls.volume","Volume"),onChange:m=>f(parseFloat(m.target.value))})]})]})]})},Uo=u.memo(Mu);function ju(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,f=d*(n-6),h=c*l,m=n-f,y=c/48*240+a;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(h+1,m,l-2,f)}}function Ru(e,t,n,r,a,o){if(!o.current){const h=[];for(let y=0;y<24;y++)h.push({ang:y/24*Math.PI*2,phase:Math.random()*Math.PI*2,baseR:Math.min(t,n)*.22+Math.random()*30});o.current={nodes:h}}const i=o.current,l=t/2,c=n/2,d=26+r*80,f=[];for(const h of i.nodes){h.phase+=.02+r*.06;const m=h.baseR+Math.sin(h.phase)*d,y=l+Math.cos(h.ang)*m,p=c+Math.sin(h.ang)*m;f.push([y,p])}e.fillStyle=`hsla(${a}, 70%, 55%, .22)`,e.strokeStyle=`hsla(${(a+40)%360}, 90%, 65%, .9)`,e.lineWidth=2,e.beginPath();for(let h=0;h<f.length;h++){const[m,y]=f[h],[p,v]=f[(h+1)%f.length],x=(m+p)/2,b=(y+v)/2;h===0?e.moveTo(x,b):e.quadraticCurveTo(m,y,x,b)}e.closePath(),e.fill(),e.stroke()}function Tu(e,t,n,r,a,o){o.current||(o.current={items:[]});const i=o.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}const $u="var(--nice-text-muted, #94a3b8)",Pu=({height:e,coverUrl:t,title:n,subtitle:r,label:a})=>s.jsx("div",{style:{textAlign:"center",color:"var(--nice-border, #e2e8f0)"},children:t?s.jsx("img",{alt:"cover",src:t,style:{height:e-24,objectFit:"contain"}}):s.jsxs("div",{style:{opacity:.8},children:[s.jsx("div",{style:{fontSize:18,fontWeight:600},children:n??"—"}),s.jsx("div",{style:{marginTop:8,fontSize:12,color:$u},children:a??r??"—"})]})});function Bt(e,t){return e+Math.random()*(t-e)}function Eu(e,t,n,r,a,o,i){i.current||(i.current={embers:[],t:0});const l=i.current,c=e.createLinearGradient(0,n,0,n*.4);c.addColorStop(0,`hsla(${(o+30)%360}, 90%, 50%, .35)`),c.addColorStop(1,`hsla(${(o+10)%360}, 90%, 50%, 0)`),e.fillStyle=c,e.fillRect(0,0,t,n);const d=6;for(let h=0;h<d;h++){const m=(h+.5)/d*t,y=(r[Math.floor((h+1)/(d+1)*r.length)]||0)/255,p=n*.18+(.25+a*.6+y*.7)*n*.55,v=e.createLinearGradient(m,n,m,n-p);v.addColorStop(0,`hsla(${(o+40)%360},100%,55%,.9)`),v.addColorStop(.5,`hsla(${(o+10)%360},100%,60%,.75)`),v.addColorStop(1,`hsla(${(o-20)%360},100%,80%,.05)`);const x=Math.sin(l.t*1.2+h*.8)*(15+a*30);e.fillStyle=v,e.beginPath(),e.moveTo(m-20,n),e.bezierCurveTo(m-35,n-p*.45,m-25+x,n-p*.75,m+x,n-p),e.bezierCurveTo(m+25+x*.3,n-p*.65,m+35,n-p*.35,m+20,n),e.closePath(),e.fill()}const f=Math.floor(1+a*6);for(let h=0;h<f;h++)l.embers.push({x:Bt(t*.25,t*.75),y:n-Bt(4,14),r:Bt(1,3),vx:Bt(-.15,.15),vy:-Bt(.6,1.8)-a*1.2,life:Bt(.8,1.6)});e.save(),e.globalCompositeOperation="lighter";for(let h=l.embers.length-1;h>=0;h--){const m=l.embers[h];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(h,1);continue}const y=e.createRadialGradient(m.x,m.y,0,m.x,m.y,m.r*3);y.addColorStop(0,`hsla(${(o+25)%360},100%,65%,.9)`),y.addColorStop(1,`hsla(${(o+25)%360},100%,65%,0)`),e.fillStyle=y,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 Au(e,t,n,r,a){const o=t/2,i=n/2,l=Math.min(t,n)*.28,c=96,d=Math.max(1,Math.floor(r.length/c));for(let f=0;f<c;f++){const h=(r[f*d]??0)/255,m=f/c*Math.PI*2,y=h*(Math.min(t,n)*.22)+6,p=o+Math.cos(m)*l,v=i+Math.sin(m)*l,x=o+Math.cos(m)*(l+y),b=i+Math.sin(m)*(l+y);e.strokeStyle=`hsl(${(a+f*3)%360}, 90%, ${40+h*40}%)`,e.lineWidth=3,e.beginPath(),e.moveTo(p,v),e.lineTo(x,b),e.stroke()}e.fillStyle=`hsla(${(a+180)%360}, 60%, 15%, .4)`,e.beginPath(),e.arc(o,i,l-8,0,Math.PI*2),e.fill()}function Nu(e,t,n,r,a){const l=t/14,c=n/8;for(let d=0;d<8;d++)for(let f=0;f<14;f++){const h=Math.min(r.length-1,d*14+f),m=r[h]/255,y=(a+f/14*210+d/8*90)%360,p=65+m*30,v=20+m*40,x=(1-m)*4;e.fillStyle=`hsl(${y}, ${p}%, ${v}%)`,e.fillRect(f*l+x,d*c+x,Math.max(1,l-2*x),Math.max(1,c-2*x))}}function Iu(e){const n=Array.from(new Set(e.filter(Boolean))).map(r=>new Promise(a=>{const o=new Image;o.crossOrigin="anonymous",o.onload=()=>a(o),o.onerror=()=>a(o),o.src=r}));return Promise.all(n)}async function Lu(e,t,n,r,a){e.current||(e.current={sprites:[],loadedUrls:[],ready:!1});const o=e.current,i=t.join("|")!==o.loadedUrls.join("|");if(!o.ready||i){const l=await Iu(t.length?t:[]);o.loadedUrls=t,o.sprites=[],o.ready=!0;const c=d=>l[d%Math.max(1,l.length)]??new Image;for(let d=0;d<n;d++){const f=Math.random()*Math.min(r,a)*.38+40;o.sprites.push({img:c(d),x:(Math.random()-.5)*f*.4,y:(Math.random()-.5)*f*.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 Du(e,t,n,r,a,o,i,l){const c=o.current;if(!(c!=null&&c.ready))return;const d=t/2,f=n/2,h=900,m=1+r*2;for(const p of c.sprites){p.ang+=p.spin*m,p.z-=p.vz*(.8+r*2.4),p.z<40&&(p.z=h);const v=Math.min(t,n)*.32+Math.sin(p.ang*.8)*18;p.x=Math.cos(p.ang)*v,p.y=Math.sin(p.ang*1.1)*v*.6}const y=[...c.sprites].sort((p,v)=>v.z-p.z);for(const p of y){const v=h/(h-p.z)*.6*p.size,x=d+p.x*v,b=f+p.y*v,S=64*v,g=64*v;e.save(),e.globalAlpha=.12+(1-p.z/h)*.2,e.fillStyle=`hsl(${(a+(1-p.z/h)*60)%360}, 90%, 60%)`,e.beginPath(),e.ellipse(x,b,S*.7,g*.7,0,0,Math.PI*2),e.fill(),e.restore(),p.img&&p.img.width?e.drawImage(p.img,x-S/2,b-g/2,S,g):(e.save(),e.fillStyle=`hsl(${(a+180)%360}, 40%, 55%)`,e.fillRect(x-S/2,b-g/2,S,g),e.restore())}}function cn(e,t){return e+Math.random()*(t-e)}function Fu(e,t,n,r,a,o){o.current||(o.current={blobs:Array.from({length:7},(d,f)=>({x:cn(t*.2,t*.8),y:cn(n*.2,n*.8),r:cn(Math.min(t,n)*.05,Math.min(t,n)*.12),vx:cn(-.6,.6),vy:cn(-.6,.6),hue:(a+f*10)%360}))});const i=o.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,f=e.createRadialGradient(c.x,c.y,c.r*.2,c.x,c.y,c.r);f.addColorStop(0,`hsla(${d}, 95%, 70%, .8)`),f.addColorStop(1,`hsla(${(d+40)%360}, 90%, 30%, 0)`),e.fillStyle=f,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="var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",e.lineWidth=2,e.strokeRect(1,1,t-2,n-2)}function Ou(e,t,n,r,a,o){o.current||(o.current={tris:[]});const i=o.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 f of i.tris){f.a+=.002+r*.02*(f.dr>0?1:-1),f.r+=Math.sin(f.a*2)*(.3+r*1.4);const h=Math.max(40,Math.min(f.r,Math.min(t,n)*.48));e.save(),e.translate(c,d),e.rotate(f.a),e.strokeStyle=`hsla(${(a+h*.2)%360}, 90%, 60%, .9)`,e.lineWidth=2.5,e.beginPath(),e.moveTo(h,0);for(let m=1;m<3;m++){const y=m*Math.PI*2/3;e.lineTo(Math.cos(y)*h,Math.sin(y)*h)}e.closePath(),e.shadowBlur=12,e.shadowColor=e.strokeStyle,e.stroke(),e.restore()}}function _u(e,t,n,r,a,o){const i=t/2,l=n/2,c=5,d=Math.min(t,n)*.42;o.current+=.01;for(let f=0;f<c;f++){const h=(f+1)/(c+1),m=h*d;e.strokeStyle=`hsla(${(a+f*30)%360}, 70%, 45%, 0.35)`,e.lineWidth=1,e.beginPath(),e.arc(i,l,m,0,Math.PI*2),e.stroke();const y=Math.floor(r.length*h|0),p=(r[y]??0)/255,v=6+f*2;for(let x=0;x<v;x++){const b=o.current*(1+f*.15)+x/v*Math.PI*2,S=m+Math.sin(b*2)*6*p,g=i+Math.cos(b)*S,k=l+Math.sin(b)*S;e.fillStyle=`hsla(${(a+f*30+x*6)%360}, 90%, ${55+p*30}%, ${.6+p*.3})`,e.beginPath(),e.arc(g,k,2+p*4,0,Math.PI*2),e.fill()}}}function zu(e,t,n,r,a){const l=t/12,c=n/6;for(let d=0;d<6;d++)for(let f=0;f<12;f++){const h=(d*12+f)%r.length,m=r[h]/255,y=(a+f/12*180+d/6*90)%360,p=70+m*25,v=25+m*35;e.fillStyle=`hsl(${y}, ${p}%, ${v}%)`,e.fillRect(f*l,d*c,Math.ceil(l),Math.ceil(c))}}function Bu(e,t,n,r,a,o){const i=t/2,l=n/2,c=2+Math.floor(r*14);for(let f=0;f<c;f++){const h=Math.random()*Math.PI*2,m=.5+Math.random()*(2.5+r*4);o.current.push({x:i,y:l,vx:Math.cos(h)*m,vy:Math.sin(h)*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=o.current;for(let f=d.length-1;f>=0;f--){const h=d[f];h.x+=h.vx,h.y+=h.vy,h.life+=1;const m=1-h.life/h.max;e.fillStyle=`hsla(${h.hue},85%,60%,${Math.max(0,m)})`,e.beginPath(),e.arc(h.x,h.y,2+m*3,0,Math.PI*2),e.fill(),(h.life>=h.max||h.x<-20||h.y<-20||h.x>t+20||h.y>n+20)&&d.splice(f,1)}d.length>1200&&d.splice(0,d.length-1200)}function Gu(e,t,n,r,a,o){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(${(o+200)%360},90%,70%,0.95)`),d.addColorStop(.5,`hsla(${(o+260)%360},80%,55%,0.6)`),d.addColorStop(1,"transparent"),e.fillStyle=d,e.beginPath(),e.arc(i,l,c,0,Math.PI*2),e.fill();const f=18+Math.floor(a*50);for(let h=0;h<f;h++){const m=h/f*Math.PI*2+r*(.6+a*1.4),y=(Math.sin(r*2+h*1.7)+Math.cos(r*1.3+h*2.1))*.15,p=c*(.4+.55*Math.abs(Math.sin(r*1.2+h))),v=6;e.save(),e.translate(i,l),e.rotate(m+y),e.beginPath(),e.moveTo(0,0);for(let b=1;b<=v;b++){const S=p/v*b,g=(Math.sin(r*3+h*.8+b)*.6+Math.cos(r*2+h+b*.7))*(8+24*a),k=S,M=g;e.lineTo(M,k)}e.globalCompositeOperation="lighter";const x=(o+h*(240/f))%360;e.strokeStyle=`hsla(${x}, 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(${(o+40)%360},90%,70%,${.25+a*.25})`,e.lineWidth=1.5,e.stroke(),e.globalCompositeOperation="source-over"}function Wu(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,f=Math.min(t,n)*.48;for(let h=0;h<96;h++){const m=r[h*i]/255,y=h/96*Math.PI*2,p=d,v=d+m*(f-d),x=l+Math.cos(y)*p,b=c+Math.sin(y)*p,S=l+Math.cos(y)*v,g=c+Math.sin(y)*v;e.strokeStyle=`hsl(${h/96*360+a},85%,60%)`,e.lineWidth=3,e.beginPath(),e.moveTo(x,b),e.lineTo(S,g),e.stroke()}e.fillStyle="var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.beginPath(),e.arc(l,c,d*.85,0,Math.PI*2),e.fill()}function Uu(e,t,n,r,a,o){const i=t/2,l=n/2,c=Math.min(t,n)*.5,d=as(r,0,Math.floor(r.length*.1))/255,f=as(r,Math.floor(r.length*.6),r.length)/255;o.current+=.01+f*.03;const h=24;for(let m=0;m<h;m++){const y=o.current+m/h*Math.PI*2,p=(.35+d*.55)*c,v=i+Math.cos(y)*p,x=l+Math.sin(y)*p,b=e.createRadialGradient(i,l,0,i,l,p),S=m/h*360+a;b.addColorStop(0,`hsla(${S},85%,65%,0.0)`),b.addColorStop(1,`hsla(${S},85%,65%,0.9)`),e.strokeStyle=b,e.lineWidth=6+f*8,e.beginPath(),e.moveTo(i,l),e.lineTo(v,x),e.stroke()}e.fillStyle="rgba(2,6,23,0.25)",e.fillRect(0,0,t,n)}function as(e,t,n){let r=0,a=0;for(let o=t;o<n;o++)r+=e[o],a++;return a?r/a:0}function Vu(e,t,n,r,a,o){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,f=t/(d-1);e.beginPath();for(let y=0;y<d;y++){const p=(r[y]-128)/128,v=Math.sin(o*1.5+y*.03)*.12,x=y*f,b=i-l-(p+v)*c;y===0?e.moveTo(x,b):e.lineTo(x,b)}const h=e.createLinearGradient(0,0,0,i-l);h.addColorStop(0,"hsla(260,90%,75%,0.9)"),h.addColorStop(1,"hsla(220,85%,60%,0.4)"),e.strokeStyle=h,e.lineWidth=2,e.stroke(),e.beginPath();for(let y=0;y<d;y++){const p=(r[y]-128)/128,v=Math.cos(o*1.3+y*.035)*.12,x=y*f,b=i+l+(p+v)*c;y===0?e.moveTo(x,b):e.lineTo(x,b)}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="var(--nice-overlay-light-8, 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"}function qu(e,t,n,r,a,o){const i=t/2,l=n/2,c=5,d=Math.min(t,n)*.12;for(let f=0;f<c;f++){const h=Math.floor(f/c*r.length),m=r[h]/255,y=d+f*d*.55+m*d*.5,p=(o+f*40)%360;e.lineWidth=3+m*6,e.strokeStyle=`hsla(${p},80%,60%,${.5+.5*a})`,e.beginPath(),e.arc(i,l,y,0,Math.PI*2),e.stroke()}}function Hu(e,t,n,r,a){const o=Math.min(r.length,256),i=Math.max(1,Math.floor(r.length/o)),l=t/o;for(let c=0;c<o;c++){const d=r[c*i]/255,f=d*(n-6),h=c*l,m=n-f,y=c/o*240+a;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(h+1,m,l-2,f)}}function Ku(e,t,n,r){e.current||(e.current={stars:[],ready:!1});const a=e.current;if(!a.ready||a.stars.length!==t){const o=[];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};o.push(l)}a.stars=o,a.ready=!0}}function Yu(e,t,n,r,a,o){const i=o.current,l=t/2,c=n/2,d=4+r*18;e.save(),e.translate(l,c);for(const f of i.stars){f.z-=d,f.z<20&&(f.x=(Math.random()-.5)*t,f.y=(Math.random()-.5)*n,f.z=900,f.pz=f.z);const h=f.x/f.z*600,m=f.y/f.z*600,y=f.x/f.pz*600,p=f.y/f.pz*600;f.pz=f.z,e.strokeStyle=`hsla(${(a+200)%360}, 90%, 70%, 0.7)`,e.lineWidth=Math.max(1,(1-f.z/900)*2),e.beginPath(),e.moveTo(y,p),e.lineTo(h,m),e.stroke()}e.restore()}function Zu(e,t,n,r){e.lineWidth=2,e.strokeStyle="var(--nice-primary-light, #c7d2fe)",e.beginPath();const a=t/r.length;for(let o=0;o<r.length;o++){const i=(r[o]-128)/128,l=o*a,c=n/2+i*(n*.45);o===0?e.moveTo(l,c):e.lineTo(l,c)}e.stroke()}const Xu=({active:e,onClick:t,title:n,children:r})=>s.jsx("button",{type:"button",onClick:t,title:n,"aria-pressed":e,style:{padding:"4px 8px",borderRadius:6,fontSize:12,border:`1px solid ${e?"var(--nice-info, #6366f1)":"var(--nice-text, #334155)"}`,background:e?"rgba(99,102,241,.12)":"rgba(15,23,42,.6)",color:e?"var(--nice-border, #e2e8f0)":"var(--nice-border, #cbd5e1)",cursor:"pointer",whiteSpace:"nowrap",lineHeight:1.2},children:r}),ma=({modes:e=[],active:t,setActive:n,rows:r=2})=>{const a=Math.max(1,r);return!e||e.length===0?null:s.jsx("div",{style:{position:"absolute",top:10,right:10,pointerEvents:"auto",zIndex:9999},children:s.jsx("div",{style:{display:"grid",gridAutoFlow:"column",gridTemplateRows:`repeat(${a}, auto)`,gridAutoColumns:"max-content",gap:6,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:6,borderRadius:10,border:"1px solid var(--nice-text, #334155)",backdropFilter:"blur(2px)",justifyItems:"end",alignItems:"start"},children:e.map(o=>s.jsx(Xu,{active:t===o,onClick:()=>n(o),title:`Tryb: ${o}`,children:o},o))})})};function Qu(e,t){const[n,r]=u.useState(()=>{try{const a=localStorage.getItem(e);return a?JSON.parse(a):t}catch{return t}});return u.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(n))}catch{}},[e,n]),[n,r]}const Ju=({vu:e,hide:t})=>{if(t)return null;const n=12,r=Math.round(e*n);return s.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px 8px",borderRadius:8,border:"1px solid var(--nice-text, #334155)",backdropFilter:"blur(2px)",pointerEvents:"none",zIndex:9998},children:Array.from({length:n}).map((a,o)=>{const i=120*(o/n);return s.jsx("div",{style:{width:6,height:18,borderRadius:2,background:o<r?`hsl(${i}, 80%, 50%)`:"var(--nice-text, #1f2937)"}},o)})})},ef="var(--player-bg, #0f172a)",ya=({kind:e,audioRef:t,width:n="100%",height:r=360,coverUrl:a,title:o,subtitle:i,label:l,defaultMode:c="cover",storageKey:d="gp-stage:mode",allowedModes:f,imageUrls:h,imageCount:m=14})=>{const y=u.useMemo(()=>f!=null&&f.length?f: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,f]),p=u.useMemo(()=>{const te=y.includes(c)?c:y[0];try{const G=localStorage.getItem(d);if(!G)return te;const B=JSON.parse(G);return y.includes(B)?B:te}catch{return te}},[y,c,d]),[v,x]=Qu(d,p),b=u.useRef(null),S=u.useRef(null),g=u.useRef(null),k=u.useRef(null),M=u.useRef(null),N=u.useRef(null),j=u.useRef(0),_=u.useRef(0),P=u.useRef([]),[V,z]=u.useState(0),A=u.useRef(null),I=u.useRef(null),L=u.useRef(null),U=u.useRef(null),Y=u.useRef(null),O=u.useRef(null),Z=u.useRef(null),H=v!=="cover"&&v!=="video";return u.useEffect(()=>{var T;if(e==="youtube"||(S.current&&(cancelAnimationFrame(S.current),S.current=null),!H))return;It();const te=an(),G=t.current;if(!G)return;if(!g.current)try{g.current=te.createMediaElementSource(G)}catch{}if(!k.current){const C=te.createAnalyser();C.fftSize=2048,C.smoothingTimeConstant=.85,k.current=C;try{(T=g.current)==null||T.connect(C)}catch{}try{C.connect(te.destination)}catch{}}const B=k.current;M.current=new Uint8Array(B.frequencyBinCount),N.current=new Uint8Array(B.fftSize);const w=()=>{const C=b.current,E=Math.max(1,Math.floor(window.devicePixelRatio||1));C.width=Math.floor(C.clientWidth*E),C.height=Math.floor(C.clientHeight*E);const F=C.getContext("2d");F==null||F.setTransform(1,0,0,1,0,0),F==null||F.scale(E,E)};w();const $=()=>w();window.addEventListener("resize",$),Ku(L,220,b.current.width,b.current.height);const R=async()=>{const C=b.current;if(!C)return;const E=C.getContext("2d");if(!E)return;const F=Math.max(1,Math.floor(window.devicePixelRatio||1)),q=C.width/F,Q=C.height/F,J=performance.now()*.001,ae=v==="waveform"||v==="rift";ae?B.getByteTimeDomainData(N.current):B.getByteFrequencyData(M.current);let re=0;const ee=ae?N.current:M.current;for(let D=0;D<ee.length;D++){const K=ae?(ee[D]-128)/128:ee[D]/255;re+=K*K}if(re=Math.sqrt(re/ee.length),z(Math.min(1,re)),E.clearRect(0,0,q,Q),v==="spectrum")Hu(E,q,Q,M.current,j.current);else if(v==="bars")ju(E,q,Q,M.current,j.current);else if(v==="waveform")Zu(E,q,Q,N.current);else if(v==="palette"){const D=(j.current+re*120)%360;zu(E,q,Q,M.current,D)}else if(v==="radial")Wu(E,q,Q,M.current,j.current);else if(v==="rays")Uu(E,q,Q,M.current,j.current,_);else if(v==="particles")Bu(E,q,Q,re,j.current,P);else if(v==="rings")qu(E,q,Q,M.current,re,j.current);else if(v==="grid"){const D=(j.current+re*160)%360;Nu(E,q,Q,M.current,D)}else if(v==="imageTornado"){const D=h!=null&&h.length?h:a?[a]:[];await Lu(A,D,m,q,Q);const K=(j.current+re*100)%360;Du(E,q,Q,re,K,A)}else if(v==="colorRipples"){const D=(j.current+re*120)%360;Tu(E,q,Q,re,D,I)}else if(v==="starfield"){const D=(j.current+60)%360;Yu(E,q,Q,re,D,L)}else if(v==="orbitals"){const D=(j.current+re*180)%360;_u(E,q,Q,M.current,D,_)}else if(v==="eqcircle"){const D=(j.current+120)%360;Au(E,q,Q,M.current,D)}else if(v==="triangles"){const D=(j.current+40)%360;Ou(E,q,Q,re,D,U)}else if(v==="blob"){const D=(j.current+90)%360;Ru(E,q,Q,re,D,Y)}else if(v==="plasma"){const D=(j.current+re*200)%360;Gu(E,q,Q,J,re,D)}else if(v==="rift")Vu(E,q,Q,N.current,re,J);else if(v==="lavaLamp"){const D=(j.current+re*80)%360;Fu(E,q,Q,re,D,O)}else if(v==="cozyFire"){const D=(j.current+re*140)%360;Eu(E,q,Q,M.current,re,D,Z)}j.current=(j.current+.4)%360,S.current=requestAnimationFrame(R)};return S.current=requestAnimationFrame(R),()=>{window.removeEventListener("resize",$),S.current&&cancelAnimationFrame(S.current)}},[H,e,t,v,h,m,a]),s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none",background:v==="cover"?"transparent":ef},children:v==="cover"?s.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:s.jsx(Pu,{height:r,coverUrl:a,title:o,subtitle:i,label:l})}):s.jsx("canvas",{ref:b,style:{width:typeof n=="number"?`${n}px`:n,height:r,borderRadius:8},role:"img","aria-label":"Stage visualizer canvas"})}),s.jsxs("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:[s.jsx(ma,{modes:y,active:v,setActive:x,rows:2}),s.jsx(Ju,{vu:V,hide:e==="youtube"})]})]})},Vo=({height:e,autoPlay:t,track:n,source:r,ytRef:a,audioRef:o,hlsRef:i,setVol:l,onEnd:c,volume:d,extractVideoId:f})=>{u.useEffect(()=>{const p=o.current;if(p){if(p.volume=d,p.crossOrigin=r!=null&&r.withCredentials?"use-credentials":"anonymous",(r==null?void 0:r.kind)==="hls"&&ku(r.url)){const v=()=>{p.src=r.url,p.load(),t&&p.play().catch(()=>{})};if(p.canPlayType("application/vnd.apple.mpegurl")){v();return}(async()=>{const b=(await import("hls.js")).default;if(b.isSupported()){const S=new b({xhrSetup:g=>{if(r!=null&&r.withCredentials&&(g.withCredentials=!0),r!=null&&r.headers)for(const[k,M]of Object.entries(r.headers))g.setRequestHeader(k,String(M))}});i.current=S,S.loadSource(r.url),S.attachMedia(p),S.on(b.Events.MANIFEST_PARSED,()=>t&&p.play().catch(()=>{}))}else v()})()}(r==null?void 0:r.kind)==="audio"&&r.url&&(p.src=r.url,p.load(),t&&p.play().catch(()=>{}))}},[r==null?void 0:r.url,r==null?void 0:r.kind,r==null?void 0:r.withCredentials,d,t]);const h=(r==null?void 0:r.kind)==="youtube",m=h?"video":"cover",y=`gp-stage:mode:${(r==null?void 0:r.kind)??"none"}`;return s.jsxs("div",{className:"gp-stage",style:{width:"100%",height:e,background:h?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(r==null?void 0:r.kind)==="youtube"&&s.jsx(Qr,{videoId:r.videoId??f(r.url),onReady:p=>{a.current=p.target,l(d),t&&p.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")&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{textAlign:"center",color:"var(--text, #e2e8f0)"},children:n!=null&&n.coverUrl?s.jsx("img",{alt:"cover",src:n.coverUrl,style:{height:e-24,objectFit:"contain"}}):s.jsxs("div",{style:{opacity:.8},children:[s.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[n==null?void 0:n.artist," — ",n==null?void 0:n.title]}),s.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()})]})}),s.jsx("audio",{ref:o,onEnded:c,onLoadedMetadata:()=>{},crossOrigin:r!=null&&r.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]}),s.jsx(ya,{kind:(r==null?void 0:r.kind)==="hls"?"hls":(r==null?void 0:r.kind)??"audio",audioRef:o,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:y},`vis-${y}`)]})};function tf(e,t){const[n,r]=u.useState(()=>{try{const a=localStorage.getItem(e);return a?JSON.parse(a):t}catch{return t}});return u.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(n))}catch{}},[e,n]),[n,r]}const nf="var(--text-dim, #94a3b8)",rf=({active:e,onClick:t,title:n,children:r})=>s.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}),qo=({kind:e,audioRef:t,width:n="100%",height:r=360,coverUrl:a,title:o,subtitle:i,label:l,defaultMode:c="cover",storageKey:d="gp-stage:mode",allowedModes:f,overlayOnly:h=!1})=>{const m=u.useMemo(()=>f!=null&&f.length?f:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette"],[e,f]),y=u.useMemo(()=>{const A=m.includes(c)?c:m[0];try{const I=localStorage.getItem(d);if(!I)return A;const L=JSON.parse(I);return m.includes(L)?L:A}catch{return A}},[m,c,d]),[p,v]=tf(d,y),x=u.useRef(null),[b,S]=u.useState(0),g=u.useRef(null),k=u.useRef(null),M=u.useRef(null),N=u.useRef(null),j=u.useRef(null),_=u.useRef(0),P=p==="spectrum"||p==="bars"||p==="waveform"||p==="palette";u.useEffect(()=>{var O;if(e==="youtube")return;if(!P){g.current&&cancelAnimationFrame(g.current);return}It();const A=an(),I=t.current;if(!I)return;if(!k.current)try{k.current=A.createMediaElementSource(I)}catch{}if(!M.current){const Z=A.createAnalyser();Z.fftSize=2048,Z.smoothingTimeConstant=.85,M.current=Z;try{(O=k.current)==null||O.connect(Z)}catch{}try{Z.connect(A.destination)}catch{}}const L=M.current;N.current=new Uint8Array(L.frequencyBinCount),j.current=new Uint8Array(L.fftSize);const U=()=>{if(!x.current)return;const Z=x.current,H=Z.getContext("2d");if(!H)return;const te=Z.width,G=Z.height;H.clearRect(0,0,te,G),p==="waveform"?L.getByteTimeDomainData(j.current):L.getByteFrequencyData(N.current);let B=0;const w=p==="waveform"?j.current:N.current;for(let $=0;$<w.length;$++){const R=p==="waveform"?(w[$]-128)/128:w[$]/255;B+=R*R}if(B=Math.sqrt(B/w.length),S(Math.min(1,B)),p==="spectrum"||p==="bars"){const $=N.current,R=p==="bars"?48:Math.min($.length,256),T=Math.floor($.length/R),C=te/R;for(let E=0;E<R;E++){const F=$[E*T]/255,q=F*(G-6),Q=E*C,J=G-q,ae=E/R*240+_.current;H.fillStyle=`hsl(${ae%360}, 80%, ${Math.max(30,40+F*30)}%)`,H.fillRect(Q+1,J,C-2,q)}}else if(p==="waveform"){const $=j.current;H.lineWidth=2,H.strokeStyle="var(--nice-primary-light, #c7d2fe)",H.beginPath();const R=te/$.length;for(let T=0;T<$.length;T++){const C=($[T]-128)/128,E=T*R,F=G/2+C*(G*.45);T===0?H.moveTo(E,F):H.lineTo(E,F)}H.stroke()}else if(p==="palette"){const T=te/12,C=G/6,E=(_.current+B*120)%360;for(let F=0;F<6;F++)for(let q=0;q<12;q++){const Q=(F*12+q)%N.current.length,J=N.current[Q]/255,ae=(E+q/12*180+F/6*90)%360,re=70+J*25,ee=25+J*35;H.fillStyle=`hsl(${ae}, ${re}%, ${ee}%)`,H.fillRect(q*T,F*C,Math.ceil(T),Math.ceil(C))}}H.strokeStyle=getComputedStyle(document.documentElement).getPropertyValue("--waveform-stroke")||"var(--nice-primary-light, #c7d2fe)",g.current=requestAnimationFrame(U)},Y=()=>{var te;const Z=x.current,H=Math.max(1,Math.floor(window.devicePixelRatio||1));Z.width=Math.floor(Z.clientWidth*H),Z.height=Math.floor(Z.clientHeight*H),(te=Z.getContext("2d"))==null||te.scale(H,H)};return Y(),window.addEventListener("resize",Y),g.current=requestAnimationFrame(U),()=>{window.removeEventListener("resize",Y),g.current&&cancelAnimationFrame(g.current)}},[P,e,t,p]);const V=()=>{if(e==="youtube")return null;const A=12,I=Math.round(b*A);return s.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px 8px",borderRadius:8,border:"1px solid var(--nice-text, #334155)",backdropFilter:"blur(2px)"},children:Array.from({length:A}).map((L,U)=>{const Y=120*(U/A);return s.jsx("div",{style:{width:6,height:18,borderRadius:2,background:U<I?`hsl(${Y}, 80%, 50%)`:"var(--nice-text, #1f2937)"}},U)})})},z=()=>s.jsx("div",{style:{textAlign:"center",color:"var(--nice-border, #e2e8f0)"},children:a?s.jsx("img",{alt:"cover",src:a,style:{height:r-24,objectFit:"contain"}}):s.jsxs("div",{style:{opacity:.8},children:[s.jsx("div",{style:{fontSize:18,fontWeight:600},children:o??"�"}),s.jsx("div",{style:{marginTop:8,fontSize:12,color:nf},children:l??i??"�"})]})});return s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:p==="cover"?s.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center",background:"transparent"},children:z()}):s.jsx("canvas",{ref:x,style:{width:typeof n=="number"?`${n}px`:n,height:r,borderRadius:8},role:"img","aria-label":"Stage visualizer canvas"})}),s.jsxs("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:[s.jsx("div",{style:{position:"absolute",top:10,right:10,display:"flex",gap:6,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px",borderRadius:10,border:"1px solid var(--nice-text, #334155)",backdropFilter:"blur(2px)",pointerEvents:"auto",zIndex:9999},children:m.map(A=>s.jsx(rf,{active:p===A,onClick:()=>v(A),title:`Tryb: ${A}`,children:A},A))}),s.jsx("div",{style:{position:"absolute",right:10,bottom:10,pointerEvents:"none",zIndex:9998},children:s.jsx(V,{})})]})]})},Ho=({artist:e,title:t,hideControls:n=!0,isPlaying:r,onTimeUpdate:a,searchYouTubeByArtistTitle:o})=>{const{t:i}=we(),[l,c]=u.useState(e||""),[d,f]=u.useState(t||""),[h,m]=u.useState(null),[y,p]=u.useState(null),v=u.useRef(null),[x,b]=u.useState({width:Math.min(560,window.innerWidth-32),height:Math.min(315,(window.innerWidth-32)*9/16)});u.useEffect(()=>{e&&t&&o&&o(e,t).then(m)},[e,t,o]),u.useEffect(()=>{y&&(r?y.playVideo():y.pauseVideo())},[r,y]),u.useEffect(()=>{if(y&&a){const g=setInterval(()=>{const k=y.getCurrentTime();a(k)},100);return()=>clearInterval(g)}},[y,a]),u.useEffect(()=>{const g=()=>{if(v.current){const k=v.current.clientWidth,M=Math.round(k*(9/16));b({width:k,height:M})}};return g(),window.addEventListener("resize",g),()=>window.removeEventListener("resize",g)},[]);const S=async()=>{if(!o)return;const g=await o(l,d);m(g)};return s.jsxs("div",{ref:v,style:{width:"100%",maxWidth:"900px",margin:"0 auto"},children:[(!e||!t||!h)&&s.jsxs("div",{children:[s.jsx("input",{value:l,onChange:g=>c(g.target.value),placeholder:i("youtubePlayer.artist","Artist"),"aria-label":i("youtubePlayer.artist","Artist")}),s.jsx("input",{value:d,onChange:g=>f(g.target.value),placeholder:i("youtubePlayer.title","Title"),"aria-label":i("youtubePlayer.title","Title")}),s.jsx("button",{onClick:S,children:i("youtubePlayer.search","Search")})]}),h&&s.jsxs("div",{children:[s.jsx(Qr,{videoId:h,opts:{width:x.width.toString(),height:x.height.toString(),playerVars:{autoplay:1,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,annotations:0}},onReady:g=>p(g.target)}),!n&&s.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px"},children:[s.jsx("button",{onClick:()=>y==null?void 0:y.playVideo(),children:"? Play"}),s.jsx("button",{onClick:()=>y==null?void 0:y.pauseVideo(),children:"? Pause"})]})]})]})},af=({kind:e,color:t})=>{const n={width:14,height:14,viewBox:"0 0 24 24",fill:t,"aria-hidden":!0};switch(e){case"youtube":return s.jsx("svg",{...n,children:s.jsx("path",{d:"M23 7.2s-.2-1.6-.9-2.3c-.8-.9-1.7-.9-2.1-1C16.9 3.5 12 3.5 12 3.5s-4.9 0-8 .4c-.4.1-1.3.1-2.1 1C1.2 5.6 1 7.2 1 7.2S.8 9.1.8 11v1.8c0 1.9.2 3.8.2 3.8s.2 1.6.9 2.3c.8.9 1.9.9 2.4 1 1.7.2 7.7.4 7.7.4s4.9 0 8-.4c.4-.1 1.3-.1 2.1-1 .7-.7.9-2.3.9-2.3s.2-1.9.2-3.8V11c0-1.9-.2-3.8-.2-3.8zM9.7 14.6V8.2l6.3 3.2-6.3 3.2z"})});case"spotify":return s.jsx("svg",{...n,children:s.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.59 14.42c-.18.3-.57.4-.87.21-2.39-1.46-5.4-1.79-8.95-.98-.34.08-.68-.13-.76-.47-.08-.34.13-.68.47-.76 3.88-.89 7.21-.5 9.89 1.13.31.19.4.58.22.87zm1.23-2.72c-.23.37-.71.49-1.08.26-2.74-1.69-6.92-2.18-10.16-1.19-.41.13-.85-.11-.97-.52-.13-.41.11-.85.52-.97 3.7-1.12 8.31-.58 11.45 1.34.37.23.49.71.24 1.08zm.11-2.84C14.55 8.84 9.5 8.66 6.43 9.6c-.49.15-1.01-.13-1.16-.62-.15-.49.13-1.01.62-1.16 3.52-1.07 9.1-.86 12.69 1.27.43.26.57.82.31 1.25-.26.43-.82.57-1.25.31z"})});case"tidal":return s.jsx("svg",{...n,children:s.jsx("path",{d:"M12 2L8 6l4 4 4-4-4-4zM4 6L0 10l4 4 4-4-4-4zm16 0l-4 4 4 4 4-4-4-4zm-8 8l-4 4 4 4 4-4-4-4z"})});case"hls":return s.jsx("svg",{...n,children:s.jsx("path",{d:"M2 12h2v6H2v-6zm4-4h2v10H6V8zm4-4h2v14h-2V4zm4 4h2v10h-2V8zm4 4h2v6h-2v-6z"})});case"audio":default:return s.jsx("svg",{...n,children:s.jsx("path",{d:"M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"})})}},ga=({data:e,display:t,callbacks:n,state:r})=>{const{id:a,index:o,artist:i,title:l,version:c,lp:d,sourcesAvailable:f=[]}=e,{allowVersion:h=!0,dragHandleProps:m}=t,{onChange:y,onRemove:p,onMoveUp:v,onMoveDown:x,onChangeLp:b,onSelectSource:S}=n,{readOnly:g=!1,canMoveUp:k=!0,canMoveDown:M=!0,activeSource:N}=r,{t:j}=we(),_=u.useRef(null);u.useEffect(()=>{!i&&_.current&&_.current.focus()},[i]);const P=I=>{if(!g&&I.key==="Enter"){const L=I.target.closest("div.gpi-row"),U=L==null?void 0:L.querySelectorAll("input[data-role='field']");if(!U||U.length===0)return;const Y=Array.from(U).indexOf(I.target),O=U[Y+1]??U[0];O==null||O.focus()}},V=I=>{const L=f.includes(I),U=N===I,Y={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid var(--nice-border, #e5e7eb)",background:U?"var(--active-bg, #eef2ff)":"var(--bg, #fff)",opacity:L?1:.35,cursor:L&&S&&!g?"pointer":"default",transition:"transform .05s ease"},O=I==="youtube"?"var(--nice-danger, #ff0000)":I==="spotify"?"var(--nice-success, #1db954)":I==="tidal"?"var(--nice-text, #111827)":I==="hls"?"var(--nice-accent, #7c3aed)":"var(--nice-text, #374151)",Z=I==="youtube"?"YouTube":I==="spotify"?"Spotify":I==="tidal"?"TIDAL":I==="hls"?"HLS":"Audio",H=j("playlistItem.sourceLabel")+": "+Z+(U?` ${j("playlistItem.sourceSelected")}`:""),te=()=>{!L||!S||g||S(I)};return s.jsx("button",{type:"button",title:Z,onClick:te,disabled:!L||g,style:Y,"aria-pressed":U,"aria-label":H,children:s.jsx(af,{kind:I,color:O})},I)},z=["youtube","tidal","spotify","hls","audio"],A=typeof d=="number"?d:o+1;return s.jsxs("div",{className:"gpi-row",role:"group","aria-label":j("playlistItem.trackNumber")+" "+(o+1),style:{display:"grid",gridTemplateColumns:h?"56px 1fr 1fr 1fr auto auto":"56px 1fr 1fr auto auto",gap:8,alignItems:"center"},children:[s.jsx("input",{type:"number",min:1,value:A,onChange:I=>b==null?void 0:b(Number(I.target.value)),disabled:g||!b,"aria-label":"Lp",title:j("playlistItem.positionOnList"),style:sf}),s.jsx("input",{ref:_,"data-role":"field",type:"text",value:i,onChange:I=>y({artist:I.target.value}),placeholder:"Artist",onKeyDown:P,disabled:g,"aria-label":"Artist",className:"gpi-input",style:jr}),s.jsx("input",{"data-role":"field",type:"text",value:l,onChange:I=>y({title:I.target.value}),placeholder:"Title",onKeyDown:P,disabled:g,"aria-label":"Title",className:"gpi-input",style:jr}),h&&s.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:I=>y({version:I.target.value||void 0}),placeholder:j("playlistItem.versionOptional"),onKeyDown:P,disabled:g,"aria-label":"Version",className:"gpi-input",style:jr}),s.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":j("playlistItem.availableSources"),children:z.map(V)}),s.jsxs("div",{className:"gpi-actions",style:{display:"flex",gap:6,justifyContent:"flex-end"},children:[m&&s.jsx("button",{type:"button",...m,draggable:!0,"aria-label":j("playlistItem.dragReorder"),title:j("playlistItem.dragReorder"),style:Dn,children:"≡"}),s.jsx("button",{type:"button",onClick:v,disabled:!k||g,"aria-label":j("playlistItem.moveUp"),title:j("playlistItem.moveUp"),style:Dn,children:"↑"}),s.jsx("button",{type:"button",onClick:x,disabled:!M||g,"aria-label":j("playlistItem.moveDown"),title:j("playlistItem.moveDown"),style:Dn,children:"↓"}),s.jsx("button",{type:"button",onClick:p,disabled:g,"aria-label":j("common.delete"),title:j("common.delete"),style:{...Dn,color:"var(--danger, #b91c1c)"},children:"✕"})]})]})},sf={width:48,border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 6px",fontSize:14,textAlign:"center"},jr={width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 10px",fontSize:14},Dn={border:"1px solid var(--nice-border, #d1d5db)",background:"var(--bg, #fff)",padding:"6px 8px",borderRadius:6,cursor:"pointer"},Gr=()=>Math.random().toString(36).slice(2,10),Fn=e=>(e??[]).map(t=>({id:Gr(),...t})),of=e=>e.map(({id:t,...n})=>n),lf=null,cf=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(),o=a.match(/^(.*?)\s*[([](.+?)[)\]]\s*$/);if(o){const i=o[1].trim(),l=o[2].trim();return{artist:r,title:i,version:l||void 0}}return{artist:r,title:a,version:void 0}},Ko=({value:e,defaultValue:t,onChange:n,allowVersion:r=!0,maxItems:a,addButtonLabel:o,emptyState:i=lf,readOnly:l=!1,autoFocusNewItem:c=!0,enableBulkPaste:d=!0})=>{const{t:f}=we(),h=e!==void 0,[m,y]=u.useState(()=>Fn(e||t)),[p,v]=u.useState(""),x=u.useRef(null),[b,S]=u.useState(null);u.useEffect(()=>{h&&y(Fn(e))},[h,JSON.stringify(e)]);const g=u.useCallback(H=>{n==null||n(of(H))},[n]),k=u.useCallback(H=>{if(h){const te=H(Fn(e));g(te)}else y(te=>{const G=H(te);return g(G),G})},[g,h,e]),M=a?m.length<a:!0,N=u.useCallback(()=>{!M||l||k(H=>[...H,{id:Gr(),artist:"",title:"",version:void 0}])},[M,l,k]),j=u.useCallback((H,te)=>{k(G=>G.map(B=>B.id===H?{...B,...te}:B))},[k]),_=u.useCallback(H=>{l||k(te=>te.filter(G=>G.id!==H))},[l,k]),P=u.useCallback((H,te)=>{k(G=>{const B=G.findIndex(T=>T.id===H);if(B<0)return G;const w=B+te;if(w<0||w>=G.length)return G;const $=[...G],[R]=$.splice(B,1);return $.splice(w,0,R),$})},[k]),V=u.useCallback((H,te)=>{k(G=>{const B=G.findIndex(T=>T.id===H);if(B<0)return G;const w=Math.max(0,Math.min(G.length-1,te-1));if(B===w)return G;const $=[...G],[R]=$.splice(B,1);return $.splice(w,0,R),$})},[k]),z=H=>te=>{l||(x.current=H,te.dataTransfer.effectAllowed="move",te.dataTransfer.setData("text/plain",H))},A=H=>te=>{l||(te.preventDefault(),te.dataTransfer.dropEffect="move",S(H))},I=H=>()=>S(te=>te===H?null:te),L=H=>te=>{if(l)return;te.preventDefault();const G=x.current??te.dataTransfer.getData("text/plain");S(null),x.current=null,!(!G||G===H)&&k(B=>{const w=B.findIndex(C=>C.id===G),$=B.findIndex(C=>C.id===H);if(w<0||$<0||w===$)return B;const R=[...B],[T]=R.splice(w,1);return R.splice($,0,T),R})},U=()=>{x.current=null,S(null)},Y=u.useCallback(()=>{if(!d||l)return;const te=p.split(/\r?\n/).map(G=>G.trim()).filter(Boolean).map(cf).filter(G=>!!G);te.length!==0&&(k(G=>{const B=(a??1/0)-G.length,w=te.slice(0,Math.max(0,B)).map($=>({id:Gr(),...$}));return[...G,...w]}),v(""))},[d,l,p,a,k]);u.useEffect(()=>{},[m.length,c]);const O=i??s.jsx("div",{style:{padding:"0.75rem",color:"var(--nice-text-secondary, #777)",fontStyle:"italic"},children:f("genericPlaylist.emptyState","No songs. Add the first one below.")}),Z=o??f("genericPlaylist.addSong","Add song");return s.jsxs("div",{className:"gp-container",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[s.jsxs("div",{className:"gp-header",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[s.jsx("h3",{style:{margin:0,fontSize:16},children:f("genericPlaylist.playlist","Playlist")}),s.jsx("div",{style:{marginLeft:"auto",display:"flex",gap:8},children:s.jsxs("button",{type:"button",onClick:N,disabled:!M||l,className:"gp-add",style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},"aria-label":Z,children:["+ ",Z]})})]}),m.length===0?s.jsx("div",{className:"gp-empty",children:O}):s.jsx("ol",{className:"gp-list",style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:8},children:m.map((H,te)=>{const G=b===H.id;return s.jsx("li",{draggable:!l,onDragStart:z(H.id),onDragOver:A(H.id),onDragLeave:I(H.id),onDrop:L(H.id),onDragEnd:U,style:{border:G?"2px dashed var(--nice-info, #6366f1)":"2px solid transparent",borderRadius:8,padding:G?4:0},children:s.jsx(ga,{data:{id:H.id,index:te,lp:te+1,artist:H.artist,title:H.title,version:r?H.version??void 0:void 0,sourcesAvailable:void 0},display:{allowVersion:r,dragHandleProps:{onDragStart:z(H.id)}},callbacks:{onChange:B=>j(H.id,B),onRemove:()=>_(H.id),onMoveUp:()=>P(H.id,-1),onMoveDown:()=>P(H.id,1),onChangeLp:B=>V(H.id,B)},state:{readOnly:l,canMoveUp:te>0,canMoveDown:te<m.length-1}})},H.id)})}),d&&!l&&s.jsx("div",{style:{marginTop:12},children:s.jsxs("details",{children:[s.jsx("summary",{style:{cursor:"pointer",color:"var(--nice-text, #374151)"},children:f("genericPlaylist.bulkPasteSummary","Paste multiple items at once")}),s.jsxs("div",{style:{marginTop:6},children:[s.jsx("textarea",{value:p,onChange:H=>v(H.target.value),placeholder:f("genericPlaylist.bulkPastePlaceholder",`Paste lines in format:
46
+ -`]})]}),c&&c.length>0&&r.jsxs("div",{style:{marginTop:24},children:[r.jsx("b",{children:i("audioPitch.waveformRms")}),r.jsx("canvas",{width:600,height:100,style:{background:"var(--nice-text, #222)",borderRadius:4,width:"100%",maxWidth:600,display:"block"},role:"img","aria-label":"Waveform and RMS visualization canvas",ref:V=>{if(!V)return;const q=V.getContext("2d");if(q){q.clearRect(0,0,600,100),q.strokeStyle="var(--nice-info, #0ff)",q.beginPath();for(let C=0;C<c.length;C+=Math.ceil(c.length/600)){const F=C/c.length*600,I=50-c[C]*48;C===0?q.moveTo(F,I):q.lineTo(F,I)}if(q.stroke(),b.length>0){q.strokeStyle="var(--nice-warning, #ff0)",q.beginPath();for(let C=0;C<b.length;C++){const F=C/b.length*600,I=100-b[C]*90;C===0?q.moveTo(F,I):q.lineTo(F,I)}q.stroke()}}}}),r.jsxs("div",{style:{color:"var(--nice-text-muted, #aaa)",fontSize:12,marginTop:4},children:[r.jsx("span",{style:{color:"var(--nice-info, #0ff)"},children:"Waveform"}),"  | "," ",r.jsx("span",{style:{color:"var(--nice-warning, #ff0)"},children:"RMS"})]})]}),!w&&k.length===0&&!S&&r.jsx("div",{style:{marginTop:16,color:"var(--nice-text-muted, #aaa)"},children:r.jsx("i",{children:i("audioPitch.noNotesDetected")})}),h&&Object.keys(f).length>0&&r.jsxs("div",{style:{marginTop:16},children:[r.jsx("h4",{children:i("audioPitch.algorithmComparison")}),Object.entries(f).map(([V,q])=>r.jsxs("div",{style:{marginBottom:12},children:[r.jsx("b",{children:V}),": ",i("audioPitch.detectedSegments")," ",q.length,r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-border, #ddd)",padding:8,borderRadius:4,marginTop:8},children:q.map(C=>`: ${Math.round(C.start*10)} ${Math.round(C.duration*10)} ${C.pitch} [${C.freq.toFixed(1)} Hz]`).join(`
47
+ `)})]},V))]})]})}const Dt=1e4,Os=5e3;function Hr(e,t=.35){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(!n)return e;const a=Math.min(255,Math.round(parseInt(n[1],16)+(255-parseInt(n[1],16))*t)),s=Math.min(255,Math.round(parseInt(n[2],16)+(255-parseInt(n[2],16))*t)),i=Math.min(255,Math.round(parseInt(n[3],16)+(255-parseInt(n[3],16))*t));return`rgb(${a},${s},${i})`}const lh=["var(--nice-warning, #facc15)","var(--nice-text-secondary, #cbd5e1)","var(--nice-warning, #d97706)"],ch=({entry:e,rank:t,animDelay:n})=>{const[a,s]=d.useState(0),[i,o]=d.useState(0),[l,c]=d.useState(0),[u,h]=d.useState(0),p=Math.min(e.classicScore,Dt),f=Math.min(e.bonusScore,Dt),y=p/Dt*Os,m=f>0?f/Dt*Os:0;return d.useEffect(()=>{let g,b=null;const x=Math.max(y,400),k=Math.max(m,m>0?300:0),v=w=>{b===null&&(b=w);const M=w-b-n;if(M<0){g=requestAnimationFrame(v);return}if(M<=x){const S=Math.min(1,M/x),R=1-Math.pow(1-S,3);s(Math.min(R*(p/Dt)*100,100)),c(Math.round(R*e.classicScore)),g=requestAnimationFrame(v);return}if(s(Math.min(p/Dt*100,100)),c(e.classicScore),k>0){const S=M-x;if(S<=k){const R=Math.min(1,S/k),T=1-Math.pow(1-R,3);o(Math.min(T*(f/Dt)*100,100)),h(Math.round(T*e.bonusScore)),g=requestAnimationFrame(v);return}o(Math.min(f/Dt*100,100)),h(e.bonusScore)}};return g=requestAnimationFrame(v),()=>cancelAnimationFrame(g)},[e.classicScore,e.bonusScore,y,m,n]),r.jsxs("div",{className:"karaoke-summary-bar",children:[r.jsx("span",{className:"karaoke-summary-bar-rank",children:t<=3?r.jsx(se.NtdMedal,{size:18,primaryColor:lh[t-1]}):`#${t}`}),r.jsx("span",{className:"karaoke-summary-bar-name",style:{color:e.color},children:e.name}),r.jsxs("div",{className:"karaoke-summary-bar-track",children:[e.bonusScore>0&&r.jsx("div",{className:"karaoke-summary-bar-fill-bonus",style:{width:`${Math.min(a+i,100)}%`,background:Hr(e.color,.45)}}),r.jsx("div",{className:"karaoke-summary-bar-fill-classic",style:{width:`${a}%`,background:`linear-gradient(90deg, ${e.color}, ${Hr(e.color,.15)})`,boxShadow:`0 0 8px ${e.color}55`}}),r.jsxs("div",{className:"karaoke-summary-bar-text",children:[l.toLocaleString(),u>0&&r.jsxs("span",{className:"karaoke-summary-bar-text-bonus",style:{color:Hr(e.color,.5)},children:["+",u.toLocaleString()]})]})]}),r.jsx("span",{className:"karaoke-summary-bar-total",children:(l+u).toLocaleString()})]})},Bs=({title:e,entries:t,highlightNames:n,playerColorMap:a})=>r.jsxs("div",{className:"karaoke-summary-rank",children:[r.jsx("h4",{className:"karaoke-summary-rank-title",children:e}),r.jsx("table",{className:"karaoke-summary-rank-table",children:r.jsx("tbody",{children:t.map((s,i)=>{const o=n.has(s.name),l=a.get(s.name);return r.jsxs("tr",{className:o?"karaoke-summary-rank-row karaoke-summary-rank-row--hl":"karaoke-summary-rank-row",children:[r.jsx("td",{className:`karaoke-summary-rank-pos${i<3?" karaoke-summary-rank-pos--top":""}`,children:s.rank}),r.jsxs("td",{className:"karaoke-summary-rank-name",style:l?{color:l}:void 0,children:[o&&"● ",s.name]}),r.jsx("td",{className:"karaoke-summary-rank-score",children:s.score.toLocaleString()})]},`${s.name}-${i}`)})})})]}),Ka=({uploadedSong:e,playerScores:t,topSingings:n,onRestart:a,onContinue:s,t:i,renderReport:o,className:l,style:c,id:u,accessMode:h,"data-testid":p})=>{const[f,y]=d.useState(!1),m=d.useMemo(()=>[...t].sort((w,M)=>M.totalScore-w.totalScore),[t]),g=d.useMemo(()=>{const w=new Map;for(const M of t)w.set(M.name,M.color);return w},[t]),b=d.useMemo(()=>new Set(t.map(w=>w.name)),[t]),x=d.useMemo(()=>m.map((w,M)=>({rank:M+1,name:w.name,score:w.totalScore,color:w.color})),[m]),k=d.useMemo(()=>{const w=n.map(S=>({name:S.playerName,score:S.score})),M=new Set;for(const S of m)M.has(S.id)||(M.add(S.id),w.push({name:S.name,score:S.totalScore}));return w.sort((S,R)=>R.score-S.score),w.slice(0,10).map((S,R)=>({rank:R+1,name:S.name,score:S.score}))},[n,m]),v=e?e.artist?`${e.artist} — ${e.title}`:e.title:i("karaokeSummary.unknownSong","Unknown song");return h==="hidden"?null:r.jsxs("div",{className:`karaoke-summary-overlay${l?` ${l}`:""}`,style:c,id:u,"data-testid":p,children:[r.jsxs("div",{className:"karaoke-summary-card",children:[r.jsx("h1",{className:"karaoke-summary-title",children:v}),r.jsx("div",{className:"karaoke-summary-bars",children:m.length===0?r.jsx("div",{className:"karaoke-summary-empty",children:i("karaokeSummary.noScores","No scores")}):m.map((w,M)=>r.jsx(ch,{entry:w,rank:M+1,animDelay:M*300},w.id))}),(m.length>1||n.length>0)&&r.jsxs("div",{className:"karaoke-summary-ranks",children:[m.length>1&&r.jsx(Bs,{title:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(se.NtdHome,{size:14})," ",i("karaokeSummary.localRanking","Session ranking")]}),entries:x,highlightNames:b,playerColorMap:g}),n.length>0&&r.jsx(Bs,{title:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(se.NtdTrophy,{size:14})," ",i("karaokeSummary.globalRanking","Top 10")]}),entries:k,highlightNames:b,playerColorMap:g})]}),r.jsxs("div",{className:"karaoke-summary-actions",children:[o&&r.jsxs("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--report",onClick:()=>y(!0),children:[r.jsx(se.NtdBarChart,{size:15})," ",i("karaokeSummary.report","Report")]}),r.jsx("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--restart",onClick:a,children:i("karaokeSummary.restart","Restart")}),r.jsx("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--continue",onClick:s,children:i("karaokeSummary.continue","Continue")})]})]}),f&&(o==null?void 0:o(()=>y(!1)))]})},dh=it.scoped("GenericPlayer"),uh=e=>/youtu(\.be|be\.com)/i.test(e),go=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),hh=e=>!!e&&/\.(mp3|aac|m4a|flac|wav|ogg)(\?.*)?$/i.test(e),ph=e=>{var i;if(!((i=e==null?void 0:e.sources)!=null&&i.length))return null;const t=o=>e.sources.find(l=>l.kind===o),n=e.sources.find(o=>o.kind==="youtube"&&(o.videoId||o.url&&uh(o.url)))??null;if(n)return n;const a=t("hls")||e.sources.find(o=>o.url&&go(o.url))||null;if(a)return a;const s=t("audio")||e.sources.find(o=>o.url&&hh(o.url))||null;return s||(e.sources[0]??null)},Pr=e=>{(!isFinite(e)||e<0)&&(e=0);const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`},fh=[.25,.5,.75,1,1.25,1.5,1.75,2],Ya=({tracks:e=[],initialIndex:t=0,autoPlay:n=!0,countdownSeconds:a=0,height:s=360,onIndexChange:i,onPlayingChange:o,onTimeUpdate:l,externalRef:c,uiMode:u="full",compactNextCount:h=3,progressBarPosition:p="inline",loop:f=!1,onEnded:y,enableKeyboardShortcuts:m=!0,shuffle:g=!1,repeatMode:b="none",playbackSpeed:x=1,abLoop:k=null,onRepeatModeChange:v,onShuffleChange:w,onSpeedChange:M,sleepTimer:S=0,onSleepTimerExpired:R})=>{const{t:T}=Te(),[j,O]=d.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),$=e[j],E=d.useMemo(()=>ph($),[$]),[D,L]=d.useState(!1),[W,Z]=d.useState(0),[A,_]=d.useState(0),[U,ne]=d.useState(.9),[V,q]=d.useState(null),[C,F]=d.useState(null),I=d.useRef(null),[P,N]=d.useState(g),[z,B]=d.useState(b),[G,Y]=d.useState(x),[X,ie]=d.useState(k),[le,te]=d.useState([]),[H,K]=d.useState(S>0?S*60:null),oe=d.useRef(null),[re,he]=d.useState(()=>Ni()),Q=d.useRef(null),de=d.useRef(null),me=d.useRef(null),xe=d.useRef(null);d.useEffect(()=>{if(P&&e.length>0){const fe=e.map((be,_e)=>_e);for(let be=fe.length-1;be>0;be--){const _e=Math.floor(Math.random()*(be+1));[fe[be],fe[_e]]=[fe[_e],fe[be]]}te(fe)}},[P,e.length]),d.useEffect(()=>(oe.current&&(window.clearInterval(oe.current),oe.current=null),S>0&&D&&(K(S*60),oe.current=window.setInterval(()=>{K(fe=>!fe||fe<=1?(oe.current&&window.clearInterval(oe.current),oe.current=null,R==null||R(),null):fe-1)},1e3)),()=>{oe.current&&window.clearInterval(oe.current)}),[S,D]);const ce=d.useCallback(fe=>{const be=Math.min(Math.max(0,fe),Math.max(0,e.length-1));O(be),i==null||i(be)},[e.length,i]),ye=d.useCallback(()=>{if(P&&le.length>0){const be=le.indexOf(j)+1;return be<le.length?le[be]:z==="all"?le[0]:-1}return j<e.length-1?j+1:z==="all"?0:-1},[j,e.length,P,le,z]),Se=d.useCallback(()=>{if(P&&le.length>0){const fe=le.indexOf(j);return fe>0?le[fe-1]:z==="all"?le[le.length-1]:-1}return j>0?j-1:z==="all"?e.length-1:-1},[j,e.length,P,le,z]),ae=d.useCallback(()=>{const fe=ye();fe>=0&&ce(fe)},[ye,ce]),ue=d.useCallback(async()=>{var fe,be;await Bt(),he(!0),(E==null?void 0:E.kind)==="youtube"?(fe=Q.current)==null||fe.playVideo():(be=de.current)==null||be.play(),L(!0),o==null||o(!0)},[E,o]),Ie=d.useCallback(()=>{var fe,be;(E==null?void 0:E.kind)==="youtube"?(fe=Q.current)==null||fe.pauseVideo():(be=de.current)==null||be.pause(),L(!1),o==null||o(!1)},[E,o]),ze=d.useCallback(()=>D?Ie():ue(),[D,ue,Ie]),$e=d.useCallback(fe=>{var pe;const be=($==null?void 0:$.startOffset)??0,_e=fe+be;(E==null?void 0:E.kind)==="youtube"?(pe=Q.current)==null||pe.seekTo(_e,!0):de.current&&(de.current.currentTime=_e);const vt=Math.max(0,fe);_(vt),l==null||l(vt)},[E,l]),Ye=d.useCallback(()=>{if(A>3){$e(0);return}const fe=Se();fe>=0&&ce(fe)},[Se,ce,A,$e]),je=d.useCallback(fe=>{var be,_e;ne(fe),q(null),(E==null?void 0:E.kind)==="youtube"?(_e=(be=Q.current)==null?void 0:be.setVolume)==null||_e.call(be,Math.round(fe*100)):de.current&&(de.current.volume=fe)},[E]),Ve=d.useCallback(()=>{V!==null?je(V):(q(U),je(0))},[U,V,je]),ht=d.useCallback(fe=>{var be,_e;Y(fe),de.current&&(de.current.playbackRate=fe),(E==null?void 0:E.kind)==="youtube"&&((_e=(be=Q.current)==null?void 0:be.setPlaybackRate)==null||_e.call(be,fe)),M==null||M(fe)},[E,M]),et=d.useCallback(()=>{const fe=["none","all","one"],be=fe[(fe.indexOf(z)+1)%fe.length];B(be),v==null||v(be)},[z,v]),Ze=d.useCallback(()=>{const fe=!P;N(fe),w==null||w(fe)},[P,w]),At=d.useCallback(fe=>{ie(fe)},[]);d.useImperativeHandle(c,()=>({play:ue,pause:Ie,toggle:ze,seekTo:$e,setVolume:je,setSpeed:ht,setRepeatMode:fe=>{B(fe),v==null||v(fe)},toggleShuffle:Ze,setABLoop:At,getUnderlyingPlayer:()=>(E==null?void 0:E.kind)==="youtube"?Q.current:(E==null?void 0:E.kind)==="hls"||(E==null?void 0:E.kind)==="audio"?de.current:null}),[ue,Ie,ze,$e,je,ht,Ze,At,E==null?void 0:E.kind]),d.useEffect(()=>{const fe=window.setInterval(()=>{let be=0,_e=0;(E==null?void 0:E.kind)==="youtube"&&Q.current?(be=Q.current.getCurrentTime()||0,_e=Q.current.getDuration()||0):de.current&&(be=de.current.currentTime||0,_e=de.current.duration||0);const vt=($==null?void 0:$.startOffset)??0,pe=Math.max(0,be-vt);_(pe),Z(_e),l==null||l(pe),X&&pe>=X.b&&$e(X.a)},250);return()=>window.clearInterval(fe)},[E==null?void 0:E.kind,l,X]),d.useEffect(()=>()=>{I.current&&(window.clearInterval(I.current),I.current=null)},[]),d.useEffect(()=>{if(me.current){try{me.current.destroy()}catch{}me.current=null}if(de.current&&(de.current.volume=U,de.current.crossOrigin=E!=null&&E.withCredentials?"use-credentials":"anonymous"),(E==null?void 0:E.kind)==="hls"&&go(E.url)){const fe=de.current;if(!fe)return;const be=()=>{fe.src=E.url,fe.load();const _e=($==null?void 0:$.startOffset)??0;try{_e&&!isNaN(_e)&&(fe.currentTime=_e)}catch{}n&&fe.play().catch(()=>{})};fe.canPlayType("application/vnd.apple.mpegurl")?be():(async()=>{var _e;try{const pe=(await import("hls.js")).default;if((_e=pe==null?void 0:pe.isSupported)!=null&&_e.call(pe)){const ve=new pe({xhrSetup:Ue=>{if(E!=null&&E.withCredentials&&(Ue.withCredentials=!0),E!=null&&E.headers)for(const[Ee,Ce]of Object.entries(E.headers))try{Ue.setRequestHeader(Ee,Ce)}catch{}}});me.current=ve,ve.loadSource(E.url),ve.attachMedia(fe),ve.on(pe.Events.MANIFEST_PARSED,()=>{n&&fe.play().catch(()=>{})})}else be()}catch(vt){dh.debug("HLS.js setup failed, falling back to native playback",vt),be()}})()}else if((E==null?void 0:E.kind)==="audio"&&E.url&&de.current){const fe=de.current;fe.src=E.url,fe.load();const be=($==null?void 0:$.startOffset)??0;try{be&&!isNaN(be)&&(fe.currentTime=be)}catch{}n&&fe.play().catch(()=>{})}I.current&&(window.clearInterval(I.current),I.current=null),F(null),_(0),Z(0),n&&(E==null?void 0:E.kind)==="youtube"&&a>0?(F(a),I.current=window.setInterval(()=>{F(fe=>{var be;if(!fe)return null;if(fe<=1){I.current&&(window.clearInterval(I.current),I.current=null);try{(be=Q.current)==null||be.playVideo()}catch{}return L(!0),o==null||o(!0),null}return fe-1})},1e3)):L(!!n)},[E==null?void 0:E.url,E==null?void 0:E.kind,E==null?void 0:E.withCredentials,JSON.stringify(E==null?void 0:E.headers),n,U]);const pt=d.useCallback(()=>{if(z==="one"){$e(0),ue();return}const fe=ye();fe>=0?ce(fe):(L(!1),o==null||o(!1),$e(0),y==null||y())},[z,ye,ce,o,$e,y,ue]);d.useEffect(()=>{if(!m)return;const fe=be=>{const _e=be.target;if(!(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable))switch(be.key){case" ":be.preventDefault(),ze();break;case"ArrowRight":be.preventDefault(),$e(Math.min(A+5,W));break;case"ArrowLeft":be.preventDefault(),$e(Math.max(0,A-5));break;case"ArrowUp":be.preventDefault(),je(Math.min(1,U+.05));break;case"ArrowDown":be.preventDefault(),je(Math.max(0,U-.05));break;case"m":case"M":Ve();break;case"n":case"N":ae();break;case"p":case"P":Ye();break;case"r":case"R":et();break;case"s":case"S":Ze();break}};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[m,ze,$e,A,W,je,U,Ve,ae,Ye,et,Ze]);const Et=(E==null?void 0:E.kind)==="youtube"||u==="full"||u==="nobuttons",ct=h>0?e.slice(j+1,j+1+h):[];return r.jsxs("div",{ref:xe,className:"gp-player",style:{display:"grid",gap:12},tabIndex:-1,children:[n&&!re&&r.jsx("div",{className:"gp-audio-activation",onClick:()=>{he(!0),ue()},style:{position:"fixed",inset:0,zIndex:200,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",cursor:"pointer"},children:r.jsx("span",{style:{color:"#fff",fontSize:24},children:"Click to activate audio"})}),Et&&r.jsxs("div",{className:"gp-stage",style:{width:"100%",height:s,background:(E==null?void 0:E.kind)==="youtube"?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(E==null?void 0:E.kind)==="youtube"&&r.jsx(Ma,{videoId:E.videoId??vh(E.url),onReady:fe=>{Q.current=fe.target,je(U);const be=($==null?void 0:$.startOffset)??0;try{be&&fe.target.seekTo(be,!0)}catch{}if(u==="nobuttons"){try{fe.target.playVideo()}catch{}L(!0)}},onEnd:pt,opts:{width:"100%",height:"100%",playerVars:{autoplay:n||u==="nobuttons"?1:0,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,loop:f?1:0}},style:{width:"100%",height:"100%"}}),C!==null&&r.jsx("div",{style:{position:"absolute",inset:0,zIndex:120,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-70, rgba(0, 0, 0, 0.7))"},children:r.jsx("span",{style:{color:"#fff",fontSize:72,fontWeight:"bold"},children:C})}),u==="nobuttons"&&r.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"auto",zIndex:100,cursor:"default"}}),((E==null?void 0:E.kind)==="audio"||(E==null?void 0:E.kind)==="hls")&&r.jsxs(r.Fragment,{children:[u==="full"&&r.jsx("div",{style:{textAlign:"center",color:"var(--text-primary, #0f172a)"},children:$!=null&&$.coverUrl?r.jsx("img",{alt:"cover",src:$.coverUrl,style:{height:s-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[$==null?void 0:$.artist," — ",$==null?void 0:$.title]}),r.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-secondary, #64748b)"},children:(E==null?void 0:E.label)??`${(E==null?void 0:E.codec)??""} ${(E==null?void 0:E.quality)??""}`.trim()})]})}),r.jsx("audio",{ref:de,onEnded:pt,onLoadedMetadata:()=>{const fe=de.current;fe&&Z(fe.duration||0)},crossOrigin:E!=null&&E.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]})]}),(u==="minimal"||u==="compact")&&r.jsx("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:r.jsxs("div",{children:[r.jsx("div",{style:{fontWeight:600},children:($==null?void 0:$.title)??""}),r.jsx("div",{style:{color:"var(--text-secondary, #64748b)",fontSize:13},children:($==null?void 0:$.artist)??""})]})}),u==="full"&&r.jsxs(r.Fragment,{children:[r.jsx(yo,{currentTime:A,duration:W}),r.jsx(mh,{isPlaying:D,index:j,count:e.length,currentTime:A,duration:W,volume:U,onPrev:Ye,onNext:ae,onToggle:ze,onSeek:$e,onVolume:je}),r.jsx(xh,{shuffleOn:P,repeatMode:z,speed:G,abLoop:X,currentTime:A,sleepRemaining:H,onToggleShuffle:Ze,onCycleRepeat:et,onSpeedChange:ht,onSetABLoop:At,onMuteToggle:Ve,isMuted:V!==null})]}),u==="progressOnly"&&r.jsx("div",{style:p==="fixedBottom"?{position:"fixed",left:0,right:0,bottom:0,padding:"8px 12px",background:"var(--nice-overlay-90, rgba(15, 23, 42, 0.9))",backdropFilter:"blur(2px)",zIndex:1e3}:{},children:r.jsx(gh,{currentTime:A,duration:W,onSeek:$e})}),(u==="minimal"||u==="compact")&&r.jsx(yh,{isPlaying:D,canPrev:j>0,canNext:j<e.length-1,onPrev:Ye,onNext:ae,onToggle:ze}),u==="compact"&&ct.length>0&&r.jsx(bh,{items:ct,onSelect:fe=>ce(j+1+fe)}),u==="nobuttons"&&r.jsx(r.Fragment,{}),u==="full"&&e.length>0&&r.jsx("div",{className:"gp-list",style:{display:"grid",gap:4},children:e.map((fe,be)=>r.jsxs("button",{onClick:()=>ce(be),style:{textAlign:"left",border:"1px solid var(--border-color)",borderRadius:8,padding:"8px 10px",background:be===j?"color-mix(in srgb, var(--color-primary) 14%, transparent)":"var(--bg-secondary)",color:"var(--text-primary)",cursor:"pointer"},title:fe.sources.map(_e=>_e.kind).join(", "),children:[r.jsx("div",{style:{fontWeight:600},children:fe.title}),r.jsx("div",{style:{color:"var(--text-secondary)",fontSize:12},children:fe.artist})]},fe.id))})]})},bt={border:"1px solid var(--border-color)",borderRadius:8,padding:"6px 10px",background:"var(--bg-secondary)",color:"var(--text-primary)",cursor:"pointer"},yo=({currentTime:e,duration:t})=>r.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[r.jsx("div",{}),r.jsxs("div",{style:{fontSize:12,color:"var(--text-secondary, #64748b)"},children:[Pr(e)," / ",Pr(t)]})]}),mh=({isPlaying:e,index:t,count:n,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek:u,onVolume:h})=>{const{t:p}=Te();return r.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("button",{onClick:o,disabled:t<=0,title:p("player.previousTrack"),"aria-label":p("player.previousTrack"),style:bt,children:r.jsx(se.NtdSkipBack,{size:16})}),r.jsx("button",{onClick:c,title:p(e?"player.pause":"player.play"),"aria-label":p(e?"player.pause":"player.play"),style:bt,children:e?r.jsx(se.NtdPause,{size:16}):r.jsx(se.NtdPlay,{size:16})}),r.jsx("button",{onClick:l,disabled:t>=n-1,title:p("player.nextTrack"),"aria-label":p("player.nextTrack"),style:bt,children:r.jsx(se.NtdSkipForward,{size:16})})]}),r.jsx("input",{type:"range",min:0,max:Math.max(1,s),step:.1,value:a,onChange:f=>u(parseFloat(f.target.value)),"aria-label":"Seek position"}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx(se.NtdVolume,{size:16}),r.jsx("input",{type:"range",min:0,max:1,step:.01,value:i,onChange:f=>h(parseFloat(f.target.value)),"aria-label":"Volume"})]})]})},gh=({currentTime:e,duration:t,onSeek:n})=>r.jsxs(r.Fragment,{children:[r.jsx(yo,{currentTime:e,duration:t}),r.jsx("input",{type:"range",min:0,max:Math.max(1,t),step:.1,value:e,onChange:a=>n(parseFloat(a.target.value)),"aria-label":"Seek position"})]}),yh=({isPlaying:e,canPrev:t,canNext:n,onPrev:a,onNext:s,onToggle:i})=>{const{t:o}=Te();return r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[r.jsx("button",{onClick:a,disabled:!t,title:o("player.previousTrack"),"aria-label":o("player.previousTrack"),style:bt,children:r.jsx(se.NtdSkipBack,{size:16})}),r.jsx("button",{onClick:i,title:o(e?"player.pause":"player.play"),"aria-label":o(e?"player.pause":"player.play"),style:bt,children:e?r.jsx(se.NtdPause,{size:16}):r.jsx(se.NtdPlay,{size:16})}),r.jsx("button",{onClick:s,disabled:!n,title:o("player.nextTrack"),"aria-label":o("player.nextTrack"),style:bt,children:r.jsx(se.NtdSkipForward,{size:16})})]})},bh=({items:e,onSelect:t})=>{const{t:n}=Te();return r.jsxs("div",{style:{border:"1px solid var(--border-color)",borderRadius:8,padding:10,background:"var(--bg-secondary)",color:"var(--text-primary)"},children:[r.jsx("div",{style:{fontWeight:600,marginBottom:6},children:n("player.upNext")}),r.jsx("ol",{style:{margin:0,paddingLeft:18},children:e.map((a,s)=>r.jsx("li",{style:{marginBottom:4},children:r.jsxs("button",{type:"button",onClick:()=>t(s),style:{border:"none",padding:0,background:"transparent",cursor:"pointer",color:"var(--text-primary, #0f172a)"},title:a.sources.map(i=>i.kind).join(", "),children:[r.jsx("span",{style:{fontWeight:600},children:a.artist})," — ",a.title]})},a.id))})]})},xh=({shuffleOn:e,repeatMode:t,speed:n,abLoop:a,currentTime:s,sleepRemaining:i,onToggleShuffle:o,onCycleRepeat:l,onSpeedChange:c,onSetABLoop:u,onMuteToggle:h,isMuted:p})=>{const{t:f}=Te(),y={none:"Off",all:"All",one:"One"},m=t==="one"?r.jsxs("span",{style:{position:"relative",display:"inline-flex"},children:[r.jsx(se.NtdRepeat,{size:16}),r.jsx("span",{style:{position:"absolute",right:-3,bottom:-3,fontSize:8,fontWeight:700},children:"1"})]}):t==="all"?r.jsx(se.NtdRepeat,{size:16}):r.jsx(se.NtdArrowRight,{size:16});return r.jsxs("div",{className:"gp-pro-controls",style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap",fontSize:13},children:[r.jsx("button",{onClick:o,title:f("player.shuffle","Shuffle"),"aria-label":f("player.shuffle","Shuffle"),style:{...bt,opacity:e?1:.4,fontWeight:e?700:400},children:r.jsx(se.NtdShuffle,{size:16})}),r.jsx("button",{onClick:l,title:`${f("player.repeat","Repeat")}: ${y[t]}`,"aria-label":`${f("player.repeat","Repeat")}: ${y[t]}`,style:{...bt,opacity:t==="none"?.4:1},children:m}),r.jsx("select",{value:n,onChange:g=>c(parseFloat(g.target.value)),title:f("player.speed","Speed"),"aria-label":f("player.speed","Speed"),style:{...bt,minWidth:56,fontSize:12},children:fh.map(g=>r.jsxs("option",{value:g,children:[g,"x"]},g))}),r.jsx("button",{onClick:h,title:f("player.mute","Mute"),"aria-label":f("player.mute","Mute"),style:{...bt,opacity:p?1:.6},children:p?r.jsx(se.NtdVolumeMute,{size:16}):r.jsx(se.NtdVolume,{size:16})}),a?r.jsxs("span",{style:{display:"flex",gap:4,alignItems:"center"},children:[r.jsxs("span",{style:{fontSize:11,color:"var(--text-secondary, #64748b)"},children:["A: ",Pr(a.a)," — B: ",Pr(a.b)]}),r.jsx("button",{onClick:()=>u(null),title:f("player.clearLoop","Clear loop"),style:{...bt,fontSize:11,padding:"2px 6px"},children:r.jsx(se.NtdClose,{size:12})})]}):r.jsx("button",{onClick:()=>u({a:s,b:s+10}),title:f("player.abLoop","A-B Loop"),"aria-label":f("player.abLoop","Set A-B Loop"),style:{...bt,opacity:.4},children:"A-B"}),i!==null&&i>0&&r.jsxs("span",{style:{marginLeft:"auto",fontSize:11,color:"var(--text-secondary, #64748b)",display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(se.NtdMoon,{size:12})," ",Math.floor(i/60),":",(i%60).toString().padStart(2,"0")]})]})};function vh(e){if(!e)return;const t=e.match(/youtu\.be\/([A-Za-z0-9_-]{6,})/);if(t)return t[1];const n=e.match(/[?&]v=([A-Za-z0-9_-]{6,})/);if(n)return n[1]}function bo(e){const t={};if(!e)return t;const n=e.split(",");for(const a of n){const s=a.trim();s.startsWith("v=")?t.youtubeId=s.substring(2):s.startsWith("co=")?t.coverImage=s.substring(3):s.startsWith("bg=")&&(t.backgroundImage=s.substring(3))}return t}function Sh(e,t="/api/karaoke/cover"){var a,s;const n=((a=e.coverImage)==null?void 0:a.startsWith("http://"))||((s=e.coverImage)==null?void 0:s.startsWith("https://"));return e.coverImage&&n?e.coverImage:e.youtubeId?`https://img.youtube.com/vi/${e.youtubeId}/hqdefault.jpg`:e.coverImage?`${t}?filePath=${encodeURIComponent(e.coverImage)}`:"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='320' height='180'%3E%3Crect width='320' height='180' fill='%23333'/%3E%3Ctext x='160' y='95' text-anchor='middle' fill='%23999' font-size='16'%3ENo Cover%3C/text%3E%3C/svg%3E"}function kh(e,t="/backgrounds"){return e.backgroundImage?`${t}/${e.backgroundImage}`:""}function xo(e,t,n=.01){let a=0;for(let o=0;o<e.length;o++)a+=e[o]*e[o];if(a=Math.sqrt(a/e.length),a<n)return 0;let s=-1,i=0;for(let o=20;o<e.length/2;o++){let l=0;for(let c=0;c<e.length/2;c++)l+=e[c]*e[c+o];l/=e.length/2,l>i&&(i=l,s=o)}return s>0?t/s:0}function Za(e,t){const n=[];return e.forEach((a,s)=>{a.forEach((i,o)=>{n.push({startTime:i.startTime+t,duration:i.duration,pitch:i.pitch,isGold:i.isGold,line:s,idx:o})})}),n}function vo(e,t,n){const a=[];return e.forEach(s=>{var c;const[i,o]=s.noteKey.split("-").map(Number),l=(c=t[i])==null?void 0:c[o];l&&s.segments.forEach(u=>{a.push({start:u.visualStart-n,end:u.visualEnd-n,pitch:l.pitch,frac:u.frac,isGold:l.isGold,noteStart:l.startTime,noteEnd:l.startTime+l.duration})})}),a}function So(e,t=120){let n=e;if(e.length>t){const a=e.length/t,s=[];for(let i=0;i<t;i++)s.push(e[Math.floor(i*a)]);n=s}return n.map(a=>({t:Math.round(a.t*1e3)/1e3,hz:Math.round(a.hz)}))}function ko(e,t,n){const s=Date.parse(e)-n;return Math.max(0,Math.round(t-s))}const wo={crepe:"var(--nice-accent, #a78bfa)",librosa:"var(--nice-success-light, #34d399)",pitchy:"var(--nice-primary-light, #60a5fa)",autocorr:"var(--nice-text-secondary, #555555)"};function wh(e){return e==="autocorr"?"Ultrastar":e.charAt(0).toUpperCase()+e.slice(1)}function jh(e){return wo[e]??"var(--nice-text-secondary, #555555)"}function Ch(e){const t=wo[e]??"var(--nice-text-secondary, #555555)";return`var(--algo-${e}, ${t})`}function jo(e,t){const n=!(t!=null&&t.includes("no-music")),a=t==null?void 0:t.includes("instrumental"),s=[];if(n){if(e.videoPath){let i=e.videoPath;if(i.startsWith("v=")){const o=bo(i);o.youtubeId&&(i=`https://www.youtube.com/watch?v=${o.youtubeId}`)}/youtu(\.be|be\.com)/i.test(i)?s.push({kind:"youtube",url:i}):/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(e.videoPath)&&s.push({kind:"audio",url:e.videoPath})}if(s.length===0){const i=a?e.instrumentalPath:e.audioPath;i&&/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(i)&&s.push({kind:"audio",url:i})}s.length===0&&e.youtubeId&&s.push({kind:"youtube",url:`https://www.youtube.com/watch?v=${e.youtubeId}`})}return{id:String(e.id??e.title??"song"),title:e.title??"—",artist:e.artist??"—",coverUrl:e.coverPath??void 0,sources:s}}function Mh(e){const t=e.videoPath??e.video??void 0;return{id:e.id,title:e.title??"",artist:e.artist??"",year:e.year,genre:e.genre,language:e.language,filePath:e.filePath,coverPath:e.coverPath,audioPath:e.audioPath??e.audio??void 0,videoPath:t,format:0,notes:e.notes??[],gap:e.gap,bpm:e.bpm,videoGap:e.videoGap,start:e.start,end:e.end,youtubeId:e.youtubeId,instrumentalPath:e.instrumentalPath,isVerified:e.isVerified,coverImage:e.coverImage,backgroundImage:e.backgroundImage}}var Xa=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(Xa||{});function Co(e,t="song.txt"){const n=e.split(/\r?\n/),a={},s=[];for(const o of n){const l=o.replace(/\uFEFF/g,"");if(l.trim()){if(l.startsWith("#")){const c=l.indexOf(":");c>0&&(a[l.slice(1,c).trim().toUpperCase()]=l.slice(c+1).trim())}else if(/^[:*\-FG]/.test(l))s.push({noteLine:l});else if(l.trim()==="E")break}}const i=o=>{if(!o)return;const l=parseFloat(o.replace(",","."));return Number.isFinite(l)?l:void 0};return{title:a.TITLE||t.replace(/\.txt$/i,""),artist:a.ARTIST||"",format:Xa.Ultrastar,bpm:i(a.BPM),gap:i(a.GAP),genre:a.GENRE||void 0,language:a.LANGUAGE||void 0,year:a.YEAR||void 0,audioPath:a.MP3||void 0,videoPath:a.VIDEO||a.MP3||void 0,notes:s}}const Rh=e=>window.btoa(unescape(encodeURIComponent(e))),Mo=({onSongUpload:e,parseSong:t,onError:n,accept:a=".txt",maxFileSize:s=5*1024*1024,t:i})=>{const{t:o}=Te(),l=i??o,c=h=>{const p=new FileReader;p.onload=async f=>{var m;if(!((m=f.target)!=null&&m.result))return;const y=f.target.result;try{const g=t?await t({fileName:h.name,data:Rh(y)}):Co(y,h.name);e(g)}catch(g){n==null||n(g)}},p.readAsText(h,"UTF-8")},u=h=>/\.txt$/i.test(h.name)?h.size===0?l("karaokeUploader.empty","The file is empty."):null:l("karaokeUploader.notTxt","Please choose an UltraStar .txt file.");return r.jsx("div",{className:"nice-karaoke-uploader",children:r.jsx(we.NiceUpload,{accept:a,maxFileSize:s,validateFile:u,multiple:!1,text:l("karaokeUploader.dropPrompt","Click or drag & drop an UltraStar file (.txt)"),onFilesSelected:h=>{const p=h[0];p&&c(p)}})})};function Nh(e,t,n,a,s){const o=a*.45;e.beginPath();for(let l=0;l<10;l++){const c=l%2===0?a:o,u=Math.PI/5*l-Math.PI/2,h=t+Math.cos(u)*c,p=n+Math.sin(u)*c;l===0?e.moveTo(h,p):e.lineTo(h,p)}e.closePath(),e.fillStyle=s,e.fill()}const Wt=60,Gs=4,Ws=["A","B","X","Y","LB","RB","LT","RT"],Ro=({lanes:e,events:t,currentTime:n,activeLanes:a,difficulty:s,feedbackQueue:i,isPlaying:o,height:l=300})=>{const c=e.length,u=d.useRef(null),h=d.useRef([]);return d.useEffect(()=>{h.current=i},[i]),d.useEffect(()=>{var v,w,M,S;const p=u.current;if(!p)return;const f=p.getContext("2d");if(!f)return;const y=window.devicePixelRatio||1,m=p.clientWidth,g=p.clientHeight;if(p.width=m*y,p.height=g*y,f.scale(y,y),f.clearRect(0,0,m,g),c===0)return;const b=m/c;for(let R=0;R<c;R++){const T=R*b;f.fillStyle=R%2===0?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",f.fillRect(T,0,b,g),R>0&&(f.strokeStyle="rgba(255,255,255,0.1)",f.lineWidth=1,f.beginPath(),f.moveTo(T,0),f.lineTo(T,g),f.stroke())}const x=g-Wt-10;f.strokeStyle="rgba(255,255,255,0.4)",f.lineWidth=2,f.setLineDash([8,4]),f.beginPath(),f.moveTo(0,x),f.lineTo(m,x),f.stroke(),f.setLineDash([]);const k=(g-Wt-20)/Gs;for(const R of t){const T=R.note.startTime,j=T+R.note.duration,O=T-n;if(O>Gs||j<n-.5)continue;const $=R.lane,E=$*b+4,D=b-8,L=x-O*k,W=R.note.duration*k,Z=n>=T-.15&&n<=j+.15,A=n>j+.15,_=((v=e[$])==null?void 0:v.color)??"#888";A?f.fillStyle="rgba(100,100,100,0.3)":Z?(f.fillStyle=_,f.shadowColor=_,f.shadowBlur=12):f.fillStyle=_+"99";const U=Math.max(W,8),ne=6;f.beginPath(),f.moveTo(E+ne,L),f.lineTo(E+D-ne,L),f.quadraticCurveTo(E+D,L,E+D,L+ne),f.lineTo(E+D,L+U-ne),f.quadraticCurveTo(E+D,L+U,E+D-ne,L+U),f.lineTo(E+ne,L+U),f.quadraticCurveTo(E,L+U,E,L+U-ne),f.lineTo(E,L+ne),f.quadraticCurveTo(E,L,E+ne,L),f.fill(),f.shadowBlur=0,R.note.isGold&&Nh(f,E+D/2,L+U/2,Math.min(7,D/4),"#fbbf24")}for(let R=0;R<c;R++){const T=R*b,j=g-Wt,O=a[R],$=((w=e[R])==null?void 0:w.color)??"#888";f.fillStyle=O?$:"rgba(30,30,30,0.9)",f.fillRect(T+2,j+2,b-4,Wt-4),f.strokeStyle=O?"#fff":$,f.lineWidth=O?3:1,f.strokeRect(T+2,j+2,b-4,Wt-4),f.fillStyle=O?"#000":"#fff",f.font=`bold ${Math.min(24,b*.3)}px monospace`,f.textAlign="center",f.textBaseline="middle",f.fillText(((M=e[R])==null?void 0:M.label)??"",T+b/2,j+Wt/2);const E=((S=e[R])==null?void 0:S.gamepadButton)??-1;E>=0&&E<Ws.length&&(f.fillStyle=O?"rgba(0,0,0,0.6)":"rgba(255,255,255,0.4)",f.font="10px sans-serif",f.fillText(Ws[E],T+b/2,j+Wt-8))}for(const R of h.current){const T=n-R.time;if(T<0||T>.8)continue;const j=Math.max(0,1-T/.8),O=R.lane*b;f.save(),f.globalAlpha=j,f.font="bold 20px sans-serif",f.textAlign="center",f.textBaseline="bottom",f.fillStyle=R.type==="perfect"?"#10b981":R.type==="good"?"#f59e0b":"#ef4444";const $=R.type==="perfect"?"PERFECT":R.type==="good"?"GOOD":"MISS";f.fillText($,O+b/2,x-10-T*40),f.restore()}},[n,e,t,a,c,o]),!o||c===0?null:r.jsxs("div",{className:"nice-pad-karaoke-overlay",style:{position:"absolute",top:0,left:0,right:0,height:l,zIndex:35,pointerEvents:"none"},children:[r.jsx("canvas",{ref:u,role:"img","aria-label":"Pad karaoke note highway — hit notes in time with the music",style:{width:"100%",height:"100%",display:"block"}}),r.jsxs("div",{style:{position:"absolute",top:8,right:12,background:"var(--nice-overlay-60, rgba(0,0,0,0.6))",color:"#fff",padding:"4px 12px",borderRadius:8,fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:1,display:"flex",alignItems:"center",gap:6},children:[r.jsx(se.NtdGamepad,{size:14})," PAD — ",s]})]})},An=["var(--player-color-1, #ef4444)","var(--player-color-2, #f59e0b)","var(--player-color-3, #10b981)","var(--player-color-4, #3b82f6)","var(--player-color-5, #8b5cf6)","var(--player-color-6, #ec4899)"],No={easy:{keys:["f","j"],buttons:[0,1],labels:["F","J"]},normal:{keys:["d","f","j","k"],buttons:[3,2,0,1],labels:["D","F","J","K"]},hard:{keys:["s","d","f","j","k","l"],buttons:[4,3,2,0,1,5],labels:["S","D","F","J","K","L"]}};function ha(e){return 440*Math.pow(2,(e-69)/12)}function To(e,t){const n=No[t],a=n.keys.length,s=[];for(const u of e)for(const h of u)s.includes(h.pitch)||s.push(h.pitch);if(s.sort((u,h)=>u-h),s.length===0)return n.keys.map((u,h)=>({index:h,key:u,gamepadButton:n.buttons[h],label:n.labels[h],minPitch:-999,maxPitch:999,color:An[h%An.length]}));const i=s[0],l=s[s.length-1]-i+1,c=[];for(let u=0;u<a;u++){const h=i+Math.floor(l*u/a),p=i+Math.floor(l*(u+1)/a)-1;c.push({index:u,key:n.keys[u],gamepadButton:n.buttons[u],label:n.labels[u],minPitch:u===0?-999:h,maxPitch:u===a-1?999:p,color:An[u%An.length]})}return c}function $o(e,t){for(const s of t)if(e>=s.minPitch&&e<=s.maxPitch)return s.index;let n=0,a=1/0;for(const s of t){const i=(s.minPitch+s.maxPitch)/2,o=Math.abs(e-i);o<a&&(a=o,n=s.index)}return n}function Po(e,t,n){const a=[];for(let s=0;s<e.length;s++)for(let i=0;i<e[s].length;i++){const o={...e[s][i]};o.startTime+=n,a.push({note:o,lane:$o(o.pitch,t),lineIndex:s,noteIndex:i})}return a.sort((s,i)=>s.note.startTime-i.note.startTime),a}class Ao{constructor(t){this.lanes=[],this.events=[],this.raf=null,this.keysDown=new Set,this.gamepadButtonsDown=new Set,this.running=!1,this.getCurrentTime=()=>0,this.lastFeedbackTime=0,this.lastActiveNote=null,this.preWindow=.15,this.postWindow=.15,this.loop=()=>{var c,u,h,p,f,y,m,g;if(!this.running)return;const s=this.getCurrentTime();this.pollGamepad();const i=this.getActiveLanes();(u=(c=this.config).onLaneActive)==null||u.call(c,i);const o=this.findActiveNote(s);if(o!==this.lastActiveNote&&(this.lastActiveNote=o,(p=(h=this.config).onCurrentNote)==null||p.call(h,o)),i.some(Boolean)&&o){const b=o.lane,x=i.indexOf(!0);if(i[b]){const k=ha(o.note.pitch);this.config.onPitch(k),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(y=(f=this.config).onHitFeedback)==null||y.call(f,{type:"perfect",lane:b,time:s}))}else if(x>=0){const v=Math.abs(x-b)*3,w=ha(o.note.pitch+v);this.config.onPitch(w),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(g=(m=this.config).onHitFeedback)==null||g.call(m,{type:"miss",lane:x,time:s}))}}this.raf=requestAnimationFrame(this.loop)},this.config=t;const n=qn(t.noteLines,t.bpm),a=(t.gap??0)/1e3;switch(this.lanes=To(n,t.difficulty),this.events=Po(n,this.lanes,a),t.difficulty){case"easy":this.preWindow=.25,this.postWindow=.25;break;case"normal":this.preWindow=.15,this.postWindow=.15;break;case"hard":this.preWindow=.08,this.postWindow=.08;break}}getLanes(){return this.lanes}getEvents(){return this.events}start(t){this.running||(this.running=!0,this.getCurrentTime=t,this.handleKeyDown=this.handleKeyDown.bind(this),this.handleKeyUp=this.handleKeyUp.bind(this),window.addEventListener("keydown",this.handleKeyDown),window.addEventListener("keyup",this.handleKeyUp),this.loop())}stop(){this.running=!1,this.raf&&(cancelAnimationFrame(this.raf),this.raf=null),window.removeEventListener("keydown",this.handleKeyDown),window.removeEventListener("keyup",this.handleKeyUp),this.keysDown.clear(),this.gamepadButtonsDown.clear()}handleKeyDown(t){var a;const n=(a=t.target)==null?void 0:a.tagName;n&&["INPUT","TEXTAREA","SELECT"].includes(n)||this.keysDown.add(t.key.toLowerCase())}handleKeyUp(t){this.keysDown.delete(t.key.toLowerCase())}pollGamepad(){var a;const t=navigator.getGamepads?Array.from(navigator.getGamepads()).filter(Boolean):[];if(!t.length)return;const n=t[0];if(n){this.gamepadButtonsDown.clear();for(let s=0;s<n.buttons.length;s++)(a=n.buttons[s])!=null&&a.pressed&&this.gamepadButtonsDown.add(s)}}getActiveLanes(){const t=new Array(this.lanes.length).fill(!1);for(const n of this.lanes)(this.keysDown.has(n.key)||this.gamepadButtonsDown.has(n.gamepadButton))&&(t[n.index]=!0);return t}findActiveNote(t){for(const n of this.events){const a=n.note.startTime-this.preWindow,s=n.note.startTime+n.note.duration+this.postWindow;if(t>=a&&t<=s)return n}return null}}const mt=it.scoped("BaseStreamClient");function Us(e,t,n){if(t===n)return e.slice();const a=Math.round(e.length*n/t),s=new Float32Array(a),i=e.length/a;for(let o=0;o<a;o++){const l=o*i,c=Math.floor(l),u=Math.min(e.length-1,c+1),h=l-c;s[o]=e[c]*(1-h)+e[u]*h}return s}function Th(e){const t=new Int16Array(e.length);for(let n=0;n<e.length;n++){const a=Math.max(-1,Math.min(1,e[n]));t[n]=a<0?Math.round(a*32768):Math.round(a*32767)}return t}const xn=16e3,$h="/scripts/pitch-worklet.js";class Eo{constructor(t){this.sendQueue=[],this.maxQueue=20,this.reconnectAttempts=0,this.maxReconnectAttempts=3,this.buffer=new Float32Array(0),this.externalStream=!1,this.usingWorklet=!1,this.closed=!1,this.started=!1,this.chunksSent=0,this.chunksDropped=0,this.responsesReceived=0,this.lastStatusLog=0,this.opts=t}onMaxReconnect(){var t,n;try{(n=(t=this.opts).onMaxReconnect)==null||n.call(t)}catch{}this.stopAudioNodes()}get useWorklet(){return!0}get workletPath(){return $h}ts(){return new Date().toISOString().slice(11,23)}connectWs(){this.ws&&this.ws.readyState!==WebSocket.CLOSING&&this.ws.readyState!==WebSocket.CLOSED||(mt.info(`[${this.ts()}] connecting to ${this.opts.wsUrl}`),this.ws=new WebSocket(this.opts.wsUrl),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{var t,n,a,s,i,o;try{(n=(t=this.opts).onOpen)==null||n.call(t)}catch{}if(this.reconnectAttempts=0,this.chunksSent=0,this.chunksDropped=0,this.responsesReceived=0,mt.info(`[${this.ts()}] ws OPEN | worklet=${this.usingWorklet}`),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.sendQueue.length){const l=this.sendQueue.length;try{for(const c of this.sendQueue)try{this.ws.send(c),this.chunksSent++,(s=(a=this.opts).onSend)==null||s.call(a,c.byteLength)}catch(u){(o=(i=this.opts).onError)==null||o.call(i,u);break}}finally{this.sendQueue=[]}mt.info(`[${this.ts()}] flushed ${l} queued chunks`)}},this.ws.onclose=t=>{var n,a;try{(a=(n=this.opts).onClose)==null||a.call(n,t)}catch{}if(mt.info(`[${this.ts()}] ws CLOSE code=${t.code} clean=${t.wasClean} | sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived}`),this.sendQueue=[],this.ws=void 0,!this.closed&&this.started)if(this.reconnectAttempts++,this.reconnectAttempts<=this.maxReconnectAttempts){const s=Math.min(300*Math.pow(1.5,this.reconnectAttempts-1),5e3);mt.info(`[${this.ts()}] auto-reconnect #${this.reconnectAttempts} in ${s.toFixed(0)}ms`),this.reconnectTimer=setTimeout(()=>{this.closed||this.connectWs()},s)}else mt.warn(`[${this.ts()}] max reconnect attempts reached`),this.onMaxReconnect();else this.stopAudioNodes()},this.ws.onerror=t=>{var n,a;mt.warn(`[${this.ts()}] ws ERROR`,t);try{(a=(n=this.opts).onError)==null||a.call(n,t)}catch{}},this.ws.onmessage=t=>{var n,a;this.responsesReceived++;try{const s=typeof t.data=="string"?t.data:new TextDecoder().decode(t.data);this.handleWsMessage(s)}catch(s){(a=(n=this.opts).onError)==null||a.call(n,s)}})}handleAudioFrame(t){var f,y,m,g,b,x,k,v;const n=new Float32Array(this.buffer.length+t.length);n.set(this.buffer,0),n.set(t,this.buffer.length),this.buffer=n;const a=this.audioCtx.sampleRate,s=Math.round((this.opts.chunkMs??200)*xn/1e3),i=Math.floor(this.buffer.length*xn/a),o=Math.floor(i/s);if(o<=0)return;const l=o*s,c=Math.floor(l*a/xn),u=this.buffer.slice(0,c);this.buffer=this.buffer.slice(c);const h=Us(u,a,xn);let p=0;for(;p+s<=h.length;){const w=h.subarray(p,p+s),S=Th(w).buffer,R=this.ws;if(R&&R.readyState===WebSocket.OPEN)try{R.send(S),this.chunksSent++,(y=(f=this.opts).onSend)==null||y.call(f,S.byteLength)}catch(j){(g=(m=this.opts).onError)==null||g.call(m,j)}else R&&R.readyState===WebSocket.CONNECTING?this.sendQueue.length<this.maxQueue&&(this.sendQueue.push(S),(x=(b=this.opts).onSend)==null||x.call(b,0)):(this.chunksDropped++,(v=(k=this.opts).onSend)==null||v.call(k,0));const T=Date.now();T-this.lastStatusLog>5e3&&(this.lastStatusLog=T,mt.info(`[${this.ts()}] STATUS: sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived} ws=${(R==null?void 0:R.readyState)??"none"} worklet=${this.usingWorklet}`)),p+=s}if(p<h.length){const w=h.subarray(p),M=Us(w,xn,a),S=new Float32Array(M.length+this.buffer.length);S.set(M,0),S.set(this.buffer,M.length),this.buffer=S}}async setupAudioNodes(t){if(this.useWorklet)try{await this.audioCtx.audioWorklet.addModule(this.workletPath);const a=new AudioWorkletNode(this.audioCtx,"pitch-processor");a.port.onmessage=s=>{this.handleAudioFrame(s.data)},t.connect(a),a.connect(this.audioCtx.destination),this.workletNode=a,this.usingWorklet=!0,mt.info(`[${this.ts()}] using AudioWorklet (pitch-processor)`);return}catch(a){mt.warn(`[${this.ts()}] AudioWorklet unavailable, falling back to ScriptProcessorNode`,a)}const n=4096;this.proc=this.audioCtx.createScriptProcessor(n,1,1),t.connect(this.proc),this.proc.connect(this.audioCtx.destination),this.proc.onaudioprocess=a=>{this.handleAudioFrame(a.inputBuffer.getChannelData(0))},this.usingWorklet=!1,mt.info(`[${this.ts()}] using ScriptProcessorNode fallback`)}stopAudioNodes(){try{this.workletNode&&(this.workletNode.port.close(),this.workletNode.disconnect(),this.workletNode=void 0)}catch{}try{this.proc&&(this.proc.onaudioprocess=null,this.proc.disconnect(),this.proc=void 0)}catch{}}async start(){if(this.closed)throw new Error("client closed");if(this.started)return;this.started=!0,(!this.ws||this.ws.readyState===WebSocket.CLOSED)&&this.connectWs(),this.mediaStream||(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:!0})),this.audioCtx=new AudioContext;const t=this.audioCtx.createMediaStreamSource(this.mediaStream);await this.setupAudioNodes(t)}async startWithMediaStream(t){if(this.closed)throw new Error("client closed");if(this.started)return;this.started=!0,this.externalStream=!0,(!this.ws||this.ws.readyState===WebSocket.CLOSED)&&this.connectWs(),this.mediaStream=t,this.audioCtx=new AudioContext;const n=this.audioCtx.createMediaStreamSource(this.mediaStream);await this.setupAudioNodes(n)}stop(){var t,n;if(mt.info(`[${this.ts()}] stop() called | closed=${this.closed} started=${this.started} sent=${this.chunksSent} responses=${this.responsesReceived}`),this.closed=!0,this.started=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.stopAudioNodes(),this.audioCtx&&this.audioCtx.state!=="closed"&&this.audioCtx.close().catch(()=>{}),!this.externalStream)try{(t=this.mediaStream)==null||t.getTracks().forEach(a=>a.stop())}catch{}try{(n=this.ws)==null||n.close()}catch{}this.ws=void 0,this.sendQueue=[]}}const Ph=it.scoped("CrepeStreaming");class Ah extends Eo{constructor(t){super({...t,chunkMs:t.chunkMs??200}),this.crepeOpts=t}get tag(){return"CrepeStreamClient"}handleWsMessage(t){var a,s;const n=JSON.parse(t);(s=(a=this.crepeOpts).onMessage)==null||s.call(a,n)}onMaxReconnect(){var t,n;Ph.warn(`[${this.tag}] [${this.ts()}] triggering fallback`),this.stopAudioNodes();try{(n=(t=this.crepeOpts).onFallback)==null||n.call(t)}catch{}}}class Eh extends Eo{constructor(t){super({...t,chunkMs:t.chunkMs??100}),this.librosaOpts=t}get tag(){return"LibrosaStreamClient"}handleWsMessage(t){var a,s;const n=JSON.parse(t);(s=(a=this.librosaOpts).onMessage)==null||s.call(a,n)}get useWorklet(){return!1}}const Pt={debug:(...e)=>{},warn:(...e)=>{typeof console<"u"&&console.warn("[KaraokePitch]",...e)}};function Ih(e){const t=new Float32Array(e);for(let n=0;n<e;n++)t[n]=.5*(1-Math.cos(2*Math.PI*n/(e-1)));return t}function Lh(e,t){const n=new Float32Array(e.length);for(let a=0;a<e.length;a++)n[a]=e[a]*t[a];return n}function Io({isPlaying:e,gameMode:t,players:n,playersMicKey:a,micAlgorithms:s={},defaultPitchAlgorithm:i="pitchy",micRmsThresholds:o={},micOffsets:l={},micGains:c={},micPitchThresholds:u={},micSmoothingWindows:h={},micHysteresisFrames:p={},micUseHanning:f={},micMonitorEnabled:y={},micMonitorVolumes:m={},currentTimeRef:g,isPadMode:b,clockOffsetMsRef:x,currentPartyIdRef:k,rtc:v}){const[w,M]=d.useState({}),S=d.useRef({}),R=d.useRef({}),[T,j]=d.useState({}),O=d.useRef({}),$=d.useRef([]),E=d.useRef(null),D=d.useRef(null),[,L]=d.useState({}),[,W]=d.useState({}),[,Z]=d.useState({}),[A,_]=d.useState({}),[U,ne]=d.useState(!0),[V,q]=d.useState(!1),C=d.useRef(n);C.current=n;const F=d.useRef(0),I=d.useRef(performance.now());return d.useEffect(()=>{$.current.forEach(G=>G()),$.current=[];const P={current:!1};function N(G,Y,X=0){g.current!==F.current&&(F.current=g.current,I.current=performance.now());const ie=Math.min(.25,(performance.now()-I.current)/1e3),le=g.current+ie-X/1e3;M(H=>{const K=H[G]||[];return{...H,[G]:[...K,{t:le,hz:Y}]}}),S.current[G]=(S.current[G]||[]).concat({t:le,hz:Y});const te=S.current[G];te.length>500&&(S.current[G]=te.slice(-500))}function z(G,Y,X,ie=.02,le=0,te=.6,H=0,K=0,oe=0,re=!1){let he=null,Q=null,de=null;return(async()=>{try{he=new AudioContext;let ce=he.createMediaStreamSource(Y);if(H>0){const $e=he.createGain();$e.gain.value=H,ce.connect($e),ce=$e}const ye=he.createAnalyser();ye.fftSize=2048,ce.connect(ye);const Se=new Float32Array(ye.fftSize),ae=re?Ih(ye.fftSize):null,ue=[];let Ie=0;if(X==="pitchy")try{const{PitchDetector:$e}=await import("pitchy");de=$e.forFloat32Array(ye.fftSize)}catch($e){Pt.warn("pitchy import failed, falling back to autocorrelation",$e)}const ze=()=>{try{ye.getFloatTimeDomainData(Se)}catch{}const $e=ae?Lh(Se,ae):Se;let Ye=0;for(let Ve=0;Ve<$e.length;Ve++)Ye+=$e[Ve]*$e[Ve];Ye=Math.sqrt(Ye/$e.length);let je=0;if(Ye>=ie)if(de)try{const[Ve,ht]=de.findPitch($e,he.sampleRate);Ve>50&&Ve<3e3&&ht>te&&(je=Ve)}catch{}else je=xo($e,he.sampleRate,ie),(je<50||je>3e3)&&(je=0);if(je>0&&K>1&&(ue.push(je),ue.length>K&&ue.shift(),je=ue.reduce((Ve,ht)=>Ve+ht,0)/ue.length),je>0)Ie=0,N(G,je,le);else if(Ie++,oe>0&&Ie<=oe&&ue.length>0){const Ve=ue[ue.length-1];Ve>0&&N(G,Ve,le)}Q=requestAnimationFrame(ze),O.current[G]=Q};ze()}catch(xe){Pt.warn("startLocalPitch error",xe)}})(),()=>{Q&&cancelAnimationFrame(Q),he&&he.close().catch(()=>{})}}function B(G,Y,X,ie=0){X==="crepe"&&D.current?(D.current.stop(),D.current=null):X==="librosa"&&E.current&&(E.current.stop(),E.current=null);const le=window.location,te=le.protocol==="https:"?"wss:":"ws:",H=X==="librosa"?`${te}//${le.host}/api/librosa/ws/pyin`:`${te}//${le.host}/api/ai/audio/pitch/ws/pitch_server`,K=X==="librosa"?L:W;K(de=>({...de,[G]:"connecting"}));const oe=[],re=de=>{if(de>0){for(oe.push(g.current);oe.length>200;)oe.shift();X==="crepe"&&Z(me=>({...me,[G]:(me[G]||0)+1}))}},he=()=>{K(de=>({...de,[G]:"closed"})),oe.length=0},Q=de=>{if(typeof de.hz=="number"&&de.hz>0){const me=de.hz,ce=(oe.length>0?oe.shift():g.current)-ie/1e3;M(ye=>{const Se=ye[G]||[];return{...ye,[G]:[...Se,{t:ce,hz:me}]}})}else oe.length>0&&oe.shift()};if(X==="librosa"){const de=new Eh({wsUrl:H,onOpen:()=>K(me=>({...me,[G]:"connected"})),onClose:he,onError:me=>{K(xe=>({...xe,[G]:"error"})),Pt.warn("Librosa WS error",me)},onMessage:Q,onSend:re});return E.current=de,de.startWithMediaStream(Y).catch(me=>{Pt.warn("Librosa client start failed",me),K(xe=>({...xe,[G]:"failed"}))}),()=>{de.stop(),E.current=null,K(me=>({...me,[G]:""}))}}else{const de=new Ah({wsUrl:H,onOpen:()=>K(me=>({...me,[G]:"connected"})),onClose:he,onError:me=>{K(xe=>({...xe,[G]:"error"})),Pt.warn("Crepe WS error",me)},onMessage:Q,onSend:re,onFallback:()=>{K(xe=>({...xe,[G]:"fallback-pitchy"})),D.current=null;const me=z(G,Y,"pitchy",.02,ie);$.current.push(me)}});return D.current=de,de.startWithMediaStream(Y).catch(me=>{Pt.warn("Crepe client start failed",me),K(xe=>({...xe,[G]:"failed"}))}),()=>{de.stop(),D.current=null,K(me=>({...me,[G]:""}))}}}if(e){if(M({}),t!=="pad"){const G={};C.current.forEach(Y=>{if(!Y.micId)return;const X=s[Y.id]||i,ie=Y.micId&&o[Y.micId]||.02,le=Y.micId&&l[Y.micId]||0,te=Y.micId&&c[Y.micId]||0,H=Y.micId&&u[Y.micId]||.6,K=Y.micId&&h[Y.micId]||0,oe=Y.micId&&p[Y.micId]||0,re=Y.micId&&f[Y.micId]||!1,he=Y.micId&&y[Y.micId]||!1,Q=(Y.micId?m[Y.micId]:void 0)??100,de=new Ea;de.startRecording({deviceId:Y.micId,onLevel:()=>{},gain:te,monitorEnabled:he,monitorVolume:Q}).then(()=>{if(P.current){de.stopRecording().catch(()=>{});return}G[Y.id]=de;const me=de.getStream();if(!me){Pt.warn(`No stream from recorder for player ${Y.id}`);return}if(X==="librosa"||X==="crepe"){const xe=B(Y.id,me,X,le);$.current.push(xe)}else{const xe=z(Y.id,me,X,ie,le,H,te,K,oe,re);$.current.push(xe)}}).catch(me=>Pt.warn(`recorder start failed for player ${Y.id}`,me))}),R.current=G}}else{const G=R.current,Y=Object.keys(G).map(Number);Promise.allSettled(Y.map(async X=>{const ie=await G[X].stopRecording();return{pid:X,blob:ie}})).then(X=>{const ie={};for(const le of X)le.status==="fulfilled"&&le.value.blob&&(ie[le.value.pid]=le.value.blob);Object.keys(ie).length>0&&j(le=>({...le,...ie}))}),R.current={},Object.values(O.current).forEach(X=>X&&cancelAnimationFrame(X)),O.current={}}return()=>{P.current=!0,$.current.forEach(G=>G()),$.current=[],Object.values(R.current).forEach(G=>G.stopRecording().catch(()=>{})),R.current={},Object.values(O.current).forEach(G=>G&&cancelAnimationFrame(G)),O.current={}}},[e,t,a,s,i,o,l,c,u,h,p,f,y,m]),d.useEffect(()=>{if(!v)return;const P=300,N=async()=>{try{const B={...S.current};for(const G of Object.keys(B)){const Y=Number(G),X=B[Y]||[];if(!X||X.length===0)continue;S.current[Y]=[];const ie=So(X,120),le={playerId:Y,points:ie,clientNowUtc:new Date().toISOString(),quantized:!0};k!=null&&k.current&&(le.EventId=k.current);try{v.isConnected()&&await v.publishTimelineUpdate(le)}catch(te){Pt.warn("failed to publish timeline update, will retry",te),S.current[Y]=(S.current[Y]||[]).concat(X).slice(-1e3)}}}catch{}},z=window.setInterval(N,P);return()=>{z&&window.clearInterval(z)}},[v,k]),d.useEffect(()=>{if(!v)return;const P=N=>{try{const z=N;if(!z||typeof z.playerId>"u"||!Array.isArray(z.points))return;const B=Number(z.playerId),G=z.points.map(Y=>({t:Y.t,hz:Y.hz}));if(!G.length)return;if(z.serverTimeUtc){const Y=ko(z.serverTimeUtc,Date.now(),(x==null?void 0:x.current)||0);_(X=>({...X,[B]:Y}))}M(Y=>{const X=Y[B]||[];return{...Y,[B]:[...X,...G]}})}catch{}};return v.onTimelineUpdate(P),()=>v.offTimelineUpdate(P)},[v,x]),{livePitch:w,setLivePitch:M,recordings:T,recordersRef:R,unsentPitchRef:S,pitchCleanupsRef:$,remoteLatencyMs:A,showRemoteTimelines:U,setShowRemoteTimelines:ne,compactTimelines:V,setCompactTimelines:q}}function Lo(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function Do(e){return e>=50?3:e>=30?2.5:e>=20?2:e>=10?1.5:1}function _o(e,t,n){const{semitoneTolerance:a,preWindow:s,postExtra:i}=n,o=n.segMs??.25,l=typeof n.completionBonusFactor=="number"?n.completionBonusFactor:.15,c=typeof n.goldFullBonusFactor=="number"?n.goldFullBonusFactor:.3,u=typeof n.difficultyMult=="number"?n.difficultyMult:1,h=!!n.disableGoldNotes;let p=0,f=0,y=0;const m=[];let g=0,b=0,x=0;const k=new Map;e.forEach((j,O)=>{const $=j.startTime,E=j.startTime+j.duration,D=$-s,L=E+i,W=t.filter(C=>C.t>=D&&C.t<=L&&C.hz>0);if(!W||W.length===0)return;const Z=Math.max(1,Math.ceil((j.duration||.25)/o)),A=Math.max(10,Math.round(100*(j.duration||1))),_=Math.max(1,Math.round(A/Z));let U=0;const ne=[];for(let C=0;C<Z;C++){const F=$+C*(j.duration/Z),I=$+(C+1)*(j.duration/Z),P=Math.min(.06,j.duration/Z*.2),N=F-P,z=I+P,B=t.filter(te=>te.t>=N&&te.t<=z&&te.hz>0);if(!B||B.length===0)continue;let G=0;B.forEach(te=>{let K=((12*Math.log2(te.hz/440)+69)%12+12)%12;for(;K-j.pitch>6;)K-=12;for(;K-j.pitch<-6;)K+=12;const oe=Math.abs(K-j.pitch);G+=oe});const Y=G/B.length;let X=0;if(a<=0)X=Y===0?1:0;else{const te=a*2;X=Math.max(0,1-Math.min(Y/te,1))}if(X<=0)continue;const ie=!h&&j.isGold?2:1,le=Math.round(_*ie*X);le>0&&(p+=le,U+=le,ne.push({segIndex:C,frac:X,add:le,segStart:N,segEnd:z,visualStart:F,visualEnd:I}))}const V=j.line??0;k.has(V)||k.set(V,{total:0,hit:0,comboBonus:0});const q=k.get(V);if(q.total++,U>0){g++,g>b&&(b=g),q.hit++;const C=Do(g),F=C>1?Math.round(U*(C-1)):0;x+=F,q.comboBonus+=F;const I=Math.max(1,Math.ceil((j.duration||.25)/o)),N=ne.length>=I,z=N?Math.round(Math.max(10,Math.round(100*(j.duration||1)))*l*(!h&&j.isGold?1.5:1)*u):0,B=N&&!h&&j.isGold?Math.round(Math.max(10,Math.round(100*(j.duration||1)))*c*u):0;f+=z,y+=B,m.push({noteKey:`${j.line??0}-${j.idx??0}`,segments:ne,totalAdded:U,completed:N,completionBonus:z,goldFullBonus:B})}else g=0});const v=[];for(const[j,O]of k.entries()){const $=O.total>0?O.hit/O.total:0;v.push({verseIndex:j,hitFraction:$,label:Lo($),comboBonus:O.comboBonus})}const w={maxCombo:b,currentCombo:0,totalComboBonus:x},M=x+f+y,S=m.length,R=m.filter(j=>j.completed).length,T={hits:S,misses:e.length-S,good:S-R,perfect:R,maxCombo:b};return{classicScore:p,bonusScore:M,totalScore:p+M,total:p,perNote:m,combo:w,verseRatings:v,noteStats:T}}function Fo(e,t){let n=0;for(const a of e){const s=Math.max(10,Math.round(100*(a.duration||1))),i=!t&&a.isGold?2:1;n+=s*i}return n}function zo(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function Oo(e,t,n){const a=Fo(t,n);if(a<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0,total:0};const s=zo(e.classicScore,a),i=Math.round(e.bonusScore/a*1e4);return{...e,classicScore:s,bonusScore:i,totalScore:s+i,total:s}}const vn={maxCombo:0,currentCombo:0,totalComboBonus:0},qs={hits:0,misses:0,good:0,perfect:0,maxCombo:0};function Bo({livePitch:e,uploadedSong:t,isPlaying:n,difficulty:a,players:s,isPadMode:i}){const[o,l]=d.useState(0),[c,u]=d.useState(0),[h,p]=d.useState(0),[f,y]=d.useState([]),[m,g]=d.useState(vn),[b,x]=d.useState([]),[k,v]=d.useState([]),[w,M]=d.useState({}),[S,R]=d.useState({}),[T,j]=d.useState({}),[O,$]=d.useState({}),[E,D]=d.useState({});return d.useEffect(()=>{if(!t||!n)return;const L=qn(t.notes.map(B=>B.noteLine),t.bpm??void 0),W=(t.gap??0)/1e3,Z=Za(L,W),A=Ir(a),_=[];let U=null,ne=null,V=null,q=[];const C={},F={},I={},P={},N={},z=i?s[0]:s.find(B=>!!B.micId)||s[0];for(let B=0;B<s.length;B++){const G=s[B],Y=(G==null?void 0:G.id)!=null?e[G.id]||[]:[];if(Y.length===0){_.push({id:G.id,name:G.name||`Player ${G.id}`,color:G.color||Je[B%Je.length],classicScore:0,bonusScore:0,totalScore:0}),C[G.id]=[],F[G.id]={...vn},I[G.id]=[],P[G.id]=0,N[G.id]={...qs};continue}const X=Ua(G.id),ie=!!(X!=null&&X.disableGoldNotes),le=_o(Z,Y,{semitoneTolerance:A.semitoneTolerance,preWindow:A.preWindow,postExtra:A.postExtra,difficultyMult:A.difficultyMult,disableGoldNotes:ie}),te=Oo(le,Z,ie);_.push({id:G.id,name:G.name||`Player ${G.id}`,color:G.color||Je[B%Je.length],classicScore:te.classicScore,bonusScore:te.bonusScore,totalScore:te.totalScore}),C[G.id]=vo(le.perNote,L,W),F[G.id]=le.combo??{...vn},I[G.id]=le.verseRatings??[],P[G.id]=te.totalScore,N[G.id]=le.noteStats??{...qs},G.id===(z==null?void 0:z.id)&&(U=te,ne=le.combo??null,V=le.verseRatings??null,q=C[G.id])}v(_),M(C),R(F),j(I),$(P),D(N),U?(l(U.classicScore),u(U.bonusScore),p(U.totalScore),y(q),g(ne??vn),x(V??[])):(l(0),u(0),p(0),y([]),g(vn),x([]))},[e,t,n,a,s,i]),{liveScore:o,liveBonusScore:c,liveTotalScore:h,liveSegmentScores:f,liveCombo:m,liveVerseRatings:b,perPlayerScores:k,perPlayerSegmentScores:w,perPlayerCombo:S,perPlayerVerseRatings:T,perPlayerTotalScores:O,perPlayerNoteStats:E}}const Dh=e=>!!e&&/youtu(\.be|be\.com)/i.test(e),_h=({players:e,song:t,initialSong:n=null,difficulty:a="normal",gameMode:s="normal",height:i=480,showTimelines:o=!0,showLyrics:l=!0,singleTimeline:c=!1,requestMicPermission:u=!0,initiallyActivated:h=!1,showUploader:p=!1,parseSong:f,micAlgorithms:y,defaultPitchAlgorithm:m="pitchy",micRmsThresholds:g,micOffsets:b,micGains:x,micPitchThresholds:k,micSmoothingWindows:v,micHysteresisFrames:w,micUseHanning:M,micMonitorEnabled:S,micMonitorVolumes:R,searchYouTubeByArtistTitle:T,fetchTopSingings:j,onSaveResults:O,rtc:$,onSongChange:E,onPlayingChange:D,onTimeUpdate:L,onEnded:W,onContinue:Z,renderReport:A,t:_,className:U,style:ne,id:V,accessMode:q,"data-testid":C})=>{var Fe;const{t:F}=Te(),I=_??F,[P,N]=d.useState(t??n??null),[z,B]=d.useState(!1),[G,Y]=d.useState(0),[X,ie]=d.useState(h),[le,te]=d.useState(!1),[H,K]=d.useState([]),[oe,re]=d.useState(""),[he,Q]=d.useState(null),[de,me]=d.useState(0),xe=s==="pad",[ce,ye]=d.useState([]),[Se,ae]=d.useState([]),[ue,Ie]=d.useState([]),[ze,$e]=d.useState([]),Ye=d.useRef(null),je=d.useRef(null),Ve=d.useRef(null),ht=d.useRef(!1),et=d.useRef(0);d.useEffect(()=>{et.current=G},[G]);const Ze=d.useRef(t);d.useEffect(()=>{t!==void 0&&t!==Ze.current&&(Ze.current=t,N(t),te(!1),Y(0),me(ge=>ge+1))},[t]);const At=d.useMemo(()=>JSON.stringify(e.map(ge=>({id:ge.id,micId:ge.micId}))),[e]),{livePitch:pt,setLivePitch:Et,recordings:ct,remoteLatencyMs:fe}=Io({isPlaying:z,gameMode:s,players:e,playersMicKey:At,micAlgorithms:y,defaultPitchAlgorithm:m,micRmsThresholds:g,micOffsets:b,micGains:x,micPitchThresholds:k,micSmoothingWindows:v,micHysteresisFrames:w,micUseHanning:M,micMonitorEnabled:S,micMonitorVolumes:R,currentTimeRef:et,isPadMode:xe,rtc:$}),be=Bo({livePitch:pt,uploadedSong:P,isPlaying:z,difficulty:a,players:e,isPadMode:xe}),_e=d.useRef(be);_e.current=be;const vt=d.useMemo(()=>P?jo(P,s):null,[P,s]),pe=((Fe=e[0])==null?void 0:Fe.id)??1;d.useEffect(()=>{var Me;if(!xe||!z||!P){(Me=Ye.current)==null||Me.stop(),Ye.current=null,ye([]),ae([]),Ie([]),$e([]);return}const ge=new Ao({difficulty:a,noteLines:P.notes.map(Pe=>Pe.noteLine),bpm:P.bpm??void 0,gap:P.gap??0,onPitch:Pe=>{const Ge=et.current;Et(De=>{const nt=De[pe]||[];return{...De,[pe]:[...nt,{t:Ge,hz:Pe}]}})},onHitFeedback:Pe=>$e(Ge=>[...Ge.slice(-20),Pe]),onLaneActive:Pe=>Ie(Pe)});return ye(ge.getLanes()),ae(ge.getEvents()),Ie(new Array(ge.getLanes().length).fill(!1)),ge.start(()=>et.current),Ye.current=ge,()=>{ge.stop(),Ye.current=null}},[xe,z,P,a,pe,Et]);const ve=d.useCallback(ge=>{B(ge),D==null||D(ge)},[D]),Ue=d.useCallback(ge=>{Y(ge),L==null||L(ge)},[L]),Ee=d.useCallback(()=>{var Me;try{Bt()}catch{}const ge=()=>{ie(!0),ht.current=!0};!xe&&u&&((Me=navigator.mediaDevices)!=null&&Me.getUserMedia)?navigator.mediaDevices.getUserMedia({audio:!0}).then(Pe=>Pe.getTracks().forEach(Ge=>Ge.stop())).catch(()=>{}).finally(ge):ge()},[xe,u]);d.useEffect(()=>{if(!X||!ht.current)return;ht.current=!1;const ge=window.setInterval(()=>{je.current&&(window.clearInterval(ge),je.current.play())},100),Me=window.setTimeout(()=>window.clearInterval(ge),3e3);return()=>{window.clearInterval(ge),window.clearTimeout(Me)}},[X]);const Ce=d.useCallback(()=>{te(!0),W==null||W();const ge=(P==null?void 0:P.id)??0,Me=_e.current,Pe=[];for(const De of e){const nt=Me.perPlayerTotalScores[De.id]??0;if(nt<=0)continue;const Ke=Me.perPlayerNoteStats[De.id];Pe.push({playerId:De.id,songId:ge,score:nt,hits:(Ke==null?void 0:Ke.hits)??0,misses:(Ke==null?void 0:Ke.misses)??0,good:(Ke==null?void 0:Ke.good)??0,perfect:(Ke==null?void 0:Ke.perfect)??0,combo:(Ke==null?void 0:Ke.maxCombo)??0})}const Ge=()=>{j&&ge>0&&Promise.resolve(j(ge)).then(K).catch(()=>{})};O&&Pe.length>0?Promise.resolve(O(Pe)).then(Ge).catch(Ge):Ge()},[e,P,O,j,W]);d.useEffect(()=>{var ge;s==="demo"&&z&&G>=12&&((ge=je.current)==null||ge.pause(),Ce())},[s,z,G,Ce]),d.useEffect(()=>{if(!P||de===0||!T||Dh(P.videoPath))return;if(P.youtubeId){const Me=`https://www.youtube.com/watch?v=${P.youtubeId}`;N(Pe=>Pe&&{...Pe,videoPath:Me});return}if(!P.artist||!P.title)return;let ge=!1;return re(I("karaokeManager.ytSearching","Searching YouTube…")),Q("searching"),Promise.resolve(T(P.artist,P.title)).then(Me=>{if(!ge)if(Me){const Pe=`https://www.youtube.com/watch?v=${Me}`;N(Ge=>Ge&&{...Ge,videoPath:Pe}),re(""),Q(null)}else re(I("karaokeManager.ytNotFound","Not found on YouTube")),Q("error"),window.setTimeout(()=>{ge||(re(""),Q(null))},4e3)}).catch(()=>{ge||(re(I("karaokeManager.ytSearchError","Search error")),Q("error"))}),()=>{ge=!0}},[de,P,T,I]);const Re=d.useCallback(()=>{var ge,Me;te(!1),Et({}),(ge=je.current)==null||ge.seekTo(0),(Me=je.current)==null||Me.play()},[Et]),Oe=d.useCallback(()=>{te(!1),Z==null||Z()},[Z]),Be=d.useCallback(ge=>{N(ge),te(!1),Y(0),me(Me=>Me+1),E==null||E(ge)},[E]),Qe=d.useMemo(()=>{if(!c)return e;const ge=e.find(Me=>!!Me.micId)||e[0];return ge?[ge]:[]},[e,c]),Ae=((P==null?void 0:P.gap)??0)/1e3;return q==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-manager${U?` ${U}`:""}`,style:{position:"relative",textAlign:"center",minHeight:i,...ne},id:V,"data-testid":C,children:[oe&&r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,margin:"10px auto",padding:"8px 16px",maxWidth:420,borderRadius:8,fontSize:14,fontWeight:500,background:"var(--nice-accent, #3b82f6)",color:"var(--nice-bg, #fff)"},children:[he==="error"?r.jsx(se.NtdClose,{size:16}):r.jsx(se.NtdSearch,{size:16}),oe]}),!P&&p&&r.jsx(Mo,{onSongUpload:Be,parseSong:f,t:I}),P&&!X&&r.jsxs("button",{type:"button",className:"nice-karaoke-manager__activate",onClick:Ee,style:{position:"absolute",inset:0,zIndex:30,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:16,border:"none",cursor:"pointer",background:"var(--nice-overlay-80, rgba(0,0,0,0.82))",color:"#fff"},children:[r.jsx("div",{style:{fontSize:56,lineHeight:0},children:xe?r.jsx(se.NtdGamepad,{size:56}):r.jsx(se.NtdMicrophone,{size:56})}),r.jsx("h2",{style:{margin:0,fontSize:22,fontWeight:700,color:"#fff"},children:I("karaokeManager.activateAudio","Tap to start")}),r.jsx("p",{style:{margin:0,maxWidth:360,fontSize:14,color:"var(--nice-text-muted, #94a3b8)"},children:xe?I("karaokeManager.padHint","Hit the notes with your keys or pad!"):I("karaokeManager.micHint","Your browser needs a tap to unlock the microphone and audio.")})]}),P&&r.jsxs("div",{ref:Ve,style:{position:"relative",width:"100%",maxWidth:1200,margin:"0 auto"},children:[r.jsx("div",{style:{width:"100%",position:"relative",zIndex:10},children:r.jsx(Ya,{tracks:vt?[vt]:[],autoPlay:!1,uiMode:"nobuttons",height:i,externalRef:je,onPlayingChange:ve,onTimeUpdate:Ue,onEnded:Ce})}),o&&X&&r.jsx("div",{style:{position:"absolute",inset:0,zIndex:20,pointerEvents:"none"},children:Qe.map((ge,Me)=>{const Pe=pt[ge.id]||[],Ge=Ae?Pe.map(De=>({t:De.t-Ae,hz:De.hz})):Pe;return r.jsx(Va,{song:P,currentTime:G,playerRef:Ve,userPitch:Ge,segmentScores:be.perPlayerSegmentScores[ge.id],combo:be.perPlayerCombo[ge.id],verseRatings:be.perPlayerVerseRatings[ge.id],config:{playerName:ge.name,score:be.perPlayerTotalScores[ge.id]??0,playerBgColor:ge.color||Je[Me%Je.length],difficultyLevel:a,isPlaying:z,playerCount:Qe.length,latencyMs:fe[ge.id]??null,top:30+Me*160}},ge.id)})}),xe&&ce.length>0&&r.jsx(Ro,{lanes:ce,events:Se,currentTime:G,activeLanes:ue,difficulty:a,feedbackQueue:ze,isPlaying:z}),l&&X&&r.jsx("div",{style:{position:"absolute",bottom:20,left:0,right:0,zIndex:25,pointerEvents:"none"},children:r.jsx(Da,{song:P,currentTime:G})})]}),le&&Object.keys(ct).length>0&&r.jsx(Fh,{recordings:ct,players:e,t:I}),le&&r.jsx(Ka,{uploadedSong:P,playerScores:be.perPlayerScores,topSingings:H,onRestart:Re,onContinue:Oe,t:I,renderReport:A})]})},Fh=({recordings:e,players:t,t:n})=>{const a=d.useMemo(()=>{const s={};for(const[i,o]of Object.entries(e))o&&(s[Number(i)]=URL.createObjectURL(o));return s},[e]);return d.useEffect(()=>()=>{for(const s of Object.values(a))URL.revokeObjectURL(s)},[a]),r.jsxs("div",{style:{margin:"24px auto",maxWidth:640,background:"var(--bg-tertiary)",borderRadius:12,padding:16,textAlign:"left"},children:[r.jsxs("h4",{style:{marginTop:0,color:"var(--nice-bg, #fff)"},children:[r.jsx(se.NtdMicrophone,{size:16})," ",n("karaokeManager.playerRecordings","Player recordings")]}),r.jsx("ul",{style:{listStyle:"none",padding:0,margin:0,color:"var(--nice-bg, #fff)"},children:t.map(s=>r.jsxs("li",{style:{marginBottom:12,display:"flex",alignItems:"center",gap:10},children:[r.jsx("b",{children:s.name||`Player ${s.id}`}),a[s.id]?r.jsxs(r.Fragment,{children:[r.jsx("audio",{controls:!0,src:a[s.id],style:{flex:1,maxWidth:300}}),r.jsxs("a",{href:a[s.id],download:`${s.name||`player-${s.id}`}-recording.webm`,style:{color:"var(--nice-accent-light, #4fc3f7)",whiteSpace:"nowrap"},children:[r.jsx(se.NtdDownload,{size:13})," ",n("karaokeManager.download","Download")]})]}):r.jsx("span",{style:{opacity:.6},children:n("karaokeManager.noRecording","No recording")})]},s.id))})]})},Go=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function nn(e){return 12*Math.log2(e/440)+69}function Qn(e){const t=Go[Math.round(e)%12],n=Math.floor(Math.round(e)/12)-1;return`${t}${n}`}function Kr(e,t){if(e.length===0)return 0;const n=t/100*(e.length-1),a=Math.floor(n),s=Math.ceil(n);return a===s?e[a]:e[a]+(e[s]-e[a])*(n-a)}function Wo(e){const{playerName:t,playerColor:n,songTitle:a,songArtist:s,songBpm:i,difficulty:o,pitchPoints:l,notes:c,verseRatings:u,combo:h,classicScore:p,bonusScore:f,totalScore:y,micSettings:m}=e,g=l.filter(ae=>ae.hz>0),b=g.map(ae=>nn(ae.hz)),x=[],k=[],v=[],w=[...c].sort((ae,ue)=>ae.startTime-ue.startTime);function M(ae){let ue=0,Ie=w.length-1;for(;ue<=Ie;){const ze=ue+Ie>>>1,$e=w[ze];if(ae<$e.startTime)Ie=ze-1;else if(ae>$e.startTime+$e.duration)ue=ze+1;else return $e.pitch}return 0}for(const ae of l){const ue=ae.hz>0?nn(ae.hz):0,Ie=M(ae.t);if(k.push({t:ae.t,sung:ue,expected:Ie}),ue>0&&Ie>0){const ze=(ue-Ie)*100;x.push(ze)}}let S=0;for(const ae of w){const ue=ae.startTime-.3,Ie=ae.startTime+ae.duration;for(;S<g.length&&g[S].t<ue;)S++;S<g.length&&g[S].t<=Ie&&v.push((g[S].t-ae.startTime)*1e3)}const R=x.map(Math.abs),T=[...R].sort((ae,ue)=>ae-ue),j=R.length>0?R.reduce((ae,ue)=>ae+ue,0)/R.length:0,O=Kr(T,50),$=R.length>1?Math.sqrt(R.reduce((ae,ue)=>ae+(ue-j)**2,0)/(R.length-1)):0,E=R.filter(ae=>ae<=50).length,D=R.filter(ae=>ae<=15).length,L=R.length>0?E/R.length*100:0,W=R.length>0?D/R.length*100:0,Z=["< −100","−100 to −50","−50 to −25","−25 to −15","−15 to 0","0 to +15","+15 to +25","+25 to +50","+50 to +100","> +100"],A=new Array(10).fill(0);for(const ae of x){const ue=ae<-100?0:ae<-50?1:ae<-25?2:ae<-15?3:ae<0?4:ae<15?5:ae<25?6:ae<50?7:ae<100?8:9;A[ue]++}const _=Z.map((ae,ue)=>({centRange:ae,count:A[ue],pct:x.length>0?A[ue]/x.length*100:0})),U=g.map(ae=>ae.hz).sort((ae,ue)=>ae-ue),ne=U.length>0?U[0]:0,V=U.length>0?U[U.length-1]:0,q=ne>0?nn(ne):0,C=V>0?nn(V):0,F=C-q,I=[...b].sort((ae,ue)=>ae-ue),P=Kr(I,10),N=Kr(I,90),z=new Array(12).fill(0);for(const ae of b){const ue=Math.round(ae)%12;ue>=0&&ue<12&&z[ue]++}const B=z.reduce((ae,ue)=>ae+ue,0),G=Go.map((ae,ue)=>({note:ae,count:z[ue],pct:B>0?z[ue]/B*100:0})),Y=zh(g),X=v.length>0?v.reduce((ae,ue)=>ae+ue,0)/v.length:0,ie=v.length>1?Math.sqrt(v.reduce((ae,ue)=>ae+(ue-X)**2,0)/(v.length-1)):0,le=ie>0?Math.max(0,Math.min(100,100-ie/2)):100;let te=0,H=0;for(let ae=1;ae<b.length;ae++){const ue=Math.abs(b[ae]-b[ae-1]);te+=ue,H++}const K=H>0?te/H*100/12:0,oe=l.filter(ae=>ae.hz<=0).length,re=l.length>0?(1-oe/l.length)*100:0,he=new Map;for(const ae of c){const ue=ae.line??0;he.has(ue)||he.set(ue,[]),he.get(ue).push(ae)}const Q=new Map;for(const ae of g){const ue=M(ae.t);if(ue<=0)continue;let Ie=0,ze=w.length-1,$e=-1;for(;Ie<=ze;){const je=Ie+ze>>>1,Ve=w[je];if(ae.t<Ve.startTime)ze=je-1;else if(ae.t>Ve.startTime+Ve.duration)Ie=je+1;else{$e=Ve.line??0;break}}if($e<0)continue;const Ye=Math.abs((nn(ae.hz)-ue)*100);Q.has($e)||Q.set($e,[]),Q.get($e).push(Ye)}const de=u.map(ae=>{const ue=he.get(ae.verseIndex)??[],Ie=Q.get(ae.verseIndex)??[],ze=Ie.length>0?Ie.reduce(($e,Ye)=>$e+Ye,0)/Ie.length:0;return{verseIndex:ae.verseIndex,label:ae.label,hitFraction:ae.hitFraction,avgCentDeviation:Math.round(ze*10)/10,noteCount:ue.length,notesHit:Math.round(ae.hitFraction*ue.length),comboBonus:ae.comboBonus}}),me=2,xe=.5,ce=l.length>0?l[l.length-1].t:0,ye=[],Se=k.filter(ae=>ae.sung>0&&ae.expected>0);if(Se.length>0){let ae=0,ue=0,Ie=0;for(let ze=0;ze<=ce;ze+=xe){const $e=ze-me/2,Ye=ze+me/2;for(;ue<Se.length&&Se[ue].t<Ye;)Math.abs(Se[ue].sung-Se[ue].expected)<=.5&&Ie++,ue++;for(;ae<ue&&Se[ae].t<$e;)Math.abs(Se[ae].sung-Se[ae].expected)<=.5&&Ie--,ae++;const je=ue-ae;ye.push({t:ze,accuracy:je>0?Ie/je*100:0})}}else for(let ae=0;ae<=ce;ae+=xe)ye.push({t:ae,accuracy:0});return{playerName:t,playerColor:n,songTitle:a,songArtist:s,songBpm:i,difficulty:o,timestamp:new Date().toISOString(),classicScore:p,bonusScore:f,totalScore:y,maxCombo:(h==null?void 0:h.maxCombo)??0,totalComboBonus:(h==null?void 0:h.totalComboBonus)??0,totalPitchPoints:l.length,avgCentDeviation:Math.round(j*10)/10,medianCentDeviation:Math.round(O*10)/10,stdDevCents:Math.round($*10)/10,intonationAccuracyPct:Math.round(L*10)/10,perfectHitPct:Math.round(W*10)/10,pitchDeviationHistogram:_,lowestHz:Math.round(ne*10)/10,highestHz:Math.round(V*10)/10,lowestNote:q>0?Qn(q):"—",highestNote:C>0?Qn(C):"—",rangeInSemitones:Math.round(F*10)/10,tessituraLow:P>0?Qn(P):"—",tessituraHigh:N>0?Qn(N):"—",pitchClassDistribution:G,vibrato:Y,avgOnsetDeviationMs:Math.round(X*10)/10,rhythmStabilityPct:Math.round(le*10)/10,jitterPct:Math.round(K*100)/100,shimmerProxy:Math.round(re*10)/10,verseMetrics:de,micSettings:m,pitchOverTime:k,accuracyOverTime:ye}}function zh(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(y=>nn(y.hz)),n=e.map(y=>y.t),a=.5,s=[],i=[];let o=0,l=0,c=0;for(let y=0;y<e.length;y++){for(l+=t[y],c++;o<y&&n[y]-n[o]>=a;)l-=t[o],c--,o++;if(c<6||(y-o)%10!==0)continue;const m=l/c;let g=0,b=t[o]-m,x=Math.abs(b);for(let w=o+1;w<=y;w++){const M=t[w]-m;M*b<0&&g++,b=M;const S=Math.abs(M);S>x&&(x=S)}const k=n[y]-n[o];if(k<=0)continue;const v=g/2/k;v>=3&&v<=12&&(s.push(v),i.push(x*100))}if(s.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const u=s.reduce((y,m)=>y+m,0)/s.length,h=i.reduce((y,m)=>y+m,0)/i.length,p=Math.sqrt(s.reduce((y,m)=>y+(m-u)**2,0)/s.length),f=Math.max(0,Math.min(100,100-p*20));return{detected:!0,avgRateHz:Math.round(u*10)/10,avgExtentCents:Math.round(h*10)/10,regularityPct:Math.round(f)}}const J={overlay:{position:"fixed",inset:0,background:"var(--nice-overlay-90, rgba(0,0,0,0.92))",display:"flex",alignItems:"flex-start",justifyContent:"center",zIndex:250,color:"var(--nice-text, #e2e8f0)",overflowY:"auto",padding:"24px 12px"},container:{background:"var(--nice-bg, #0f172a)",borderRadius:16,padding:32,width:"min(960px, 95vw)",boxShadow:"0 16px 48px var(--nice-overlay-60, rgba(0,0,0,0.6))",fontFamily:"'Segoe UI', system-ui, -apple-system, sans-serif"},header:{textAlign:"center",marginBottom:24,borderBottom:"2px solid var(--nice-border, #334155)",paddingBottom:20},title:{fontSize:28,fontWeight:800,color:"var(--nice-text, #f1f5f9)",margin:"0 0 4px"},subtitle:{fontSize:14,color:"var(--nice-text-muted, #64748b)",margin:0},sectionTitle:{fontSize:18,fontWeight:700,color:"var(--nice-accent, #38bdf8)",margin:"28px 0 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",paddingBottom:6,display:"flex",alignItems:"center",gap:8},table:{width:"100%",borderCollapse:"collapse",fontSize:13,margin:"8px 0"},th:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"left",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},thRight:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"right",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},td:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-secondary, #cbd5e1)"},tdRight:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",textAlign:"right",color:"var(--nice-text, #e2e8f0)",fontWeight:500},tdBold:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text, #f1f5f9)",fontWeight:700},kpiGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:12,margin:"12px 0"},kpiCard:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:"14px 16px",textAlign:"center",border:"1px solid var(--nice-border, #334155)"},kpiValue:{fontSize:26,fontWeight:800,color:"var(--nice-warning, #fbbf24)"},kpiLabel:{fontSize:11,color:"var(--nice-text-muted, #64748b)",marginTop:2,textTransform:"uppercase",letterSpacing:.8},kpiUnit:{fontSize:13,fontWeight:400,color:"var(--nice-text-muted, #94a3b8)",marginLeft:2},chartWrap:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:16,margin:"12px 0",border:"1px solid var(--nice-border, #334155)"},chartTitle:{fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:8,textAlign:"center"},badge:e=>({display:"inline-block",padding:"2px 10px",borderRadius:20,background:e,color:"#fff",fontSize:12,fontWeight:700}),btnPrimary:{background:"var(--nice-info, #3b82f6)",color:"#fff",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:700,cursor:"pointer"},btnSecondary:{background:"var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:600,cursor:"pointer"},row:{display:"flex",gap:16,flexWrap:"wrap"},half:{flex:"1 1 45%",minWidth:280},footer:{textAlign:"center",marginTop:24,paddingTop:16,borderTop:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #475569)",fontSize:11}};function gt(e){return e>=90?"#22c55e":e>=70?"#84cc16":e>=50?"#eab308":e>=30?"#f97316":"#ef4444"}function Vs(e){switch(e){case"Perfect":return"#22c55e";case"Great":return"#84cc16";case"Good":return"#eab308";case"OK":return"#f97316";default:return"#ef4444"}}const Oh=({uploadedSong:e,playerScores:t,livePitch:n,liveVerseRatings:a,liveCombo:s,difficulty:i,micSettings:o,onClose:l,t:c,className:u,style:h,id:p,accessMode:f,"data-testid":y})=>{const{t:m}=Te(),g=c??m,b=d.useRef(null),x=d.useMemo(()=>{if(!e)return[];const _=qn(e.notes.map(ne=>ne.noteLine),e.bpm??void 0),U=(e.gap??0)/1e3;return Za(_,U)},[e]),k=d.useMemo(()=>e?t.map(_=>{const U=n[_.id]||[];return Wo({playerName:_.name,playerColor:_.color,songTitle:e.title,songArtist:e.artist,songBpm:e.bpm??0,difficulty:i,pitchPoints:U,notes:x,verseRatings:a,combo:s,classicScore:_.classicScore,bonusScore:_.bonusScore,totalScore:_.totalScore,micSettings:o[_.id]??null})}):[],[e,t,n,a,s,i,x,o]),v=d.useCallback(()=>{var q,C;if(!b.current)return;const _=`<!DOCTYPE html>
48
+ <html lang="en"><head><meta charset="utf-8">
49
+ <title>Vocal Performance Report — ${((q=k[0])==null?void 0:q.songTitle)??"Karaoke"}</title>
50
+ <style>
51
+ body{margin:0;padding:24px;background:var(--nice-bg, #0f172a);color:var(--nice-text, #e2e8f0);font-family:'Segoe UI',system-ui,sans-serif}
52
+ table{border-collapse:collapse;width:100%}th,td{padding:6px 10px;border-bottom:1px solid var(--nice-bg-secondary, #1e293b);text-align:left}
53
+ th{background:var(--nice-bg-secondary, #1e293b);color:var(--nice-text-muted, #94a3b8);font-size:12px;text-transform:uppercase}
54
+ .kpi{background:var(--nice-bg-secondary, #1e293b);border-radius:10px;padding:14px;text-align:center;border:1px solid var(--nice-border, #334155)}
55
+ .val{font-size:24px;font-weight:800;color:var(--nice-warning, #fbbf24)}.lbl{font-size:11px;color:var(--nice-text-muted, #64748b);text-transform:uppercase}
56
+ @media print{body{background:#fff;color:#000}th{background:var(--nice-bg-secondary, #f0f0f0);color:var(--nice-text-muted, #333)}td{color:var(--nice-text-muted, #333);border-color:var(--nice-border, #ddd)}}
57
+ </style></head><body>
58
+ ${b.current.innerHTML}
59
+ </body></html>`,U=new Blob([_],{type:"text/html"}),ne=URL.createObjectURL(U),V=document.createElement("a");V.href=ne,V.download=`vocal-report-${(((C=k[0])==null?void 0:C.songTitle)??"karaoke").replace(/[^a-z0-9]/gi,"_")}.html`,V.click(),URL.revokeObjectURL(ne)},[k]),w=d.useCallback(()=>window.print(),[]),M=d.useCallback(()=>{var q;const _=JSON.stringify(k,null,2),U=new Blob([_],{type:"application/json"}),ne=URL.createObjectURL(U),V=document.createElement("a");V.href=ne,V.download=`vocal-data-${(((q=k[0])==null?void 0:q.songTitle)??"karaoke").replace(/[^a-z0-9]/gi,"_")}.json`,V.click(),URL.revokeObjectURL(ne)},[k]);if(k.length===0||f==="hidden")return null;const S=k[0],R=Ir(i),T=S.intonationAccuracyPct*.3+S.perfectHitPct*.2+S.rhythmStabilityPct*.15+S.shimmerProxy*.1+Math.min(100,S.maxCombo/Math.max(x.length,1)*100)*.1+Math.min(100,S.totalScore/1e4*100)*.15,j=T>=95?"A+":T>=90?"A":T>=85?"A−":T>=80?"B+":T>=75?"B":T>=70?"B−":T>=65?"C+":T>=60?"C":T>=55?"C−":T>=50?"D+":T>=45?"D":T>=40?"D−":"F",O={"A+":g("vocalReport.gradeAPlus","Outstanding — professional-level control."),A:g("vocalReport.gradeA","Excellent intonation and timing."),"A−":g("vocalReport.gradeAMinus","Very strong performance."),"B+":g("vocalReport.gradeBPlus","Great, with minor pitch slips."),B:g("vocalReport.gradeB","Solid and consistent."),"B−":g("vocalReport.gradeBMinus","Good, room to tighten timing."),"C+":g("vocalReport.gradeCPlus","Decent — practice pitch accuracy."),C:g("vocalReport.gradeC","Average; work on intonation."),"C−":g("vocalReport.gradeCMinus","Passable; needs steadier pitch."),"D+":g("vocalReport.gradeDPlus","Below average — keep practising."),D:g("vocalReport.gradeD","Weak intonation throughout."),"D−":g("vocalReport.gradeDMinus","Struggling with pitch and timing."),F:g("vocalReport.gradeF","Off-pitch for most notes.")};let $=0;const E=[{metric:g("vocalReport.radarIntonation","Intonation"),value:S.intonationAccuracyPct,max:100},{metric:g("vocalReport.radarPerfectHits","Perfect hits"),value:S.perfectHitPct,max:100},{metric:g("vocalReport.radarRhythm","Rhythm"),value:S.rhythmStabilityPct,max:100},{metric:g("vocalReport.radarVocalRange","Range"),value:Math.min(100,S.rangeInSemitones/24*100),max:100},{metric:g("vocalReport.radarStability","Stability"),value:S.shimmerProxy,max:100},{metric:g("vocalReport.radarCombo","Combo"),value:Math.min(100,S.maxCombo/Math.max(x.length,1)*100),max:100}],D=[{name:g("vocalReport.perfLabel","Perfect"),value:S.perfectHitPct,fill:"var(--nice-success, #22c55e)"},{name:g("vocalReport.goodLabel","Good"),value:S.intonationAccuracyPct-S.perfectHitPct,fill:"var(--nice-success, #84cc16)"},{name:g("vocalReport.offPitch","Off-pitch"),value:100-S.intonationAccuracyPct,fill:"var(--nice-danger, #ef4444)"}].filter(_=>_.value>0),L=S.pitchClassDistribution.filter(_=>_.count>0).sort((_,U)=>U.pct-_.pct),W=S.verseMetrics.map(_=>({verse:`V${_.verseIndex+1}`,accuracy:Math.round(_.hitFraction*100),label:_.label})),Z=(()=>{const _=S.pitchOverTime;if(_.length<=500)return _;const U=Math.ceil(_.length/500);return _.filter((ne,V)=>V%U===0)})(),A=g("vocalReport.cents","cents");return r.jsxs("div",{className:u,style:{...J.overlay,...h},id:p,"data-testid":y,onClick:_=>_.target===_.currentTarget&&l(),children:[r.jsx("style",{children:`
60
+ @media print {
61
+ body { background: #fff !important; color: #000 !important; }
62
+ * { color-adjust: exact !important; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
63
+ }
64
+ `}),r.jsxs("div",{ref:b,style:J.container,children:[r.jsxs("div",{style:J.header,children:[r.jsxs("h1",{style:{...J.title,display:"inline-flex",alignItems:"center",gap:8},children:[r.jsx(se.NtdBarChart,{size:26})," ",g("vocalReport.title","Vocal Performance Report")]}),r.jsxs("p",{style:J.subtitle,children:[S.songArtist," — ",S.songTitle,"  | ",g("vocalReport.difficulty","Difficulty"),": ",r.jsx("strong",{children:S.difficulty})," "," | ",new Date(S.timestamp).toLocaleString()]}),r.jsxs("div",{style:{marginTop:16,display:"flex",justifyContent:"center",alignItems:"center",gap:16},children:[r.jsx("div",{style:{width:72,height:72,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:`linear-gradient(135deg, ${gt(T)}44, ${gt(T)})`,border:`3px solid ${gt(T)}`,boxShadow:`0 0 20px ${gt(T)}44`},children:r.jsx("span",{style:{fontSize:28,fontWeight:900,color:"#fff"},children:j})}),r.jsxs("div",{style:{textAlign:"left"},children:[r.jsxs("div",{style:{fontSize:14,fontWeight:700,color:gt(T)},children:[g("vocalReport.overallGrade","Overall grade"),": ",T.toFixed(1),"%"]}),r.jsx("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",maxWidth:360},children:O[j]??""})]})]})]}),r.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end",marginBottom:16,flexWrap:"wrap"},children:[r.jsxs("button",{style:J.btnPrimary,onClick:v,children:[r.jsx(se.NtdDownload,{size:14})," ",g("vocalReport.downloadHtml","Download HTML")]}),r.jsxs("button",{style:J.btnSecondary,onClick:w,children:[r.jsx(se.NtdPrint,{size:14})," ",g("vocalReport.printPdf","Print / PDF")]}),r.jsxs("button",{style:J.btnSecondary,onClick:M,children:[r.jsx(se.NtdCode,{size:14})," ",g("vocalReport.exportJson","Export JSON")]}),r.jsxs("button",{style:J.btnSecondary,onClick:l,children:[r.jsx(se.NtdClose,{size:14})," ",g("vocalReport.close","Close")]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++$,". ",g("vocalReport.scoreOverview","Score overview")]}),r.jsxs("div",{style:J.kpiGrid,children:[r.jsxs("div",{style:J.kpiCard,children:[r.jsx("div",{style:J.kpiValue,children:S.totalScore.toLocaleString()}),r.jsx("div",{style:J.kpiLabel,children:g("vocalReport.totalScore","Total score")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsx("div",{style:J.kpiValue,children:S.classicScore.toLocaleString()}),r.jsx("div",{style:J.kpiLabel,children:g("vocalReport.classicScore","Classic score")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsx("div",{style:J.kpiValue,children:S.bonusScore.toLocaleString()}),r.jsx("div",{style:J.kpiLabel,children:g("vocalReport.bonusScore","Bonus score")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsxs("div",{style:J.kpiValue,children:[S.maxCombo,"×"]}),r.jsx("div",{style:J.kpiLabel,children:g("vocalReport.maxCombo","Max combo")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsxs("div",{style:{...J.kpiValue,color:gt(S.intonationAccuracyPct)},children:[S.intonationAccuracyPct,"%"]}),r.jsx("div",{style:J.kpiLabel,children:g("vocalReport.intonationAccuracy","Intonation accuracy")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsxs("div",{style:{...J.kpiValue,color:gt(S.perfectHitPct)},children:[S.perfectHitPct,"%"]}),r.jsx("div",{style:J.kpiLabel,children:g("vocalReport.perfectHits","Perfect hits")})]})]}),k.length>1&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:J.sectionTitle,children:[++$,". ",g("vocalReport.playerComparison","Player comparison")]}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:"#"}),r.jsx("th",{style:J.th,children:g("vocalReport.player","Player")}),r.jsx("th",{style:J.thRight,children:g("vocalReport.classic","Classic")}),r.jsx("th",{style:J.thRight,children:g("vocalReport.bonus","Bonus")}),r.jsx("th",{style:J.thRight,children:g("vocalReport.total","Total")}),r.jsx("th",{style:J.thRight,children:g("vocalReport.intonation","Intonation")}),r.jsx("th",{style:J.thRight,children:g("vocalReport.perfect","Perfect")}),r.jsx("th",{style:J.thRight,children:g("vocalReport.range","Range")})]})}),r.jsx("tbody",{children:k.map((_,U)=>r.jsxs("tr",{children:[r.jsx("td",{style:J.td,children:U+1}),r.jsx("td",{style:{...J.tdBold,color:_.playerColor},children:_.playerName}),r.jsx("td",{style:J.tdRight,children:_.classicScore.toLocaleString()}),r.jsx("td",{style:J.tdRight,children:_.bonusScore.toLocaleString()}),r.jsx("td",{style:{...J.tdRight,fontWeight:700,color:"var(--nice-warning, #fbbf24)"},children:_.totalScore.toLocaleString()}),r.jsx("td",{style:J.tdRight,children:r.jsxs("span",{style:J.badge(gt(_.intonationAccuracyPct)),children:[_.intonationAccuracyPct,"%"]})}),r.jsx("td",{style:J.tdRight,children:r.jsxs("span",{style:J.badge(gt(_.perfectHitPct)),children:[_.perfectHitPct,"%"]})}),r.jsxs("td",{style:J.tdRight,children:[_.lowestNote,"–",_.highestNote]})]},U))})]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++$,". ",g("vocalReport.pitchAccuracy","Pitch accuracy")]}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:g("vocalReport.metric","Metric")}),r.jsx("th",{style:J.thRight,children:g("vocalReport.value","Value")}),r.jsx("th",{style:J.th,children:g("vocalReport.description","Description")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.meanAbsDev","Mean abs. deviation")}),r.jsxs("td",{style:J.tdRight,children:[S.avgCentDeviation,r.jsxs("span",{style:J.kpiUnit,children:[" ",A]})]}),r.jsx("td",{style:J.td,children:g("vocalReport.meanAbsDevDesc","Average distance from the target pitch.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.medianDev","Median deviation")}),r.jsxs("td",{style:J.tdRight,children:[S.medianCentDeviation,r.jsxs("span",{style:J.kpiUnit,children:[" ",A]})]}),r.jsx("td",{style:J.td,children:g("vocalReport.medianDevDesc","Typical deviation, robust to outliers.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.stdDev","Std. deviation")}),r.jsxs("td",{style:J.tdRight,children:[S.stdDevCents,r.jsxs("span",{style:J.kpiUnit,children:[" ",A]})]}),r.jsx("td",{style:J.td,children:g("vocalReport.stdDevDesc","Consistency of pitch (lower = steadier).")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.intonationAccuracyLabel","Intonation accuracy")}),r.jsxs("td",{style:{...J.tdRight,color:gt(S.intonationAccuracyPct)},children:[S.intonationAccuracyPct,"%"]}),r.jsx("td",{style:J.td,children:g("vocalReport.intonationAccuracyDesc","Share of frames within tolerance.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.perfectHitRate","Perfect-hit rate")}),r.jsxs("td",{style:{...J.tdRight,color:gt(S.perfectHitPct)},children:[S.perfectHitPct,"%"]}),r.jsx("td",{style:J.td,children:g("vocalReport.perfectHitRateDesc","Notes hit dead-on.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.totalPitchSamples","Total pitch samples")}),r.jsx("td",{style:J.tdRight,children:S.totalPitchPoints.toLocaleString()}),r.jsx("td",{style:J.td,children:g("vocalReport.totalPitchSamplesDesc","Number of analysed pitch frames.")})]})]})]}),r.jsxs("div",{style:J.chartWrap,children:[r.jsx("div",{style:J.chartTitle,children:g("vocalReport.deviationDistribution","Deviation distribution")}),r.jsx(Ne.ResponsiveContainer,{width:"100%",height:220,children:r.jsxs(Ne.BarChart,{data:S.pitchDeviationHistogram,margin:{top:5,right:20,bottom:5,left:20},children:[r.jsx(Ne.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),r.jsx(Ne.XAxis,{dataKey:"centRange",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:10},angle:-25,textAnchor:"end",height:50}),r.jsx(Ne.YAxis,{tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),r.jsx(Ne.Bar,{dataKey:"count",name:g("vocalReport.samples","Samples"),radius:[4,4,0,0],children:S.pitchDeviationHistogram.map((_,U)=>r.jsx(Ne.Cell,{fill:_.centRange.includes("−15 to 0")||_.centRange.includes("0 to +15")?"var(--nice-success, #22c55e)":_.centRange.includes("25")?"var(--nice-warning, #eab308)":"var(--nice-danger, #ef4444)"},U))})]})})]}),r.jsxs("div",{style:J.row,children:[r.jsxs("div",{style:{...J.chartWrap,...J.half},children:[r.jsx("div",{style:J.chartTitle,children:g("vocalReport.hitClassification","Hit classification")}),r.jsx(Ne.ResponsiveContainer,{width:"100%",height:220,children:r.jsxs(Ne.PieChart,{children:[r.jsx(Ne.Pie,{data:D,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:80,label:({name:_,value:U})=>`${_}: ${Number(U).toFixed(1)}%`,labelLine:{stroke:"var(--nice-text-muted, #64748b)"},stroke:"var(--nice-bg, #0f172a)",strokeWidth:2,children:D.map((_,U)=>r.jsx(Ne.Cell,{fill:_.fill},U))}),r.jsx(Ne.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}})]})})]}),r.jsxs("div",{style:{...J.chartWrap,...J.half},children:[r.jsx("div",{style:J.chartTitle,children:g("vocalReport.performanceProfile","Performance profile")}),r.jsx(Ne.ResponsiveContainer,{width:"100%",height:220,children:r.jsxs(Ne.RadarChart,{data:E,cx:"50%",cy:"50%",outerRadius:75,children:[r.jsx(Ne.PolarGrid,{stroke:"var(--nice-border, #334155)"}),r.jsx(Ne.PolarAngleAxis,{dataKey:"metric",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.Radar,{name:"Score",dataKey:"value",stroke:"var(--nice-info, #3b82f6)",fill:"var(--nice-info, #3b82f6)",fillOpacity:.3,strokeWidth:2})]})})]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++$,". ",g("vocalReport.pitchTracking","Pitch tracking")]}),r.jsxs("div",{style:J.chartWrap,children:[r.jsx("div",{style:J.chartTitle,children:g("vocalReport.sungVsExpected","Sung vs expected")}),r.jsx(Ne.ResponsiveContainer,{width:"100%",height:260,children:r.jsxs(Ne.LineChart,{data:Z,margin:{top:5,right:20,bottom:5,left:20},children:[r.jsx(Ne.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),r.jsx(Ne.XAxis,{dataKey:"t",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11},tickFormatter:_=>`${_.toFixed(0)}s`}),r.jsx(Ne.YAxis,{domain:["auto","auto"],tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),r.jsx(Ne.Legend,{wrapperStyle:{color:"var(--nice-text-muted, #94a3b8)",fontSize:12}}),r.jsx(Ne.Line,{type:"monotone",dataKey:"expected",name:g("vocalReport.expected","Expected"),stroke:"var(--nice-success, #22c55e)",dot:!1,strokeWidth:2,strokeOpacity:.6}),r.jsx(Ne.Line,{type:"monotone",dataKey:"sung",name:g("vocalReport.sung","Sung"),stroke:"var(--nice-info, #3b82f6)",dot:!1,strokeWidth:1.5})]})})]}),r.jsxs("div",{style:J.chartWrap,children:[r.jsx("div",{style:J.chartTitle,children:g("vocalReport.rollingAccuracy","Rolling accuracy")}),r.jsx(Ne.ResponsiveContainer,{width:"100%",height:180,children:r.jsxs(Ne.AreaChart,{data:S.accuracyOverTime,margin:{top:5,right:20,bottom:5,left:20},children:[r.jsx(Ne.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),r.jsx(Ne.XAxis,{dataKey:"t",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11},tickFormatter:_=>`${_.toFixed(0)}s`}),r.jsx(Ne.YAxis,{domain:[0,100],tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),r.jsx(Ne.Area,{type:"monotone",dataKey:"accuracy",stroke:"var(--nice-accent, #8b5cf6)",fill:"var(--nice-accent, #8b5cf6)",fillOpacity:.2,strokeWidth:2})]})})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++$,". ",g("vocalReport.vocalRange","Vocal range")]}),r.jsxs("div",{style:J.row,children:[r.jsx("div",{style:J.half,children:r.jsx("table",{style:J.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.lowestNote","Lowest note")}),r.jsxs("td",{style:J.tdRight,children:[S.lowestNote," (",S.lowestHz," Hz)"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.highestNote","Highest note")}),r.jsxs("td",{style:J.tdRight,children:[S.highestNote," (",S.highestHz," Hz)"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.rangeLabel","Range")}),r.jsxs("td",{style:J.tdRight,children:[S.rangeInSemitones," ",g("vocalReport.semitones","semitones")]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.tessitura","Tessitura")}),r.jsxs("td",{style:J.tdRight,children:[S.tessituraLow," — ",S.tessituraHigh]})]})]})})}),r.jsxs("div",{style:{...J.chartWrap,...J.half},children:[r.jsx("div",{style:J.chartTitle,children:g("vocalReport.chromagram","Chromagram")}),r.jsx(Ne.ResponsiveContainer,{width:"100%",height:180,children:r.jsxs(Ne.BarChart,{data:L,margin:{top:5,right:10,bottom:5,left:10},children:[r.jsx(Ne.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),r.jsx(Ne.XAxis,{dataKey:"note",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.YAxis,{tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),r.jsx(Ne.Bar,{dataKey:"pct",name:g("vocalReport.usagePct","Usage %"),radius:[4,4,0,0],fill:"var(--nice-primary, #6366f1)"})]})})]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++$,". ",g("vocalReport.vibratoStability","Vibrato & stability")]}),r.jsxs("div",{style:J.row,children:[r.jsx("div",{style:J.half,children:r.jsx("table",{style:J.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.vibratoDetected","Vibrato detected")}),r.jsx("td",{style:J.tdRight,children:r.jsx("span",{style:J.badge(S.vibrato.detected?"var(--nice-success, #22c55e)":"var(--nice-text-muted, #64748b)"),children:S.vibrato.detected?g("vocalReport.yes","Yes"):g("vocalReport.no","No")})})]}),S.vibrato.detected&&r.jsxs(r.Fragment,{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.avgRate","Avg. rate")}),r.jsxs("td",{style:J.tdRight,children:[S.vibrato.avgRateHz," Hz"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.avgExtent","Avg. extent")}),r.jsxs("td",{style:J.tdRight,children:["±",S.vibrato.avgExtentCents," ",A]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.regularity","Regularity")}),r.jsxs("td",{style:J.tdRight,children:[S.vibrato.regularityPct,"%"]})]})]})]})})}),r.jsx("div",{style:J.half,children:r.jsx("table",{style:J.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.jitter","Jitter")}),r.jsxs("td",{style:J.tdRight,children:[S.jitterPct,"%"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.vocalPresence","Vocal presence")}),r.jsxs("td",{style:J.tdRight,children:[S.shimmerProxy,"%"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.avgOnsetDev","Avg. onset deviation")}),r.jsxs("td",{style:J.tdRight,children:[S.avgOnsetDeviationMs," ms"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.rhythmStability","Rhythm stability")}),r.jsx("td",{style:J.tdRight,children:r.jsxs("span",{style:J.badge(gt(S.rhythmStabilityPct)),children:[S.rhythmStabilityPct,"%"]})})]})]})})})]}),S.verseMetrics.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:J.sectionTitle,children:[++$,". ",g("vocalReport.verseBreakdown","Per-verse breakdown")]}),r.jsxs("div",{style:J.chartWrap,children:[r.jsx("div",{style:J.chartTitle,children:g("vocalReport.accuracyByVerse","Accuracy by verse")}),r.jsx(Ne.ResponsiveContainer,{width:"100%",height:200,children:r.jsxs(Ne.BarChart,{data:W,margin:{top:5,right:20,bottom:5,left:20},children:[r.jsx(Ne.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),r.jsx(Ne.XAxis,{dataKey:"verse",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.YAxis,{domain:[0,100],tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),r.jsx(Ne.Bar,{dataKey:"accuracy",name:g("vocalReport.hitPct","Hit %"),radius:[4,4,0,0],children:W.map((_,U)=>r.jsx(Ne.Cell,{fill:Vs(_.label)},U))})]})})]}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:g("vocalReport.verse","Verse")}),r.jsx("th",{style:J.th,children:g("vocalReport.rating","Rating")}),r.jsx("th",{style:J.thRight,children:g("vocalReport.hitPct","Hit %")}),r.jsx("th",{style:J.thRight,children:g("vocalReport.avgDeviation","Avg. dev.")}),r.jsx("th",{style:J.thRight,children:g("vocalReport.notes","Notes")}),r.jsx("th",{style:J.thRight,children:g("vocalReport.notesHit","Hit")}),r.jsx("th",{style:J.thRight,children:g("vocalReport.comboBonus","Combo bonus")})]})}),r.jsx("tbody",{children:S.verseMetrics.map((_,U)=>r.jsxs("tr",{children:[r.jsxs("td",{style:J.td,children:[g("vocalReport.verse","Verse")," ",_.verseIndex+1]}),r.jsx("td",{style:J.td,children:r.jsx("span",{style:J.badge(Vs(_.label)),children:_.label})}),r.jsxs("td",{style:J.tdRight,children:[(_.hitFraction*100).toFixed(1),"%"]}),r.jsxs("td",{style:J.tdRight,children:[_.avgCentDeviation," ¢"]}),r.jsx("td",{style:J.tdRight,children:_.noteCount}),r.jsx("td",{style:J.tdRight,children:_.notesHit}),r.jsxs("td",{style:J.tdRight,children:["+",_.comboBonus]})]},U))})]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++$,". ",g("vocalReport.scoringConfig","Scoring configuration")]}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:g("vocalReport.parameter","Parameter")}),r.jsx("th",{style:J.thRight,children:g("vocalReport.value","Value")}),r.jsx("th",{style:J.th,children:g("vocalReport.description","Description")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.difficultyLevel","Difficulty level")}),r.jsx("td",{style:J.tdRight,children:S.difficulty}),r.jsx("td",{style:J.td,children:g("vocalReport.difficultyLevelDesc","Affects tolerance and multiplier.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.semitoneTolerance","Semitone tolerance")}),r.jsx("td",{style:J.tdRight,children:R.semitoneTolerance}),r.jsx("td",{style:J.td,children:g("vocalReport.semitoneToleranceDesc","Pitch window counted as a hit.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.preWindow","Pre window")}),r.jsxs("td",{style:J.tdRight,children:[R.preWindow," s"]}),r.jsx("td",{style:J.td,children:g("vocalReport.preWindowDesc","Lead-in time before a note.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.postExtra","Post extra")}),r.jsxs("td",{style:J.tdRight,children:[R.postExtra," s"]}),r.jsx("td",{style:J.td,children:g("vocalReport.postExtraDesc","Grace time after a note.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.difficultyMultiplier","Difficulty multiplier")}),r.jsxs("td",{style:J.tdRight,children:[R.difficultyMult,"×"]}),r.jsx("td",{style:J.td,children:g("vocalReport.difficultyMultiplierDesc","Score scaling for difficulty.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.songBpm","Song BPM")}),r.jsx("td",{style:J.tdRight,children:S.songBpm}),r.jsx("td",{style:J.td,children:g("vocalReport.songBpmDesc","Tempo used for note timing.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.totalNotes","Total notes")}),r.jsx("td",{style:J.tdRight,children:x.length}),r.jsx("td",{style:J.td,children:g("vocalReport.totalNotesDesc","Number of scored notes in the song.")})]})]})]}),k.some(_=>_.micSettings)&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:J.sectionTitle,children:[++$,". ",g("vocalReport.micConfig","Microphone configuration")]}),k.map((_,U)=>_.micSettings&&r.jsxs("div",{style:{marginBottom:16},children:[k.length>1&&r.jsx("h4",{style:{color:_.playerColor,margin:"0 0 8px",fontSize:14},children:_.playerName}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:g("vocalReport.setting","Setting")}),r.jsx("th",{style:J.thRight,children:g("vocalReport.value","Value")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.device","Device")}),r.jsx("td",{style:J.tdRight,children:_.micSettings.deviceLabel||_.micSettings.deviceId})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.pitchAlgorithm","Pitch algorithm")}),r.jsx("td",{style:J.tdRight,children:_.micSettings.algorithm})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.inputGain","Input gain")}),r.jsxs("td",{style:J.tdRight,children:[_.micSettings.gain,"×"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.rmsThreshold","RMS threshold")}),r.jsx("td",{style:J.tdRight,children:_.micSettings.rmsThreshold})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.pitchThreshold","Pitch threshold")}),r.jsx("td",{style:J.tdRight,children:_.micSettings.pitchThreshold})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.smoothingWindow","Smoothing window")}),r.jsxs("td",{style:J.tdRight,children:[_.micSettings.smoothingWindow," ",g("vocalReport.frames","frames")]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.hysteresisFrames","Hysteresis frames")}),r.jsx("td",{style:J.tdRight,children:_.micSettings.hysteresisFrames})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.hanningWindow","Hanning window")}),r.jsx("td",{style:J.tdRight,children:_.micSettings.useHanning?g("vocalReport.enabled","Enabled"):g("vocalReport.disabled","Disabled")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.latencyOffset","Latency offset")}),r.jsxs("td",{style:J.tdRight,children:[_.micSettings.latencyOffsetMs," ms"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:g("vocalReport.monitor","Monitor")}),r.jsx("td",{style:J.tdRight,children:_.micSettings.monitorEnabled?`${g("vocalReport.on","On")} (${Math.round(_.micSettings.monitorVolume*100)}%)`:g("vocalReport.off","Off")})]})]})]})]},U))]}),r.jsx("div",{style:J.footer,children:r.jsxs("p",{children:[g("vocalReport.footerGenerated","Report generated")," ·"," ",S.timestamp.replace(/[-:T.Z]/g,"").slice(0,14)]})})]})]})},Bh="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100'%3E%3Crect width='100' height='100' fill='%23334155'/%3E%3Ccircle cx='42' cy='64' r='8' fill='%2394a3b8'/%3E%3Crect x='48' y='34' width='3' height='32' fill='%2394a3b8'/%3E%3C/svg%3E";function Gh(e){if(!e)return"";const t=Math.floor(e/60),n=Math.round(e%60);return`${t}:${n.toString().padStart(2,"0")}`}function Hs(e){return Array.from(new Set(e.filter(t=>!!t))).sort((t,n)=>t.localeCompare(n))}const Uo=d.memo(({song:e,index:t,active:n,coverUrl:a,topScore:s,selected:i,multiSelect:o,disabled:l,t:c,onPlay:u,onToggleSelect:h,onFocusRow:p})=>{const f=()=>{o?h(e.id):l||u==null||u(e)};return r.jsxs("div",{className:`nice-ksb-row${i?" nice-ksb-row--selected":""}${n?" nice-ksb-row--active":""}`,role:"option","aria-selected":i,"data-ksb-index":t,tabIndex:n?0:-1,onClick:f,onFocus:()=>p(t),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),f())},children:[o&&r.jsx("input",{type:"checkbox",className:"nice-ksb-row__check",checked:i,onChange:()=>h(e.id),onClick:y=>y.stopPropagation(),"aria-label":e.title}),r.jsx("img",{className:"nice-ksb-row__cover",src:a,alt:"",loading:"lazy"}),r.jsxs("div",{className:"nice-ksb-row__main",children:[r.jsx("div",{className:"nice-ksb-row__title",children:e.title}),r.jsx("div",{className:"nice-ksb-row__artist",children:e.artist||"—"})]}),r.jsxs("div",{className:"nice-ksb-row__meta",children:[e.genre&&r.jsx("span",{className:"nice-ksb-badge",children:e.genre}),e.year&&r.jsx("span",{className:"nice-ksb-badge",children:e.year}),e.durationSec?r.jsx("span",{className:"nice-ksb-badge",children:Gh(e.durationSec)}):null,e.externalSource&&r.jsx("span",{className:"nice-ksb-badge nice-ksb-badge--src",children:e.externalSource}),s&&r.jsxs("span",{className:"nice-ksb-badge nice-ksb-badge--score",title:s.playerName,children:[r.jsx(se.NtdTrophy,{size:11})," ",s.score.toLocaleString()]})]}),!o&&r.jsxs("button",{type:"button",className:"nice-ksb-row__play",disabled:l,onClick:y=>{y.stopPropagation(),u==null||u(e)},children:[r.jsx(se.NtdPlay,{size:13})," ",c("karaokeBrowser.play","Play")]})]})});Uo.displayName="NiceKaraokeSongRow";const Wh=({songs:e,fetchSongs:t,loading:n=!1,getCover:a,getTopScore:s,onPlay:i,onSelect:o,multiSelect:l=!1,maxSelections:c=0,showSidebar:u=!0,enableGamepad:h=!0,disabled:p=!1,disabledReason:f,t:y,className:m,style:g,id:b,accessMode:x,"data-testid":k})=>{const{t:v}=Te(),w=y??v,[M,S]=d.useState(""),[R,T]=d.useState(""),[j,O]=d.useState(""),[$,E]=d.useState(""),[D,L]=d.useState("artist"),[W,Z]=d.useState("asc"),[A,_]=d.useState({type:"all"}),[U,ne]=d.useState(new Set),[V,q]=d.useState([]),[C,F]=d.useState(!1);d.useEffect(()=>{const ce=setTimeout(()=>T(M),300);return()=>clearTimeout(ce)},[M]),d.useEffect(()=>{if(e||!t)return;let ce=!1;return F(!0),Promise.resolve(t({searchQuery:R.trim()||void 0,genres:j?[j]:void 0,languages:$?[$]:void 0})).then(ye=>!ce&&q(ye)).catch(()=>!ce&&q([])).finally(()=>!ce&&F(!1)),()=>{ce=!0}},[e,t,R,j,$]);const I=e??V,P=d.useMemo(()=>Hs(I.map(ce=>ce.genre)),[I]),N=d.useMemo(()=>Hs(I.map(ce=>ce.language)),[I]),z=d.useMemo(()=>{let ce=I;const ye=R.trim().toLowerCase();ye&&(ce=ce.filter(ae=>`${ae.title} ${ae.artist}`.toLowerCase().includes(ye))),j&&(ce=ce.filter(ae=>ae.genre===j)),$&&(ce=ce.filter(ae=>ae.language===$)),A.type==="genre"&&(ce=ce.filter(ae=>ae.genre===A.value)),A.type==="language"&&(ce=ce.filter(ae=>ae.language===A.value));const Se=W==="asc"?1:-1;return[...ce].sort((ae,ue)=>{const Ie=ae[D]??"",ze=ue[D]??"";return typeof Ie=="number"&&typeof ze=="number"?(Ie-ze)*Se:String(Ie).localeCompare(String(ze))*Se})},[I,R,j,$,A,D,W]),B=ce=>{ne(ye=>{const Se=new Set(ye);return Se.has(ce)?Se.delete(ce):(c===0||Se.size<c)&&Se.add(ce),Se})},G=()=>{const ce=I.filter(ye=>U.has(ye.id));o==null||o({songs:ce})},Y=n||C,X=ce=>{ce===D?Z(ye=>ye==="asc"?"desc":"asc"):(L(ce),Z("asc"))},ie=d.useRef(null),[le,te]=d.useState(0),H=d.useRef(0),K=d.useRef(z);K.current=z,d.useEffect(()=>{te(ce=>{const ye=Math.min(Math.max(0,ce),Math.max(0,z.length-1));return H.current=ye,ye})},[z.length]);const oe=d.useCallback(ce=>{var Se;const ye=(Se=ie.current)==null?void 0:Se.querySelector(`[data-ksb-index="${ce}"]`);ye==null||ye.focus(),ye==null||ye.scrollIntoView({block:"nearest"})},[]),re=d.useCallback(ce=>{H.current=ce,te(ce)},[]),he=d.useCallback((ce,ye=!0)=>{const Se=K.current.length;if(Se===0)return;const ae=Math.min(Se-1,Math.max(0,ce));H.current=ae,te(ae),ye&&requestAnimationFrame(()=>oe(ae))},[oe]),Q=d.useCallback(ce=>he(H.current+ce),[he]),de=ce=>{const ye=K.current[ce];ye&&(l?B(ye.id):p||i==null||i(ye))},me=ce=>{switch(ce.key){case"ArrowDown":ce.preventDefault(),Q(1);break;case"ArrowUp":ce.preventDefault(),Q(-1);break;case"Home":ce.preventDefault(),he(0);break;case"End":ce.preventDefault(),he(K.current.length-1);break;case"PageDown":ce.preventDefault(),Q(5);break;case"PageUp":ce.preventDefault(),Q(-5);break}},xe=aa.useGamepad({enabled:h,actions:{navUp:{button:"DpadUp",onPress:()=>Q(-1),repeatDelay:350,repeatRate:110},navDown:{button:"DpadDown",onPress:()=>Q(1),repeatDelay:350,repeatRate:110},stickUp:{axis:"LeftY",axisDirection:"negative",onPress:()=>Q(-1),repeatDelay:350,repeatRate:130},stickDown:{axis:"LeftY",axisDirection:"positive",onPress:()=>Q(1),repeatDelay:350,repeatRate:130},select:{button:"A",onPress:()=>de(H.current)},confirm:{button:"Start",onPress:()=>{l&&G()}}}});return x==="hidden"?null:r.jsxs("div",{className:`nice-ksb${m?` ${m}`:""}`,style:g,id:b,"data-testid":k,children:[u&&r.jsxs("aside",{className:"nice-ksb__sidebar",children:[r.jsxs("button",{type:"button",className:`nice-ksb__node${A.type==="all"?" nice-ksb__node--active":""}`,onClick:()=>_({type:"all"}),children:[r.jsx(se.NtdMusic,{size:14})," ",w("karaokeBrowser.allSongs","All songs")," (",I.length,")"]}),P.length>0&&r.jsxs("div",{className:"nice-ksb__facet",children:[r.jsx("div",{className:"nice-ksb__facet-title",children:w("karaokeBrowser.genres","Genres")}),P.map(ce=>r.jsx("button",{type:"button",className:`nice-ksb__node${A.type==="genre"&&A.value===ce?" nice-ksb__node--active":""}`,onClick:()=>_({type:"genre",value:ce}),children:ce},ce))]}),N.length>0&&r.jsxs("div",{className:"nice-ksb__facet",children:[r.jsx("div",{className:"nice-ksb__facet-title",children:w("karaokeBrowser.languages","Languages")}),N.map(ce=>r.jsx("button",{type:"button",className:`nice-ksb__node${A.type==="language"&&A.value===ce?" nice-ksb__node--active":""}`,onClick:()=>_({type:"language",value:ce}),children:ce},ce))]})]}),r.jsxs("div",{className:"nice-ksb__main",children:[r.jsxs("div",{className:"nice-ksb__toolbar",children:[r.jsx("input",{className:"nice-ksb__search",type:"search",value:M,placeholder:w("karaokeBrowser.search","Search title or artist…"),onChange:ce=>S(ce.target.value)}),r.jsx("div",{className:"nice-ksb__sort",children:["artist","title","year","genre"].map(ce=>r.jsxs("button",{type:"button",className:`nice-ksb__sort-btn${D===ce?" nice-ksb__sort-btn--active":""}`,onClick:()=>X(ce),children:[w(`karaokeBrowser.sort.${ce}`,ce),D===ce&&(W==="asc"?r.jsx(se.NtdChevronUp,{size:12}):r.jsx(se.NtdChevronDown,{size:12}))]},ce))}),r.jsxs("span",{className:`nice-ksb__navhint${xe.connected?" nice-ksb__navhint--pad":""}`,title:w("karaokeBrowser.navHint","Navigate with ↑ ↓ or the D-pad · Enter / A to play"),children:[xe.connected?r.jsx(se.NtdGamepad,{size:14}):r.jsx(se.NtdMove,{size:14}),r.jsx("span",{className:"nice-ksb__navhint-keys",children:xe.connected?"D-pad · A":"↑ ↓ · Enter"})]})]}),p&&f&&r.jsx("div",{className:"nice-ksb__disabled",children:f}),r.jsx("div",{className:"nice-ksb__list",role:"listbox","aria-multiselectable":l,"aria-label":w("karaokeBrowser.songs","Songs"),ref:ie,onKeyDown:me,children:Y?r.jsx("div",{className:"nice-ksb__empty",children:w("karaokeBrowser.loading","Loading…")}):z.length===0?r.jsx("div",{className:"nice-ksb__empty",children:w("karaokeBrowser.noResults","No songs found")}):z.map((ce,ye)=>r.jsx(Uo,{song:ce,index:ye,active:ye===le,coverUrl:(a==null?void 0:a(ce))||ce.coverImage||ce.externalCoverUrl||ce.coverPath||Bh,topScore:s==null?void 0:s(ce),selected:U.has(ce.id),multiSelect:l,disabled:p,t:w,onPlay:i,onToggleSelect:B,onFocusRow:re},ce.id))}),l&&r.jsxs("div",{className:"nice-ksb__footer",children:[r.jsxs("span",{children:[U.size,c>0?` / ${c}`:""," ",w("karaokeBrowser.selected","selected")]}),r.jsx("button",{type:"button",className:"nice-ksb__confirm",disabled:U.size===0,onClick:G,children:w("karaokeBrowser.confirm","Add selected")})]})]})]})};function qo(e,t,n=50,a=30){const s=Math.round(e/1e3*t),i=Math.round(n/1e3*t),o=Math.max(1,Math.round(a/1e3*t)),l=new Float32Array(s);for(let c=0;c<o;c++){const u=.5*(1-Math.cos(2*Math.PI*c/(o-1))),h=i+c-Math.floor(o/2);h>=0&&h<s&&(l[h]=u)}return l}function Ks(e,t,n=1e3){const a=Math.max(1,Math.round(t/n)),s=Math.ceil(e.length/a),i=new Float32Array(s);for(let l=0;l<s;l++){const c=l*a,u=Math.min(e.length,c+a);let h=0;for(let p=c;p<u;p++)h+=Math.abs(e[p]);i[l]=h/(u-c||1)}let o=0;for(let l=0;l<i.length;l++)i[l]>o&&(o=i[l]);if(o>0)for(let l=0;l<i.length;l++)i[l]=i[l]/o;return{env:i,factor:a}}function Uh(e,t){const n=e.length,a=t.length;if(n===0||a===0)return 0;let s={lag:0,score:-1/0};const i=Math.min(2e3,a);for(let o=-i;o<=i;o++){let l=0,c=0,u=0;for(let f=0;f<n;f++){const y=f+o+Math.floor((a-n)/2);if(y<0||y>=a)continue;const m=e[f],g=t[y];l+=m*g,c+=m*m,u+=g*g}const h=Math.sqrt(Math.max(1e-9,c*u)),p=l/h;p>s.score&&(s={lag:o,score:p})}return s.lag}function Vo(e,t,n=50,a=30){try{const s=Math.max(300,Math.round(e.length/t*1e3)),i=qo(s,t,n,a),o=Ks(e,t,1e3),l=Ks(i,t,1e3),u=Uh(l.env,o.env)*1e3/1e3;return Math.round(u)}catch{return null}}const qh=({deviceId:e,initialOffsetMs:t=null,onSave:n,onClose:a,rounds:s=3,t:i,className:o,style:l,id:c,accessMode:u,"data-testid":h})=>{const{t:p}=Te(),f=i??p,[y,m]=d.useState(null),[g,b]=d.useState(t),[x,k]=d.useState(!1),[v,w]=d.useState([]),[M,S]=d.useState(0),[R,T]=d.useState(!1),j=d.useRef(!1);d.useEffect(()=>{b(t??null)},[t,e]);const O=async()=>{const L=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),W=new AudioContext,Z=W.sampleRate,A=W.createMediaStreamSource(L),_=W.createScriptProcessor(2048,1,1);A.connect(_),_.connect(W.destination);const U=1200,ne=Math.round(U/1e3*Z),V=new Float32Array(ne);let q=0,C=!1;_.onaudioprocess=B=>{if(C)return;const G=B.inputBuffer.getChannelData(0),Y=Math.min(G.length,ne-q);Y>0&&(V.set(G.subarray(0,Y),q),q+=Y),q>=ne&&(C=!0)},await new Promise(B=>setTimeout(B,80));const F=new AudioContext,I=F.createOscillator(),P=F.createGain();I.type="sine",I.frequency.value=1e3,P.gain.value=1e-4,I.connect(P),P.connect(F.destination);const N=F.currentTime+.05;P.gain.setValueAtTime(1e-4,N-.01),P.gain.linearRampToValueAtTime(1,N),P.gain.linearRampToValueAtTime(1e-4,N+.06),I.start(N-.02),I.stop(N+.1),await new Promise(B=>{const G=()=>{if(C||q>=ne){B();return}setTimeout(G,50)};setTimeout(()=>{C=!0,B()},U+500),G()}),_.onaudioprocess=null;try{_.disconnect()}catch{}try{A.disconnect()}catch{}try{await F.close()}catch{}try{await W.close()}catch{}L.getTracks().forEach(B=>B.stop());const z=V.subarray(0,q);return Vo(z,Z,130,30)},$=async()=>{if(!j.current){j.current=!0,T(!0),m(f("latencyCalibrator.requestingMic","Requesting microphone — click allow if prompted")),b(null),w([]),S(0);try{const L=[];for(let Z=0;Z<s;Z++){m(`${f("latencyCalibrator.playingTone","Playing test tone and recording…")} (${Z+1}/${s})`),S(Math.round(Z/s*100));const A=await O();A!==null&&(L.push(Math.max(-500,Math.min(2e3,Math.round(A)))),w([...L])),Z<s-1&&await new Promise(_=>setTimeout(_,400))}if(S(100),L.length===0){m(f("latencyCalibrator.noSignal","No signal detected — try louder or check the microphone"));return}let W;if(L.length>=3){const A=[...L].sort((_,U)=>_-U).slice(1,-1);W=Math.round(A.reduce((_,U)=>_+U,0)/A.length)}else W=Math.round(L.reduce((Z,A)=>Z+A,0)/L.length);b(W),m(`${f("latencyCalibrator.measured","Measured")} ~${W} ms (${L.length}: ${L.join(", ")} ms)`)}catch(L){m(`${f("latencyCalibrator.calibrationError","Calibration error: ")}${L instanceof Error?L.message:String(L)}`)}finally{j.current=!1,T(!1)}}},E=async()=>{if(!(g===null||!n)){k(!0);try{await n(Math.round(g)),m(f("latencyCalibrator.saved","Saved"))}catch(L){m(`${f("latencyCalibrator.saveError","Save error: ")}${String(L)}`)}finally{k(!1)}}},D={padding:"7px 16px",border:"none",borderRadius:8,cursor:"pointer",fontWeight:600};return u==="hidden"?null:r.jsxs("div",{className:`nice-latency-calibrator${o?` ${o}`:""}`,style:{padding:12,color:"var(--nice-text, inherit)",...l},id:c,"data-testid":h,children:[r.jsxs("h5",{style:{margin:"0 0 8px",display:"flex",alignItems:"center",gap:6},children:[r.jsx(se.NtdSettings,{size:16})," ",f("latencyCalibrator.title","Latency calibrator — microphone")]}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:[f("latencyCalibrator.device","Device"),": ",r.jsx("small",{children:e||"—"})]}),r.jsxs("div",{style:{marginTop:8,display:"flex",gap:8},children:[r.jsx("button",{type:"button",onClick:$,disabled:R,style:{...D,background:"var(--nice-accent, #3b82f6)",color:"var(--nice-bg, #fff)"},children:f("latencyCalibrator.calibrate","Calibrate")}),r.jsx("button",{type:"button",onClick:()=>{b(null),m(null),w([]),S(0)},style:{...D,background:"var(--bg-tertiary)",color:"var(--nice-text, #e2e8f0)"},children:f("latencyCalibrator.clear","Clear")})]}),R&&r.jsx("div",{style:{marginTop:8,height:6,borderRadius:3,background:"var(--bg-tertiary)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${M}%`,background:"var(--nice-accent, #3b82f6)",transition:"width 0.2s"}})}),v.length>0&&r.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:[f("latencyCalibrator.rounds","Rounds"),": ",v.join(", ")," ms"]}),r.jsxs("div",{style:{marginTop:8,fontSize:13},children:[r.jsxs("div",{children:[f("latencyCalibrator.status","Status"),": ",y??f("latencyCalibrator.none","none")]}),r.jsxs("div",{children:[f("latencyCalibrator.measuredOffset","Measured offset"),":"," ",g!==null?r.jsxs("strong",{children:[g," ms"]}):"—"]})]}),r.jsxs("div",{style:{marginTop:12,display:"flex",gap:8},children:[n&&r.jsx("button",{type:"button",onClick:E,disabled:g===null||x,style:{...D,background:"var(--nice-success, #22c55e)",color:"var(--nice-bg, #fff)",opacity:g===null||x?.5:1},children:f("latencyCalibrator.save","Save")}),a&&r.jsx("button",{type:"button",onClick:a,style:{...D,background:"transparent",border:"1px solid var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)"},children:f("latencyCalibrator.close","Close")})]})]})},Vh=[{value:"normal",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(se.NtdMicrophone,{size:14})," Mic"]})},{value:"pad",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(se.NtdGamepad,{size:14})," Pad"]})},{value:"demo",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(se.NtdStopwatch,{size:14})," Demo"]})}],Ho=({players:e,onPlayersChange:t,gameMode:n="normal",onGameModeChange:a,gameModes:s=Vh,difficulty:i="normal",onDifficultyChange:o,audioInputs:l,maxPlayers:c=4,onCalibrate:u,t:h,className:p,style:f,id:y,accessMode:m,"data-testid":g})=>{const{t:b}=Te(),x=h??b,[k,v]=d.useState([]);d.useEffect(()=>{var $,E,D;if(l||!(($=navigator.mediaDevices)!=null&&$.enumerateDevices))return;let j=!1;const O=()=>navigator.mediaDevices.enumerateDevices().then(L=>!j&&v(L.filter(W=>W.kind==="audioinput"))).catch(()=>{});return O(),(D=(E=navigator.mediaDevices).addEventListener)==null||D.call(E,"devicechange",O),()=>{var L,W;j=!0,(W=(L=navigator.mediaDevices).removeEventListener)==null||W.call(L,"devicechange",O)}},[l]);const w=l??k,M=d.useMemo(()=>[{value:"",label:x("karaokeSetup.noMic","No microphone")},...w.map((j,O)=>({value:j.deviceId,label:j.label||`${x("karaokeSetup.microphone","Microphone")} ${O+1}`}))],[w,x]),S=(j,O)=>t(e.map($=>$.id===j?{...$,...O}:$)),R=()=>{if(e.length>=c)return;const j=e.reduce((O,$)=>Math.max(O,$.id),0)+1;t([...e,{id:j,name:`${x("karaokeSetup.player","Player")} ${e.length+1}`,color:Je[e.length%Je.length],micId:null}])},T=j=>t(e.filter(O=>O.id!==j));return m==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-setup${p?` ${p}`:""}`,style:{display:"flex",flexDirection:"column",gap:16,...f},id:y,"data-testid":g,children:[r.jsxs("div",{style:{display:"flex",gap:24,flexWrap:"wrap"},children:[r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:12,fontWeight:600,marginBottom:6,color:"var(--nice-text-muted, #94a3b8)"},children:x("karaokeSetup.mode","Game mode")}),r.jsx(we.NiceSegmentedControl,{options:s,value:n,onChange:j=>a==null?void 0:a(j)})]}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:12,fontWeight:600,marginBottom:6,color:"var(--nice-text-muted, #94a3b8)"},children:x("karaokeSetup.difficulty","Difficulty")}),r.jsx(we.NiceSegmentedControl,{options:[{value:"easy",label:x("karaokeSetup.easy","Easy")},{value:"normal",label:x("karaokeSetup.normal","Normal")},{value:"hard",label:x("karaokeSetup.hard","Hard")}],value:i,onChange:j=>o==null?void 0:o(j)})]})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[r.jsxs("div",{style:{fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:[x("karaokeSetup.players","Players")," (",e.length,"/",c,")"]}),e.map(j=>r.jsx(we.NiceCard,{children:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[r.jsx(we.NiceColorPicker,{value:j.color||Je[0],onChange:O=>S(j.id,{color:O})}),r.jsx("div",{style:{flex:"1 1 160px",minWidth:140},children:r.jsx(we.NiceTextInput,{value:j.name,onChange:O=>S(j.id,{name:O}),placeholder:x("karaokeSetup.playerName","Player name"),size:"sm"})}),r.jsx("div",{style:{flex:"1 1 180px",minWidth:150},children:r.jsx(we.NiceSelect,{options:M,value:j.micId??"",onChange:O=>S(j.id,{micId:(typeof O=="string"?O:O[0])||null}),placeholder:x("karaokeSetup.selectMic","Microphone"),size:"sm"})}),u&&j.micId&&r.jsxs(we.NiceButton,{variant:"ghost",size:"sm",onClick:()=>u(j.micId),children:[r.jsx(se.NtdSettings,{size:14})," ",x("karaokeSetup.calibrate","Calibrate")]}),r.jsx(we.NiceButton,{variant:"danger",size:"sm",onClick:()=>T(j.id),"aria-label":x("karaokeSetup.remove","Remove"),children:r.jsx(se.NtdClose,{size:14})})]})},j.id)),r.jsx("div",{children:r.jsxs(we.NiceButton,{variant:"primary",onClick:R,disabled:e.length>=c,children:[r.jsx(se.NtdPlus,{size:14})," ",x("karaokeSetup.addPlayer","Add player")]})})]})]})},Hh=["freeForAll","roundRobin","hostOnly","firstCome"],Kh={freeForAll:se.NtdDice,roundRobin:se.NtdRepeat,hostOnly:se.NtdCrown,firstCome:se.NtdLightning},Yh={freeForAll:"success",roundRobin:"warning",hostOnly:"info",firstCome:"danger"},Ko=({players:e,mode:t,onModeChange:n,turnTimeSec:a=30,hostIndex:s=0,onActivePlayerChange:i,myPlayerIndex:o,t:l,className:c,style:u,id:h,accessMode:p,"data-testid":f})=>{const{t:y}=Te(),m=l??y,g={freeForAll:m("songSelection.freeForAll","Free for all"),roundRobin:m("songSelection.roundRobin","Round robin"),hostOnly:m("songSelection.hostOnly","Host only"),firstCome:m("songSelection.firstCome","First come")},[b,x]=d.useState(0),[k,v]=d.useState(a),w=d.useRef(null),[M,S]=d.useState(null),[R,T]=d.useState(!1),[j,O]=d.useState(null),$=d.useRef(null),E=d.useMemo(()=>t==="hostOnly"?s:t==="roundRobin"?b%Math.max(1,e.length):t==="firstCome"?R?-1:j??-1:-1,[t,b,e.length,s,R,j]);d.useEffect(()=>{i==null||i(E)},[E,i]),d.useEffect(()=>{if(t!=="roundRobin"||a<=0){w.current&&clearInterval(w.current);return}return v(a),w.current=setInterval(()=>{v(A=>A<=1?(x(_=>_+1),a):A-1)},1e3),()=>{w.current&&clearInterval(w.current)}},[t,a,b]);const D=d.useCallback(()=>{O(null),T(!1),S(3),$.current&&clearInterval($.current),$.current=setInterval(()=>{S(A=>A===null||A<=1?($.current&&clearInterval($.current),T(!0),null):A-1)},1e3)},[]);d.useEffect(()=>()=>{$.current&&clearInterval($.current)},[]),d.useEffect(()=>{t!=="firstCome"&&(S(null),T(!1),O(null))},[t]);const L=d.useCallback(()=>{x(A=>A+1),v(a)},[a]),W=A=>{var _;return((_=e[A])==null?void 0:_.name)||`${m("songSelection.player","Player")} ${A+1}`},Z=E>=0&&E<e.length?e[E]:null;return p==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-selection-mode${c?` ${c}`:""}`,style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,padding:"8px 12px",background:"var(--bg-secondary)",borderRadius:10,border:"1px solid var(--nice-border, #333)",...u},id:h,"data-testid":f,children:[r.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:Hh.map(A=>r.jsxs(we.NiceButton,{size:"sm",variant:t===A?Yh[A]:"outline",onClick:()=>n==null?void 0:n(A),children:[d.createElement(Kh[A],{size:14})," ",g[A]]},A))}),t!=="freeForAll"&&t!=="firstCome"&&Z&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsxs(we.NiceBadge,{variant:E===o?"success":"secondary",children:[r.jsx(se.NtdMicrophone,{size:12})," ",W(E)]}),E===o&&r.jsx("span",{style:{color:"var(--nice-success, #4caf50)",fontSize:12,fontWeight:600},children:m("songSelection.yourTurn","Your turn!")})]}),t==="roundRobin"&&a>0&&r.jsx("div",{style:{flex:1,minWidth:120,maxWidth:200},children:r.jsx(we.NiceProgress,{value:k,max:a,variant:k<=5?"error":k<=10?"warning":"info",showLabel:!0,formatValue:A=>`${A}s`})}),t==="roundRobin"&&r.jsxs(we.NiceButton,{size:"sm",variant:"ghost",onClick:L,children:[m("songSelection.next","Next")," ",r.jsx(se.NtdPlay,{size:12})]}),t==="firstCome"&&r.jsxs(r.Fragment,{children:[M!==null&&r.jsx("div",{style:{fontSize:32,fontWeight:900,color:"var(--nice-error, #f44336)",minWidth:60,textAlign:"center"},children:M}),R&&j===null&&r.jsxs(we.NiceBadge,{variant:"danger",children:[r.jsx(se.NtdLightning,{size:12})," ",m("songSelection.raceGo","GO! Pick a song!")]}),j!==null&&j<e.length&&r.jsxs(we.NiceBadge,{variant:"success",children:[r.jsx(se.NtdTrophy,{size:12})," ",W(j)," ",m("songSelection.raceWon","picks!")]}),r.jsx(we.NiceButton,{size:"sm",variant:M!==null?"secondary":"danger",onClick:D,disabled:M!==null,children:j!==null?r.jsxs(r.Fragment,{children:[r.jsx(se.NtdRepeat,{size:12})," ",m("songSelection.raceAgain","New race")]}):r.jsxs(r.Fragment,{children:[r.jsx(se.NtdLightning,{size:12})," ",m("songSelection.raceStart","Start race")]})})]})]})};function Zh(e,t,n,a){return d.useMemo(()=>e==="freeForAll"?!0:e==="firstCome"?t===-1:e==="hostOnly"?a===n:e==="roundRobin"?a===t:!1,[e,t,n,a])}const Xh=({players:e,onPlayersChange:t,gameMode:n,onGameModeChange:a,gameModes:s,difficulty:i,onDifficultyChange:o,audioInputs:l,maxPlayers:c=4,onCalibrate:u,initialSelectionMode:h="freeForAll",turnTimeSec:p=30,hostIndex:f=0,myPlayerIndex:y,onChange:m,variant:g="bar",t:b,className:x,style:k,id:v,accessMode:w,"data-testid":M})=>{const{t:S}=Te(),R=b??S,[T,j]=d.useState([]);d.useEffect(()=>{var F,I,P;if(l||!((F=navigator.mediaDevices)!=null&&F.enumerateDevices))return;let q=!1;const C=()=>navigator.mediaDevices.enumerateDevices().then(N=>!q&&j(N.filter(z=>z.kind==="audioinput"))).catch(()=>{});return C(),(P=(I=navigator.mediaDevices).addEventListener)==null||P.call(I,"devicechange",C),()=>{var N,z;q=!0,(z=(N=navigator.mediaDevices).removeEventListener)==null||z.call(N,"devicechange",C)}},[l]);const O=l??T,$=O.length===0,E=e.some(q=>!q.micId),D=!E,[L,W]=d.useState(h),[Z,A]=d.useState(-1),_=d.useCallback((q,C)=>{m==null||m({selectionMode:q,activePickerIndex:C,allMicsAssigned:D,noInputDevices:$})},[m,D,$]),U=d.useCallback(q=>{W(q),_(q,Z)},[_,Z]),ne=d.useCallback(q=>{A(q),_(L,q)},[_,L]),V=d.useMemo(()=>({padding:10,borderRadius:8,fontWeight:700,marginTop:8,textAlign:"center"}),[]);return w==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-session-join${x?` ${x}`:""}`,style:g==="card"?{background:"var(--bg-secondary)",borderRadius:12,padding:16,...k}:k,id:v,"data-testid":M,children:[r.jsx(Ho,{players:e,onPlayersChange:t,gameMode:n,onGameModeChange:a,gameModes:s,difficulty:i,onDifficultyChange:o,audioInputs:O,maxPlayers:c,onCalibrate:u,t:R}),$&&r.jsxs("div",{style:{...V,background:"var(--nice-error, #ef4444)",color:"#fff"},children:[R("karaokeSessionJoin.noInputDevices","No microphone detected"),r.jsx("br",{}),r.jsx("span",{style:{fontWeight:400,fontSize:13},children:R("karaokeSessionJoin.noInputDevicesHint","Connect a microphone to sing.")})]}),!$&&E&&r.jsx("div",{style:{...V,background:"var(--nice-warning, #f59e0b)",color:"var(--nice-bg, #222)",fontSize:14},children:R("karaokeSessionJoin.assignMicWarning","Assign a microphone to each player.")}),e.length>1&&r.jsx("div",{style:{marginTop:12},children:r.jsx(Ko,{players:e,mode:L,onModeChange:U,onActivePlayerChange:ne,turnTimeSec:p,hostIndex:f,myPlayerIndex:y,t:R})})]})};function We(e,t){var s;const n=((s=t.split(".").pop())==null?void 0:s.toLowerCase())??"",a=n==="otf"?"opentype":n==="woff2"?"woff2":n==="woff"?"woff":"truetype";return{family:e,url:`/fonts/${t}`,format:a}}const Qh=[We("Belagak","BelagakRegular-dr1zE.otf"),We("Big Scratch Brush","BigScratchBrush-PVY9g.ttf"),We("Gerhaus","Gerhaus-PK69E.ttf"),We("Gerhaus Italic","GerhausItalic-d96l7.ttf"),We("Handone Medium","HandoneMedium-nAevO.otf"),We("Handson Bold","HandsonBold-9MnrL.otf"),We("Kineks Round Bold","KineksRoundBold-7OR34.ttf"),We("Kineks Round Light","KineksRoundLight-m2r35.ttf"),We("Kineks Round Medium","KineksRoundMedium-drejZ.ttf"),We("Kineks Round","KineksRoundRegular-PVRl7.ttf"),We("Kineks Round SemiBold","KineksRoundSemiBold-LVWG3.ttf"),We("Lemon Jelly","LemonJellyPersonalUse-dEqR.ttf"),We("Lemon Milk Bold","LemonMilkBold-gx2B3.otf"),We("Lemon Milk Bold Italic","LemonMilkBoldItalic-PKZ3P.otf"),We("Lemon Milk Light","LemonMilkLight-owxMq.otf"),We("Lemon Milk Light Italic","LemonMilkLightItalic-7BjPE.otf"),We("Lemon Milk Medium","LemonMilkMedium-mLZYV.otf"),We("Lemon Milk Medium Italic","LemonMilkMediumItalic-d95nl.otf"),We("Lemon Milk","LemonMilkRegular-X3XE2.otf"),We("Lemon Milk Italic","LemonMilkRegularItalic-L3AEy.otf"),We("Pemage","PemageRegular-YqrdO.otf"),We("Rosmatika","RosmatikaRegular-BWA45.ttf"),We("Scabber","Scabber-q2Mn0.ttf"),We("Stylish Calligraphy","StylishCalligraphyDemo-XPZZ.ttf"),We("Super Adorable","SuperAdorable-MAvyp.ttf"),We("Super Chiby","SuperChiby-BL62V.ttf"),We("Super Joyful","SuperJoyful-lxwPq.ttf"),We("Super Kindly","SuperKindly-drE8E.ttf"),We("Super Meatball","SuperMeatball-Yq1Gy.ttf")],Qa="nice2dev-karaoke-display",Jh=[{value:"Arial",label:"Arial (default)"},{value:"Georgia, serif",label:"Georgia"},{value:"'Courier New', monospace",label:"Courier New"},{value:"'Trebuchet MS', sans-serif",label:"Trebuchet MS"},{value:"Impact, sans-serif",label:"Impact"},...Qh.map(e=>({value:e.family,label:e.family}))],Yo=[{id:"default",name:"Cyan ? Yellow ? Amber",sungGradient:["#00e5ff","#ffe600","#ffab00"],goldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,229,255,0.6)"},{id:"neon-pink",name:"Neon Pink ? Violet ? Blue",sungGradient:["#ff1493","#9b59b6","var(--nice-primary, #3498db)"],goldGradient:["var(--nice-warning, #FFD700)","#FF69B4","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,20,147,0.6)"},{id:"fire",name:"Red ? Orange ? Yellow",sungGradient:["#ff1744","#ff9100","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#FF6D00","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,23,68,0.6)"},{id:"ocean",name:"Deep Blue ? Teal ? Aqua",sungGradient:["#1a237e","#00897b","#00e5ff"],goldGradient:["var(--nice-warning, #FFD700)","#00BCD4","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,137,123,0.6)"},{id:"forest",name:"Green ? Lime ? Yellow",sungGradient:["#1b5e20","#76ff03","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#76ff03","var(--nice-warning, #FFD700)"],glowColor:"rgba(118,255,3,0.6)"},{id:"retro",name:"Orange ? Pink ? Purple",sungGradient:["#ff6d00","var(--nice-accent-pink, #e91e63)","#7b1fa2"],goldGradient:["var(--nice-warning, #FFD700)","var(--nice-accent-pink, #e91e63)","var(--nice-warning, #FFD700)"],glowColor:"rgba(233,30,99,0.6)"}],pn={presetId:"default",customSungGradient:["#00e5ff","#ffe600","#ffab00"],customGoldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],customGlowColor:"rgba(0,229,255,0.6)",animationMode:"ball",fontFamily:"Arial",transitionEffect:"none",curtainPrimaryColor:"#8b0000",curtainSecondaryColor:"#1a0000",curtainDurationMs:900,immersiveMode:!1};let Ys=!1;function Zo(){try{const e=localStorage.getItem(Qa);if(e){const t=JSON.parse(e);return{...pn,...t}}}catch{}return{...pn}}async function ep(e){if(Ys||(Ys=!0,!e))return;const t=await e();if(t)try{const n=JSON.parse(t),a={...pn,...n};localStorage.setItem(Qa,JSON.stringify(a))}catch{}}function tp(e){const t=JSON.stringify(e);localStorage.setItem(Qa,t),Ja(e)}function Xo(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=Yo.find(n=>n.id===e.presetId);return t?{sungGradient:t.sungGradient,goldGradient:t.goldGradient,glowColor:t.glowColor}:{sungGradient:pn.customSungGradient,goldGradient:pn.customGoldGradient,glowColor:pn.customGlowColor}}function Ja(e){const{sungGradient:t,goldGradient:n,glowColor:a}=Xo(e),s=document.documentElement;s.style.setProperty("--karaoke-sung-gradient",`linear-gradient(90deg, ${t[0]} 0%, ${t[1]} 60%, ${t[2]} 100%)`),s.style.setProperty("--karaoke-gold-gradient",`linear-gradient(90deg, ${n[0]}, ${n[1]}, ${n[2]})`),s.style.setProperty("--karaoke-gold-glow-first",`0 0 12px ${n[0]}`),s.style.setProperty("--karaoke-active-glow",`0 0 10px ${a}, 0 0 4px ${t[1]}80`),s.style.setProperty("--karaoke-active-drop-first",`0 0 6px ${a}`),s.style.setProperty("--karaoke-active-bg",`linear-gradient(90deg, transparent 0%, ${t[0]}14 20%, ${t[1]}10 80%, transparent 100%)`),s.style.setProperty("--karaoke-font-family",e.fontFamily||"Arial")}function np(){const e=Zo();Ja(e)}function rp(e){const t=(e||"").split(/\r?\n/),n=[];for(let a=0;a<t.length;a++){const s=t[a].trim();if(s&&/^[:*F]\s/.test(s)){const i=s.slice(1).trim().split(/\s+/),o=parseInt(i[0]||"0",10),l=parseInt(i[1]||"0",10),c=isNaN(o)?0:o/10,u=isNaN(l)?0:l/10;n.push({lineIndex:a,start:c,duration:u,raw:t[a]})}}return n}const ap=({index:e,style:t,data:n})=>{const{lines:a,notes:s,currentIndex:i,animationConfig:o}=n,l=a[e]??"",c=s.findIndex(k=>k.lineIndex===e),u=c>=0&&c===i,h=(o==null?void 0:o.enabled)??!0,p=(o==null?void 0:o.durationMs)??300,f=(o==null?void 0:o.translateX)??8,y=(o==null?void 0:o.scale)??1.01,m=(o==null?void 0:o.easing)??"cubic-bezier(.22,1,.36,1)",g=(o==null?void 0:o.opacityInactive)??.9,b=(o==null?void 0:o.boxShadow)??"0 6px 18px var(--nice-primary-tint-8, rgba(3,102,214,0.08))",x={transition:h?`transform ${p}ms ${m}, opacity ${p}ms ${m}`:"none",transform:u?`translateX(${f}px) scale(${y})`:"translateX(0px) scale(1)",opacity:u?1:g,boxShadow:u?b:"none"};return r.jsx("div",{style:{...t,padding:"4px 6px",borderRadius:4},"data-note-idx":c>=0?c:void 0,children:r.jsx("div",{style:{...x,background:u?"var(--nice-primary-tint-12, rgba(0,130,200,0.12))":"transparent",padding:"4px 6px",borderRadius:4},children:r.jsx("code",{style:{fontFamily:"monospace",whiteSpace:"pre-wrap"},children:l})})})},Qo=({ultrastarText:e,audioUrl:t,audioRef:n,animationConfig:a})=>{const{t:s}=Te(),i=d.useRef(null),o=n??i,[l,c]=d.useState(!1),u=d.useMemo(()=>rp(e),[e]),h=d.useRef(null),p=d.useRef(null),f=d.useRef(null),y=d.useRef(0),m=d.useRef(0),[g,b]=d.useState(-1),x=d.useMemo(()=>(e||"").split(/\r?\n/),[e]),k=28,v=x.length*k,w=d.useMemo(()=>({lines:x,notes:u,currentIndex:g,animationConfig:a}),[x,u,g,a]);return d.useEffect(()=>{const M=o.current;M&&(l?M.play().catch(()=>c(!1)):M.pause())},[l,o]),d.useEffect(()=>{const M=o.current;if(!M)return;let S=-1;const R=a??null,T=R&&typeof R.scrollSmooth=="number"?R.scrollSmooth:.18;let j=performance.now();const O=()=>{var V,q;const $=performance.now(),E=Math.max(0,Math.min(.2,($-j)/1e3));j=$;const D=M.currentTime||0;y.current=D;let L=-1;for(let C=0;C<u.length;C++){const F=u[C];if(D>=F.start&&D<F.start+Math.max(.001,F.duration)){L=C;break}}L!==S&&(S=L,b(L));let W=0;if(S>=0){const C=((V=u[S])==null?void 0:V.lineIndex)??0,F=((q=p.current)==null?void 0:q.clientHeight)??220;W=C*k-F/2+k/2;const I=Math.max(0,v-F);(isNaN(W)||!isFinite(W))&&(W=0),W=Math.max(0,Math.min(W,I))}const Z=1-Math.pow(Math.max(0,1-T),Math.min(4,E*60)),ne=(((a==null?void 0:a.scrollEasing)||"easeOutCubic")==="linear"?C=>C:C=>1-Math.pow(1-C,3))(Z);m.current=m.current+(W-m.current)*ne;try{const C=p.current;C&&typeof C.scrollTop=="number"&&(C.scrollTop=Math.round(m.current))}catch{}f.current=requestAnimationFrame(O)};return f.current=requestAnimationFrame(O),()=>{f.current&&cancelAnimationFrame(f.current)}},[o,u,v,a]),r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[r.jsx("button",{onClick:()=>c(M=>!M),disabled:!t,children:l?"Pause":"Play"}),r.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-secondary, #666)"},children:[(y.current||0).toFixed(2),"s"]}),r.jsxs("div",{style:{marginLeft:"auto",fontSize:13,color:"var(--nice-text-secondary, #666)"},children:["Notes: ",u.length]})]}),r.jsx("div",{style:{border:"1px solid var(--nice-border, #ddd)",height:220,overflow:"hidden",padding:8,position:"relative"},children:e?r.jsx(Hc.FixedSizeList,{height:220,width:"100%",itemCount:x.length,itemSize:k,ref:h,outerRef:p,itemData:w,children:ap}):r.jsx("div",{style:{color:"var(--nice-text-secondary, #888)"},children:s("karaokeEditor.noText","No text")})}),!n&&r.jsx("audio",{ref:i,src:t||void 0,preload:"metadata",style:{display:"none"}})]})};function sp(e){const t=(e||"").split(/\r?\n/).map(a=>a.replace(/\s+$/,"")),n=[];for(let a=0;a<t.length;a++){const s=t[a].trim();if(/^[:*F]\s/.test(s)){const i=s.slice(1).trim().split(/\s+/),o=parseInt(i[0]||"0",10)/10||0,l=parseInt(i[1]||"0",10)/10||.1;n.push({lineIndex:a,start:o,duration:l})}}return{lines:t,notes:n}}function Jo({ultrastarText:e,audioUrl:t,audioRef:n,ytRef:a}){const s=d.useRef(null),i=d.useRef(null),o=d.useRef([]),l=d.useRef([]),c=d.useRef(null),u=d.useRef(t);return u.current=t,d.useEffect(()=>{const{lines:h,notes:p}=sp(e);o.current=h,l.current=p;const f=c.current;f&&"rebuildTexts"in f&&typeof f.rebuildTexts=="function"&&f.rebuildTexts()},[e]),d.useEffect(()=>{let h=!0;return(async()=>{var S;if(!h||!s.current)return;const p=await import("phaser"),f="default"in p?p.default:p;if(!s.current||!h)return;const y=o,m=l,g=c,b=n,x=a,k=u;class v extends f.Scene{constructor(){super({key:"preview"}),this.texts=[],this.audioEl=null}create(){if(g.current=this,this.rebuildTexts(),x!=null&&x.current)this.audioEl=null;else if(b!=null&&b.current)this.audioEl=b.current;else{const T=document.querySelector("audio");T instanceof HTMLAudioElement?this.audioEl=T:k.current?(this.audioEl=document.createElement("audio"),this.audioEl.src=k.current,this.audioEl.preload="metadata",this.audioEl.style.display="none",document.body.appendChild(this.audioEl)):this.audioEl=null}}rebuildTexts(){for(const E of this.texts)E.destroy();this.texts=[];const T={font:"18px monospace",color:"var(--nice-bg, #fff)"},j=22;let O=20;const $=y.current;for(let E=0;E<$.length;E++){const D=this.add.text(10,O,$[E]||" ",T).setOrigin(0,0);this.texts.push(D),O+=j}}update(){let T=0;if(x!=null&&x.current&&typeof x.current.getCurrentTime=="function")try{T=x.current.getCurrentTime()||0}catch{T=0}else T=this.audioEl&&this.audioEl.currentTime||0;for(let O=0;O<this.texts.length;O++)this.texts[O].setStyle({backgroundColor:void 0,color:"var(--nice-bg, #fff)"});const j=m.current;for(const O of j)if(T>=O.start&&T<O.start+Math.max(.001,O.duration)){const $=this.texts[O.lineIndex];$&&$.setStyle({backgroundColor:"rgba(0,130,200,0.16)",color:"var(--nice-info, #00aaff)"})}}}const w=((S=s.current)==null?void 0:S.clientWidth)??640,M={type:f.AUTO,parent:s.current,width:w,height:Math.round(w/2),backgroundColor:"#101010",scene:[v]};i.current=new f.Game(M)})(),()=>{h=!1,c.current=null;try{const p=i.current;p&&typeof p.destroy=="function"&&p.destroy(!0)}catch{}}},[]),r.jsx("div",{ref:s,style:{width:"100%",height:340}})}const ip=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),Zs=e=>{(!isFinite(e)||e<0)&&(e=0);const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`},Yr={border:"1px solid var(--border-color)",borderRadius:8,padding:"6px 10px",background:"var(--bg-secondary)",color:"var(--text-primary)",cursor:"pointer"},op=({isPlaying:e,index:t,count:n,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek:u,onVolume:h})=>{const{t:p}=Te();return r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[r.jsx("div",{}),r.jsxs("div",{style:{fontSize:12,color:"var(--text-secondary)"},children:[Zs(a)," / ",Zs(s)]})]}),r.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("button",{onClick:o,disabled:t<=0,title:p("playerControls.prev","Prev"),"aria-label":p("playerControls.previousTrack","Previous track"),style:Yr,children:r.jsx(se.NtdSkipBack,{size:16})}),r.jsx("button",{onClick:c,title:e?p("playerControls.pause","Pause"):p("playerControls.play","Play"),"aria-label":e?p("playerControls.pause","Pause"):p("playerControls.play","Play"),style:Yr,children:e?r.jsx(se.NtdPause,{size:16}):r.jsx(se.NtdPlay,{size:16})}),r.jsx("button",{onClick:l,disabled:t>=n-1,title:p("playerControls.next","Next"),"aria-label":p("playerControls.nextTrack","Next track"),style:Yr,children:r.jsx(se.NtdSkipForward,{size:16})})]}),r.jsx("input",{type:"range",min:0,max:Math.max(1,s),step:.1,value:a,"aria-label":p("playerControls.seekPosition","Seek position"),onChange:f=>u(parseFloat(f.target.value))}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx(se.NtdVolume,{size:16}),r.jsx("input",{type:"range",min:0,max:1,step:.01,value:i,"aria-label":p("playerControls.volume","Volume"),onChange:f=>h(parseFloat(f.target.value))})]})]})]})},el=d.memo(op);function lp(e,t,n,a,s){const o=Math.max(1,Math.floor(a.length/48)),l=t/48;for(let c=0;c<48;c++){const u=a[c*o]/255,h=u*(n-6),p=c*l,f=n-h,y=c/48*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+u*30)}%)`,e.fillRect(p+1,f,l-2,h)}}function cp(e,t,n,a,s,i){if(!i.current){const p=[];for(let y=0;y<24;y++)p.push({ang:y/24*Math.PI*2,phase:Math.random()*Math.PI*2,baseR:Math.min(t,n)*.22+Math.random()*30});i.current={nodes:p}}const o=i.current,l=t/2,c=n/2,u=26+a*80,h=[];for(const p of o.nodes){p.phase+=.02+a*.06;const f=p.baseR+Math.sin(p.phase)*u,y=l+Math.cos(p.ang)*f,m=c+Math.sin(p.ang)*f;h.push([y,m])}e.fillStyle=`hsla(${s}, 70%, 55%, .22)`,e.strokeStyle=`hsla(${(s+40)%360}, 90%, 65%, .9)`,e.lineWidth=2,e.beginPath();for(let p=0;p<h.length;p++){const[f,y]=h[p],[m,g]=h[(p+1)%h.length],b=(f+m)/2,x=(y+g)/2;p===0?e.moveTo(b,x):e.quadraticCurveTo(f,y,b,x)}e.closePath(),e.fill(),e.stroke()}function dp(e,t,n,a,s,i){i.current||(i.current={items:[]});const o=i.current;Math.random()<.06+a*.25&&o.items.push({x:Math.random()*t,y:Math.random()*n,r:8+Math.random()*24,life:1,hue:(s+Math.random()*120)%360});const l=[];for(const c of o.items){c.r+=2+a*14,c.life*=.975-a*.02,c.life>.04&&l.push(c);const u=e.createRadialGradient(c.x,c.y,1,c.x,c.y,c.r);u.addColorStop(0,`hsla(${c.hue}, 90%, 60%, ${.35*c.life})`),u.addColorStop(.6,`hsla(${(c.hue+40)%360}, 80%, 55%, ${.18*c.life})`),u.addColorStop(1,`hsla(${(c.hue+80)%360}, 70%, 50%, 0)`),e.fillStyle=u,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}o.items=l}const up="var(--nice-text-muted, #94a3b8)",hp=({height:e,coverUrl:t,title:n,subtitle:a,label:s})=>r.jsx("div",{style:{textAlign:"center",color:"var(--nice-border, #e2e8f0)"},children:t?r.jsx("img",{alt:"cover",src:t,style:{height:e-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsx("div",{style:{fontSize:18,fontWeight:600},children:n??"—"}),r.jsx("div",{style:{marginTop:8,fontSize:12,color:up},children:s??a??"—"})]})});function Xt(e,t){return e+Math.random()*(t-e)}function pp(e,t,n,a,s,i,o){o.current||(o.current={embers:[],t:0});const l=o.current,c=e.createLinearGradient(0,n,0,n*.4);c.addColorStop(0,`hsla(${(i+30)%360}, 90%, 50%, .35)`),c.addColorStop(1,`hsla(${(i+10)%360}, 90%, 50%, 0)`),e.fillStyle=c,e.fillRect(0,0,t,n);const u=6;for(let p=0;p<u;p++){const f=(p+.5)/u*t,y=(a[Math.floor((p+1)/(u+1)*a.length)]||0)/255,m=n*.18+(.25+s*.6+y*.7)*n*.55,g=e.createLinearGradient(f,n,f,n-m);g.addColorStop(0,`hsla(${(i+40)%360},100%,55%,.9)`),g.addColorStop(.5,`hsla(${(i+10)%360},100%,60%,.75)`),g.addColorStop(1,`hsla(${(i-20)%360},100%,80%,.05)`);const b=Math.sin(l.t*1.2+p*.8)*(15+s*30);e.fillStyle=g,e.beginPath(),e.moveTo(f-20,n),e.bezierCurveTo(f-35,n-m*.45,f-25+b,n-m*.75,f+b,n-m),e.bezierCurveTo(f+25+b*.3,n-m*.65,f+35,n-m*.35,f+20,n),e.closePath(),e.fill()}const h=Math.floor(1+s*6);for(let p=0;p<h;p++)l.embers.push({x:Xt(t*.25,t*.75),y:n-Xt(4,14),r:Xt(1,3),vx:Xt(-.15,.15),vy:-Xt(.6,1.8)-s*1.2,life:Xt(.8,1.6)});e.save(),e.globalCompositeOperation="lighter";for(let p=l.embers.length-1;p>=0;p--){const f=l.embers[p];if(f.x+=f.vx,f.y+=f.vy,f.vy-=.01,f.life-=.015+s*.02,f.life<=0||f.y<-10){l.embers.splice(p,1);continue}const y=e.createRadialGradient(f.x,f.y,0,f.x,f.y,f.r*3);y.addColorStop(0,`hsla(${(i+25)%360},100%,65%,.9)`),y.addColorStop(1,`hsla(${(i+25)%360},100%,65%,0)`),e.fillStyle=y,e.beginPath(),e.arc(f.x,f.y,f.r*3,0,Math.PI*2),e.fill()}e.restore(),e.fillStyle="rgba(60,36,22,.9)",e.fillRect(t*.2,n-10,t*.6,6),l.t+=.02+s*.08}function fp(e,t,n,a,s){const i=t/2,o=n/2,l=Math.min(t,n)*.28,c=96,u=Math.max(1,Math.floor(a.length/c));for(let h=0;h<c;h++){const p=(a[h*u]??0)/255,f=h/c*Math.PI*2,y=p*(Math.min(t,n)*.22)+6,m=i+Math.cos(f)*l,g=o+Math.sin(f)*l,b=i+Math.cos(f)*(l+y),x=o+Math.sin(f)*(l+y);e.strokeStyle=`hsl(${(s+h*3)%360}, 90%, ${40+p*40}%)`,e.lineWidth=3,e.beginPath(),e.moveTo(m,g),e.lineTo(b,x),e.stroke()}e.fillStyle=`hsla(${(s+180)%360}, 60%, 15%, .4)`,e.beginPath(),e.arc(i,o,l-8,0,Math.PI*2),e.fill()}function mp(e,t,n,a,s){const l=t/14,c=n/8;for(let u=0;u<8;u++)for(let h=0;h<14;h++){const p=Math.min(a.length-1,u*14+h),f=a[p]/255,y=(s+h/14*210+u/8*90)%360,m=65+f*30,g=20+f*40,b=(1-f)*4;e.fillStyle=`hsl(${y}, ${m}%, ${g}%)`,e.fillRect(h*l+b,u*c+b,Math.max(1,l-2*b),Math.max(1,c-2*b))}}function gp(e){const n=Array.from(new Set(e.filter(Boolean))).map(a=>new Promise(s=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>s(i),i.onerror=()=>s(i),i.src=a}));return Promise.all(n)}async function yp(e,t,n,a,s){e.current||(e.current={sprites:[],loadedUrls:[],ready:!1});const i=e.current,o=t.join("|")!==i.loadedUrls.join("|");if(!i.ready||o){const l=await gp(t.length?t:[]);i.loadedUrls=t,i.sprites=[],i.ready=!0;const c=u=>l[u%Math.max(1,l.length)]??new Image;for(let u=0;u<n;u++){const h=Math.random()*Math.min(a,s)*.38+40;i.sprites.push({img:c(u),x:(Math.random()-.5)*h*.4,y:(Math.random()-.5)*h*.4,z:Math.random()*600+100,ang:Math.random()*Math.PI*2,spin:(Math.random()*.03+.01)*(Math.random()<.5?-1:1),vz:Math.random()*1.2+.2,size:Math.random()*.35+.65})}}}function bp(e,t,n,a,s,i,o,l){const c=i.current;if(!(c!=null&&c.ready))return;const u=t/2,h=n/2,p=900,f=1+a*2;for(const m of c.sprites){m.ang+=m.spin*f,m.z-=m.vz*(.8+a*2.4),m.z<40&&(m.z=p);const g=Math.min(t,n)*.32+Math.sin(m.ang*.8)*18;m.x=Math.cos(m.ang)*g,m.y=Math.sin(m.ang*1.1)*g*.6}const y=[...c.sprites].sort((m,g)=>g.z-m.z);for(const m of y){const g=p/(p-m.z)*.6*m.size,b=u+m.x*g,x=h+m.y*g,k=64*g,v=64*g;e.save(),e.globalAlpha=.12+(1-m.z/p)*.2,e.fillStyle=`hsl(${(s+(1-m.z/p)*60)%360}, 90%, 60%)`,e.beginPath(),e.ellipse(b,x,k*.7,v*.7,0,0,Math.PI*2),e.fill(),e.restore(),m.img&&m.img.width?e.drawImage(m.img,b-k/2,x-v/2,k,v):(e.save(),e.fillStyle=`hsl(${(s+180)%360}, 40%, 55%)`,e.fillRect(b-k/2,x-v/2,k,v),e.restore())}}function Sn(e,t){return e+Math.random()*(t-e)}function xp(e,t,n,a,s,i){i.current||(i.current={blobs:Array.from({length:7},(u,h)=>({x:Sn(t*.2,t*.8),y:Sn(n*.2,n*.8),r:Sn(Math.min(t,n)*.05,Math.min(t,n)*.12),vx:Sn(-.6,.6),vy:Sn(-.6,.6),hue:(s+h*10)%360}))});const o=i.current,l=.6+a*2.2;e.save(),e.globalCompositeOperation="lighter";for(const c of o.blobs){c.x+=c.vx*l,c.y+=c.vy*l,c.vy-=.01-a*.015,c.x<c.r&&(c.x=c.r,c.vx=Math.abs(c.vx)),c.x>t-c.r&&(c.x=t-c.r,c.vx=-Math.abs(c.vx)),c.y<c.r&&(c.y=c.r,c.vy=Math.abs(c.vy)),c.y>n-c.r&&(c.y=n-c.r,c.vy=-Math.abs(c.vy));const u=(c.hue+a*120)%360,h=e.createRadialGradient(c.x,c.y,c.r*.2,c.x,c.y,c.r);h.addColorStop(0,`hsla(${u}, 95%, 70%, .8)`),h.addColorStop(1,`hsla(${(u+40)%360}, 90%, 30%, 0)`),e.fillStyle=h,e.shadowBlur=18,e.shadowColor=`hsl(${u}, 100%, 60%)`,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}e.restore(),e.strokeStyle="var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",e.lineWidth=2,e.strokeRect(1,1,t-2,n-2)}function vp(e,t,n,a,s,i){i.current||(i.current={tris:[]});const o=i.current,l=6;for(;o.tris.length<l;)o.tris.push({a:Math.random()*Math.PI*2,r:30+Math.random()*Math.min(t,n)*.35,dr:(Math.random()*.6+.2)*(Math.random()<.5?-1:1)});const c=t/2,u=n/2;for(const h of o.tris){h.a+=.002+a*.02*(h.dr>0?1:-1),h.r+=Math.sin(h.a*2)*(.3+a*1.4);const p=Math.max(40,Math.min(h.r,Math.min(t,n)*.48));e.save(),e.translate(c,u),e.rotate(h.a),e.strokeStyle=`hsla(${(s+p*.2)%360}, 90%, 60%, .9)`,e.lineWidth=2.5,e.beginPath(),e.moveTo(p,0);for(let f=1;f<3;f++){const y=f*Math.PI*2/3;e.lineTo(Math.cos(y)*p,Math.sin(y)*p)}e.closePath(),e.shadowBlur=12,e.shadowColor=e.strokeStyle,e.stroke(),e.restore()}}function Sp(e,t,n,a,s,i){const o=t/2,l=n/2,c=5,u=Math.min(t,n)*.42;i.current+=.01;for(let h=0;h<c;h++){const p=(h+1)/(c+1),f=p*u;e.strokeStyle=`hsla(${(s+h*30)%360}, 70%, 45%, 0.35)`,e.lineWidth=1,e.beginPath(),e.arc(o,l,f,0,Math.PI*2),e.stroke();const y=Math.floor(a.length*p|0),m=(a[y]??0)/255,g=6+h*2;for(let b=0;b<g;b++){const x=i.current*(1+h*.15)+b/g*Math.PI*2,k=f+Math.sin(x*2)*6*m,v=o+Math.cos(x)*k,w=l+Math.sin(x)*k;e.fillStyle=`hsla(${(s+h*30+b*6)%360}, 90%, ${55+m*30}%, ${.6+m*.3})`,e.beginPath(),e.arc(v,w,2+m*4,0,Math.PI*2),e.fill()}}}function kp(e,t,n,a,s){const l=t/12,c=n/6;for(let u=0;u<6;u++)for(let h=0;h<12;h++){const p=(u*12+h)%a.length,f=a[p]/255,y=(s+h/12*180+u/6*90)%360,m=70+f*25,g=25+f*35;e.fillStyle=`hsl(${y}, ${m}%, ${g}%)`,e.fillRect(h*l,u*c,Math.ceil(l),Math.ceil(c))}}function wp(e,t,n,a,s,i){const o=t/2,l=n/2,c=2+Math.floor(a*14);for(let h=0;h<c;h++){const p=Math.random()*Math.PI*2,f=.5+Math.random()*(2.5+a*4);i.current.push({x:o,y:l,vx:Math.cos(p)*f,vy:Math.sin(p)*f,life:0,max:40+Math.random()*60,hue:(s+Math.random()*60)%360})}e.fillStyle="rgba(2,6,23,0.2)",e.fillRect(0,0,t,n);const u=i.current;for(let h=u.length-1;h>=0;h--){const p=u[h];p.x+=p.vx,p.y+=p.vy,p.life+=1;const f=1-p.life/p.max;e.fillStyle=`hsla(${p.hue},85%,60%,${Math.max(0,f)})`,e.beginPath(),e.arc(p.x,p.y,2+f*3,0,Math.PI*2),e.fill(),(p.life>=p.max||p.x<-20||p.y<-20||p.x>t+20||p.y>n+20)&&u.splice(h,1)}u.length>1200&&u.splice(0,u.length-1200)}function jp(e,t,n,a,s,i){e.fillStyle="rgba(10,16,28,0.25)",e.fillRect(0,0,t,n);const o=t/2,l=n/2,c=Math.min(t,n)*(.38+s*.12),u=e.createRadialGradient(o,l,c*.1,o,l,c);u.addColorStop(0,`hsla(${(i+200)%360},90%,70%,0.95)`),u.addColorStop(.5,`hsla(${(i+260)%360},80%,55%,0.6)`),u.addColorStop(1,"transparent"),e.fillStyle=u,e.beginPath(),e.arc(o,l,c,0,Math.PI*2),e.fill();const h=18+Math.floor(s*50);for(let p=0;p<h;p++){const f=p/h*Math.PI*2+a*(.6+s*1.4),y=(Math.sin(a*2+p*1.7)+Math.cos(a*1.3+p*2.1))*.15,m=c*(.4+.55*Math.abs(Math.sin(a*1.2+p))),g=6;e.save(),e.translate(o,l),e.rotate(f+y),e.beginPath(),e.moveTo(0,0);for(let x=1;x<=g;x++){const k=m/g*x,v=(Math.sin(a*3+p*.8+x)*.6+Math.cos(a*2+p+x*.7))*(8+24*s),w=k,M=v;e.lineTo(M,w)}e.globalCompositeOperation="lighter";const b=(i+p*(240/h))%360;e.strokeStyle=`hsla(${b}, 90%, ${60+s*20}%, ${.35+s*.4})`,e.lineWidth=2+s*2,e.stroke(),e.restore()}e.beginPath(),e.arc(o,l,c*(.98+.02*Math.sin(a*2)),0,Math.PI*2),e.strokeStyle=`hsla(${(i+40)%360},90%,70%,${.25+s*.25})`,e.lineWidth=1.5,e.stroke(),e.globalCompositeOperation="source-over"}function Cp(e,t,n,a,s){const o=Math.max(1,Math.floor(a.length/96)),l=t/2,c=n/2,u=Math.min(t,n)*.22,h=Math.min(t,n)*.48;for(let p=0;p<96;p++){const f=a[p*o]/255,y=p/96*Math.PI*2,m=u,g=u+f*(h-u),b=l+Math.cos(y)*m,x=c+Math.sin(y)*m,k=l+Math.cos(y)*g,v=c+Math.sin(y)*g;e.strokeStyle=`hsl(${p/96*360+s},85%,60%)`,e.lineWidth=3,e.beginPath(),e.moveTo(b,x),e.lineTo(k,v),e.stroke()}e.fillStyle="var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.beginPath(),e.arc(l,c,u*.85,0,Math.PI*2),e.fill()}function Mp(e,t,n,a,s,i){const o=t/2,l=n/2,c=Math.min(t,n)*.5,u=Xs(a,0,Math.floor(a.length*.1))/255,h=Xs(a,Math.floor(a.length*.6),a.length)/255;i.current+=.01+h*.03;const p=24;for(let f=0;f<p;f++){const y=i.current+f/p*Math.PI*2,m=(.35+u*.55)*c,g=o+Math.cos(y)*m,b=l+Math.sin(y)*m,x=e.createRadialGradient(o,l,0,o,l,m),k=f/p*360+s;x.addColorStop(0,`hsla(${k},85%,65%,0.0)`),x.addColorStop(1,`hsla(${k},85%,65%,0.9)`),e.strokeStyle=x,e.lineWidth=6+h*8,e.beginPath(),e.moveTo(o,l),e.lineTo(g,b),e.stroke()}e.fillStyle="rgba(2,6,23,0.25)",e.fillRect(0,0,t,n)}function Xs(e,t,n){let a=0,s=0;for(let i=t;i<n;i++)a+=e[i],s++;return s?a/s:0}function Rp(e,t,n,a,s,i){e.fillStyle="rgba(10,16,28,0.35)",e.fillRect(0,0,t,n);const o=n/2,l=Math.max(8,18-s*10),c=n*.35*(.6+s*.7),u=a.length,h=t/(u-1);e.beginPath();for(let y=0;y<u;y++){const m=(a[y]-128)/128,g=Math.sin(i*1.5+y*.03)*.12,b=y*h,x=o-l-(m+g)*c;y===0?e.moveTo(b,x):e.lineTo(b,x)}const p=e.createLinearGradient(0,0,0,o-l);p.addColorStop(0,"hsla(260,90%,75%,0.9)"),p.addColorStop(1,"hsla(220,85%,60%,0.4)"),e.strokeStyle=p,e.lineWidth=2,e.stroke(),e.beginPath();for(let y=0;y<u;y++){const m=(a[y]-128)/128,g=Math.cos(i*1.3+y*.035)*.12,b=y*h,x=o+l+(m+g)*c;y===0?e.moveTo(b,x):e.lineTo(b,x)}const f=e.createLinearGradient(0,o+l,0,n);f.addColorStop(0,"hsla(190,90%,65%,0.9)"),f.addColorStop(1,"hsla(160,85%,55%,0.4)"),e.strokeStyle=f,e.lineWidth=2,e.stroke(),e.globalCompositeOperation="lighter",e.strokeStyle="var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.lineWidth=6,e.beginPath(),e.moveTo(0,o-l),e.lineTo(t,o-l),e.stroke(),e.beginPath(),e.moveTo(0,o+l),e.lineTo(t,o+l),e.stroke(),e.globalCompositeOperation="source-over"}function Np(e,t,n,a,s,i){const o=t/2,l=n/2,c=5,u=Math.min(t,n)*.12;for(let h=0;h<c;h++){const p=Math.floor(h/c*a.length),f=a[p]/255,y=u+h*u*.55+f*u*.5,m=(i+h*40)%360;e.lineWidth=3+f*6,e.strokeStyle=`hsla(${m},80%,60%,${.5+.5*s})`,e.beginPath(),e.arc(o,l,y,0,Math.PI*2),e.stroke()}}function Tp(e,t,n,a,s){const i=Math.min(a.length,256),o=Math.max(1,Math.floor(a.length/i)),l=t/i;for(let c=0;c<i;c++){const u=a[c*o]/255,h=u*(n-6),p=c*l,f=n-h,y=c/i*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+u*30)}%)`,e.fillRect(p+1,f,l-2,h)}}function $p(e,t,n,a){e.current||(e.current={stars:[],ready:!1});const s=e.current;if(!s.ready||s.stars.length!==t){const i=[];for(let o=0;o<t;o++){const l={x:(Math.random()-.5)*n,y:(Math.random()-.5)*a,z:Math.random()*800+100,pz:0};i.push(l)}s.stars=i,s.ready=!0}}function Pp(e,t,n,a,s,i){const o=i.current,l=t/2,c=n/2,u=4+a*18;e.save(),e.translate(l,c);for(const h of o.stars){h.z-=u,h.z<20&&(h.x=(Math.random()-.5)*t,h.y=(Math.random()-.5)*n,h.z=900,h.pz=h.z);const p=h.x/h.z*600,f=h.y/h.z*600,y=h.x/h.pz*600,m=h.y/h.pz*600;h.pz=h.z,e.strokeStyle=`hsla(${(s+200)%360}, 90%, 70%, 0.7)`,e.lineWidth=Math.max(1,(1-h.z/900)*2),e.beginPath(),e.moveTo(y,m),e.lineTo(p,f),e.stroke()}e.restore()}function Ap(e,t,n,a){e.lineWidth=2,e.strokeStyle="var(--nice-primary-light, #c7d2fe)",e.beginPath();const s=t/a.length;for(let i=0;i<a.length;i++){const o=(a[i]-128)/128,l=i*s,c=n/2+o*(n*.45);i===0?e.moveTo(l,c):e.lineTo(l,c)}e.stroke()}const Ep=({active:e,onClick:t,title:n,children:a})=>r.jsx("button",{type:"button",onClick:t,title:n,"aria-pressed":e,style:{padding:"4px 8px",borderRadius:6,fontSize:12,border:`1px solid ${e?"var(--nice-info, #6366f1)":"var(--nice-text, #334155)"}`,background:e?"rgba(99,102,241,.12)":"var(--nice-overlay-60, rgba(15,23,42,.6))",color:e?"var(--nice-border, #e2e8f0)":"var(--nice-border, #cbd5e1)",cursor:"pointer",whiteSpace:"nowrap",lineHeight:1.2},children:a}),es=({modes:e=[],active:t,setActive:n,rows:a=2})=>{const s=Math.max(1,a);return!e||e.length===0?null:r.jsx("div",{style:{position:"absolute",top:10,right:10,pointerEvents:"auto",zIndex:9999},children:r.jsx("div",{style:{display:"grid",gridAutoFlow:"column",gridTemplateRows:`repeat(${s}, auto)`,gridAutoColumns:"max-content",gap:6,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:6,borderRadius:10,border:"1px solid var(--nice-text, #334155)",backdropFilter:"blur(2px)",justifyItems:"end",alignItems:"start"},children:e.map(i=>r.jsx(Ep,{active:t===i,onClick:()=>n(i),title:`Tryb: ${i}`,children:i},i))})})};function Ip(e,t){const[n,a]=d.useState(()=>{try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}});return d.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(n))}catch{}},[e,n]),[n,a]}const Lp=({vu:e,hide:t})=>{if(t)return null;const n=12,a=Math.round(e*n);return r.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px 8px",borderRadius:8,border:"1px solid var(--nice-text, #334155)",backdropFilter:"blur(2px)",pointerEvents:"none",zIndex:9998},children:Array.from({length:n}).map((s,i)=>{const o=120*(i/n);return r.jsx("div",{style:{width:6,height:18,borderRadius:2,background:i<a?`hsl(${o}, 80%, 50%)`:"var(--nice-text, #1f2937)"}},i)})})},Dp="var(--player-bg, #0f172a)";function _p(e,t){const n=e.length;for(let a=0;a<n;a++){const s=a/n,i=.55*Math.exp(-Math.pow((s-(.12+.08*Math.sin(t*.7)))*7,2))+.45*Math.exp(-Math.pow((s-(.4+.15*Math.sin(t*1.1+1)))*9,2))+.3*(1-s)*(.55+.45*Math.sin(t*2+a*.06));e[a]=Math.max(0,Math.min(255,Math.floor(i*255)))}}function Fp(e,t){const n=e.length;for(let a=0;a<n;a++){const s=a/n*Math.PI*2,i=Math.sin(s*3+t*3)*.5+Math.sin(s*7+t*2)*.28;e[a]=Math.max(0,Math.min(255,Math.floor(128+i*110)))}}const ts=({kind:e,audioRef:t,width:n="100%",height:a=360,coverUrl:s,title:i,subtitle:o,label:l,defaultMode:c="cover",storageKey:u="gp-stage:mode",allowedModes:h,imageUrls:p,imageCount:f=14,autoAnimate:y=!1})=>{const m=d.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette","radial","rays","particles","rings","grid","imageTornado","colorRipples","starfield","orbitals","eqcircle","triangles","blob","plasma","lavaLamp","cozyFire","rift"],[e,h]),g=d.useMemo(()=>{const V=m.includes(c)?c:m[0];try{const q=localStorage.getItem(u);if(!q)return V;const C=JSON.parse(q);return m.includes(C)?C:V}catch{return V}},[m,c,u]),[b,x]=Ip(u,g),k=d.useRef(null),v=d.useRef(null),w=d.useRef(null),M=d.useRef(null),S=d.useRef(null),R=d.useRef(null),T=d.useRef(0),j=d.useRef(0),O=d.useRef([]),[$,E]=d.useState(0),D=d.useRef(null),L=d.useRef(null),W=d.useRef(null),Z=d.useRef(null),A=d.useRef(null),_=d.useRef(null),U=d.useRef(null),ne=b!=="cover"&&b!=="video";return d.useEffect(()=>{var N;if(e==="youtube"||(v.current&&(cancelAnimationFrame(v.current),v.current=null),!ne))return;Bt();const V=mn(),q=t.current;if(!q&&!y)return;if(q&&!w.current)try{w.current=V.createMediaElementSource(q)}catch{}if(q&&!M.current){const z=V.createAnalyser();z.fftSize=2048,z.smoothingTimeConstant=.85,M.current=z;try{(N=w.current)==null||N.connect(z)}catch{}try{z.connect(V.destination)}catch{}}const C=M.current;S.current=new Uint8Array(C?C.frequencyBinCount:1024),R.current=new Uint8Array(C?C.fftSize:2048);const F=()=>{const z=k.current,B=Math.max(1,Math.floor(window.devicePixelRatio||1));z.width=Math.floor(z.clientWidth*B),z.height=Math.floor(z.clientHeight*B);const G=z.getContext("2d");G==null||G.setTransform(1,0,0,1,0,0),G==null||G.scale(B,B)};F();const I=()=>F();window.addEventListener("resize",I),$p(W,220,k.current.width,k.current.height);const P=async()=>{const z=k.current;if(!z)return;const B=z.getContext("2d");if(!B)return;const G=Math.max(1,Math.floor(window.devicePixelRatio||1)),Y=z.width/G,X=z.height/G,ie=performance.now()*.001,le=b==="waveform"||b==="rift";C&&(le?C.getByteTimeDomainData(R.current):C.getByteFrequencyData(S.current)),y&&(_p(S.current,ie),Fp(R.current,ie));let te=0;const H=le?R.current:S.current;for(let K=0;K<H.length;K++){const oe=le?(H[K]-128)/128:H[K]/255;te+=oe*oe}if(te=Math.sqrt(te/H.length),E(Math.min(1,te)),B.clearRect(0,0,Y,X),b==="spectrum")Tp(B,Y,X,S.current,T.current);else if(b==="bars")lp(B,Y,X,S.current,T.current);else if(b==="waveform")Ap(B,Y,X,R.current);else if(b==="palette"){const K=(T.current+te*120)%360;kp(B,Y,X,S.current,K)}else if(b==="radial")Cp(B,Y,X,S.current,T.current);else if(b==="rays")Mp(B,Y,X,S.current,T.current,j);else if(b==="particles")wp(B,Y,X,te,T.current,O);else if(b==="rings")Np(B,Y,X,S.current,te,T.current);else if(b==="grid"){const K=(T.current+te*160)%360;mp(B,Y,X,S.current,K)}else if(b==="imageTornado"){const K=p!=null&&p.length?p:s?[s]:[];await yp(D,K,f,Y,X);const oe=(T.current+te*100)%360;bp(B,Y,X,te,oe,D)}else if(b==="colorRipples"){const K=(T.current+te*120)%360;dp(B,Y,X,te,K,L)}else if(b==="starfield"){const K=(T.current+60)%360;Pp(B,Y,X,te,K,W)}else if(b==="orbitals"){const K=(T.current+te*180)%360;Sp(B,Y,X,S.current,K,j)}else if(b==="eqcircle"){const K=(T.current+120)%360;fp(B,Y,X,S.current,K)}else if(b==="triangles"){const K=(T.current+40)%360;vp(B,Y,X,te,K,Z)}else if(b==="blob"){const K=(T.current+90)%360;cp(B,Y,X,te,K,A)}else if(b==="plasma"){const K=(T.current+te*200)%360;jp(B,Y,X,ie,te,K)}else if(b==="rift")Rp(B,Y,X,R.current,te,ie);else if(b==="lavaLamp"){const K=(T.current+te*80)%360;xp(B,Y,X,te,K,_)}else if(b==="cozyFire"){const K=(T.current+te*140)%360;pp(B,Y,X,S.current,te,K,U)}T.current=(T.current+.4)%360,v.current=requestAnimationFrame(P)};return v.current=requestAnimationFrame(P),()=>{window.removeEventListener("resize",I),v.current&&cancelAnimationFrame(v.current)}},[ne,e,t,b,p,f,s,y]),r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none",background:b==="cover"?"transparent":Dp},children:b==="cover"?r.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:r.jsx(hp,{height:a,coverUrl:s,title:i,subtitle:o,label:l})}):r.jsx("canvas",{ref:k,style:{width:typeof n=="number"?`${n}px`:n,height:a,borderRadius:8},role:"img","aria-label":"Stage visualizer canvas"})}),r.jsxs("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:[r.jsx(es,{modes:m,active:b,setActive:x,rows:2}),r.jsx(Lp,{vu:$,hide:e==="youtube"})]})]})},tl=({height:e,autoPlay:t,track:n,source:a,ytRef:s,audioRef:i,hlsRef:o,setVol:l,onEnd:c,volume:u,extractVideoId:h})=>{d.useEffect(()=>{const m=i.current;if(m){if(m.volume=u,m.crossOrigin=a!=null&&a.withCredentials?"use-credentials":"anonymous",(a==null?void 0:a.kind)==="hls"&&ip(a.url)){const g=()=>{m.src=a.url,m.load(),t&&m.play().catch(()=>{})};if(m.canPlayType("application/vnd.apple.mpegurl")){g();return}(async()=>{const x=(await import("hls.js")).default;if(x.isSupported()){const k=new x({xhrSetup:v=>{if(a!=null&&a.withCredentials&&(v.withCredentials=!0),a!=null&&a.headers)for(const[w,M]of Object.entries(a.headers))v.setRequestHeader(w,String(M))}});o.current=k,k.loadSource(a.url),k.attachMedia(m),k.on(x.Events.MANIFEST_PARSED,()=>t&&m.play().catch(()=>{}))}else g()})()}(a==null?void 0:a.kind)==="audio"&&a.url&&(m.src=a.url,m.load(),t&&m.play().catch(()=>{}))}},[a==null?void 0:a.url,a==null?void 0:a.kind,a==null?void 0:a.withCredentials,u,t]);const p=(a==null?void 0:a.kind)==="youtube",f=p?"video":"cover",y=`gp-stage:mode:${(a==null?void 0:a.kind)??"none"}`;return r.jsxs("div",{className:"gp-stage",style:{width:"100%",height:e,background:p?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(a==null?void 0:a.kind)==="youtube"&&r.jsx(Ma,{videoId:a.videoId??h(a.url),onReady:m=>{s.current=m.target,l(u),t&&m.target.playVideo()},onEnd:c,opts:{width:"100%",height:"100%",playerVars:{autoplay:t?1:0,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3}},style:{width:"100%",height:"100%"}}),((a==null?void 0:a.kind)==="audio"||(a==null?void 0:a.kind)==="hls")&&r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{textAlign:"center",color:"var(--text, #e2e8f0)"},children:n!=null&&n.coverUrl?r.jsx("img",{alt:"cover",src:n.coverUrl,style:{height:e-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[n==null?void 0:n.artist," — ",n==null?void 0:n.title]}),r.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-dim, #94a3b8)"},children:(a==null?void 0:a.label)??`${(a==null?void 0:a.codec)??""} ${(a==null?void 0:a.quality)??""}`.trim()})]})}),r.jsx("audio",{ref:i,onEnded:c,onLoadedMetadata:()=>{},crossOrigin:a!=null&&a.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]}),r.jsx(ts,{kind:(a==null?void 0:a.kind)==="hls"?"hls":(a==null?void 0:a.kind)??"audio",audioRef:i,hlsRef:o,height:e,coverUrl:n==null?void 0:n.coverUrl,title:n==null?void 0:n.title,subtitle:n==null?void 0:n.artist,label:(a==null?void 0:a.label)??`${(a==null?void 0:a.codec)??""} ${(a==null?void 0:a.quality)??""}`.trim(),defaultMode:f,storageKey:y},`vis-${y}`)]})};function zp(e,t){const[n,a]=d.useState(()=>{try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}});return d.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(n))}catch{}},[e,n]),[n,a]}const Op="var(--text-dim, #94a3b8)",Bp=({active:e,onClick:t,title:n,children:a})=>r.jsx("button",{type:"button",onClick:t,title:n,style:{padding:"4px 8px",borderRadius:6,fontSize:12,border:`1px solid ${e?"var(--accent, #6366f1)":"var(--border-muted, #334155)"}`,background:e?"var(--accent-muted, rgba(99,102,241,.12))":"var(--surface-overlay, rgba(15,23,42,.6))",color:e?"var(--text-on-accent, #e2e8f0)":"var(--text, #cbd5e1)",cursor:"pointer"},children:a}),nl=({kind:e,audioRef:t,width:n="100%",height:a=360,coverUrl:s,title:i,subtitle:o,label:l,defaultMode:c="cover",storageKey:u="gp-stage:mode",allowedModes:h,overlayOnly:p=!1})=>{const f=d.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette"],[e,h]),y=d.useMemo(()=>{const E=f.includes(c)?c:f[0];try{const D=localStorage.getItem(u);if(!D)return E;const L=JSON.parse(D);return f.includes(L)?L:E}catch{return E}},[f,c,u]),[m,g]=zp(u,y),b=d.useRef(null),[x,k]=d.useState(0),v=d.useRef(null),w=d.useRef(null),M=d.useRef(null),S=d.useRef(null),R=d.useRef(null),T=d.useRef(0),j=m==="spectrum"||m==="bars"||m==="waveform"||m==="palette";d.useEffect(()=>{var A;if(e==="youtube")return;if(!j){v.current&&cancelAnimationFrame(v.current);return}Bt();const E=mn(),D=t.current;if(!D)return;if(!w.current)try{w.current=E.createMediaElementSource(D)}catch{}if(!M.current){const _=E.createAnalyser();_.fftSize=2048,_.smoothingTimeConstant=.85,M.current=_;try{(A=w.current)==null||A.connect(_)}catch{}try{_.connect(E.destination)}catch{}}const L=M.current;S.current=new Uint8Array(L.frequencyBinCount),R.current=new Uint8Array(L.fftSize);const W=()=>{if(!b.current)return;const _=b.current,U=_.getContext("2d");if(!U)return;const ne=_.width,V=_.height;U.clearRect(0,0,ne,V),m==="waveform"?L.getByteTimeDomainData(R.current):L.getByteFrequencyData(S.current);let q=0;const C=m==="waveform"?R.current:S.current;for(let F=0;F<C.length;F++){const I=m==="waveform"?(C[F]-128)/128:C[F]/255;q+=I*I}if(q=Math.sqrt(q/C.length),k(Math.min(1,q)),m==="spectrum"||m==="bars"){const F=S.current,I=m==="bars"?48:Math.min(F.length,256),P=Math.floor(F.length/I),N=ne/I;for(let z=0;z<I;z++){const B=F[z*P]/255,G=B*(V-6),Y=z*N,X=V-G,ie=z/I*240+T.current;U.fillStyle=`hsl(${ie%360}, 80%, ${Math.max(30,40+B*30)}%)`,U.fillRect(Y+1,X,N-2,G)}}else if(m==="waveform"){const F=R.current;U.lineWidth=2,U.strokeStyle="var(--nice-primary-light, #c7d2fe)",U.beginPath();const I=ne/F.length;for(let P=0;P<F.length;P++){const N=(F[P]-128)/128,z=P*I,B=V/2+N*(V*.45);P===0?U.moveTo(z,B):U.lineTo(z,B)}U.stroke()}else if(m==="palette"){const P=ne/12,N=V/6,z=(T.current+q*120)%360;for(let B=0;B<6;B++)for(let G=0;G<12;G++){const Y=(B*12+G)%S.current.length,X=S.current[Y]/255,ie=(z+G/12*180+B/6*90)%360,le=70+X*25,te=25+X*35;U.fillStyle=`hsl(${ie}, ${le}%, ${te}%)`,U.fillRect(G*P,B*N,Math.ceil(P),Math.ceil(N))}}U.strokeStyle=getComputedStyle(document.documentElement).getPropertyValue("--waveform-stroke")||"var(--nice-primary-light, #c7d2fe)",v.current=requestAnimationFrame(W)},Z=()=>{var ne;const _=b.current,U=Math.max(1,Math.floor(window.devicePixelRatio||1));_.width=Math.floor(_.clientWidth*U),_.height=Math.floor(_.clientHeight*U),(ne=_.getContext("2d"))==null||ne.scale(U,U)};return Z(),window.addEventListener("resize",Z),v.current=requestAnimationFrame(W),()=>{window.removeEventListener("resize",Z),v.current&&cancelAnimationFrame(v.current)}},[j,e,t,m]);const O=()=>{if(e==="youtube")return null;const E=12,D=Math.round(x*E);return r.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px 8px",borderRadius:8,border:"1px solid var(--nice-text, #334155)",backdropFilter:"blur(2px)"},children:Array.from({length:E}).map((L,W)=>{const Z=120*(W/E);return r.jsx("div",{style:{width:6,height:18,borderRadius:2,background:W<D?`hsl(${Z}, 80%, 50%)`:"var(--nice-text, #1f2937)"}},W)})})},$=()=>r.jsx("div",{style:{textAlign:"center",color:"var(--nice-border, #e2e8f0)"},children:s?r.jsx("img",{alt:"cover",src:s,style:{height:a-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsx("div",{style:{fontSize:18,fontWeight:600},children:i??""}),r.jsx("div",{style:{marginTop:8,fontSize:12,color:Op},children:l??o??""})]})});return r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:m==="cover"?r.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center",background:"transparent"},children:$()}):r.jsx("canvas",{ref:b,style:{width:typeof n=="number"?`${n}px`:n,height:a,borderRadius:8},role:"img","aria-label":"Stage visualizer canvas"})}),r.jsxs("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:[r.jsx("div",{style:{position:"absolute",top:10,right:10,display:"flex",gap:6,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px",borderRadius:10,border:"1px solid var(--nice-text, #334155)",backdropFilter:"blur(2px)",pointerEvents:"auto",zIndex:9999},children:f.map(E=>r.jsx(Bp,{active:m===E,onClick:()=>g(E),title:`Tryb: ${E}`,children:E},E))}),r.jsx("div",{style:{position:"absolute",right:10,bottom:10,pointerEvents:"none",zIndex:9998},children:r.jsx(O,{})})]})]})},rl=({artist:e,title:t,hideControls:n=!0,isPlaying:a,onTimeUpdate:s,searchYouTubeByArtistTitle:i})=>{const{t:o}=Te(),[l,c]=d.useState(e||""),[u,h]=d.useState(t||""),[p,f]=d.useState(null),[y,m]=d.useState(null),g=d.useRef(null),[b,x]=d.useState({width:Math.min(560,window.innerWidth-32),height:Math.min(315,(window.innerWidth-32)*9/16)});d.useEffect(()=>{e&&t&&i&&i(e,t).then(f)},[e,t,i]),d.useEffect(()=>{y&&(a?y.playVideo():y.pauseVideo())},[a,y]),d.useEffect(()=>{if(y&&s){const v=setInterval(()=>{const w=y.getCurrentTime();s(w)},100);return()=>clearInterval(v)}},[y,s]),d.useEffect(()=>{const v=()=>{if(g.current){const w=g.current.clientWidth,M=Math.round(w*(9/16));x({width:w,height:M})}};return v(),window.addEventListener("resize",v),()=>window.removeEventListener("resize",v)},[]);const k=async()=>{if(!i)return;const v=await i(l,u);f(v)};return r.jsxs("div",{ref:g,style:{width:"100%",maxWidth:"900px",margin:"0 auto"},children:[(!e||!t||!p)&&r.jsxs("div",{children:[r.jsx("input",{value:l,onChange:v=>c(v.target.value),placeholder:o("youtubePlayer.artist","Artist"),"aria-label":o("youtubePlayer.artist","Artist")}),r.jsx("input",{value:u,onChange:v=>h(v.target.value),placeholder:o("youtubePlayer.title","Title"),"aria-label":o("youtubePlayer.title","Title")}),r.jsx("button",{onClick:k,children:o("youtubePlayer.search","Search")})]}),p&&r.jsxs("div",{children:[r.jsx(Ma,{videoId:p,opts:{width:b.width.toString(),height:b.height.toString(),playerVars:{autoplay:1,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,annotations:0}},onReady:v=>m(v.target)}),!n&&r.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px"},children:[r.jsx("button",{onClick:()=>y==null?void 0:y.playVideo(),children:"? Play"}),r.jsx("button",{onClick:()=>y==null?void 0:y.pauseVideo(),children:"? Pause"})]})]})]})},Qs=e=>({name:e,dirs:new Map,files:[]}),Gp=e=>(e??[]).map(t=>t instanceof File?{file:t}:t),Wp=e=>e.replace(/\\/g,"/"),Up=e=>{const t=Qs("/");for(const n of e){const a=Wp(n.path??n.file.name).split("/").filter(Boolean);if(a.length<=1){t.files.push({file:n.file,path:a[0]??n.file.name});continue}let s=t;for(let i=0;i<a.length-1;i++){const o=a[i];s.dirs.has(o)||s.dirs.set(o,Qs(o)),s=s.dirs.get(o)}s.files.push({file:n.file,path:a[a.length-1]??n.file.name})}return t},pa=e=>e.slice().sort((t,n)=>(t.path??t.file.name).localeCompare(n.path??n.file.name)),qp={tidal:se.NtdWave,spotify:se.NtdMusic,youtube:se.NtdPlay},fa=({q:e,setQ:t,t:n})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[r.jsx("div",{style:{flex:1},children:r.jsx(we.NiceTextInput,{value:e,onChange:t,placeholder:n("libraryExplorer.searchPlaceholder","Search…"),size:"sm"})}),e&&r.jsx(we.NiceButton,{variant:"ghost",size:"sm",onClick:()=>t(""),children:r.jsx(se.NtdClose,{size:14})})]}),ma=({files:e,t,onOpenInEditor:n,onPlayFile:a})=>e.length?r.jsx("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:r.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[r.jsx("thead",{children:r.jsxs("tr",{style:{color:"var(--nice-text-muted, #94a3b8)",textAlign:"left"},children:[r.jsx("th",{style:{padding:"8px 12px",fontWeight:600},children:t("libraryExplorer.colFile","File")}),r.jsx("th",{style:{padding:"8px 12px",fontWeight:600},children:t("libraryExplorer.colType","Type")}),r.jsx("th",{style:{padding:"8px 12px",fontWeight:600,width:200},children:t("libraryExplorer.colActions","Actions")})]})}),r.jsx("tbody",{children:e.map(s=>{const i=s.path??s.file.name;return r.jsxs("tr",{style:{borderTop:"1px solid var(--nice-border, #1e293b)"},children:[r.jsx("td",{style:{padding:"6px 12px",maxWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),r.jsx("td",{style:{padding:"6px 12px",color:"var(--nice-text-muted, #94a3b8)"},children:s.file.type||"—"}),r.jsxs("td",{style:{padding:"6px 12px",display:"flex",gap:6},children:[n&&r.jsxs(we.NiceButton,{variant:"outline",size:"sm",onClick:()=>n(s.file),children:[r.jsx(se.NtdEdit,{size:13})," ",t("libraryExplorer.openInEditor","Edit")]}),a&&r.jsxs(we.NiceButton,{variant:"primary",size:"sm",onClick:()=>a(s.file),children:[r.jsx(se.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]})]},i)})})]})}):r.jsx("div",{style:{fontSize:13,color:"var(--nice-text-muted, #94a3b8)",padding:12},children:t("libraryExplorer.noFiles","No files")}),al=({streams:e,t,onPlayStream:n})=>e.length?r.jsxs("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:[r.jsx("div",{style:{padding:"8px 12px",fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:t("libraryExplorer.streaming","Streaming")}),r.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:e.map(a=>r.jsxs("li",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,borderTop:"1px solid var(--nice-border, #1e293b)",padding:"8px 12px"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.title}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",display:"flex",alignItems:"center",gap:4},children:[d.createElement(qp[a.provider],{size:12})," ",a.provider.toUpperCase(),a.artist?` • ${a.artist}`:""]})]}),n&&r.jsxs(we.NiceButton,{variant:"primary",size:"sm",onClick:()=>n(a),children:[r.jsx(se.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]},`${a.provider}:${a.id}`))})]}):null,Zr=({name:e,enabled:t})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 8px",fontSize:13},children:[r.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:t?"var(--nice-success, #10b981)":"var(--nice-border, #d1d5db)"}}),r.jsx("span",{style:{color:t?"inherit":"var(--nice-text-muted, #94a3b8)"},children:e})]}),Vp=({variant:e="full",files:t=[],streams:n=[],enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,t:c,style:u,id:h,accessMode:p,"data-testid":f})=>{const{t:y}=Te(),m=c??y,[g,b]=d.useState(""),x=d.useMemo(()=>Gp(t),[t]),k=d.useCallback(M=>{const S=g.trim().toLowerCase();return!S||M.toLowerCase().includes(S)},[g]),v=d.useMemo(()=>pa(x).filter(M=>k(`${M.path??M.file.name} ${M.file.type||""}`)),[x,k]),w=d.useMemo(()=>n.filter(M=>k(`${M.title} ${M.artist??""} ${M.provider}`)),[n,k]);return p==="hidden"?null:e==="minimal"?r.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...u},id:h,"data-testid":f,children:[r.jsx(fa,{q:g,setQ:b,t:m}),r.jsx(ma,{files:v,t:m,onOpenInEditor:s,onPlayFile:i}),r.jsx(al,{streams:w,t:m,onPlayStream:o})]}):e==="onlyFiles"?r.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...u},id:h,"data-testid":f,children:[r.jsx(fa,{q:g,setQ:b,t:m}),r.jsx(ma,{files:v,t:m,onOpenInEditor:s,onPlayFile:i})]}):r.jsx(Hp,{q:g,setQ:b,normFiles:x,filteredStreams:w,enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,style:u,id:h,"data-testid":f,t:m})},Hp=({q:e,setQ:t,normFiles:n,filteredStreams:a,enableProviders:s,onOpenInEditor:i,onPlayFile:o,onPlayStream:l,className:c,style:u,id:h,"data-testid":p,t:f})=>{const y=d.useMemo(()=>Up(n),[n]),[m,g]=d.useState({}),[b,x]=d.useState("/"),k=S=>g(R=>({...R,[S]:!R[S]})),v=(S,R)=>{const T=R==="/"?`/${S.name}`:`${R}${S.name}/`,j=R==="/"&&S.name==="/",O=m[T]??j,$=Array.from(S.dirs.keys()).sort();return r.jsxs("div",{children:[!j&&r.jsxs("button",{type:"button",onClick:()=>{k(T),x(T)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"4px 8px",border:"none",borderRadius:6,cursor:"pointer",textAlign:"left",background:b===T?"var(--nice-accent-tint-20, rgba(99,102,241,0.2))":"transparent",color:"var(--nice-text, inherit)"},children:[r.jsx("span",{style:{display:"inline-flex"},children:O?r.jsx(se.NtdFolderOpen,{size:14}):r.jsx(se.NtdFolder,{size:14})}),r.jsx("span",{style:{fontSize:13},children:S.name})]}),(j||O)&&r.jsx("div",{style:{paddingLeft:j?0:16},children:$.map(E=>v(S.dirs.get(E),T))})]},T)},w=d.useMemo(()=>{let S;if(b==="/")S=pa(n);else{const R=b.replace(/^\//,"").split("/").filter(Boolean);let T=y;for(const j of R){const O=T.dirs.get(j);if(!O)return[];T=O}S=pa(T.files)}return e?S.filter(R=>(R.path??R.file.name).toLowerCase().includes(e.toLowerCase())):S},[b,y,n,e]),M={tidal:(s==null?void 0:s.tidal)??!0,spotify:(s==null?void 0:s.spotify)??!0,youtube:(s==null?void 0:s.youtube)??!0};return r.jsxs("div",{className:c,style:{display:"flex",gap:12,color:"var(--nice-text, #e2e8f0)",...u},id:h,"data-testid":p,children:[r.jsxs("div",{style:{flex:"0 0 220px",border:"1px solid var(--nice-border, #334155)",borderRadius:12,padding:8},children:[r.jsx("div",{style:{padding:"0 8px 8px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:f("libraryExplorer.library","Library")}),v(y,"/"),r.jsxs("div",{style:{marginTop:16,borderTop:"1px solid var(--nice-border, #1e293b)",paddingTop:8},children:[r.jsx("div",{style:{padding:"0 8px 4px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:f("libraryExplorer.streaming","Streaming")}),r.jsx(Zr,{name:"Tidal",enabled:M.tidal}),r.jsx(Zr,{name:"Spotify",enabled:M.spotify}),r.jsx(Zr,{name:"YouTube",enabled:M.youtube})]})]}),r.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[r.jsx(fa,{q:e,setQ:t,t:f}),r.jsx(ma,{files:w,t:f,onOpenInEditor:i,onPlayFile:o}),(M.tidal||M.spotify||M.youtube)&&r.jsx(al,{streams:a.filter(S=>M[S.provider]),t:f,onPlayStream:l})]})]})},Kp=({kind:e,color:t})=>{const n={width:14,height:14,viewBox:"0 0 24 24",fill:t,"aria-hidden":!0};switch(e){case"youtube":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M23 7.2s-.2-1.6-.9-2.3c-.8-.9-1.7-.9-2.1-1C16.9 3.5 12 3.5 12 3.5s-4.9 0-8 .4c-.4.1-1.3.1-2.1 1C1.2 5.6 1 7.2 1 7.2S.8 9.1.8 11v1.8c0 1.9.2 3.8.2 3.8s.2 1.6.9 2.3c.8.9 1.9.9 2.4 1 1.7.2 7.7.4 7.7.4s4.9 0 8-.4c.4-.1 1.3-.1 2.1-1 .7-.7.9-2.3.9-2.3s.2-1.9.2-3.8V11c0-1.9-.2-3.8-.2-3.8zM9.7 14.6V8.2l6.3 3.2-6.3 3.2z"})});case"spotify":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.59 14.42c-.18.3-.57.4-.87.21-2.39-1.46-5.4-1.79-8.95-.98-.34.08-.68-.13-.76-.47-.08-.34.13-.68.47-.76 3.88-.89 7.21-.5 9.89 1.13.31.19.4.58.22.87zm1.23-2.72c-.23.37-.71.49-1.08.26-2.74-1.69-6.92-2.18-10.16-1.19-.41.13-.85-.11-.97-.52-.13-.41.11-.85.52-.97 3.7-1.12 8.31-.58 11.45 1.34.37.23.49.71.24 1.08zm.11-2.84C14.55 8.84 9.5 8.66 6.43 9.6c-.49.15-1.01-.13-1.16-.62-.15-.49.13-1.01.62-1.16 3.52-1.07 9.1-.86 12.69 1.27.43.26.57.82.31 1.25-.26.43-.82.57-1.25.31z"})});case"tidal":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 2L8 6l4 4 4-4-4-4zM4 6L0 10l4 4 4-4-4-4zm16 0l-4 4 4 4 4-4-4-4zm-8 8l-4 4 4 4 4-4-4-4z"})});case"hls":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M2 12h2v6H2v-6zm4-4h2v10H6V8zm4-4h2v14h-2V4zm4 4h2v10h-2V8zm4 4h2v6h-2v-6z"})});case"audio":default:return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"})})}},ns=({data:e,display:t,callbacks:n,state:a})=>{const{id:s,index:i,artist:o,title:l,version:c,lp:u,sourcesAvailable:h=[]}=e,{allowVersion:p=!0,dragHandleProps:f}=t,{onChange:y,onRemove:m,onMoveUp:g,onMoveDown:b,onChangeLp:x,onSelectSource:k}=n,{readOnly:v=!1,canMoveUp:w=!0,canMoveDown:M=!0,activeSource:S}=a,{t:R}=Te(),T=d.useRef(null);d.useEffect(()=>{!o&&T.current&&T.current.focus()},[o]);const j=D=>{if(!v&&D.key==="Enter"){const L=D.target.closest("div.gpi-row"),W=L==null?void 0:L.querySelectorAll("input[data-role='field']");if(!W||W.length===0)return;const Z=Array.from(W).indexOf(D.target),A=W[Z+1]??W[0];A==null||A.focus()}},O=D=>{const L=h.includes(D),W=S===D,Z={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid var(--nice-border, #e5e7eb)",background:W?"var(--active-bg, #eef2ff)":"var(--bg, #fff)",opacity:L?1:.35,cursor:L&&k&&!v?"pointer":"default",transition:"transform .05s ease"},A=D==="youtube"?"var(--nice-danger, #ff0000)":D==="spotify"?"var(--nice-success, #1db954)":D==="tidal"?"var(--nice-text, #111827)":D==="hls"?"var(--nice-accent, #7c3aed)":"var(--nice-text, #374151)",_=D==="youtube"?"YouTube":D==="spotify"?"Spotify":D==="tidal"?"TIDAL":D==="hls"?"HLS":"Audio",U=R("playlistItem.sourceLabel")+": "+_+(W?` ${R("playlistItem.sourceSelected")}`:""),ne=()=>{!L||!k||v||k(D)};return r.jsx("button",{type:"button",title:_,onClick:ne,disabled:!L||v,style:Z,"aria-pressed":W,"aria-label":U,children:r.jsx(Kp,{kind:D,color:A})},D)},$=["youtube","tidal","spotify","hls","audio"],E=typeof u=="number"?u:i+1;return r.jsxs("div",{className:"gpi-row",role:"group","aria-label":R("playlistItem.trackNumber")+" "+(i+1),style:{display:"grid",gridTemplateColumns:p?"56px 1fr 1fr 1fr auto auto":"56px 1fr 1fr auto auto",gap:8,alignItems:"center"},children:[r.jsx("input",{type:"number",min:1,value:E,onChange:D=>x==null?void 0:x(Number(D.target.value)),disabled:v||!x,"aria-label":"Lp",title:R("playlistItem.positionOnList"),style:Yp}),r.jsx("input",{ref:T,"data-role":"field",type:"text",value:o,onChange:D=>y({artist:D.target.value}),placeholder:"Artist",onKeyDown:j,disabled:v,"aria-label":"Artist",className:"gpi-input",style:Xr}),r.jsx("input",{"data-role":"field",type:"text",value:l,onChange:D=>y({title:D.target.value}),placeholder:"Title",onKeyDown:j,disabled:v,"aria-label":"Title",className:"gpi-input",style:Xr}),p&&r.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:D=>y({version:D.target.value||void 0}),placeholder:R("playlistItem.versionOptional"),onKeyDown:j,disabled:v,"aria-label":"Version",className:"gpi-input",style:Xr}),r.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":R("playlistItem.availableSources"),children:$.map(O)}),r.jsxs("div",{className:"gpi-actions",style:{display:"flex",gap:6,justifyContent:"flex-end"},children:[f&&r.jsx("button",{type:"button",...f,draggable:!0,"aria-label":R("playlistItem.dragReorder"),title:R("playlistItem.dragReorder"),style:Jn,children:"≡"}),r.jsx("button",{type:"button",onClick:g,disabled:!w||v,"aria-label":R("playlistItem.moveUp"),title:R("playlistItem.moveUp"),style:Jn,children:"↑"}),r.jsx("button",{type:"button",onClick:b,disabled:!M||v,"aria-label":R("playlistItem.moveDown"),title:R("playlistItem.moveDown"),style:Jn,children:"↓"}),r.jsx("button",{type:"button",onClick:m,disabled:v,"aria-label":R("common.delete"),title:R("common.delete"),style:{...Jn,color:"var(--danger, #b91c1c)"},children:r.jsx(se.NtdClose,{size:14})})]})]})},Yp={width:48,border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 6px",fontSize:14,textAlign:"center"},Xr={width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 10px",fontSize:14},Jn={border:"1px solid var(--nice-border, #d1d5db)",background:"var(--bg, #fff)",padding:"6px 8px",borderRadius:6,cursor:"pointer"},ga=()=>Math.random().toString(36).slice(2,10),er=e=>(e??[]).map(t=>({id:ga(),...t})),Zp=e=>e.map(({id:t,...n})=>n),Xp=null,Qp=e=>{const t=e.trim();if(!t)return null;const n=t.split(/\s[-�]\s/);if(n.length<2){const o=t.split(/[;|]/).map(l=>l.trim());return o.length>=2?{artist:o[0],title:o[1],version:o[2]||void 0}:null}const a=n[0].trim(),s=n.slice(1).join(" - ").trim(),i=s.match(/^(.*?)\s*[([](.+?)[)\]]\s*$/);if(i){const o=i[1].trim(),l=i[2].trim();return{artist:a,title:o,version:l||void 0}}return{artist:a,title:s,version:void 0}},sl=({value:e,defaultValue:t,onChange:n,allowVersion:a=!0,maxItems:s,addButtonLabel:i,emptyState:o=Xp,readOnly:l=!1,autoFocusNewItem:c=!0,enableBulkPaste:u=!0})=>{const{t:h}=Te(),p=e!==void 0,[f,y]=d.useState(()=>er(e||t)),[m,g]=d.useState(""),b=d.useRef(null),[x,k]=d.useState(null);d.useEffect(()=>{p&&y(er(e))},[p,JSON.stringify(e)]);const v=d.useCallback(U=>{n==null||n(Zp(U))},[n]),w=d.useCallback(U=>{if(p){const ne=U(er(e));v(ne)}else y(ne=>{const V=U(ne);return v(V),V})},[v,p,e]),M=s?f.length<s:!0,S=d.useCallback(()=>{!M||l||w(U=>[...U,{id:ga(),artist:"",title:"",version:void 0}])},[M,l,w]),R=d.useCallback((U,ne)=>{w(V=>V.map(q=>q.id===U?{...q,...ne}:q))},[w]),T=d.useCallback(U=>{l||w(ne=>ne.filter(V=>V.id!==U))},[l,w]),j=d.useCallback((U,ne)=>{w(V=>{const q=V.findIndex(P=>P.id===U);if(q<0)return V;const C=q+ne;if(C<0||C>=V.length)return V;const F=[...V],[I]=F.splice(q,1);return F.splice(C,0,I),F})},[w]),O=d.useCallback((U,ne)=>{w(V=>{const q=V.findIndex(P=>P.id===U);if(q<0)return V;const C=Math.max(0,Math.min(V.length-1,ne-1));if(q===C)return V;const F=[...V],[I]=F.splice(q,1);return F.splice(C,0,I),F})},[w]),$=U=>ne=>{l||(b.current=U,ne.dataTransfer.effectAllowed="move",ne.dataTransfer.setData("text/plain",U))},E=U=>ne=>{l||(ne.preventDefault(),ne.dataTransfer.dropEffect="move",k(U))},D=U=>()=>k(ne=>ne===U?null:ne),L=U=>ne=>{if(l)return;ne.preventDefault();const V=b.current??ne.dataTransfer.getData("text/plain");k(null),b.current=null,!(!V||V===U)&&w(q=>{const C=q.findIndex(N=>N.id===V),F=q.findIndex(N=>N.id===U);if(C<0||F<0||C===F)return q;const I=[...q],[P]=I.splice(C,1);return I.splice(F,0,P),I})},W=()=>{b.current=null,k(null)},Z=d.useCallback(()=>{if(!u||l)return;const ne=m.split(/\r?\n/).map(V=>V.trim()).filter(Boolean).map(Qp).filter(V=>!!V);ne.length!==0&&(w(V=>{const q=(s??1/0)-V.length,C=ne.slice(0,Math.max(0,q)).map(F=>({id:ga(),...F}));return[...V,...C]}),g(""))},[u,l,m,s,w]);d.useEffect(()=>{},[f.length,c]);const A=o??r.jsx("div",{style:{padding:"0.75rem",color:"var(--nice-text-secondary, #777)",fontStyle:"italic"},children:h("genericPlaylist.emptyState","No songs. Add the first one below.")}),_=i??h("genericPlaylist.addSong","Add song");return r.jsxs("div",{className:"gp-container",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[r.jsxs("div",{className:"gp-header",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[r.jsx("h3",{style:{margin:0,fontSize:16},children:h("genericPlaylist.playlist","Playlist")}),r.jsx("div",{style:{marginLeft:"auto",display:"flex",gap:8},children:r.jsxs("button",{type:"button",onClick:S,disabled:!M||l,className:"gp-add",style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},"aria-label":_,children:["+ ",_]})})]}),f.length===0?r.jsx("div",{className:"gp-empty",children:A}):r.jsx("ol",{className:"gp-list",style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:8},children:f.map((U,ne)=>{const V=x===U.id;return r.jsx("li",{draggable:!l,onDragStart:$(U.id),onDragOver:E(U.id),onDragLeave:D(U.id),onDrop:L(U.id),onDragEnd:W,style:{border:V?"2px dashed var(--nice-info, #6366f1)":"2px solid transparent",borderRadius:8,padding:V?4:0},children:r.jsx(ns,{data:{id:U.id,index:ne,lp:ne+1,artist:U.artist,title:U.title,version:a?U.version??void 0:void 0,sourcesAvailable:void 0},display:{allowVersion:a,dragHandleProps:{onDragStart:$(U.id)}},callbacks:{onChange:q=>R(U.id,q),onRemove:()=>T(U.id),onMoveUp:()=>j(U.id,-1),onMoveDown:()=>j(U.id,1),onChangeLp:q=>O(U.id,q)},state:{readOnly:l,canMoveUp:ne>0,canMoveDown:ne<f.length-1}})},U.id)})}),u&&!l&&r.jsx("div",{style:{marginTop:12},children:r.jsxs("details",{children:[r.jsx("summary",{style:{cursor:"pointer",color:"var(--nice-text, #374151)"},children:h("genericPlaylist.bulkPasteSummary","Paste multiple items at once")}),r.jsxs("div",{style:{marginTop:6},children:[r.jsx("textarea",{value:m,onChange:U=>g(U.target.value),placeholder:h("genericPlaylist.bulkPastePlaceholder",`Paste lines in format:
48
65
  Artist - Title (Version)
49
66
  Artist � Title [Remastered 2011]
50
- OR: Artist;Title;Version`),rows:3,style:{width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:8,fontFamily:"inherit"}}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:6},children:[s.jsx("div",{style:{color:"var(--nice-text-secondary, #6b7280)",fontSize:12},children:f("genericPlaylist.bulkPasteHint","Each line will be added as a separate song.")}),s.jsx("button",{type:"button",onClick:Y,disabled:!p.trim(),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},children:f("genericPlaylist.addFromList","Add from list")})]})]})]})})]})},ss=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #f59e0b)","var(--nice-warning, #eab308)","var(--nice-success, #84cc16)","var(--nice-success, #22c55e)","var(--nice-info, #14b8a6)","var(--nice-info, #06b6d4)","var(--nice-primary, #3b82f6)","var(--nice-info, #6366f1)","var(--nice-accent, #8b5cf6)","var(--nice-accent, #a855f7)","var(--nice-accent-pink, #d946ef)","var(--nice-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)","#78716c","var(--nice-text-secondary, #64748b)","var(--nice-text, #000000)"],On=["??","??","??","??","??","??","??","??","??","?","??","??","??","??","??","??"],Yo=({tags:e,onCreateTag:t,onUpdateTag:n,onDeleteTag:r,selectedTracks:a,onAssignTag:o,onUnassignTag:i})=>{const{t:l}=we(),[c,d]=u.useState(null),[f,h]=u.useState(""),[m,y]=u.useState(ss[8]),[p,v]=u.useState(On[0]),[x,b]=u.useState(!1),[S,g]=u.useState(null),[k,M]=u.useState(""),[N,j]=u.useState(""),[_,P]=u.useState(""),V=u.useCallback(O=>{d(O.id),M(O.name),j(O.color),P(O.icon||On[0])},[]),z=u.useCallback(()=>{c&&k.trim()&&(n(c,k.trim(),N,_),d(null))},[c,k,N,_,n]),A=u.useCallback(()=>{f.trim()&&(t(f.trim(),m,p),h(""),b(!1))},[f,m,p,t]),I=u.useCallback(O=>{S===O?(r(O),g(null)):(g(O),setTimeout(()=>g(null),3e3))},[S,r]),L=a&&a.length>0,U=O=>!a||a.length===0?!1:a.every(Z=>Z.tags.includes(O)),Y=O=>!a||a.length===0?!1:a.some(Z=>Z.tags.includes(O))&&!U(O);return s.jsxs("div",{style:{border:"1px solid var(--border-color, #e5e7eb)",borderRadius:10,background:"var(--card-bg, #fff)",overflow:"hidden"},children:[s.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:[s.jsx("span",{style:{fontSize:"1rem"},children:"???"}),s.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:l("playlistManager.tagManager")}),s.jsx("div",{style:{flex:1}}),s.jsxs("button",{onClick:()=>b(!x),style:{background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"4px 10px",fontSize:"0.72rem",cursor:"pointer"},children:["+ ",l("playlistManager.newTag")]})]}),s.jsxs("div",{style:{padding:12},children:[x&&s.jsxs("div",{style:{border:"1px solid var(--border-color, #d1d5db)",borderRadius:8,padding:10,marginBottom:12,background:"var(--surface-bg, #f9fafb)"},children:[s.jsxs("div",{style:{display:"flex",gap:6,marginBottom:8},children:[s.jsx("input",{type:"text",value:f,onChange:O=>h(O.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:O=>O.key==="Enter"&&A()}),s.jsx("button",{onClick:A,disabled:!f.trim(),style:{background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"5px 12px",fontSize:"0.78rem",cursor:"pointer",opacity:f.trim()?1:.5},children:"?"})]}),s.jsxs("div",{style:{marginBottom:6},children:[s.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.color")}),s.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:ss.map(O=>s.jsx("div",{onClick:()=>y(O),style:{width:20,height:20,borderRadius:"50%",background:O,cursor:"pointer",border:m===O?"3px solid var(--accent, #3b82f6)":"2px solid transparent",boxSizing:"border-box"}},O))})]}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.icon")}),s.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:On.map(O=>s.jsx("div",{onClick:()=>v(O),style:{width:26,height:26,borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"0.85rem",background:p===O?"var(--accent-bg, #eff6ff)":"transparent",border:p===O?"1px solid var(--accent, #3b82f6)":"1px solid transparent"},children:O},O))})]})]}),L&&s.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?s.jsx("div",{style:{textAlign:"center",padding:20,opacity:.3,fontSize:"0.82rem"},children:l("playlistManager.noTags")}):s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.map(O=>s.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderRadius:8,border:"1px solid var(--border-color, #e5e7eb)",background:c===O.id?"var(--surface-bg, #f9fafb)":"transparent"},children:c===O.id?s.jsxs(s.Fragment,{children:[s.jsx("select",{value:_,onChange:Z=>P(Z.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:On.map(Z=>s.jsx("option",{value:Z,children:Z},Z))}),s.jsx("input",{type:"color",value:N,onChange:Z=>j(Z.target.value),style:{width:24,height:24,border:"none",cursor:"pointer",padding:0}}),s.jsx("input",{type:"text",value:k,onChange:Z=>M(Z.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:Z=>Z.key==="Enter"&&z()}),s.jsx("button",{onClick:z,style:_n("var(--accent, #3b82f6)"),children:"?"}),s.jsx("button",{onClick:()=>d(null),style:_n("var(--text-secondary, #9ca3af)"),children:"?"})]}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 10px",borderRadius:20,background:`${O.color}18`,color:O.color,fontWeight:600,fontSize:"0.78rem"},children:[O.icon&&s.jsx("span",{children:O.icon}),O.name]}),L&&o&&i&&s.jsx("input",{type:"checkbox",checked:U(O.id),ref:Z=>{Z&&(Z.indeterminate=Y(O.id))},onChange:()=>{const Z=a.map(H=>H.id);U(O.id)?i(Z,O.id):o(Z,O.id)},style:{cursor:"pointer"}}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:()=>V(O),style:_n("var(--text-secondary, #9ca3af)"),title:l("playlistManager.editTag"),children:"?"}),s.jsx("button",{onClick:()=>I(O.id),style:_n(S===O.id?"var(--error, #ef4444)":"var(--text-secondary, #9ca3af)"),title:S===O.id?l("playlistManager.confirmDelete"):l("playlistManager.deleteTag"),children:S===O.id?"?":"??"})]})},O.id))})]})]})},_n=e=>({background:"none",border:"none",cursor:"pointer",fontSize:"0.82rem",color:e,padding:"2px 4px"});var ba=(e=>(e.Static="static",e.Dynamic="dynamic",e))(ba||{}),Zo=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(Zo||{}),Xo=(e=>(e.Left="left",e.Right="right",e))(Xo||{}),Xe=(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))(Xe||{}),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||{}),Qo=(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))(Qo||{}),Yt=(e=>(e.Asc="asc",e.Desc="desc",e))(Yt||{}),dt=(e=>(e.Library="library",e.Spotify="spotify",e.Tidal="tidal",e.YouTube="youtube",e.MusicBrainz="musicbrainz",e.Import="import",e.Manual="manual",e))(dt||{});const df=[{value:Xe.Artist,label:"Artist"},{value:Xe.Title,label:"Title"},{value:Xe.Album,label:"Album"},{value:Xe.Genre,label:"Genre"},{value:Xe.Year,label:"Year"},{value:Xe.Duration,label:"Duration (s)"},{value:Xe.Rating,label:"Rating"},{value:Xe.PlayCount,label:"Play Count"},{value:Xe.Tag,label:"Tag"},{value:Xe.Source,label:"Source"},{value:Xe.AddedDate,label:"Added Date"}],uf=[{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 ff(e){return"logic"in e&&"rules"in e}function Wr(){return{id:crypto.randomUUID(),field:Xe.Artist,operator:Qe.Contains,value:""}}function Jo(){return{id:crypto.randomUUID(),logic:"and",rules:[Wr()]}}const hf=({rule:e,onChange:t,onRemove:n})=>s.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[s.jsx("select",{className:"form-select form-select-sm",style:{width:130},value:e.field,onChange:r=>t({...e,field:r.target.value}),children:df.map(r=>s.jsx("option",{value:r.value,children:r.label},r.value))}),s.jsx("select",{className:"form-select form-select-sm",style:{width:130},value:e.operator,onChange:r=>t({...e,operator:r.target.value}),children:uf.map(r=>s.jsx("option",{value:r.value,children:r.label},r.value))}),s.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&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-muted",children:"–"}),s.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})})]}),s.jsx("button",{className:"btn btn-outline-danger btn-sm",onClick:n,title:"Remove rule",children:"✕"})]}),ei=({group:e,onChange:t,onRemove:n,depth:r=0})=>{const{t:a}=we(),o=u.useCallback((h,m)=>{const y=[...e.rules];y[h]=m,t({...e,rules:y})},[e,t]),i=u.useCallback(h=>{const m=e.rules.filter((y,p)=>p!==h);t({...e,rules:m.length>0?m:[Wr()]})},[e,t]),l=u.useCallback(()=>{t({...e,rules:[...e.rules,Wr()]})},[e,t]),c=u.useCallback(()=>{t({...e,rules:[...e.rules,Jo()]})},[e,t]),d=u.useCallback(()=>{t({...e,logic:e.logic==="and"?"or":"and"})},[e,t]),f=e.logic==="and"?"var(--bs-primary)":"var(--bs-warning)";return s.jsxs("div",{className:"p-2 mb-2 rounded",style:{borderLeft:`3px solid ${f}`,backgroundColor:r%2===0?"rgba(var(--bs-body-color-rgb), 0.03)":"transparent"},children:[s.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[s.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()}),s.jsx("span",{className:"text-muted small",children:a("playlistManager.matchAll","Match all / any of these rules")}),s.jsxs("div",{className:"ms-auto d-flex gap-1",children:[s.jsx("button",{className:"btn btn-outline-secondary btn-sm",onClick:l,title:"Add rule",children:"+ Rule"}),r<3&&s.jsx("button",{className:"btn btn-outline-secondary btn-sm",onClick:c,title:"Add nested group",children:"+ Group"}),n&&s.jsx("button",{className:"btn btn-outline-danger btn-sm",onClick:n,title:"Remove group",children:"✕"})]})]}),e.rules.map((h,m)=>ff(h)?s.jsx(ei,{group:h,onChange:y=>o(m,y),onRemove:()=>i(m),depth:r+1},h.id):s.jsx(hf,{rule:h,onChange:y=>o(m,y),onRemove:()=>i(m)},h.id))]})},ti=({rules:e,onChange:t,limit:n,onLimitChange:r})=>{const{t:a}=we(),o=e??Jo();return s.jsxs("div",{className:"border rounded p-3",children:[s.jsxs("h6",{className:"mb-3",children:["🔄 ",a("playlistManager.dynamicRules","Dynamic Playlist Rules")]}),s.jsx("p",{className:"text-muted small mb-3",children:a("playlistManager.dynamicRulesHint","Tracks matching these rules will automatically be included in the playlist.")}),s.jsx(ei,{group:o,onChange:t}),r&&s.jsxs("div",{className:"d-flex align-items-center gap-2 mt-3 pt-2 border-top",children:[s.jsx("label",{className:"form-label mb-0 small",children:a("playlistManager.maxTracks","Max tracks:")}),s.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)}}),s.jsx("span",{className:"text-muted small",children:a("playlistManager.leaveEmptyForAll","(leave empty for unlimited)")})]})]})},os=e=>{if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`},pf={library:"??",spotify:"??",tidal:"?",youtube:"??",musicbrainz:"??",import:"??",manual:"?"},va=({tracks:e,tags:t,selectedTrackIds:n,onSelectionChange:r,onPlay:a,onRemove:o,onReorder:i,onTagTracks:l,onRateTracks:c,sortField:d,sortDir:f,onSortChange:h,filterText:m,onFilterChange:y,compact:p=!1,draggable:v=!1,onDragStart:x,dropTarget:b=!1,onDrop:S})=>{const{t:g}=we(),[k,M]=u.useState(null),[N,j]=u.useState(null),_=u.useRef(null),P=u.useMemo(()=>{let w=e??[];if(m.trim()){const $=m.toLowerCase();w=w.filter(R=>{var T,C;return R.title.toLowerCase().includes($)||R.artist.toLowerCase().includes($)||((T=R.album)==null?void 0:T.toLowerCase().includes($))||((C=R.genre)==null?void 0:C.toLowerCase().includes($))})}return[...w].sort(($,R)=>{const T=f==="asc"?1:-1;switch(d){case"title":return T*$.title.localeCompare(R.title);case"artist":return T*$.artist.localeCompare(R.artist);case"album":return T*($.album??"").localeCompare(R.album??"");case"duration":return T*(($.duration??0)-(R.duration??0));case"year":return T*(($.year??0)-(R.year??0));case"rating":return T*(($.rating??0)-(R.rating??0));case"addedDate":return T*($.addedAt??"").localeCompare(R.addedAt??"");case"custom":return T*(($.customOrder??0)-(R.customOrder??0));default:return 0}})},[e,m,d,f]),V=u.useCallback((w,$)=>{const R=P[w];if(R){if($.ctrlKey||$.metaKey){const T=new Set(n);T.has(R.id)?T.delete(R.id):T.add(R.id),r(T)}else if($.shiftKey&&_.current!==null){const T=Math.min(_.current,w),C=Math.max(_.current,w),E=new Set(n);for(let F=T;F<=C;F++)E.add(P[F].id);r(E)}else r(new Set([R.id]));_.current=w}},[P,n,r]),z=u.useCallback(()=>{n.size===P.length?r(new Set):r(new Set(P.map(w=>w.id)))},[P,n,r]),A=({field:w,label:$,width:R})=>{const T=d===w;return s.jsxs("div",{style:{width:R,flex:R?void 0:1,cursor:"pointer",userSelect:"none",fontWeight:T?700:500,fontSize:"0.72rem",textTransform:"uppercase",letterSpacing:"0.04em",opacity:T?1:.6,display:"flex",alignItems:"center",gap:4},onClick:()=>{T?h(w,f===Yt.Asc?Yt.Desc:Yt.Asc):h(w,Yt.Asc)},children:[$,T&&s.jsx("span",{children:"?"})]})},I=u.useCallback((w,$)=>{const R=n.has(w.id)?Array.from(n):[w.id];$.dataTransfer.setData("trackIds",JSON.stringify(R)),$.dataTransfer.effectAllowed="move",x==null||x(R,$)},[n,x]),L=u.useCallback((w,$)=>{$.preventDefault(),$.dataTransfer.dropEffect="move",M(w)},[]),U=u.useCallback((w,$)=>{$.preventDefault(),M(null);try{const R=$.dataTransfer.getData("trackIds");if(R&&i){const T=JSON.parse(R),C=P.filter(q=>!T.includes(q.id)),E=P.filter(q=>T.includes(q.id)),F=Math.min(w,C.length);C.splice(F,0,...E),i(C.map(q=>q.id))}}catch{}},[P,i]),Y=u.useCallback(w=>{w.preventDefault(),M(null),S==null||S(w)},[S]),O=u.useMemo(()=>new Map(t.map(w=>[w.id,w])),[t]),Z=w=>w.replace(/[^a-z0-9_-]/gi,"-"),H=p?36:48,te={display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)",color:"var(--text-secondary, #6b7280)"},G=(w,$)=>({display:"flex",alignItems:"center",gap:8,padding:p?"4px 12px":"6px 12px",height:H,cursor:"pointer",background:$?"var(--accent-light, #dbeafe)":w?"var(--selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--border-subtle, #f3f4f6)",transition:"background 0.1s"}),B=P.length>0&&n.size===P.length;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:b?w=>{w.preventDefault(),w.dataTransfer.dropEffect="copy"}:void 0,onDrop:b?Y:void 0,children:[s.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)",display:"flex",gap:8,alignItems:"center"},children:[s.jsx("input",{type:"text",value:m,onChange:w=>y(w.target.value),placeholder:"?? "+g("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)"}}),s.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[P.length,"/",(e??[]).length]}),n.size>0&&o&&s.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:()=>o(Array.from(n)),children:["?? ",n.size]})]}),s.jsxs("div",{style:te,children:[s.jsx("div",{style:{width:28},children:s.jsx("input",{type:"checkbox",checked:B,onChange:z,style:{cursor:"pointer"}})}),s.jsx("div",{style:{width:20},children:"#"}),!p&&s.jsx("div",{style:{width:44}}),s.jsx(A,{field:"title",label:g("playlistManager.colTitle")}),s.jsx(A,{field:"artist",label:g("playlistManager.colArtist")}),!p&&s.jsx(A,{field:"album",label:g("playlistManager.colAlbum")}),s.jsx(A,{field:"duration",label:g("playlistManager.colDuration"),width:60}),!p&&s.jsx(A,{field:"year",label:g("playlistManager.colYear"),width:50}),s.jsx("div",{style:{width:30}})," ",!p&&s.jsx("div",{style:{width:60}})," ",s.jsx("div",{style:{width:24}})," "]}),s.jsxs("div",{style:{flex:1,overflow:"auto"},children:[P.length===0&&s.jsx("div",{style:{padding:24,textAlign:"center",opacity:.4,fontSize:"0.85rem"},children:e.length===0?g("playlistManager.emptyPlaylist"):g("playlistManager.noMatchingTracks")}),P.map((w,$)=>{const R=n.has(w.id),T=k===$;return s.jsxs("div",{style:G(R,T),onClick:C=>V($,C),onDoubleClick:()=>a==null?void 0:a(w),draggable:v,onDragStart:C=>I(w,C),onDragOver:C=>L($,C),onDrop:C=>U($,C),onDragLeave:()=>M(null),children:[s.jsx("div",{style:{width:28},children:s.jsx("input",{type:"checkbox",checked:R,onChange:()=>{const C=new Set(n);R?C.delete(w.id):C.add(w.id),r(C)},onClick:C=>C.stopPropagation(),style:{cursor:"pointer"}})}),s.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:$+1}),!p&&s.jsx("div",{style:{width:44,height:36,flexShrink:0},children:w.coverUrl?s.jsx("img",{src:w.coverUrl,alt:w.title||g("common.coverArt","Cover art"),style:{width:36,height:36,borderRadius:4,objectFit:"cover"},loading:"lazy"}):s.jsx("div",{style:{width:36,height:36,borderRadius:4,background:"var(--surface-bg, #f3f4f6)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.9rem"},children:"??"})}),s.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",fontWeight:500},children:w.title}),s.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",opacity:.7},children:w.artist}),!p&&s.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",opacity:.5},children:w.album}),s.jsx("div",{style:{width:60,fontSize:"0.78rem",opacity:.5,textAlign:"right"},children:os(w.duration)}),!p&&s.jsx("div",{style:{width:50,fontSize:"0.72rem",opacity:.4,textAlign:"center"},children:w.year||""}),s.jsx("div",{style:{width:30,textAlign:"center",fontSize:"0.75rem"},title:w.source,children:pf[w.source]??"?"}),!p&&s.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[w.tags.slice(0,2).map(C=>{const E=O.get(C);if(!E)return null;const F=`--tag-${Z(C)}`;return s.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${F}-bg, ${E.color}22)`,color:`var(${F}, ${E.color})`,whiteSpace:"nowrap"},children:E.name},C)}),w.tags.length>2&&s.jsxs("span",{style:{fontSize:"0.6rem",opacity:.4},children:["+",w.tags.length-2]})]}),s.jsxs("div",{style:{width:24,display:"flex",alignItems:"center"},children:[s.jsx("button",{style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:2,opacity:.5,position:"relative"},onClick:C=>{C.stopPropagation(),j(N===w.id?null:w.id)},title:g("playlistManager.morActions"),children:"?"}),N===w.id&&t.length>0&&s.jsxs("div",{style:{position:"absolute",right:12,marginTop:4,background:"var(--card-bg, #fff)",border:"1px solid var(--border-color, #e5e7eb)",borderRadius:8,padding:8,zIndex:100,boxShadow:"0 4px 12px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",minWidth:140},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:g("playlistManager.assignTag")}),t.map(C=>{const E=w.tags.includes(C.id);return s.jsxs("div",{style:{padding:"4px 8px",borderRadius:4,cursor:"pointer",fontSize:"0.78rem",display:"flex",alignItems:"center",gap:6,background:E?`var(--tag-${Z(C.id)}-bg, ${C.color}22)`:"transparent"},onClick:F=>{F.stopPropagation();const q=n.size>0?Array.from(n):[w.id];E||l==null||l(q,[C.id]),j(null)},children:[s.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:`var(--tag-${Z(C.id)}, ${C.color})`,flexShrink:0}}),s.jsx("span",{children:C.name}),E&&s.jsx("span",{style:{marginLeft:"auto"},children:"?"})]},C.id)})]})]})]},w.id)})]}),s.jsxs("div",{style:{padding:"6px 12px",borderTop:"1px solid var(--border-color, #e5e7eb)",fontSize:"0.72rem",opacity:.5,display:"flex",gap:16},children:[s.jsxs("span",{children:[P.length," ",g("playlistManager.tracks")]}),s.jsx("span",{children:os(P.reduce((w,$)=>w+($.duration??0),0))}),n.size>0&&s.jsxs("span",{children:[n.size," ",g("playlistManager.selected")]})]})]})},is=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),ni=({playlists:e=[],tags:t=[],onCopyTracks:n=()=>{},onMoveTracks:r=()=>{},onRemoveTracks:a=()=>{},onReorderTracks:o=()=>{},onPlay:i=()=>{},onTagTracks:l=()=>{},initialLeftId:c,initialRightId:d,library:f,queue:h,onAddToQueue:m,onRemoveFromQueue:y})=>{const{t:p}=we(),[v,x]=u.useState(()=>is(c??null)),[b,S]=u.useState(()=>is(d??null)),[g,k]=u.useState("left"),[M,N]=u.useState(null),[j,_]=u.useState(50),[P,V]=u.useState(!1),z=u.useMemo(()=>e.find(T=>T.id===v.playlistId),[e,v.playlistId]),A=u.useMemo(()=>e.find(T=>T.id===b.playlistId),[e,b.playlistId]),I=u.useCallback((T,C)=>{T==="left"?x(E=>({...E,...C})):S(E=>({...E,...C}))},[]),L=u.useCallback(T=>T==="left"?v:b,[v,b]),U=T=>T==="left"?"right":"left",Y=u.useCallback(T=>{const C=L(T),E=L(U(T));!C.playlistId||!E.playlistId||C.selectedTrackIds.size===0||(n(C.playlistId,E.playlistId,Array.from(C.selectedTrackIds)),I(T,{selectedTrackIds:new Set}))},[L,n,I]),O=u.useCallback(T=>{const C=L(T),E=L(U(T));!C.playlistId||!E.playlistId||C.selectedTrackIds.size===0||(r(C.playlistId,E.playlistId,Array.from(C.selectedTrackIds)),I(T,{selectedTrackIds:new Set}))},[L,r,I]),Z=u.useCallback(T=>{const C=L(T);!C.playlistId||C.selectedTrackIds.size===0||N({operation:"copy",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[L]),H=u.useCallback(T=>{const C=L(T);!C.playlistId||C.selectedTrackIds.size===0||N({operation:"cut",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[L]),te=u.useCallback(T=>{const C=L(T);!M||!C.playlistId||(M.operation==="copy"?n(M.sourcePlaylistId,C.playlistId,M.trackIds):r(M.sourcePlaylistId,C.playlistId,M.trackIds),N(null))},[M,L,n,r]),G=u.useCallback(T=>{T.key==="Tab"&&!T.shiftKey&&(T.preventDefault(),k(C=>U(C))),(T.ctrlKey||T.metaKey)&&T.key==="c"&&Z(g),(T.ctrlKey||T.metaKey)&&T.key==="x"&&H(g),(T.ctrlKey||T.metaKey)&&T.key==="v"&&te(g)},[g,Z,H,te]),B=u.useCallback(()=>V(!0),[]),w=u.useCallback(T=>{if(!P)return;const C=T.currentTarget.getBoundingClientRect(),E=(T.clientX-C.left)/C.width*100;_(Math.max(20,Math.min(80,E)))},[P]),$=u.useCallback(()=>V(!1),[]),R=T=>{const C=L(T),E=T==="left"?z:A,F=g===T,Q=!!L(U(T)).playlistId;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",border:F?"2px solid var(--accent, #3b82f6)":"2px solid transparent",borderRadius:8,overflow:"hidden",background:"var(--card-bg, #fff)"},onClick:()=>k(T),children:[s.jsx("div",{style:{padding:"8px 12px",background:F?"var(--accent, #3b82f6)":"var(--surface-bg, #f3f4f6)",color:F?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:s.jsxs("select",{value:C.playlistId??"",onChange:J=>I(T,{playlistId:J.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:F?"var(--accent-overlay, #ffffff30)":"var(--input-bg, #fff)",color:F?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)"},children:[s.jsx("option",{value:"",children:p("playlistManager.selectPlaylist")}),e.map(J=>s.jsxs("option",{value:J.id,children:[J.name," (",J.trackCount,")"]},J.id))]})}),s.jsxs("div",{style:{display:"flex",gap:4,padding:"4px 8px",borderBottom:"1px solid var(--border-color, #e5e7eb)",flexWrap:"wrap"},children:[s.jsxs("button",{style:Rr(!1),onClick:()=>Y(T),disabled:!C.playlistId||!Q||C.selectedTrackIds.size===0,title:p("playlistManager.copyToOther"),children:["???"," ",p("playlistManager.copy")]}),s.jsxs("button",{style:Rr(!1),onClick:()=>O(T),disabled:!C.playlistId||!Q||C.selectedTrackIds.size===0,title:p("playlistManager.moveToOther"),children:["??"," ",p("playlistManager.move")]}),s.jsx("div",{style:{flex:1}}),M&&s.jsxs("button",{style:Rr(!0),onClick:()=>te(T),disabled:!C.playlistId,children:["?? ",p("playlistManager.paste")," (",M.trackIds.length,")"]})]}),E?s.jsx(va,{tracks:E.tracks,tags:t,selectedTrackIds:C.selectedTrackIds,onSelectionChange:J=>I(T,{selectedTrackIds:J}),onPlay:i,onRemove:J=>a(E.id,J),onReorder:J=>o(E.id,J),onTagTracks:l,sortField:C.sortField,sortDir:C.sortDir,onSortChange:(J,ae)=>I(T,{sortField:J,sortDir:ae}),filterText:C.filterText,onFilterChange:J=>I(T,{filterText:J}),compact:!0,draggable:!0}):s.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",opacity:.3,fontSize:"0.85rem"},children:p("playlistManager.selectPlaylistPrompt")})]})};return s.jsxs("div",{style:{display:"flex",height:"100%",userSelect:P?"none":"auto"},onKeyDown:G,onMouseMove:w,onMouseUp:$,tabIndex:0,children:[s.jsx("div",{style:{width:`${j}%`,minWidth:200},children:R("left")}),s.jsx("div",{style:{width:6,cursor:"col-resize",background:P?"var(--accent, #3b82f6)":"var(--border-color, #e5e7eb)",transition:P?"none":"background 0.15s",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseDown:B,children:s.jsx("div",{style:{width:2,height:40,borderRadius:1,background:P?"var(--btn-text, #fff)":"var(--text-secondary, #9ca3af)"}})}),s.jsx("div",{style:{flex:1,minWidth:200},children:R("right")})]})},Rr=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"}),ri="av:local-playlists";function mf(){try{const e=localStorage.getItem(ri);return e?JSON.parse(e):[]}catch{return[]}}function yf(e){const t=JSON.stringify(e);try{localStorage.setItem(ri,t)}catch{}}function xa(){const[e,t]=u.useState(()=>mf()),n=u.useRef(!1);return u.useEffect(()=>{n.current=!0},[]),u.useEffect(()=>{yf(e)},[e]),u.useMemo(()=>({list:()=>e,get:a=>e.find(o=>o.id===a),create:a=>{const o=new Date().toISOString(),i={id:crypto.randomUUID(),name:a,items:[],updatedAt:o};return t(l=>[i,...l]),i},rename:(a,o)=>t(i=>i.map(l=>l.id===a?{...l,name:o,updatedAt:new Date().toISOString()}:l)),remove:a=>t(o=>o.filter(i=>i.id!==a)),replaceItems:(a,o)=>t(i=>i.map(l=>l.id===a?{...l,items:o,updatedAt:new Date().toISOString()}:l)),addItems:(a,o)=>t(i=>i.map(l=>l.id===a?{...l,items:[...l.items,...o],updatedAt:new Date().toISOString()}:l))}),[e])}const gf=nt.scoped("PlaylistList"),bf={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,background:"var(--nice-bg, #fff)"},vf={...bf,padding:"8px 10px",cursor:"pointer"},ai={border:"1px solid var(--border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--bg, #fff)",cursor:"pointer"},xf={...ai,background:"var(--primary, #4f46e5)",borderColor:"var(--primary, #4f46e5)",color:"var(--bg, #fff)"},wa=({selectedId:e,onSelect:t,onCreateRemote:n})=>{const{t:r}=we(),a=xa(),[o,i]=u.useState(""),l=u.useMemo(()=>a.list(),[a]);return s.jsxs("div",{style:{display:"grid",gap:10},children:[s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("input",{placeholder:r("playlistList.playlistName","Playlist name..."),value:o,onChange:c=>i(c.target.value),style:{flex:1,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px"},"aria-label":"Playlist name"}),s.jsxs("button",{type:"button",disabled:!o.trim(),style:o.trim()?xf:{...ai,cursor:"not-allowed",color:"var(--muted, #9ca3af)",background:"var(--bg-muted, #f3f4f6)"},onClick:async()=>{const c=a.create(o.trim());if(i(""),n)try{await n({platform:"tidal",name:c.name,songs:c.items})}catch(d){gf.error("Remote playlist create failed:",d)}t==null||t(c)},children:["+ ",r("common.add","Add")]})]}),s.jsxs("div",{style:{display:"grid",gap:6},children:[l.map(c=>{const d=c.id===e;return s.jsxs("button",{onClick:()=>t==null?void 0:t(c),style:{...vf,background:d?"var(--active-bg, #eef2ff)":"var(--bg, #fff)"},children:[s.jsx("div",{style:{fontWeight:600},children:c.name}),s.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&&s.jsx("div",{style:{color:"var(--muted, #6b7280)"},children:r("playlistList.emptyState","No playlists. Add the first one ↑")})]})]})},wf=nt.scoped("PlaylistBrowser"),ls={display:"grid",gap:12},cs=e=>({artist:(e.artists??[]).join(", "),title:e.title}),si=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:n,tracks:r,view:a,onSelect:o,onPlay:i})=>{var x;const{t:l}=we(),c=xa(),[d,f]=u.useState(null),[h,m]=u.useState(""),[,y]=u.useState([]),p=d==null?void 0:d.id,v=(b,S)=>{if("addItems"in c){c.addItems(b.id,S);const k=c.list().find(M=>M.id===b.id)||b;f(k);return}const g=c;if("update"in c&&typeof g.update=="function"){const k=Array.from([...b.items||[],...S]);g.update({...b,items:k});const M=c.list().find(N=>N.id===b.id)||{...b,items:k};f(M);return}wf.warn("useLocalPlaylists: missing addItems/update method — update hook implementation.")};return s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(min(200px, 100%), 320px) 1fr",gap:16},children:[s.jsxs("div",{style:ls,children:[s.jsx("h3",{style:{margin:0},children:l("playlistBrowser.playlists")}),s.jsx(wa,{selectedId:p,onSelect:f}),d&&s.jsxs("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:[l("playlistBrowser.selected","Selected"),": ",s.jsx("strong",{children:d.name})," �"," ",((x=d.items)==null?void 0:x.length)??0," ",l("playlistBrowser.tracks","tracks")]})]}),s.jsxs("div",{style:ls,children:[s.jsx("h3",{style:{margin:0},children:l("playlistBrowser.library")}),s.jsxs("div",{children:[e==null?void 0:e({placeholder:l("playlistBrowser.searchAndAdd","Search and add to playlist..."),onSelect:b=>{d&&v(d,[cs(b)])}}),s.jsx("input",{placeholder:l("playlistBrowser.fullSearch","Full search (Enter does not add, full list below)"),value:h,onChange:b=>m(b.target.value),style:{width:"100%",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px",marginTop:10}})]}),t==null?void 0:t({query:h,onSelect:b=>{d&&v(d,[cs(b)])}}),n==null?void 0:n({onPlayNow:b=>y(b),onAddToQueue:b=>y(S=>[...S,...b]),onAddDescriptors:b=>d&&v(d,b)})]})]})};var At=(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))(At||{});const oi=(e,t=null)=>e.filter(n=>n.parentId===t).sort((n,r)=>n.sortOrder-r.sortOrder).map(n=>({...n,children:oi(e,n.id)})),Sf={[At.Spotify]:{icon:"??",label:"Spotify",color:"var(--source-spotify, #1DB954)",bg:"var(--source-spotify-bg, #1DB95418)"},[At.Tidal]:{icon:"?",label:"Tidal",color:"var(--source-tidal, #000000)",bg:"var(--source-tidal-bg, #00000010)"},[At.YouTube]:{icon:"??",label:"YouTube",color:"var(--source-youtube, #FF0000)",bg:"var(--source-youtube-bg, #FF000010)"}},ii=({folders:e,playlists:t,tags:n,services:r,activeFolderId:a,activePlaylistId:o,onSelectFolder:i,onSelectPlaylist:l,onCreateFolder:c,onRenameFolder:d,onDeleteFolder:f,onCreatePlaylist:h,onConnectService:m,onDisconnectService:y,onDragPlaylistToFolder:p,collapsed:v=!1,onToggleCollapse:x})=>{const{t:b}=we(),[S,g]=u.useState(new Set),[k,M]=u.useState(!1),[N,j]=u.useState(""),[_,P]=u.useState(null),[V,z]=u.useState(!1),[A,I]=u.useState(""),[L,U]=u.useState("static"),[Y,O]=u.useState(null),[Z,H]=u.useState(""),[te,G]=u.useState(null),[B,w]=u.useState(!1),$=u.useMemo(()=>oi(e),[e]),R=u.useCallback(X=>{g(fe=>{const be=new Set(fe);return be.has(X)?be.delete(X):be.add(X),be})},[]),T=u.useCallback(()=>{N.trim()&&(c(N.trim(),_),j(""),M(!1))},[N,_,c]),C=u.useCallback(()=>{A.trim()&&(h(A.trim(),L,a),I(""),z(!1))},[A,L,a,h]),E=u.useCallback(X=>{Z.trim()&&(d(X,Z.trim()),O(null),H(""))},[Z,d]),F=u.useCallback((X,fe)=>{X.preventDefault(),X.dataTransfer.dropEffect="move",G(fe)},[]),q=u.useCallback((X,fe)=>{X.preventDefault();const be=X.dataTransfer.getData("playlistId");be&&p&&p(be,fe),G(null)},[p]),Q=u.useCallback(()=>G(null),[]),J=u.useCallback(X=>t.filter(fe=>(fe.folderId??null)===X),[t]),ae={width:v?48:280,minWidth:v?48:280,background:"var(--sidebar-bg, #f8f9fa)",borderRight:"1px solid var(--border-color, #e5e7eb)",display:"flex",flexDirection:"column",transition:"width 0.2s, min-width 0.2s",overflow:"hidden",height:"100%"},re={padding:"8px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)"},ee=(X,fe=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:fe?"var(--accent-light, #dbeafe)":X?"var(--accent, #3b82f6)":"transparent",color:X?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",transition:"background 0.15s",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),D={background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:"2px 6px",borderRadius:4,color:"var(--text-secondary, #6b7280)"},K={fontSize:"0.8rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)",width:"100%"},se=(X,fe)=>{var Se,ne;const be=S.has(X.id),Re=a===X.id,Fe=te===X.id,Te=J(X.id);return s.jsxs("div",{children:[s.jsxs("div",{style:{...ee(Re,Fe),paddingLeft:12+fe*16},onClick:()=>{i(X.id),X.children&&X.children.length>0&&R(X.id)},onDragOver:oe=>F(oe,X.id),onDrop:oe=>q(oe,X.id),onDragLeave:Q,children:[s.jsx("span",{style:{width:14,textAlign:"center",flexShrink:0,fontSize:"0.7rem"},children:(((Se=X.children)==null?void 0:Se.length)||0)>0||Te.length>0?"?":"�"}),Y===X.id?s.jsx("input",{value:Z,onChange:oe=>H(oe.target.value),onKeyDown:oe=>{oe.key==="Enter"&&E(X.id),oe.key==="Escape"&&O(null)},onBlur:()=>E(X.id),autoFocus:!0,style:{...K,flex:1},onClick:oe=>oe.stopPropagation()}):s.jsxs(s.Fragment,{children:[s.jsx("span",{children:X.icon??"??"}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:X.name}),s.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:Te.length}),s.jsx("button",{style:D,onClick:oe=>{oe.stopPropagation(),O(X.id),H(X.name)},title:b("common.rename"),children:"?"}),s.jsx("button",{style:{...D,color:"var(--error, #ef4444)"},onClick:oe=>{oe.stopPropagation(),f(X.id)},title:b("common.delete"),children:"?"})]})]}),be&&s.jsxs(s.Fragment,{children:[Te.map(oe=>ce(oe,fe+1)),(ne=X.children)==null?void 0:ne.map(oe=>se(oe,fe+1))]})]},X.id)},ce=(X,fe)=>{const be=o===X.id;return s.jsxs("div",{style:{...ee(be),paddingLeft:12+fe*16+22},onClick:()=>l(X.id),draggable:!0,onDragStart:Re=>{Re.dataTransfer.setData("playlistId",X.id),Re.dataTransfer.effectAllowed="move"},children:[s.jsx("span",{style:{fontSize:"0.7rem"},children:X.type==="dynamic"?"?":"??"}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:X.name}),s.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:X.trackCount})]},X.id)};if(v)return s.jsx("div",{style:ae,children:s.jsx("button",{style:{...D,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:x,title:b("playlistManager.expandSidebar"),children:"?"})});const pe=J(null);return s.jsxs("div",{style:ae,children:[s.jsxs("div",{style:{...re,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s.jsxs("span",{style:{fontWeight:700,fontSize:"0.85rem"},children:["?? ",b("playlistManager.title")]}),s.jsx("button",{style:D,onClick:x,title:b("playlistManager.collapseSidebar"),children:"?"})]}),s.jsxs("div",{style:{...re,display:"flex",gap:4,flexWrap:"wrap"},children:[s.jsxs("button",{style:{...D,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:6,padding:"4px 10px"},onClick:()=>z(!0),children:["+ ",b("playlistManager.newPlaylist")]}),s.jsxs("button",{style:{...D,border:"1px solid var(--border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{M(!0),P(a)},children:["?? ",b("playlistManager.newFolder")]})]}),V&&s.jsxs("div",{style:{...re,display:"flex",flexDirection:"column",gap:6},children:[s.jsx("input",{value:A,onChange:X=>I(X.target.value),placeholder:b("playlistManager.playlistName"),style:K,autoFocus:!0,onKeyDown:X=>{X.key==="Enter"&&C(),X.key==="Escape"&&z(!1)}}),s.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[s.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[s.jsx("input",{type:"radio",checked:L==="static",onChange:()=>U("static")}),b("playlistManager.static")]}),s.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[s.jsx("input",{type:"radio",checked:L==="dynamic",onChange:()=>U("dynamic")}),"? ",b("playlistManager.dynamic")]}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{style:{...D,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:C,"aria-label":"Confirm create playlist",children:"?"}),s.jsx("button",{style:D,onClick:()=>z(!1),"aria-label":"Cancel create playlist",children:"?"})]})]}),k&&s.jsxs("div",{style:{...re,display:"flex",gap:6},children:[s.jsx("input",{value:N,onChange:X=>j(X.target.value),placeholder:b("playlistManager.folderName"),style:{...K,flex:1},autoFocus:!0,onKeyDown:X=>{X.key==="Enter"&&T(),X.key==="Escape"&&M(!1)}}),s.jsx("button",{style:{...D,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:T,"aria-label":"Confirm create folder",children:"?"}),s.jsx("button",{style:D,onClick:()=>M(!1),"aria-label":"Cancel create folder",children:"?"})]}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsxs("div",{style:ee(a===null&&o===null,te==="__root__"),onClick:()=>i(null),onDragOver:X=>F(X,null),onDrop:X=>q(X,null),onDragLeave:Q,children:[s.jsx("span",{children:"??"}),s.jsx("span",{style:{flex:1},children:b("playlistManager.allPlaylists")}),s.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:t.length})]}),pe.map(X=>ce(X,0)),$.map(X=>se(X,0))]}),n.length>0&&s.jsxs("div",{style:re,children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:b("playlistManager.tags")}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:n.map(X=>s.jsxs("span",{style:{fontSize:"0.7rem",padding:"2px 8px",borderRadius:12,background:X.color+"22",color:X.color,border:`1px solid ${X.color}44`,cursor:"pointer"},children:[X.icon&&`${X.icon} `,X.name]},X.id))})]}),s.jsxs("div",{style:re,children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",cursor:"pointer",fontSize:"0.7rem",fontWeight:600,opacity:.6},onClick:()=>w(!B),children:[s.jsxs("span",{children:["?? ",b("playlistManager.services")]}),s.jsx("span",{children:"?"})]}),B&&s.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[At.Spotify,At.Tidal,At.YouTube].map(X=>{const fe=Sf[X],be=r.find(Re=>Re.platform===X);return s.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:[s.jsx("span",{children:fe.icon}),s.jsx("span",{style:{flex:1},children:fe.label}),be!=null&&be.connected?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:"0.65rem",opacity:.6},children:be.username??b("playlistManager.connected")}),s.jsx("button",{style:{...D,color:"var(--nice-danger, #ef4444)"},onClick:()=>y(X),children:"?"})]}):s.jsx("button",{style:{...D,background:fe.color,color:"var(--nice-bg, #fff)",borderRadius:4,padding:"2px 8px"},onClick:()=>m(X),children:b("playlistManager.connect")})]},X)})})]})]})},Cf=({playlist:e,tags:t,onPlay:n,selectedTrackIds:r,onSelectionChange:a})=>{const{t:o}=we(),i=u.useCallback(l=>{const c=new Set(r);c.has(l)?c.delete(l):c.add(l),a(c)},[r,a]);return e.tracks.length===0?s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:60,opacity:.3},children:[s.jsx("span",{style:{fontSize:"2rem",marginBottom:8},children:"??"}),s.jsx("span",{style:{fontSize:"0.82rem"},children:o("playlistManager.emptyPlaylist")})]}):s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(160px, 1fr))",gap:10},children:e.tracks.map(l=>{const c=r.has(l.id);return s.jsxs("div",{onClick:()=>i(l.id),onDoubleClick:()=>n(l),style:{border:c?"2px solid var(--accent, #3b82f6)":"1px solid var(--border-color, #e5e7eb)",borderRadius:10,padding:10,cursor:"pointer",background:c?"var(--accent-bg, #eff6ff)":"var(--card-bg, #fff)",transition:"all 0.12s"},children:[s.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:6,background:"linear-gradient(135deg, var(--playlist-track-bg1, #6366f140), var(--playlist-track-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"1.5rem",marginBottom:6},children:"?"}),s.jsx("div",{style:{fontWeight:500,fontSize:"0.78rem",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.title}),s.jsx("div",{style:{fontSize:"0.68rem",opacity:.5,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.artist})]},l.id)})})},li=u.memo(Cf),ds=e=>e.replace(/[^a-z0-9_-]/gi,"-"),us={background:"none",border:"none",cursor:"pointer",fontSize:"0.78rem",padding:"2px 4px",opacity:.4},kf=({playlists:e,folders:t,tags:n,activeFolderId:r,onSelectPlaylist:a,onDeletePlaylist:o,onDuplicatePlaylist:i})=>{const{t:l}=we(),c=u.useMemo(()=>r?e.filter(d=>d.folderId===r):e,[e,r]);return c.length===0?s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:60,opacity:.4},children:[s.jsx("span",{style:{fontSize:"2.5rem",marginBottom:12},children:"??"}),s.jsx("span",{style:{fontSize:"0.85rem"},children:l("playlistManager.emptyState")})]}):s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))",gap:12},children:c.map(d=>{var h;const f=t.find(m=>m.id===d.folderId);return s.jsxs("div",{onClick:()=>a(d.id),style:{border:"1px solid var(--border-color, #e5e7eb)",borderRadius:12,padding:16,cursor:"pointer",background:"var(--card-bg, #fff)",transition:"box-shadow 0.15s, transform 0.15s"},onMouseEnter:m=>{m.currentTarget.style.boxShadow="0 4px 12px var(--nice-overlay-8, rgba(0, 0, 0, 0.08))",m.currentTarget.style.transform="translateY(-1px)"},onMouseLeave:m=>{m.currentTarget.style.boxShadow="none",m.currentTarget.style.transform="none"},children:[s.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:8,background:"linear-gradient(135deg, var(--playlist-cover-bg1, #6366f140), var(--playlist-cover-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"2.5rem",marginBottom:10},children:d.type===ba.Dynamic?"?":"??"}),s.jsx("div",{style:{fontWeight:600,fontSize:"0.85rem",marginBottom:2},children:d.name}),s.jsxs("div",{style:{fontSize:"0.72rem",opacity:.5},children:[d.trackCount," ",l("playlistManager.tracks"),f&&` � ?? ${f.name}`]}),((h=d.tags)==null?void 0:h.length)>0&&s.jsx("div",{style:{display:"flex",gap:4,marginTop:6,flexWrap:"wrap"},children:d.tags.slice(0,3).map(m=>{const y=n.find(p=>p.id===m);return y?s.jsx("span",{style:{padding:"1px 8px",borderRadius:12,background:`var(--tag-${ds(m)}-bg, ${y.color}18)`,color:`var(--tag-${ds(m)}, ${y.color})`,fontSize:"0.65rem",fontWeight:500},children:y.name},m):null})}),s.jsxs("div",{style:{display:"flex",gap:4,marginTop:8},children:[s.jsx("button",{onClick:m=>{m.stopPropagation(),i(d.id)},style:us,title:l("playlistManager.duplicate"),children:"??"}),s.jsx("button",{onClick:m=>{m.stopPropagation(),o(d.id)},style:us,title:l("playlistManager.delete"),children:"??"})]})]},d.id)})})},ci=u.memo(kf),fs=[{value:dt.Library,label:"Library",icon:"??",hex:"var(--nice-info, #6366f1)",css:"var(--source-library, #6366f1)",cssBg:"var(--source-library-bg, #6366f118)"},{value:dt.Spotify,label:"Spotify",icon:"??",hex:"var(--nice-success, #1db954)",css:"var(--source-spotify, #1db954)",cssBg:"var(--source-spotify-bg, #1db95418)"},{value:dt.Tidal,label:"Tidal",icon:"?",hex:"var(--nice-text, #000000)",css:"var(--source-tidal, #000000)",cssBg:"var(--source-tidal-bg, #00000018)"},{value:dt.YouTube,label:"YouTube",icon:"??",hex:"var(--nice-danger, #ff0000)",css:"var(--source-youtube, #ff0000)",cssBg:"var(--source-youtube-bg, #ff000018)"},{value:dt.MusicBrainz,label:"MusicBrainz",icon:"??",hex:"#ba478f",css:"var(--source-musicbrainz, #ba478f)",cssBg:"var(--source-musicbrainz-bg, #ba478f18)"}],di=({onSearch:e,results:t,isSearching:n,onAddToPlaylist:r,onPlayPreview:a})=>{const{t:o}=we(),[i,l]=u.useState(""),[c,d]=u.useState(new Set([dt.Library,dt.Spotify,dt.Tidal,dt.YouTube])),[f,h]=u.useState(new Set),[m,y]=u.useState(!1),p=u.useRef(null),v=u.useCallback(j=>{d(_=>{const P=new Set(_);return P.has(j)?P.delete(j):P.add(j),P})},[]),x=u.useCallback(j=>{l(j),p.current&&clearTimeout(p.current),j.trim().length>=2&&(p.current=setTimeout(()=>{e(j.trim(),Array.from(c))},350))},[c,e]),b=u.useCallback(j=>{j.preventDefault(),i.trim().length>=2&&e(i.trim(),Array.from(c))},[i,c,e]),S=u.useCallback(j=>{h(_=>{const P=new Set(_);return P.has(j)?P.delete(j):P.add(j),P})},[]),g=u.useCallback(()=>{f.size===t.length?h(new Set):h(new Set(t.map(j=>j.id)))},[f,t]),k=u.useCallback(()=>{const j=t.filter(_=>f.has(_.id));j.length>0&&(r(j),h(new Set))},[t,f,r]),M=j=>{if(!j)return"--:--";const _=Math.floor(j/60),P=j%60;return`${_}:${P.toString().padStart(2,"0")}`},N=j=>{const _=fs.find(P=>P.value===j);return _?_.icon:"?"};return s.jsxs("div",{style:{border:"1px solid var(--border-color, #e5e7eb)",borderRadius:10,background:"var(--card-bg, #fff)",overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 12px",gap:8,cursor:"pointer",background:"var(--surface-bg, #f9fafb)"},onClick:()=>y(!m),children:[s.jsx("span",{style:{fontSize:"1rem"},children:"??"}),s.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:o("playlistManager.search")}),s.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",opacity:.5},children:"?"})]}),m&&s.jsxs("div",{style:{padding:"0 12px 12px"},children:[s.jsx("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap"},children:fs.map(j=>{const _=c.has(j.value);return s.jsxs("button",{onClick:()=>v(j.value),style:{padding:"4px 10px",borderRadius:20,border:_?`2px solid ${j.css}`:"1px solid var(--border-color, #d1d5db)",background:_?j.cssBg:"transparent",color:_?j.css:"var(--text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:_?600:400,transition:"all 0.15s"},children:[j.icon," ",j.label]},j.value)})}),s.jsxs("form",{onSubmit:b,style:{display:"flex",gap:6,marginBottom:8},children:[s.jsx("input",{type:"text",value:i,onChange:j=>x(j.target.value),placeholder:o("playlistManager.searchPlaceholder"),style:{flex:1,padding:"6px 12px",borderRadius:8,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)",fontSize:"0.82rem"}}),s.jsx("button",{type:"submit",disabled:i.trim().length<2||n,style:{padding:"6px 14px",borderRadius:8,border:"none",background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.82rem",cursor:"pointer",opacity:i.trim().length<2?.5:1},children:n?"?":"??"})]}),t.length>0&&s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",gap:6,marginBottom:4,alignItems:"center"},children:[s.jsxs("label",{style:{fontSize:"0.72rem",display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:f.size===t.length&&t.length>0,onChange:g}),o("playlistManager.selectAll")]}),s.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[t.length," ",o("playlistManager.results")]}),s.jsx("div",{style:{flex:1}}),f.size>0&&s.jsxs("button",{onClick:k,style:{padding:"3px 10px",borderRadius:6,border:"none",background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.72rem",cursor:"pointer"},children:["? ",o("playlistManager.addSelected")," (",f.size,")"]})]}),s.jsx("div",{style:{maxHeight:300,overflowY:"auto",borderRadius:6,border:"1px solid var(--border-color, #e5e7eb)"},children:t.map(j=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:"1px solid var(--border-color, #f3f4f6)",background:f.has(j.id)?"var(--accent-bg, #eff6ff)":"transparent",cursor:"pointer",fontSize:"0.78rem"},onClick:()=>S(j.id),children:[s.jsx("input",{type:"checkbox",checked:f.has(j.id),readOnly:!0}),s.jsx("span",{children:N(j.source)}),j.imageUrl&&s.jsx("img",{src:j.imageUrl,alt:j.title||o("common.coverArt","Cover art"),style:{width:28,height:28,borderRadius:4,objectFit:"cover"}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:j.title}),s.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[j.artist,j.album?` � ${j.album}`:""]})]}),s.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:M(j.duration)}),a&&s.jsx("button",{onClick:_=>{_.stopPropagation(),a(j)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem"},title:o("playlistManager.preview"),children:"?"})]},j.id))})]}),n&&s.jsxs("div",{style:{textAlign:"center",padding:20,opacity:.5,fontSize:"0.82rem"},children:["? ",o("playlistManager.searching"),"..."]}),!n&&i.trim().length>=2&&t.length===0&&s.jsx("div",{style:{textAlign:"center",padding:20,opacity:.4,fontSize:"0.82rem"},children:o("playlistManager.noResults")})]})]})},Mf=[{value:1,label:"Spotify",icon:"🟢",color:"var(--source-spotify, #1db954)"},{value:2,label:"Tidal",icon:"⬛",color:"var(--source-tidal, #000000)"},{value:3,label:"Apple Music",icon:"🍎",color:"var(--source-apple, #fa243c)"},{value:4,label:"YouTube",icon:"🔴",color:"var(--source-youtube, #ff0000)"},{value:99,label:"Manual Paste",icon:"📋",color:"var(--source-manual, #6366f1)"}],jf={display:"flex",flexDirection:"column",gap:16,padding:24,borderRadius:12,background:"var(--panel-bg, #ffffff)",border:"1px solid var(--border, #e2e8f0)",maxWidth:640,minHeight:400},Rf={display:"flex",justifyContent:"space-between",alignItems:"center"},Tf={display:"flex",gap:4,marginBottom:8},wn={padding:"8px 20px",borderRadius:6,border:"none",background:"var(--accent, #6366f1)",color:"var(--nice-bg, #fff)",cursor:"pointer",fontWeight:600},zn={...wn,background:"transparent",color:"var(--text, #334155)",border:"1px solid var(--border, #e2e8f0)"},hs={padding:12,borderRadius:8,border:"1px solid var(--border, #e2e8f0)",cursor:"pointer",transition:"border-color 0.15s"},ui=["connect","browse","tracks","options","importing","done"];function $f(e){return ui.indexOf(e)}function Pf(e){if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const fi=({connections:e=[],onConnect:t=()=>{},onDisconnect:n=()=>{},onFetchPlaylists:r=async()=>[],onFetchTracks:a=async()=>[],onImport:o=async()=>({playlistName:"",imported:0,skipped:0,failed:0,failedTracks:[]}),onClose:i=()=>{},targetFolders:l,sources:c})=>{const{t:d}=we(),[f,h]=u.useState("connect"),[m,y]=u.useState(null),[p,v]=u.useState([]),[x,b]=u.useState(null),[S,g]=u.useState([]),[k,M]=u.useState(new Set),[N,j]=u.useState(!1),[_,P]=u.useState(null),[V,z]=u.useState(null),[A,I]=u.useState(null),[L,U]=u.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[Y,O]=u.useState(""),Z=u.useMemo(()=>new Set(e.filter(D=>D.connected).map(D=>D.platform)),[e]),H=u.useCallback(D=>e.find(K=>K.platform===D),[e]),te=u.useCallback(D=>{if(y(D),D===99){h("tracks"),O(""),g([]),j(!1);return}Z.has(D)?(h("browse"),j(!0),I(null),r(D).then(K=>{v(K),j(!1)}).catch(K=>{I(String(K)),j(!1)})):t(D)},[Z,t,r]),G=u.useCallback(D=>{b(D),h("tracks"),j(!0),I(null),a(D).then(K=>{g(K),M(new Set(K.map(se=>se.externalId))),j(!1)}).catch(K=>{I(String(K)),j(!1)})},[a]),B=u.useCallback(D=>{M(K=>{const se=new Set(K);return se.has(D)?se.delete(D):se.add(D),se})},[]),w=u.useCallback(()=>{M(D=>D.size===S.length?new Set:new Set(S.map(K=>K.externalId)))},[S]),$=u.useCallback(async()=>{if(!x)return;const D=S.filter(K=>k.has(K.externalId));if(D.length!==0){h("importing"),P({total:D.length,imported:0,skipped:0,failed:0}),I(null);try{const K=await o(x,D,L),se=K&&typeof K=="object"&&"imported"in K?K:{playlistName:x.name,imported:D.length,skipped:0,failed:0,failedTracks:[]};z(se),h("done")}catch(K){I(String(K)),h("options")}}},[x,S,k,L,o]),R=f!=="connect"&&f!=="importing"&&f!=="done",T=u.useCallback(()=>{switch(f){case"browse":h("connect");break;case"tracks":h("browse");break;case"options":h("tracks");break}},[f]),C=()=>s.jsx("div",{style:Tf,children:ui.map((D,K)=>s.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:K<=$f(f)?"var(--accent, #6366f1)":"var(--border, #e2e8f0)",transition:"background 0.2s"}},D))}),E=()=>s.jsxs("div",{style:{display:"grid",gap:12},children:[s.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:d("importWizard.selectPlatform","Select a music platform to import from")}),Mf.map(D=>{const K=H(D.value),se=Z.has(D.value);return s.jsxs("div",{style:{...hs,display:"flex",alignItems:"center",gap:12,borderColor:se?D.color:void 0},onClick:()=>te(D.value),role:"button",tabIndex:0,onKeyDown:ce=>ce.key==="Enter"&&te(D.value),children:[s.jsx("span",{style:{fontSize:24},children:D.icon}),s.jsxs("div",{style:{flex:1},children:[s.jsx("strong",{children:D.label}),(K==null?void 0:K.username)&&s.jsx("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:K.username})]}),se?s.jsxs("span",{style:{color:D.color,fontSize:12,fontWeight:600},children:[d("importWizard.connected","Connected")," ✓"]}):s.jsx("span",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:d("importWizard.clickToConnect","Click to connect")})]},D.value)})]}),F=()=>s.jsxs("div",{style:{display:"grid",gap:12},children:[s.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:d("importWizard.selectPlaylist","Select a playlist to import")}),N?s.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--text-dim, #64748b)"},children:d("importWizard.loading","Loading playlists…")}):s.jsxs("div",{style:{display:"grid",gap:8,maxHeight:320,overflowY:"auto"},children:[p.map(D=>s.jsxs("div",{style:{...hs,display:"flex",alignItems:"center",gap:12},onClick:()=>G(D),role:"button",tabIndex:0,onKeyDown:K=>K.key==="Enter"&&G(D),children:[D.coverUrl&&s.jsx("img",{src:D.coverUrl,alt:"",style:{width:48,height:48,borderRadius:6,objectFit:"cover"}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:D.name}),D.description&&s.jsx("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:D.description})]}),s.jsxs("span",{style:{fontSize:12,color:"var(--text-dim, #64748b)",whiteSpace:"nowrap"},children:[D.trackCount," ",d("importWizard.tracks","tracks")]})]},D.id)),p.length===0&&s.jsx("div",{style:{textAlign:"center",padding:24,color:"var(--text-dim, #64748b)"},children:d("importWizard.noPlaylists","No playlists found")})]})]}),q=u.useCallback(D=>{const se=D.split(`
51
- `).map(ce=>ce.trim()).filter(Boolean).map((ce,pe)=>{const X=ce.match(/^(.+?)\s*[-–—]\s*(.+)$/);return X?{externalId:`paste-${pe}`,title:X[2].trim(),artist:X[1].trim(),album:void 0,duration:0}:{externalId:`paste-${pe}`,title:ce,artist:"",album:void 0,duration:0}});g(se),M(new Set(se.map(ce=>ce.externalId)))},[]),Q=()=>s.jsxs("div",{style:{display:"grid",gap:12},children:[m===99&&S.length===0&&s.jsxs("div",{style:{display:"grid",gap:8},children:[s.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:d("importWizard.pasteInstructions",'Paste your track list below (one track per line). Use "Artist - Title" format for best results.')}),s.jsx("textarea",{value:Y,onChange:D=>O(D.target.value),placeholder:`Daft Punk - Get Lucky
67
+ OR: Artist;Title;Version`),rows:3,style:{width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:8,fontFamily:"inherit"}}),r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:6},children:[r.jsx("div",{style:{color:"var(--nice-text-secondary, #6b7280)",fontSize:12},children:h("genericPlaylist.bulkPasteHint","Each line will be added as a separate song.")}),r.jsx("button",{type:"button",onClick:Z,disabled:!m.trim(),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},children:h("genericPlaylist.addFromList","Add from list")})]})]})]})})]})},Js=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #f59e0b)","var(--nice-warning, #eab308)","var(--nice-success, #84cc16)","var(--nice-success, #22c55e)","var(--nice-info, #14b8a6)","var(--nice-info, #06b6d4)","var(--nice-primary, #3b82f6)","var(--nice-info, #6366f1)","var(--nice-accent, #8b5cf6)","var(--nice-accent, #a855f7)","var(--nice-accent-pink, #d946ef)","var(--nice-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)","var(--nice-text-muted, #78716c)","var(--nice-text-secondary, #64748b)","var(--nice-text, #000000)"],tr=["??","??","??","??","??","??","??","??","??","?","??","??","??","??","??","??"],il=({tags:e,onCreateTag:t,onUpdateTag:n,onDeleteTag:a,selectedTracks:s,onAssignTag:i,onUnassignTag:o})=>{const{t:l}=Te(),[c,u]=d.useState(null),[h,p]=d.useState(""),[f,y]=d.useState(Js[8]),[m,g]=d.useState(tr[0]),[b,x]=d.useState(!1),[k,v]=d.useState(null),[w,M]=d.useState(""),[S,R]=d.useState(""),[T,j]=d.useState(""),O=d.useCallback(A=>{u(A.id),M(A.name),R(A.color),j(A.icon||tr[0])},[]),$=d.useCallback(()=>{c&&w.trim()&&(n(c,w.trim(),S,T),u(null))},[c,w,S,T,n]),E=d.useCallback(()=>{h.trim()&&(t(h.trim(),f,m),p(""),x(!1))},[h,f,m,t]),D=d.useCallback(A=>{k===A?(a(A),v(null)):(v(A),setTimeout(()=>v(null),3e3))},[k,a]),L=s&&s.length>0,W=A=>!s||s.length===0?!1:s.every(_=>_.tags.includes(A)),Z=A=>!s||s.length===0?!1:s.some(_=>_.tags.includes(A))&&!W(A);return r.jsxs("div",{style:{border:"1px solid var(--border-color, #e5e7eb)",borderRadius:10,background:"var(--card-bg, #fff)",overflow:"hidden"},children:[r.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border-color, #e5e7eb)",display:"flex",alignItems:"center",gap:8,background:"var(--surface-bg, #f9fafb)"},children:[r.jsx("span",{style:{fontSize:"1rem"},children:"???"}),r.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:l("playlistManager.tagManager")}),r.jsx("div",{style:{flex:1}}),r.jsxs("button",{onClick:()=>x(!b),style:{background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"4px 10px",fontSize:"0.72rem",cursor:"pointer"},children:["+ ",l("playlistManager.newTag")]})]}),r.jsxs("div",{style:{padding:12},children:[b&&r.jsxs("div",{style:{border:"1px solid var(--border-color, #d1d5db)",borderRadius:8,padding:10,marginBottom:12,background:"var(--surface-bg, #f9fafb)"},children:[r.jsxs("div",{style:{display:"flex",gap:6,marginBottom:8},children:[r.jsx("input",{type:"text",value:h,onChange:A=>p(A.target.value),placeholder:l("playlistManager.tagName"),style:{flex:1,padding:"5px 10px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",fontSize:"0.8rem",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)"},onKeyDown:A=>A.key==="Enter"&&E()}),r.jsx("button",{onClick:E,disabled:!h.trim(),style:{background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"5px 12px",fontSize:"0.78rem",cursor:"pointer",opacity:h.trim()?1:.5},children:"?"})]}),r.jsxs("div",{style:{marginBottom:6},children:[r.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.color")}),r.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:Js.map(A=>r.jsx("div",{onClick:()=>y(A),style:{width:20,height:20,borderRadius:"50%",background:A,cursor:"pointer",border:f===A?"3px solid var(--accent, #3b82f6)":"2px solid transparent",boxSizing:"border-box"}},A))})]}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.icon")}),r.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:tr.map(A=>r.jsx("div",{onClick:()=>g(A),style:{width:26,height:26,borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"0.85rem",background:m===A?"var(--accent-bg, #eff6ff)":"transparent",border:m===A?"1px solid var(--accent, #3b82f6)":"1px solid transparent"},children:A},A))})]})]}),L&&r.jsx("div",{style:{padding:"6px 10px",background:"var(--accent-bg, #eff6ff)",borderRadius:6,marginBottom:8,fontSize:"0.72rem",color:"var(--accent, #3b82f6)"},children:l("playlistManager.bulkTagHint")+": "+s.length}),e.length===0?r.jsx("div",{style:{textAlign:"center",padding:20,opacity:.3,fontSize:"0.82rem"},children:l("playlistManager.noTags")}):r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.map(A=>r.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderRadius:8,border:"1px solid var(--border-color, #e5e7eb)",background:c===A.id?"var(--surface-bg, #f9fafb)":"transparent"},children:c===A.id?r.jsxs(r.Fragment,{children:[r.jsx("select",{value:T,onChange:_=>j(_.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:tr.map(_=>r.jsx("option",{value:_,children:_},_))}),r.jsx("input",{type:"color",value:S,onChange:_=>R(_.target.value),style:{width:24,height:24,border:"none",cursor:"pointer",padding:0}}),r.jsx("input",{type:"text",value:w,onChange:_=>M(_.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:_=>_.key==="Enter"&&$()}),r.jsx("button",{onClick:$,style:nr("var(--accent, #3b82f6)"),children:"?"}),r.jsx("button",{onClick:()=>u(null),style:nr("var(--text-secondary, #9ca3af)"),children:"?"})]}):r.jsxs(r.Fragment,{children:[r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 10px",borderRadius:20,background:`${A.color}18`,color:A.color,fontWeight:600,fontSize:"0.78rem"},children:[A.icon&&r.jsx("span",{children:A.icon}),A.name]}),L&&i&&o&&r.jsx("input",{type:"checkbox",checked:W(A.id),ref:_=>{_&&(_.indeterminate=Z(A.id))},onChange:()=>{const _=s.map(U=>U.id);W(A.id)?o(_,A.id):i(_,A.id)},style:{cursor:"pointer"}}),r.jsx("div",{style:{flex:1}}),r.jsx("button",{onClick:()=>O(A),style:nr("var(--text-secondary, #9ca3af)"),title:l("playlistManager.editTag"),children:"?"}),r.jsx("button",{onClick:()=>D(A.id),style:nr(k===A.id?"var(--error, #ef4444)":"var(--text-secondary, #9ca3af)"),title:k===A.id?l("playlistManager.confirmDelete"):l("playlistManager.deleteTag"),children:k===A.id?"?":"??"})]})},A.id))})]})]})},nr=e=>({background:"none",border:"none",cursor:"pointer",fontSize:"0.82rem",color:e,padding:"2px 4px"});var rs=(e=>(e.Static="static",e.Dynamic="dynamic",e))(rs||{}),ol=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(ol||{}),ll=(e=>(e.Left="left",e.Right="right",e))(ll||{}),ot=(e=>(e.Artist="artist",e.Title="title",e.Album="album",e.Genre="genre",e.Year="year",e.Duration="duration",e.Rating="rating",e.PlayCount="playCount",e.Tag="tag",e.Source="source",e.AddedDate="addedDate",e))(ot||{}),lt=(e=>(e.Equals="eq",e.NotEquals="neq",e.Contains="contains",e.NotContains="notContains",e.StartsWith="startsWith",e.GreaterThan="gt",e.LessThan="lt",e.Between="between",e.In="in",e.NotIn="notIn",e))(lt||{}),cl=(e=>(e.Title="title",e.Artist="artist",e.Album="album",e.Duration="duration",e.AddedDate="addedDate",e.Year="year",e.Rating="rating",e.Custom="custom",e))(cl||{}),sn=(e=>(e.Asc="asc",e.Desc="desc",e))(sn||{}),kt=(e=>(e.Library="library",e.Spotify="spotify",e.Tidal="tidal",e.YouTube="youtube",e.MusicBrainz="musicbrainz",e.Import="import",e.Manual="manual",e))(kt||{});const Jp=[{value:ot.Artist,label:"Artist"},{value:ot.Title,label:"Title"},{value:ot.Album,label:"Album"},{value:ot.Genre,label:"Genre"},{value:ot.Year,label:"Year"},{value:ot.Duration,label:"Duration (s)"},{value:ot.Rating,label:"Rating"},{value:ot.PlayCount,label:"Play Count"},{value:ot.Tag,label:"Tag"},{value:ot.Source,label:"Source"},{value:ot.AddedDate,label:"Added Date"}],ef=[{value:lt.Equals,label:"="},{value:lt.NotEquals,label:"≠"},{value:lt.Contains,label:"contains"},{value:lt.NotContains,label:"not contains"},{value:lt.StartsWith,label:"starts with"},{value:lt.GreaterThan,label:">"},{value:lt.LessThan,label:"<"},{value:lt.Between,label:"between"},{value:lt.In,label:"in"},{value:lt.NotIn,label:"not in"}];function tf(e){return"logic"in e&&"rules"in e}function ya(){return{id:crypto.randomUUID(),field:ot.Artist,operator:lt.Contains,value:""}}function dl(){return{id:crypto.randomUUID(),logic:"and",rules:[ya()]}}const nf=({rule:e,onChange:t,onRemove:n})=>r.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[r.jsx("select",{className:"form-select form-select-sm",style:{width:130},value:e.field,onChange:a=>t({...e,field:a.target.value}),children:Jp.map(a=>r.jsx("option",{value:a.value,children:a.label},a.value))}),r.jsx("select",{className:"form-select form-select-sm",style:{width:130},value:e.operator,onChange:a=>t({...e,operator:a.target.value}),children:ef.map(a=>r.jsx("option",{value:a.value,children:a.label},a.value))}),r.jsx("input",{type:"text",className:"form-control form-control-sm",style:{width:160},value:e.value,placeholder:"Value",onChange:a=>t({...e,value:a.target.value})}),e.operator===lt.Between&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-muted",children:"–"}),r.jsx("input",{type:"text",className:"form-control form-control-sm",style:{width:120},value:e.value2??"",placeholder:"Value 2",onChange:a=>t({...e,value2:a.target.value})})]}),r.jsx("button",{className:"btn btn-outline-danger btn-sm",onClick:n,title:"Remove rule","aria-label":"Remove rule",children:r.jsx(se.NtdClose,{size:14})})]}),ul=({group:e,onChange:t,onRemove:n,depth:a=0})=>{const{t:s}=Te(),i=d.useCallback((p,f)=>{const y=[...e.rules];y[p]=f,t({...e,rules:y})},[e,t]),o=d.useCallback(p=>{const f=e.rules.filter((y,m)=>m!==p);t({...e,rules:f.length>0?f:[ya()]})},[e,t]),l=d.useCallback(()=>{t({...e,rules:[...e.rules,ya()]})},[e,t]),c=d.useCallback(()=>{t({...e,rules:[...e.rules,dl()]})},[e,t]),u=d.useCallback(()=>{t({...e,logic:e.logic==="and"?"or":"and"})},[e,t]),h=e.logic==="and"?"var(--bs-primary)":"var(--bs-warning)";return r.jsxs("div",{className:"p-2 mb-2 rounded",style:{borderLeft:`3px solid ${h}`,backgroundColor:a%2===0?"rgba(var(--bs-body-color-rgb), 0.03)":"transparent"},children:[r.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[r.jsx("button",{className:`btn btn-sm ${e.logic==="and"?"btn-primary":"btn-warning"}`,onClick:u,title:s("playlistManager.toggleLogic","Toggle AND/OR"),children:e.logic.toUpperCase()}),r.jsx("span",{className:"text-muted small",children:s("playlistManager.matchAll","Match all / any of these rules")}),r.jsxs("div",{className:"ms-auto d-flex gap-1",children:[r.jsx("button",{className:"btn btn-outline-secondary btn-sm",onClick:l,title:"Add rule",children:"+ Rule"}),a<3&&r.jsx("button",{className:"btn btn-outline-secondary btn-sm",onClick:c,title:"Add nested group",children:"+ Group"}),n&&r.jsx("button",{className:"btn btn-outline-danger btn-sm",onClick:n,title:"Remove group","aria-label":"Remove group",children:r.jsx(se.NtdClose,{size:14})})]})]}),e.rules.map((p,f)=>tf(p)?r.jsx(ul,{group:p,onChange:y=>i(f,y),onRemove:()=>o(f),depth:a+1},p.id):r.jsx(nf,{rule:p,onChange:y=>i(f,y),onRemove:()=>o(f)},p.id))]})},hl=({rules:e,onChange:t,limit:n,onLimitChange:a})=>{const{t:s}=Te(),i=e??dl();return r.jsxs("div",{className:"border rounded p-3",children:[r.jsxs("h6",{className:"mb-3",children:[r.jsx(se.NtdRepeat,{size:14})," ",s("playlistManager.dynamicRules","Dynamic Playlist Rules")]}),r.jsx("p",{className:"text-muted small mb-3",children:s("playlistManager.dynamicRulesHint","Tracks matching these rules will automatically be included in the playlist.")}),r.jsx(ul,{group:i,onChange:t}),a&&r.jsxs("div",{className:"d-flex align-items-center gap-2 mt-3 pt-2 border-top",children:[r.jsx("label",{className:"form-label mb-0 small",children:s("playlistManager.maxTracks","Max tracks:")}),r.jsx("input",{type:"number",className:"form-control form-control-sm",style:{width:100},min:0,value:n??"",placeholder:"∞",onChange:o=>{const l=parseInt(o.target.value,10);a(isNaN(l)||l<=0?void 0:l)}}),r.jsx("span",{className:"text-muted small",children:s("playlistManager.leaveEmptyForAll","(leave empty for unlimited)")})]})]})},ei=e=>{if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`},rf={library:"??",spotify:"??",tidal:"?",youtube:"??",musicbrainz:"??",import:"??",manual:"?"},as=({tracks:e,tags:t,selectedTrackIds:n,onSelectionChange:a,onPlay:s,onRemove:i,onReorder:o,onTagTracks:l,onRateTracks:c,sortField:u,sortDir:h,onSortChange:p,filterText:f,onFilterChange:y,compact:m=!1,draggable:g=!1,onDragStart:b,dropTarget:x=!1,onDrop:k})=>{const{t:v}=Te(),[w,M]=d.useState(null),[S,R]=d.useState(null),T=d.useRef(null),j=d.useMemo(()=>{let C=e??[];if(f.trim()){const F=f.toLowerCase();C=C.filter(I=>{var P,N;return I.title.toLowerCase().includes(F)||I.artist.toLowerCase().includes(F)||((P=I.album)==null?void 0:P.toLowerCase().includes(F))||((N=I.genre)==null?void 0:N.toLowerCase().includes(F))})}return[...C].sort((F,I)=>{const P=h==="asc"?1:-1;switch(u){case"title":return P*F.title.localeCompare(I.title);case"artist":return P*F.artist.localeCompare(I.artist);case"album":return P*(F.album??"").localeCompare(I.album??"");case"duration":return P*((F.duration??0)-(I.duration??0));case"year":return P*((F.year??0)-(I.year??0));case"rating":return P*((F.rating??0)-(I.rating??0));case"addedDate":return P*(F.addedAt??"").localeCompare(I.addedAt??"");case"custom":return P*((F.customOrder??0)-(I.customOrder??0));default:return 0}})},[e,f,u,h]),O=d.useCallback((C,F)=>{const I=j[C];if(I){if(F.ctrlKey||F.metaKey){const P=new Set(n);P.has(I.id)?P.delete(I.id):P.add(I.id),a(P)}else if(F.shiftKey&&T.current!==null){const P=Math.min(T.current,C),N=Math.max(T.current,C),z=new Set(n);for(let B=P;B<=N;B++)z.add(j[B].id);a(z)}else a(new Set([I.id]));T.current=C}},[j,n,a]),$=d.useCallback(()=>{n.size===j.length?a(new Set):a(new Set(j.map(C=>C.id)))},[j,n,a]),E=({field:C,label:F,width:I})=>{const P=u===C;return r.jsxs("div",{style:{width:I,flex:I?void 0:1,cursor:"pointer",userSelect:"none",fontWeight:P?700:500,fontSize:"0.72rem",textTransform:"uppercase",letterSpacing:"0.04em",opacity:P?1:.6,display:"flex",alignItems:"center",gap:4},onClick:()=>{P?p(C,h===sn.Asc?sn.Desc:sn.Asc):p(C,sn.Asc)},children:[F,P&&r.jsx("span",{children:"?"})]})},D=d.useCallback((C,F)=>{const I=n.has(C.id)?Array.from(n):[C.id];F.dataTransfer.setData("trackIds",JSON.stringify(I)),F.dataTransfer.effectAllowed="move",b==null||b(I,F)},[n,b]),L=d.useCallback((C,F)=>{F.preventDefault(),F.dataTransfer.dropEffect="move",M(C)},[]),W=d.useCallback((C,F)=>{F.preventDefault(),M(null);try{const I=F.dataTransfer.getData("trackIds");if(I&&o){const P=JSON.parse(I),N=j.filter(G=>!P.includes(G.id)),z=j.filter(G=>P.includes(G.id)),B=Math.min(C,N.length);N.splice(B,0,...z),o(N.map(G=>G.id))}}catch{}},[j,o]),Z=d.useCallback(C=>{C.preventDefault(),M(null),k==null||k(C)},[k]),A=d.useMemo(()=>new Map(t.map(C=>[C.id,C])),[t]),_=C=>C.replace(/[^a-z0-9_-]/gi,"-"),U=m?36:48,ne={display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)",color:"var(--text-secondary, #6b7280)"},V=(C,F)=>({display:"flex",alignItems:"center",gap:8,padding:m?"4px 12px":"6px 12px",height:U,cursor:"pointer",background:F?"var(--accent-light, #dbeafe)":C?"var(--selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--border-subtle, #f3f4f6)",transition:"background 0.1s"}),q=j.length>0&&n.size===j.length;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:x?C=>{C.preventDefault(),C.dataTransfer.dropEffect="copy"}:void 0,onDrop:x?Z:void 0,children:[r.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)",display:"flex",gap:8,alignItems:"center"},children:[r.jsx("input",{type:"text",value:f,onChange:C=>y(C.target.value),placeholder:"?? "+v("playlistManager.filterTracks"),style:{flex:1,fontSize:"0.82rem",padding:"6px 10px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #f9fafb)",color:"var(--text-primary, #1f2937)"}}),r.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[j.length,"/",(e??[]).length]}),n.size>0&&i&&r.jsxs("button",{style:{fontSize:"0.72rem",padding:"4px 8px",borderRadius:4,border:"1px solid var(--error, #ef4444)",background:"transparent",color:"var(--error, #ef4444)",cursor:"pointer"},onClick:()=>i(Array.from(n)),children:["?? ",n.size]})]}),r.jsxs("div",{style:ne,children:[r.jsx("div",{style:{width:28},children:r.jsx("input",{type:"checkbox",checked:q,onChange:$,style:{cursor:"pointer"}})}),r.jsx("div",{style:{width:20},children:"#"}),!m&&r.jsx("div",{style:{width:44}}),r.jsx(E,{field:"title",label:v("playlistManager.colTitle")}),r.jsx(E,{field:"artist",label:v("playlistManager.colArtist")}),!m&&r.jsx(E,{field:"album",label:v("playlistManager.colAlbum")}),r.jsx(E,{field:"duration",label:v("playlistManager.colDuration"),width:60}),!m&&r.jsx(E,{field:"year",label:v("playlistManager.colYear"),width:50}),r.jsx("div",{style:{width:30}})," ",!m&&r.jsx("div",{style:{width:60}})," ",r.jsx("div",{style:{width:24}})," "]}),r.jsxs("div",{style:{flex:1,overflow:"auto"},children:[j.length===0&&r.jsx("div",{style:{padding:24,textAlign:"center",opacity:.4,fontSize:"0.85rem"},children:e.length===0?v("playlistManager.emptyPlaylist"):v("playlistManager.noMatchingTracks")}),j.map((C,F)=>{const I=n.has(C.id),P=w===F;return r.jsxs("div",{style:V(I,P),onClick:N=>O(F,N),onDoubleClick:()=>s==null?void 0:s(C),draggable:g,onDragStart:N=>D(C,N),onDragOver:N=>L(F,N),onDrop:N=>W(F,N),onDragLeave:()=>M(null),children:[r.jsx("div",{style:{width:28},children:r.jsx("input",{type:"checkbox",checked:I,onChange:()=>{const N=new Set(n);I?N.delete(C.id):N.add(C.id),a(N)},onClick:N=>N.stopPropagation(),style:{cursor:"pointer"}})}),r.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:F+1}),!m&&r.jsx("div",{style:{width:44,height:36,flexShrink:0},children:C.coverUrl?r.jsx("img",{src:C.coverUrl,alt:C.title||v("common.coverArt","Cover art"),style:{width:36,height:36,borderRadius:4,objectFit:"cover"},loading:"lazy"}):r.jsx("div",{style:{width:36,height:36,borderRadius:4,background:"var(--surface-bg, #f3f4f6)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.9rem"},children:"??"})}),r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",fontWeight:500},children:C.title}),r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",opacity:.7},children:C.artist}),!m&&r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",opacity:.5},children:C.album}),r.jsx("div",{style:{width:60,fontSize:"0.78rem",opacity:.5,textAlign:"right"},children:ei(C.duration)}),!m&&r.jsx("div",{style:{width:50,fontSize:"0.72rem",opacity:.4,textAlign:"center"},children:C.year||""}),r.jsx("div",{style:{width:30,textAlign:"center",fontSize:"0.75rem"},title:C.source,children:rf[C.source]??"?"}),!m&&r.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[C.tags.slice(0,2).map(N=>{const z=A.get(N);if(!z)return null;const B=`--tag-${_(N)}`;return r.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${B}-bg, ${z.color}22)`,color:`var(${B}, ${z.color})`,whiteSpace:"nowrap"},children:z.name},N)}),C.tags.length>2&&r.jsxs("span",{style:{fontSize:"0.6rem",opacity:.4},children:["+",C.tags.length-2]})]}),r.jsxs("div",{style:{width:24,display:"flex",alignItems:"center"},children:[r.jsx("button",{style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:2,opacity:.5,position:"relative"},onClick:N=>{N.stopPropagation(),R(S===C.id?null:C.id)},title:v("playlistManager.morActions"),children:"?"}),S===C.id&&t.length>0&&r.jsxs("div",{style:{position:"absolute",right:12,marginTop:4,background:"var(--card-bg, #fff)",border:"1px solid var(--border-color, #e5e7eb)",borderRadius:8,padding:8,zIndex:100,boxShadow:"0 4px 12px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",minWidth:140},children:[r.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:v("playlistManager.assignTag")}),t.map(N=>{const z=C.tags.includes(N.id);return r.jsxs("div",{style:{padding:"4px 8px",borderRadius:4,cursor:"pointer",fontSize:"0.78rem",display:"flex",alignItems:"center",gap:6,background:z?`var(--tag-${_(N.id)}-bg, ${N.color}22)`:"transparent"},onClick:B=>{B.stopPropagation();const G=n.size>0?Array.from(n):[C.id];z||l==null||l(G,[N.id]),R(null)},children:[r.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:`var(--tag-${_(N.id)}, ${N.color})`,flexShrink:0}}),r.jsx("span",{children:N.name}),z&&r.jsx("span",{style:{marginLeft:"auto"},children:"?"})]},N.id)})]})]})]},C.id)})]}),r.jsxs("div",{style:{padding:"6px 12px",borderTop:"1px solid var(--border-color, #e5e7eb)",fontSize:"0.72rem",opacity:.5,display:"flex",gap:16},children:[r.jsxs("span",{children:[j.length," ",v("playlistManager.tracks")]}),r.jsx("span",{children:ei(j.reduce((C,F)=>C+(F.duration??0),0))}),n.size>0&&r.jsxs("span",{children:[n.size," ",v("playlistManager.selected")]})]})]})},ti=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),pl=({playlists:e=[],tags:t=[],onCopyTracks:n=()=>{},onMoveTracks:a=()=>{},onRemoveTracks:s=()=>{},onReorderTracks:i=()=>{},onPlay:o=()=>{},onTagTracks:l=()=>{},initialLeftId:c,initialRightId:u,library:h,queue:p,onAddToQueue:f,onRemoveFromQueue:y})=>{const{t:m}=Te(),[g,b]=d.useState(()=>ti(c??null)),[x,k]=d.useState(()=>ti(u??null)),[v,w]=d.useState("left"),[M,S]=d.useState(null),[R,T]=d.useState(50),[j,O]=d.useState(!1),$=d.useMemo(()=>e.find(P=>P.id===g.playlistId),[e,g.playlistId]),E=d.useMemo(()=>e.find(P=>P.id===x.playlistId),[e,x.playlistId]),D=d.useCallback((P,N)=>{P==="left"?b(z=>({...z,...N})):k(z=>({...z,...N}))},[]),L=d.useCallback(P=>P==="left"?g:x,[g,x]),W=P=>P==="left"?"right":"left",Z=d.useCallback(P=>{const N=L(P),z=L(W(P));!N.playlistId||!z.playlistId||N.selectedTrackIds.size===0||(n(N.playlistId,z.playlistId,Array.from(N.selectedTrackIds)),D(P,{selectedTrackIds:new Set}))},[L,n,D]),A=d.useCallback(P=>{const N=L(P),z=L(W(P));!N.playlistId||!z.playlistId||N.selectedTrackIds.size===0||(a(N.playlistId,z.playlistId,Array.from(N.selectedTrackIds)),D(P,{selectedTrackIds:new Set}))},[L,a,D]),_=d.useCallback(P=>{const N=L(P);!N.playlistId||N.selectedTrackIds.size===0||S({operation:"copy",sourcePlaylistId:N.playlistId,trackIds:Array.from(N.selectedTrackIds)})},[L]),U=d.useCallback(P=>{const N=L(P);!N.playlistId||N.selectedTrackIds.size===0||S({operation:"cut",sourcePlaylistId:N.playlistId,trackIds:Array.from(N.selectedTrackIds)})},[L]),ne=d.useCallback(P=>{const N=L(P);!M||!N.playlistId||(M.operation==="copy"?n(M.sourcePlaylistId,N.playlistId,M.trackIds):a(M.sourcePlaylistId,N.playlistId,M.trackIds),S(null))},[M,L,n,a]),V=d.useCallback(P=>{P.key==="Tab"&&!P.shiftKey&&(P.preventDefault(),w(N=>W(N))),(P.ctrlKey||P.metaKey)&&P.key==="c"&&_(v),(P.ctrlKey||P.metaKey)&&P.key==="x"&&U(v),(P.ctrlKey||P.metaKey)&&P.key==="v"&&ne(v)},[v,_,U,ne]),q=d.useCallback(()=>O(!0),[]),C=d.useCallback(P=>{if(!j)return;const N=P.currentTarget.getBoundingClientRect(),z=(P.clientX-N.left)/N.width*100;T(Math.max(20,Math.min(80,z)))},[j]),F=d.useCallback(()=>O(!1),[]),I=P=>{const N=L(P),z=P==="left"?$:E,B=v===P,Y=!!L(W(P)).playlistId;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",border:B?"2px solid var(--accent, #3b82f6)":"2px solid transparent",borderRadius:8,overflow:"hidden",background:"var(--card-bg, #fff)"},onClick:()=>w(P),children:[r.jsx("div",{style:{padding:"8px 12px",background:B?"var(--accent, #3b82f6)":"var(--surface-bg, #f3f4f6)",color:B?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:r.jsxs("select",{value:N.playlistId??"",onChange:X=>D(P,{playlistId:X.target.value||null,selectedTrackIds:new Set}),style:{flex:1,fontSize:"0.82rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",background:B?"var(--accent-overlay, #ffffff30)":"var(--input-bg, #fff)",color:B?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)"},children:[r.jsx("option",{value:"",children:m("playlistManager.selectPlaylist")}),e.map(X=>r.jsxs("option",{value:X.id,children:[X.name," (",X.trackCount,")"]},X.id))]})}),r.jsxs("div",{style:{display:"flex",gap:4,padding:"4px 8px",borderBottom:"1px solid var(--border-color, #e5e7eb)",flexWrap:"wrap"},children:[r.jsxs("button",{style:Qr(!1),onClick:()=>Z(P),disabled:!N.playlistId||!Y||N.selectedTrackIds.size===0,title:m("playlistManager.copyToOther"),children:["???"," ",m("playlistManager.copy")]}),r.jsxs("button",{style:Qr(!1),onClick:()=>A(P),disabled:!N.playlistId||!Y||N.selectedTrackIds.size===0,title:m("playlistManager.moveToOther"),children:["??"," ",m("playlistManager.move")]}),r.jsx("div",{style:{flex:1}}),M&&r.jsxs("button",{style:Qr(!0),onClick:()=>ne(P),disabled:!N.playlistId,children:["?? ",m("playlistManager.paste")," (",M.trackIds.length,")"]})]}),z?r.jsx(as,{tracks:z.tracks,tags:t,selectedTrackIds:N.selectedTrackIds,onSelectionChange:X=>D(P,{selectedTrackIds:X}),onPlay:o,onRemove:X=>s(z.id,X),onReorder:X=>i(z.id,X),onTagTracks:l,sortField:N.sortField,sortDir:N.sortDir,onSortChange:(X,ie)=>D(P,{sortField:X,sortDir:ie}),filterText:N.filterText,onFilterChange:X=>D(P,{filterText:X}),compact:!0,draggable:!0}):r.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",opacity:.3,fontSize:"0.85rem"},children:m("playlistManager.selectPlaylistPrompt")})]})};return r.jsxs("div",{style:{display:"flex",height:"100%",userSelect:j?"none":"auto"},onKeyDown:V,onMouseMove:C,onMouseUp:F,tabIndex:0,children:[r.jsx("div",{style:{width:`${R}%`,minWidth:200},children:I("left")}),r.jsx("div",{style:{width:6,cursor:"col-resize",background:j?"var(--accent, #3b82f6)":"var(--border-color, #e5e7eb)",transition:j?"none":"background 0.15s",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseDown:q,children:r.jsx("div",{style:{width:2,height:40,borderRadius:1,background:j?"var(--btn-text, #fff)":"var(--text-secondary, #9ca3af)"}})}),r.jsx("div",{style:{flex:1,minWidth:200},children:I("right")})]})},Qr=e=>({background:e?"var(--accent, #3b82f6)":"transparent",color:e?"var(--btn-text, #fff)":"var(--text-secondary, #6b7280)",border:e?"none":"1px solid var(--border-color, #d1d5db)",borderRadius:6,padding:"3px 8px",fontSize:"0.72rem",cursor:"pointer",whiteSpace:"nowrap"}),fl="av:local-playlists";function af(){try{const e=localStorage.getItem(fl);return e?JSON.parse(e):[]}catch{return[]}}function sf(e){const t=JSON.stringify(e);try{localStorage.setItem(fl,t)}catch{}}function ss(){const[e,t]=d.useState(()=>af()),n=d.useRef(!1);return d.useEffect(()=>{n.current=!0},[]),d.useEffect(()=>{sf(e)},[e]),d.useMemo(()=>({list:()=>e,get:s=>e.find(i=>i.id===s),create:s=>{const i=new Date().toISOString(),o={id:crypto.randomUUID(),name:s,items:[],updatedAt:i};return t(l=>[o,...l]),o},rename:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,name:i,updatedAt:new Date().toISOString()}:l)),remove:s=>t(i=>i.filter(o=>o.id!==s)),replaceItems:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,items:i,updatedAt:new Date().toISOString()}:l)),addItems:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,items:[...l.items,...i],updatedAt:new Date().toISOString()}:l))}),[e])}const of=it.scoped("PlaylistList"),lf={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,background:"var(--nice-bg, #fff)"},cf={...lf,padding:"8px 10px",cursor:"pointer"},ml={border:"1px solid var(--border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--bg, #fff)",cursor:"pointer"},df={...ml,background:"var(--primary, #4f46e5)",borderColor:"var(--primary, #4f46e5)",color:"var(--bg, #fff)"},is=({selectedId:e,onSelect:t,onCreateRemote:n})=>{const{t:a}=Te(),s=ss(),[i,o]=d.useState(""),l=d.useMemo(()=>s.list(),[s]);return r.jsxs("div",{style:{display:"grid",gap:10},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("input",{placeholder:a("playlistList.playlistName","Playlist name..."),value:i,onChange:c=>o(c.target.value),style:{flex:1,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px"},"aria-label":"Playlist name"}),r.jsxs("button",{type:"button",disabled:!i.trim(),style:i.trim()?df:{...ml,cursor:"not-allowed",color:"var(--muted, #9ca3af)",background:"var(--bg-muted, #f3f4f6)"},onClick:async()=>{const c=s.create(i.trim());if(o(""),n)try{await n({platform:"tidal",name:c.name,songs:c.items})}catch(u){of.error("Remote playlist create failed:",u)}t==null||t(c)},children:["+ ",a("common.add","Add")]})]}),r.jsxs("div",{style:{display:"grid",gap:6},children:[l.map(c=>{const u=c.id===e;return r.jsxs("button",{onClick:()=>t==null?void 0:t(c),style:{...cf,background:u?"var(--active-bg, #eef2ff)":"var(--bg, #fff)"},children:[r.jsx("div",{style:{fontWeight:600},children:c.name}),r.jsxs("div",{style:{color:"var(--text-dim, #64748b)",fontSize:12},children:[c.items.length+" "+a("playlistList.songs","songs")," \\u2022"," ",new Date(c.updatedAt).toLocaleString()]})]},c.id)}),!l.length&&r.jsx("div",{style:{color:"var(--muted, #6b7280)"},children:a("playlistList.emptyState","No playlists. Add the first one ↑")})]})]})},uf=it.scoped("PlaylistBrowser"),ni={display:"grid",gap:12},ri=e=>({artist:(e.artists??[]).join(", "),title:e.title}),gl=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:n,tracks:a,view:s,onSelect:i,onPlay:o})=>{var b;const{t:l}=Te(),c=ss(),[u,h]=d.useState(null),[p,f]=d.useState(""),[,y]=d.useState([]),m=u==null?void 0:u.id,g=(x,k)=>{if("addItems"in c){c.addItems(x.id,k);const w=c.list().find(M=>M.id===x.id)||x;h(w);return}const v=c;if("update"in c&&typeof v.update=="function"){const w=Array.from([...x.items||[],...k]);v.update({...x,items:w});const M=c.list().find(S=>S.id===x.id)||{...x,items:w};h(M);return}uf.warn("useLocalPlaylists: missing addItems/update method — update hook implementation.")};return r.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(min(200px, 100%), 320px) 1fr",gap:16},children:[r.jsxs("div",{style:ni,children:[r.jsx("h3",{style:{margin:0},children:l("playlistBrowser.playlists")}),r.jsx(is,{selectedId:m,onSelect:h}),u&&r.jsxs("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:[l("playlistBrowser.selected","Selected"),": ",r.jsx("strong",{children:u.name})," �"," ",((b=u.items)==null?void 0:b.length)??0," ",l("playlistBrowser.tracks","tracks")]})]}),r.jsxs("div",{style:ni,children:[r.jsx("h3",{style:{margin:0},children:l("playlistBrowser.library")}),r.jsxs("div",{children:[e==null?void 0:e({placeholder:l("playlistBrowser.searchAndAdd","Search and add to playlist..."),onSelect:x=>{u&&g(u,[ri(x)])}}),r.jsx("input",{placeholder:l("playlistBrowser.fullSearch","Full search (Enter does not add, full list below)"),value:p,onChange:x=>f(x.target.value),style:{width:"100%",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px",marginTop:10}})]}),t==null?void 0:t({query:p,onSelect:x=>{u&&g(u,[ri(x)])}}),n==null?void 0:n({onPlayNow:x=>y(x),onAddToQueue:x=>y(k=>[...k,...x]),onAddDescriptors:x=>u&&g(u,x)})]})]})};var qt=(e=>(e[e.None=0]="None",e[e.Spotify=1]="Spotify",e[e.Tidal=2]="Tidal",e[e.YouTube=4]="YouTube",e[e.All=7]="All",e))(qt||{});const yl=(e,t=null)=>e.filter(n=>n.parentId===t).sort((n,a)=>n.sortOrder-a.sortOrder).map(n=>({...n,children:yl(e,n.id)})),hf={[qt.Spotify]:{icon:"??",label:"Spotify",color:"var(--source-spotify, #1DB954)",bg:"var(--source-spotify-bg, #1DB95418)"},[qt.Tidal]:{icon:"?",label:"Tidal",color:"var(--source-tidal, #000000)",bg:"var(--source-tidal-bg, #00000010)"},[qt.YouTube]:{icon:"??",label:"YouTube",color:"var(--source-youtube, #FF0000)",bg:"var(--source-youtube-bg, #FF000010)"}},bl=({folders:e,playlists:t,tags:n,services:a,activeFolderId:s,activePlaylistId:i,onSelectFolder:o,onSelectPlaylist:l,onCreateFolder:c,onRenameFolder:u,onDeleteFolder:h,onCreatePlaylist:p,onConnectService:f,onDisconnectService:y,onDragPlaylistToFolder:m,collapsed:g=!1,onToggleCollapse:b})=>{const{t:x}=Te(),[k,v]=d.useState(new Set),[w,M]=d.useState(!1),[S,R]=d.useState(""),[T,j]=d.useState(null),[O,$]=d.useState(!1),[E,D]=d.useState(""),[L,W]=d.useState("static"),[Z,A]=d.useState(null),[_,U]=d.useState(""),[ne,V]=d.useState(null),[q,C]=d.useState(!1),F=d.useMemo(()=>yl(e),[e]),I=d.useCallback(Q=>{v(de=>{const me=new Set(de);return me.has(Q)?me.delete(Q):me.add(Q),me})},[]),P=d.useCallback(()=>{S.trim()&&(c(S.trim(),T),R(""),M(!1))},[S,T,c]),N=d.useCallback(()=>{E.trim()&&(p(E.trim(),L,s),D(""),$(!1))},[E,L,s,p]),z=d.useCallback(Q=>{_.trim()&&(u(Q,_.trim()),A(null),U(""))},[_,u]),B=d.useCallback((Q,de)=>{Q.preventDefault(),Q.dataTransfer.dropEffect="move",V(de)},[]),G=d.useCallback((Q,de)=>{Q.preventDefault();const me=Q.dataTransfer.getData("playlistId");me&&m&&m(me,de),V(null)},[m]),Y=d.useCallback(()=>V(null),[]),X=d.useCallback(Q=>t.filter(de=>(de.folderId??null)===Q),[t]),ie={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%"},le={padding:"8px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)"},te=(Q,de=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:de?"var(--accent-light, #dbeafe)":Q?"var(--accent, #3b82f6)":"transparent",color:Q?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",transition:"background 0.15s",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),H={background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:"2px 6px",borderRadius:4,color:"var(--text-secondary, #6b7280)"},K={fontSize:"0.8rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)",width:"100%"},oe=(Q,de)=>{var Se,ae;const me=k.has(Q.id),xe=s===Q.id,ce=ne===Q.id,ye=X(Q.id);return r.jsxs("div",{children:[r.jsxs("div",{style:{...te(xe,ce),paddingLeft:12+de*16},onClick:()=>{o(Q.id),Q.children&&Q.children.length>0&&I(Q.id)},onDragOver:ue=>B(ue,Q.id),onDrop:ue=>G(ue,Q.id),onDragLeave:Y,children:[r.jsx("span",{style:{width:14,textAlign:"center",flexShrink:0,fontSize:"0.7rem"},children:(((Se=Q.children)==null?void 0:Se.length)||0)>0||ye.length>0?"?":"�"}),Z===Q.id?r.jsx("input",{value:_,onChange:ue=>U(ue.target.value),onKeyDown:ue=>{ue.key==="Enter"&&z(Q.id),ue.key==="Escape"&&A(null)},onBlur:()=>z(Q.id),autoFocus:!0,style:{...K,flex:1},onClick:ue=>ue.stopPropagation()}):r.jsxs(r.Fragment,{children:[r.jsx("span",{children:Q.icon??"??"}),r.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:Q.name}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:ye.length}),r.jsx("button",{style:H,onClick:ue=>{ue.stopPropagation(),A(Q.id),U(Q.name)},title:x("common.rename"),children:"?"}),r.jsx("button",{style:{...H,color:"var(--error, #ef4444)"},onClick:ue=>{ue.stopPropagation(),h(Q.id)},title:x("common.delete"),children:"?"})]})]}),me&&r.jsxs(r.Fragment,{children:[ye.map(ue=>re(ue,de+1)),(ae=Q.children)==null?void 0:ae.map(ue=>oe(ue,de+1))]})]},Q.id)},re=(Q,de)=>{const me=i===Q.id;return r.jsxs("div",{style:{...te(me),paddingLeft:12+de*16+22},onClick:()=>l(Q.id),draggable:!0,onDragStart:xe=>{xe.dataTransfer.setData("playlistId",Q.id),xe.dataTransfer.effectAllowed="move"},children:[r.jsx("span",{style:{fontSize:"0.7rem"},children:Q.type==="dynamic"?"?":"??"}),r.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:Q.name}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:Q.trackCount})]},Q.id)};if(g)return r.jsx("div",{style:ie,children:r.jsx("button",{style:{...H,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:b,title:x("playlistManager.expandSidebar"),children:"?"})});const he=X(null);return r.jsxs("div",{style:ie,children:[r.jsxs("div",{style:{...le,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[r.jsxs("span",{style:{fontWeight:700,fontSize:"0.85rem"},children:["?? ",x("playlistManager.title")]}),r.jsx("button",{style:H,onClick:b,title:x("playlistManager.collapseSidebar"),children:"?"})]}),r.jsxs("div",{style:{...le,display:"flex",gap:4,flexWrap:"wrap"},children:[r.jsxs("button",{style:{...H,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:6,padding:"4px 10px"},onClick:()=>$(!0),children:["+ ",x("playlistManager.newPlaylist")]}),r.jsxs("button",{style:{...H,border:"1px solid var(--border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{M(!0),j(s)},children:["?? ",x("playlistManager.newFolder")]})]}),O&&r.jsxs("div",{style:{...le,display:"flex",flexDirection:"column",gap:6},children:[r.jsx("input",{value:E,onChange:Q=>D(Q.target.value),placeholder:x("playlistManager.playlistName"),style:K,autoFocus:!0,onKeyDown:Q=>{Q.key==="Enter"&&N(),Q.key==="Escape"&&$(!1)}}),r.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[r.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[r.jsx("input",{type:"radio",checked:L==="static",onChange:()=>W("static")}),x("playlistManager.static")]}),r.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[r.jsx("input",{type:"radio",checked:L==="dynamic",onChange:()=>W("dynamic")}),"? ",x("playlistManager.dynamic")]}),r.jsx("div",{style:{flex:1}}),r.jsx("button",{style:{...H,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:N,"aria-label":"Confirm create playlist",children:"?"}),r.jsx("button",{style:H,onClick:()=>$(!1),"aria-label":"Cancel create playlist",children:"?"})]})]}),w&&r.jsxs("div",{style:{...le,display:"flex",gap:6},children:[r.jsx("input",{value:S,onChange:Q=>R(Q.target.value),placeholder:x("playlistManager.folderName"),style:{...K,flex:1},autoFocus:!0,onKeyDown:Q=>{Q.key==="Enter"&&P(),Q.key==="Escape"&&M(!1)}}),r.jsx("button",{style:{...H,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:P,"aria-label":"Confirm create folder",children:"?"}),r.jsx("button",{style:H,onClick:()=>M(!1),"aria-label":"Cancel create folder",children:"?"})]}),r.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[r.jsxs("div",{style:te(s===null&&i===null,ne==="__root__"),onClick:()=>o(null),onDragOver:Q=>B(Q,null),onDrop:Q=>G(Q,null),onDragLeave:Y,children:[r.jsx("span",{children:"??"}),r.jsx("span",{style:{flex:1},children:x("playlistManager.allPlaylists")}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:t.length})]}),he.map(Q=>re(Q,0)),F.map(Q=>oe(Q,0))]}),n.length>0&&r.jsxs("div",{style:le,children:[r.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:x("playlistManager.tags")}),r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:n.map(Q=>r.jsxs("span",{style:{fontSize:"0.7rem",padding:"2px 8px",borderRadius:12,background:Q.color+"22",color:Q.color,border:`1px solid ${Q.color}44`,cursor:"pointer"},children:[Q.icon&&`${Q.icon} `,Q.name]},Q.id))})]}),r.jsxs("div",{style:le,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",cursor:"pointer",fontSize:"0.7rem",fontWeight:600,opacity:.6},onClick:()=>C(!q),children:[r.jsxs("span",{children:["?? ",x("playlistManager.services")]}),r.jsx("span",{children:"?"})]}),q&&r.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[qt.Spotify,qt.Tidal,qt.YouTube].map(Q=>{const de=hf[Q],me=a.find(xe=>xe.platform===Q);return r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 8px",borderRadius:6,border:"1px solid var(--border-color, #e5e7eb)",fontSize:"0.78rem"},children:[r.jsx("span",{children:de.icon}),r.jsx("span",{style:{flex:1},children:de.label}),me!=null&&me.connected?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{fontSize:"0.65rem",opacity:.6},children:me.username??x("playlistManager.connected")}),r.jsx("button",{style:{...H,color:"var(--nice-danger, #ef4444)"},onClick:()=>y(Q),children:"?"})]}):r.jsx("button",{style:{...H,background:de.color,color:"var(--nice-bg, #fff)",borderRadius:4,padding:"2px 8px"},onClick:()=>f(Q),children:x("playlistManager.connect")})]},Q)})})]})]})},pf=({playlist:e,tags:t,onPlay:n,selectedTrackIds:a,onSelectionChange:s})=>{const{t:i}=Te(),o=d.useCallback(l=>{const c=new Set(a);c.has(l)?c.delete(l):c.add(l),s(c)},[a,s]);return e.tracks.length===0?r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:60,opacity:.3},children:[r.jsx("span",{style:{fontSize:"2rem",marginBottom:8},children:"??"}),r.jsx("span",{style:{fontSize:"0.82rem"},children:i("playlistManager.emptyPlaylist")})]}):r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(160px, 1fr))",gap:10},children:e.tracks.map(l=>{const c=a.has(l.id);return r.jsxs("div",{onClick:()=>o(l.id),onDoubleClick:()=>n(l),style:{border:c?"2px solid var(--accent, #3b82f6)":"1px solid var(--border-color, #e5e7eb)",borderRadius:10,padding:10,cursor:"pointer",background:c?"var(--accent-bg, #eff6ff)":"var(--card-bg, #fff)",transition:"all 0.12s"},children:[r.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:6,background:"linear-gradient(135deg, var(--playlist-track-bg1, #6366f140), var(--playlist-track-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"1.5rem",marginBottom:6},children:"?"}),r.jsx("div",{style:{fontWeight:500,fontSize:"0.78rem",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.title}),r.jsx("div",{style:{fontSize:"0.68rem",opacity:.5,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.artist})]},l.id)})})},xl=d.memo(pf),ai=e=>e.replace(/[^a-z0-9_-]/gi,"-"),si={background:"none",border:"none",cursor:"pointer",fontSize:"0.78rem",padding:"2px 4px",opacity:.4},ff=({playlists:e,folders:t,tags:n,activeFolderId:a,onSelectPlaylist:s,onDeletePlaylist:i,onDuplicatePlaylist:o})=>{const{t:l}=Te(),c=d.useMemo(()=>a?e.filter(u=>u.folderId===a):e,[e,a]);return c.length===0?r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:60,opacity:.4},children:[r.jsx("span",{style:{fontSize:"2.5rem",marginBottom:12},children:"??"}),r.jsx("span",{style:{fontSize:"0.85rem"},children:l("playlistManager.emptyState")})]}):r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))",gap:12},children:c.map(u=>{var p;const h=t.find(f=>f.id===u.folderId);return r.jsxs("div",{onClick:()=>s(u.id),style:{border:"1px solid var(--border-color, #e5e7eb)",borderRadius:12,padding:16,cursor:"pointer",background:"var(--card-bg, #fff)",transition:"box-shadow 0.15s, transform 0.15s"},onMouseEnter:f=>{f.currentTarget.style.boxShadow="0 4px 12px var(--nice-overlay-8, rgba(0, 0, 0, 0.08))",f.currentTarget.style.transform="translateY(-1px)"},onMouseLeave:f=>{f.currentTarget.style.boxShadow="none",f.currentTarget.style.transform="none"},children:[r.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:8,background:"linear-gradient(135deg, var(--playlist-cover-bg1, #6366f140), var(--playlist-cover-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"2.5rem",marginBottom:10},children:u.type===rs.Dynamic?"?":"??"}),r.jsx("div",{style:{fontWeight:600,fontSize:"0.85rem",marginBottom:2},children:u.name}),r.jsxs("div",{style:{fontSize:"0.72rem",opacity:.5},children:[u.trackCount," ",l("playlistManager.tracks"),h&&` � ?? ${h.name}`]}),((p=u.tags)==null?void 0:p.length)>0&&r.jsx("div",{style:{display:"flex",gap:4,marginTop:6,flexWrap:"wrap"},children:u.tags.slice(0,3).map(f=>{const y=n.find(m=>m.id===f);return y?r.jsx("span",{style:{padding:"1px 8px",borderRadius:12,background:`var(--tag-${ai(f)}-bg, ${y.color}18)`,color:`var(--tag-${ai(f)}, ${y.color})`,fontSize:"0.65rem",fontWeight:500},children:y.name},f):null})}),r.jsxs("div",{style:{display:"flex",gap:4,marginTop:8},children:[r.jsx("button",{onClick:f=>{f.stopPropagation(),o(u.id)},style:si,title:l("playlistManager.duplicate"),children:"??"}),r.jsx("button",{onClick:f=>{f.stopPropagation(),i(u.id)},style:si,title:l("playlistManager.delete"),children:"??"})]})]},u.id)})})},vl=d.memo(ff),ii=[{value:kt.Library,label:"Library",icon:"??",hex:"var(--nice-info, #6366f1)",css:"var(--source-library, #6366f1)",cssBg:"var(--source-library-bg, #6366f118)"},{value:kt.Spotify,label:"Spotify",icon:"??",hex:"var(--nice-success, #1db954)",css:"var(--source-spotify, #1db954)",cssBg:"var(--source-spotify-bg, #1db95418)"},{value:kt.Tidal,label:"Tidal",icon:"?",hex:"var(--nice-text, #000000)",css:"var(--source-tidal, #000000)",cssBg:"var(--source-tidal-bg, #00000018)"},{value:kt.YouTube,label:"YouTube",icon:"??",hex:"var(--nice-danger, #ff0000)",css:"var(--source-youtube, #ff0000)",cssBg:"var(--source-youtube-bg, #ff000018)"},{value:kt.MusicBrainz,label:"MusicBrainz",icon:"??",hex:"#ba478f",css:"var(--source-musicbrainz, #ba478f)",cssBg:"var(--source-musicbrainz-bg, #ba478f18)"}],Sl=({onSearch:e,results:t,isSearching:n,onAddToPlaylist:a,onPlayPreview:s})=>{const{t:i}=Te(),[o,l]=d.useState(""),[c,u]=d.useState(new Set([kt.Library,kt.Spotify,kt.Tidal,kt.YouTube])),[h,p]=d.useState(new Set),[f,y]=d.useState(!1),m=d.useRef(null),g=d.useCallback(R=>{u(T=>{const j=new Set(T);return j.has(R)?j.delete(R):j.add(R),j})},[]),b=d.useCallback(R=>{l(R),m.current&&clearTimeout(m.current),R.trim().length>=2&&(m.current=setTimeout(()=>{e(R.trim(),Array.from(c))},350))},[c,e]),x=d.useCallback(R=>{R.preventDefault(),o.trim().length>=2&&e(o.trim(),Array.from(c))},[o,c,e]),k=d.useCallback(R=>{p(T=>{const j=new Set(T);return j.has(R)?j.delete(R):j.add(R),j})},[]),v=d.useCallback(()=>{h.size===t.length?p(new Set):p(new Set(t.map(R=>R.id)))},[h,t]),w=d.useCallback(()=>{const R=t.filter(T=>h.has(T.id));R.length>0&&(a(R),p(new Set))},[t,h,a]),M=R=>{if(!R)return"--:--";const T=Math.floor(R/60),j=R%60;return`${T}:${j.toString().padStart(2,"0")}`},S=R=>{const T=ii.find(j=>j.value===R);return T?T.icon:"?"};return r.jsxs("div",{style:{border:"1px solid var(--border-color, #e5e7eb)",borderRadius:10,background:"var(--card-bg, #fff)",overflow:"hidden"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 12px",gap:8,cursor:"pointer",background:"var(--surface-bg, #f9fafb)"},onClick:()=>y(!f),children:[r.jsx("span",{style:{fontSize:"1rem"},children:"??"}),r.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:i("playlistManager.search")}),r.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",opacity:.5},children:"?"})]}),f&&r.jsxs("div",{style:{padding:"0 12px 12px"},children:[r.jsx("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap"},children:ii.map(R=>{const T=c.has(R.value);return r.jsxs("button",{onClick:()=>g(R.value),style:{padding:"4px 10px",borderRadius:20,border:T?`2px solid ${R.css}`:"1px solid var(--border-color, #d1d5db)",background:T?R.cssBg:"transparent",color:T?R.css:"var(--text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:T?600:400,transition:"all 0.15s"},children:[R.icon," ",R.label]},R.value)})}),r.jsxs("form",{onSubmit:x,style:{display:"flex",gap:6,marginBottom:8},children:[r.jsx("input",{type:"text",value:o,onChange:R=>b(R.target.value),placeholder:i("playlistManager.searchPlaceholder"),style:{flex:1,padding:"6px 12px",borderRadius:8,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)",fontSize:"0.82rem"}}),r.jsx("button",{type:"submit",disabled:o.trim().length<2||n,style:{padding:"6px 14px",borderRadius:8,border:"none",background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.82rem",cursor:"pointer",opacity:o.trim().length<2?.5:1},children:n?"?":"??"})]}),t.length>0&&r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",gap:6,marginBottom:4,alignItems:"center"},children:[r.jsxs("label",{style:{fontSize:"0.72rem",display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:h.size===t.length&&t.length>0,onChange:v}),i("playlistManager.selectAll")]}),r.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[t.length," ",i("playlistManager.results")]}),r.jsx("div",{style:{flex:1}}),h.size>0&&r.jsxs("button",{onClick:w,style:{padding:"3px 10px",borderRadius:6,border:"none",background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.72rem",cursor:"pointer"},children:["? ",i("playlistManager.addSelected")," (",h.size,")"]})]}),r.jsx("div",{style:{maxHeight:300,overflowY:"auto",borderRadius:6,border:"1px solid var(--border-color, #e5e7eb)"},children:t.map(R=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:"1px solid var(--border-color, #f3f4f6)",background:h.has(R.id)?"var(--accent-bg, #eff6ff)":"transparent",cursor:"pointer",fontSize:"0.78rem"},onClick:()=>k(R.id),children:[r.jsx("input",{type:"checkbox",checked:h.has(R.id),readOnly:!0}),r.jsx("span",{children:S(R.source)}),R.imageUrl&&r.jsx("img",{src:R.imageUrl,alt:R.title||i("common.coverArt","Cover art"),style:{width:28,height:28,borderRadius:4,objectFit:"cover"}}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsx("div",{style:{fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:R.title}),r.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[R.artist,R.album?` � ${R.album}`:""]})]}),r.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:M(R.duration)}),s&&r.jsx("button",{onClick:T=>{T.stopPropagation(),s(R)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem"},title:i("playlistManager.preview"),children:"?"})]},R.id))})]}),n&&r.jsxs("div",{style:{textAlign:"center",padding:20,opacity:.5,fontSize:"0.82rem"},children:["? ",i("playlistManager.searching"),"..."]}),!n&&o.trim().length>=2&&t.length===0&&r.jsx("div",{style:{textAlign:"center",padding:20,opacity:.4,fontSize:"0.82rem"},children:i("playlistManager.noResults")})]})]})},mf=[{value:1,label:"Spotify",icon:r.jsx(se.NtdMusic,{size:16}),color:"var(--source-spotify, #1db954)"},{value:2,label:"Tidal",icon:r.jsx(se.NtdMusic,{size:16}),color:"var(--source-tidal, #000000)"},{value:3,label:"Apple Music",icon:r.jsx(se.NtdMusic,{size:16}),color:"var(--source-apple, #fa243c)"},{value:4,label:"YouTube",icon:r.jsx(se.NtdMusic,{size:16}),color:"var(--source-youtube, #ff0000)"},{value:99,label:"Manual Paste",icon:r.jsx(se.NtdMusic,{size:16}),color:"var(--source-manual, #6366f1)"}],gf={display:"flex",flexDirection:"column",gap:16,padding:24,borderRadius:12,background:"var(--panel-bg, #ffffff)",border:"1px solid var(--border, #e2e8f0)",maxWidth:640,minHeight:400},yf={display:"flex",justifyContent:"space-between",alignItems:"center"},bf={display:"flex",gap:4,marginBottom:8},En={padding:"8px 20px",borderRadius:6,border:"none",background:"var(--accent, #6366f1)",color:"var(--nice-bg, #fff)",cursor:"pointer",fontWeight:600},rr={...En,background:"transparent",color:"var(--text, #334155)",border:"1px solid var(--border, #e2e8f0)"},oi={padding:12,borderRadius:8,border:"1px solid var(--border, #e2e8f0)",cursor:"pointer",transition:"border-color 0.15s"},kl=["connect","browse","tracks","options","importing","done"];function xf(e){return kl.indexOf(e)}function vf(e){if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const wl=({connections:e=[],onConnect:t=()=>{},onDisconnect:n=()=>{},onFetchPlaylists:a=async()=>[],onFetchTracks:s=async()=>[],onImport:i=async()=>({playlistName:"",imported:0,skipped:0,failed:0,failedTracks:[]}),onClose:o=()=>{},targetFolders:l,sources:c})=>{const{t:u}=Te(),[h,p]=d.useState("connect"),[f,y]=d.useState(null),[m,g]=d.useState([]),[b,x]=d.useState(null),[k,v]=d.useState([]),[w,M]=d.useState(new Set),[S,R]=d.useState(!1),[T,j]=d.useState(null),[O,$]=d.useState(null),[E,D]=d.useState(null),[L,W]=d.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[Z,A]=d.useState(""),_=d.useMemo(()=>new Set(e.filter(H=>H.connected).map(H=>H.platform)),[e]),U=d.useCallback(H=>e.find(K=>K.platform===H),[e]),ne=d.useCallback(H=>{if(y(H),H===99){p("tracks"),A(""),v([]),R(!1);return}_.has(H)?(p("browse"),R(!0),D(null),a(H).then(K=>{g(K),R(!1)}).catch(K=>{D(String(K)),R(!1)})):t(H)},[_,t,a]),V=d.useCallback(H=>{x(H),p("tracks"),R(!0),D(null),s(H).then(K=>{v(K),M(new Set(K.map(oe=>oe.externalId))),R(!1)}).catch(K=>{D(String(K)),R(!1)})},[s]),q=d.useCallback(H=>{M(K=>{const oe=new Set(K);return oe.has(H)?oe.delete(H):oe.add(H),oe})},[]),C=d.useCallback(()=>{M(H=>H.size===k.length?new Set:new Set(k.map(K=>K.externalId)))},[k]),F=d.useCallback(async()=>{if(!b)return;const H=k.filter(K=>w.has(K.externalId));if(H.length!==0){p("importing"),j({total:H.length,imported:0,skipped:0,failed:0}),D(null);try{const K=await i(b,H,L),oe=K&&typeof K=="object"&&"imported"in K?K:{playlistName:b.name,imported:H.length,skipped:0,failed:0,failedTracks:[]};$(oe),p("done")}catch(K){D(String(K)),p("options")}}},[b,k,w,L,i]),I=h!=="connect"&&h!=="importing"&&h!=="done",P=d.useCallback(()=>{switch(h){case"browse":p("connect");break;case"tracks":p("browse");break;case"options":p("tracks");break}},[h]),N=()=>r.jsx("div",{style:bf,children:kl.map((H,K)=>r.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:K<=xf(h)?"var(--accent, #6366f1)":"var(--border, #e2e8f0)",transition:"background 0.2s"}},H))}),z=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[r.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:u("importWizard.selectPlatform","Select a music platform to import from")}),mf.map(H=>{const K=U(H.value),oe=_.has(H.value);return r.jsxs("div",{style:{...oi,display:"flex",alignItems:"center",gap:12,borderColor:oe?H.color:void 0},onClick:()=>ne(H.value),role:"button",tabIndex:0,onKeyDown:re=>re.key==="Enter"&&ne(H.value),children:[r.jsx("span",{style:{color:H.color,display:"inline-flex"},"aria-hidden":"true",children:H.icon}),r.jsxs("div",{style:{flex:1},children:[r.jsx("strong",{children:H.label}),(K==null?void 0:K.username)&&r.jsx("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:K.username})]}),oe?r.jsxs("span",{style:{color:H.color,fontSize:12,fontWeight:600},children:[u("importWizard.connected","Connected")," ",r.jsx(se.NtdCheck,{size:12})]}):r.jsx("span",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:u("importWizard.clickToConnect","Click to connect")})]},H.value)})]}),B=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[r.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:u("importWizard.selectPlaylist","Select a playlist to import")}),S?r.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--text-dim, #64748b)"},children:u("importWizard.loading","Loading playlists…")}):r.jsxs("div",{style:{display:"grid",gap:8,maxHeight:320,overflowY:"auto"},children:[m.map(H=>r.jsxs("div",{style:{...oi,display:"flex",alignItems:"center",gap:12},onClick:()=>V(H),role:"button",tabIndex:0,onKeyDown:K=>K.key==="Enter"&&V(H),children:[H.coverUrl&&r.jsx("img",{src:H.coverUrl,alt:"",style:{width:48,height:48,borderRadius:6,objectFit:"cover"}}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsx("div",{style:{fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:H.name}),H.description&&r.jsx("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:H.description})]}),r.jsxs("span",{style:{fontSize:12,color:"var(--text-dim, #64748b)",whiteSpace:"nowrap"},children:[H.trackCount," ",u("importWizard.tracks","tracks")]})]},H.id)),m.length===0&&r.jsx("div",{style:{textAlign:"center",padding:24,color:"var(--text-dim, #64748b)"},children:u("importWizard.noPlaylists","No playlists found")})]})]}),G=d.useCallback(H=>{const oe=H.split(`
68
+ `).map(re=>re.trim()).filter(Boolean).map((re,he)=>{const Q=re.match(/^(.+?)\s*[-–—]\s*(.+)$/);return Q?{externalId:`paste-${he}`,title:Q[2].trim(),artist:Q[1].trim(),album:void 0,duration:0}:{externalId:`paste-${he}`,title:re,artist:"",album:void 0,duration:0}});v(oe),M(new Set(oe.map(re=>re.externalId)))},[]),Y=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[f===99&&k.length===0&&r.jsxs("div",{style:{display:"grid",gap:8},children:[r.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:u("importWizard.pasteInstructions",'Paste your track list below (one track per line). Use "Artist - Title" format for best results.')}),r.jsx("textarea",{value:Z,onChange:H=>A(H.target.value),placeholder:`Daft Punk - Get Lucky
52
69
  The Weeknd - Blinding Lights
53
- Tame Impala - Let It Happen`,rows:10,style:{width:"100%",padding:12,borderRadius:6,border:"1px solid var(--border, #e2e8f0)",fontFamily:"monospace",fontSize:13,resize:"vertical"}}),s.jsx("button",{style:{...wn,opacity:Y.trim().length===0?.5:1},disabled:Y.trim().length===0,onClick:()=>q(Y),type:"button",children:d("importWizard.parseTracks","Parse Tracks")})]}),(m!==99||S.length>0)&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("p",{style:{margin:0,fontWeight:600},children:[x==null?void 0:x.name," — ",k.size,"/",S.length," ",d("importWizard.selected","selected")]}),s.jsx("button",{style:zn,onClick:w,type:"button",children:k.size===S.length?d("importWizard.deselectAll","Deselect All"):d("importWizard.selectAll","Select All")})]}),N?s.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--text-dim, #64748b)"},children:d("importWizard.loadingTracks","Loading tracks…")}):s.jsx("div",{style:{maxHeight:320,overflowY:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid var(--border, #e2e8f0)",textAlign:"left"},children:[s.jsx("th",{style:{padding:"4px 8px",width:32}}),s.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.title","Title")}),s.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.artist","Artist")}),s.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.album","Album")}),s.jsx("th",{style:{padding:"4px 8px",textAlign:"right"},children:d("importWizard.duration","Duration")})]})}),s.jsx("tbody",{children:S.map(D=>{const K=k.has(D.externalId);return s.jsxs("tr",{style:{borderBottom:"1px solid var(--border, #e2e8f0)",opacity:K?1:.5,cursor:"pointer"},onClick:()=>B(D.externalId),children:[s.jsx("td",{style:{padding:"6px 8px"},children:s.jsx("input",{type:"checkbox",checked:K,readOnly:!0})}),s.jsx("td",{style:{padding:"6px 8px",fontWeight:500},children:D.title}),s.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:D.artist}),s.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:D.album??"—"}),s.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--text-dim, #64748b)"},children:Pf(D.duration)})]},D.externalId)})})]})}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsxs("button",{style:{...wn,opacity:k.size===0?.5:1},disabled:k.size===0,onClick:()=>h("options"),type:"button",children:[d("importWizard.next","Next")," →"]})})]})]}),J=()=>s.jsxs("div",{style:{display:"grid",gap:16},children:[s.jsx("p",{style:{margin:0,fontWeight:600},children:d("importWizard.importOptions","Import options")}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:L.mergeTags,onChange:D=>U(K=>({...K,mergeTags:D.target.checked}))}),d("importWizard.mergeTags","Merge tags from source playlist")]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:L.mergeFolders,onChange:D=>U(K=>({...K,mergeFolders:D.target.checked}))}),d("importWizard.mergeFolders","Merge into existing folder structure")]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:L.overwriteExisting,onChange:D=>U(K=>({...K,overwriteExisting:D.target.checked}))}),d("importWizard.overwrite","Overwrite existing tracks (match by ISRC)")]}),l&&l.length>0&&s.jsxs("div",{style:{display:"grid",gap:4},children:[s.jsx("label",{style:{fontSize:13,fontWeight:500},children:d("importWizard.targetFolder","Target folder")}),s.jsxs("select",{style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border, #e2e8f0)"},value:L.targetFolderId??"",onChange:D=>U(K=>({...K,targetFolderId:D.target.value||void 0})),children:[s.jsx("option",{value:"",children:d("importWizard.root","— Root —")}),l.map(D=>s.jsx("option",{value:D.id,children:D.name},D.id))]})]}),s.jsx("div",{style:{marginTop:8,padding:12,borderRadius:8,background:"var(--info-bg, #eff6ff)",fontSize:13},children:d("importWizard.summary",`Ready to import ${k.size} tracks from "${(x==null?void 0:x.name)??""}"`)}),s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[s.jsx("button",{style:zn,onClick:T,type:"button",children:d("importWizard.back","← Back")}),s.jsx("button",{style:wn,onClick:$,type:"button",children:d("importWizard.startImport","Start Import")})]})]}),ae=()=>{const D=_?Math.round(_.imported/_.total*100):0;return s.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[s.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:d("importWizard.importing","Importing…")}),s.jsx("div",{style:{height:8,borderRadius:4,background:"var(--border, #e2e8f0)",overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${D}%`,background:"var(--accent, #6366f1)",borderRadius:4,transition:"width 0.3s"}})}),_&&s.jsxs("div",{style:{fontSize:13,color:"var(--text-dim, #64748b)"},children:[_.imported," / ",_.total," ",d("importWizard.tracks","tracks"),_.currentTrack&&s.jsxs("div",{style:{marginTop:4},children:["🎵 ",_.currentTrack]})]})]})},re=()=>s.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[s.jsx("span",{style:{fontSize:48},children:"✅"}),s.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:d("importWizard.complete","Import Complete")}),V&&s.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[s.jsxs("div",{children:[s.jsx("strong",{children:V.imported})," ",d("importWizard.imported","imported")]}),V.skipped>0&&s.jsxs("div",{style:{color:"var(--warning, #f59e0b)"},children:[V.skipped," ",d("importWizard.skipped","skipped (duplicates)")]}),V.failed>0&&s.jsxs("div",{style:{color:"var(--error, #ef4444)"},children:[V.failed," ",d("importWizard.failed","failed")]}),V.failedTracks.length>0&&s.jsxs("details",{style:{textAlign:"left",marginTop:8,fontSize:12,color:"var(--text-dim, #64748b)"},children:[s.jsx("summary",{style:{cursor:"pointer"},children:d("importWizard.showFailed","Show failed tracks")}),s.jsx("ul",{style:{marginTop:4,paddingLeft:20},children:V.failedTracks.map((D,K)=>s.jsx("li",{children:D},K))})]})]}),s.jsx("button",{style:wn,onClick:i,type:"button",children:d("importWizard.close","Done")})]}),ee={connect:d("importWizard.stepConnect","Connect"),browse:d("importWizard.stepBrowse","Browse"),tracks:d("importWizard.stepTracks","Select Tracks"),options:d("importWizard.stepOptions","Options"),importing:d("importWizard.stepImporting","Importing"),done:d("importWizard.stepDone","Done")};return s.jsxs("div",{style:jf,children:[C(),s.jsxs("div",{style:Rf,children:[s.jsxs("h2",{style:{margin:0,fontSize:18},children:[d("importWizard.title","Import Playlist")," — ",ee[f]]}),R&&s.jsxs("button",{style:zn,onClick:T,type:"button",children:["← ",d("importWizard.back","Back")]}),f==="connect"&&s.jsx("button",{style:zn,onClick:i,type:"button",children:"✕"})]}),A&&s.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--error-bg, #fef2f2)",color:"var(--error, #ef4444)",fontSize:13},children:A}),f==="connect"&&E(),f==="browse"&&F(),f==="tracks"&&Q(),f==="options"&&J(),f==="importing"&&ae(),f==="done"&&re()]})},Ef=[{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}],Af="concert-harp",Sa=Object.fromEntries(Ef.map(e=>[e.id,e])),Nf="nice2dev-note-sound-set";function hi(){try{const e=localStorage.getItem(Nf);if(e&&Sa[e])return e}catch{}return Af}function ps(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function pi(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 Tr(e,t){const n=pi(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function If(e){const t=pi(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function mi(){const e=ps("--text-primary")||"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",t=ps("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",a=If(e)<.45;return{base:Tr(e,.92),staffLine:Tr(e,.22),outline:a?"var(--nice-overlay-light-75, rgba(255, 255, 255, 0.75))":"var(--nice-overlay-55, rgba(0, 0, 0, 0.55))",accents:[Tr(t,.95)],isDark:n,notesDark:a}}const mr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),yi=46,ut=5,Zn=4,Lf=(yi-(ut-1)*Zn)/2,Df=6,Ff=18,Of=110,_f=50,yr=mr?_f:Of,zf=mr?4:2,Bf=mr?2:4,ms=mr?1:0,Gf=180,ys=2.8,gs=40,Wf=14,bs=1.2,Uf=16,$r=[64,67,71,74,77],qt=64,Sn=77;function Vf(e){const t=Math.max(0,Math.min(ut-1,e)),n=Math.floor(t),r=Math.min(n+1,ut-1),a=t-n;return Math.round($r[n]+($r[r]-$r[n])*a)}function qf(e){return(Math.max(qt-1*(Sn-qt)/(ut-1),Math.min(Sn+1*(Sn-qt)/(ut-1),e))-qt)/(Sn-qt)*(ut-1)}const vs=2.5,xs=.72,Hf=.55,Cn=new Map;let Xn=null;async function Kf(e){const t=e??hi(),n=Sa[t];if(!n||!n.dir){Cn.clear(),Xn=t;return}if(Xn===t&&Cn.size>0)return;Cn.clear(),Xn=t;const r=an(),a=[];for(let o=qt;o<=Sn;o++)a.push(fetch(`/assets/soundfonts/notes/${n.dir}/note-${o}.mp3`).then(i=>i.arrayBuffer()).then(i=>r.decodeAudioData(i)).then(i=>{Cn.set(o,i)}).catch(()=>{}));await Promise.all(a)}function ws(e){const t=Cn.get(e);if(!t)return;const n=an(),r=n.createBufferSource();r.buffer=t;const a=n.createGain();a.gain.value=.7,r.connect(a).connect(n.destination),r.start()}const Ss=["𝅘𝅥","𝅘𝅥𝅮","𝅘𝅥𝅯","𝅘𝅥𝅰","𝅘𝅥𝅱","♪","♫","♬"];function Yf(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 Zf(e){const t=Yf(42),n=[];for(let r=0;r<e;r++){const o=t()<.15?0:-1;n.push({x:t(),lineIdx:t()*(ut+1)-.5,char:Ss[Math.floor(t()*Ss.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:o})}return n.sort((r,a)=>r.x-a.x),n}const tt=Zf(yr),dn=new Float32Array(yr),Bn=new Float32Array(yr),kn=new Float32Array(yr);let Ur=!1;const Xf=(ut-1)/2;function Qf(){if(!Ur){Ur=!0;for(let e=0;e<tt.length;e++)kn[e]=tt[e].lineIdx}}let Vr=[],Cs="";function Jf(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function eh(e){const t=Jf(e);t===Cs&&Vr.length===tt.length||(Cs=t,Vr=tt.map(n=>{const r=Math.ceil(n.size*1.6),a=r*2,o=document.createElement("canvas");o.width=a,o.height=a;const i=o.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:o,ox:r,oy:r}}))}function gi({pitchMidiRef:e}={}){const t=u.useRef(null),n=u.useRef(0),r=u.useRef(0),a=u.useRef(0),o=u.useRef(null),i=u.useRef(0),l=u.useRef(0),c=u.useRef(null),d=u.useRef(null),f=u.useRef(!1),h=u.useCallback((v,x,b)=>{const S=Lf+v*Zn,g=x/b*Math.PI*2;return S+Math.sin(g)*Df},[]),m=u.useCallback(v=>{const x=t.current;if(!x)return;if(l.current++,ms>0&&l.current%(ms+1)!==0){a.current=v,n.current=requestAnimationFrame(m);return}const b=x.getContext("2d");if(!b)return;const S=Math.min(window.devicePixelRatio||1,Bf),g=x.getBoundingClientRect(),k=g.width,M=g.height;(x.width!==Math.round(k*S)||x.height!==Math.round(M*S))&&(x.width=Math.round(k*S),x.height=Math.round(M*S),b.setTransform(S,0,0,S,0,0));const N=a.current?(v-a.current)/1e3:0;a.current=v,r.current=(r.current+Ff*N)%k,b.clearRect(0,0,k,M),i.current++,(!o.current||i.current%60===0)&&(o.current=mi());const j=o.current;eh(j),b.strokeStyle=j.staffLine,b.lineWidth=.7;for(let z=0;z<ut;z++){b.beginPath();for(let A=0;A<=k;A+=zf){const I=h(z,A,k);A===0?b.moveTo(A,I):b.lineTo(A,I)}b.stroke()}const _=r.current,P=(e==null?void 0:e.current)??null;if(P!==null){Qf();const z=qf(P),A=vs*N;for(let I=0;I<tt.length;I++){const U=(tt[I].lineIdx-Xf)*Hf,O=z*xs+(z+U)*(1-xs)-kn[I];kn[I]+=O>0?Math.min(A,O):Math.max(-A,O)}}else if(Ur){const z=vs*.4*N;for(let A=0;A<tt.length;A++){const L=tt[A].lineIdx-kn[A];kn[A]+=L>0?Math.min(z,L):Math.max(-z,L)}}const V=c.current;V&&(V.timer-=N,V.timer<=0&&(c.current=null));for(let z=0;z<tt.length;z++){const A=tt[z];if(Bn[z]>0){Bn[z]-=N;const U=Math.max(0,Bn[z]/ys);dn[z]+=Gf*U*N,dn[z]>k&&(dn[z]-=k)}const I=Vr[z];if(!I)continue;const L=A.lineIdx;for(let U=0;U<2;U++){let O=((A.x*k-_-dn[z]+U*k)%k+k)%k;const Z=h(Math.max(0,Math.min(ut-1,Math.round(L))),O,k),H=(L-Math.round(L))*Zn;let te=Z+H;if(V&&V.timer>0){const G=O-V.x,B=te-V.y,w=Math.sqrt(G*G+B*B);if(w<gs&&w>.1){const $=V.timer/bs,R=Wf*(1-w/gs)*$;O+=G/w*R,te+=B/w*R}}b.drawImage(I.canvas,O-I.ox,te-I.oy)}}n.current=requestAnimationFrame(m)},[h]),y=u.useCallback(v=>{const x=t.current;if(!x)return;const b=x.getBoundingClientRect(),S=v.clientX-b.left,g=v.clientY-b.top,k=b.width,M=r.current;let N=1/0,j=-1;for(let _=0;_<tt.length;_++){const P=tt[_],z=((P.x*k-M-dn[_])%k+k)%k,A=h(Math.max(0,Math.min(ut-1,Math.round(P.lineIdx))),z,k),I=(P.lineIdx-Math.round(P.lineIdx))*Zn,L=A+I,U=z-S,Y=L-g,O=U*U+Y*Y;O<N&&(N=O,j=_)}if(j>=0&&Math.sqrt(N)<Uf){Bn[j]=ys;const _=tt[j],P=Vf(_.lineIdx);try{It();const V=hi(),z=Sa[V];z!=null&&z.dir&&(Xn!==V||!f.current?(f.current=!0,Kf(V).then(()=>ws(P))):ws(P))}catch{}}c.current={x:S,y:g,timer:bs}},[h]),p=u.useCallback(v=>{const x=t.current;if(!x)return;const b=x.getBoundingClientRect(),S=v.clientX-b.left,g=v.clientY-b.top;d.current={x:S,y:g},c.current&&c.current.timer>0&&(c.current.x=S,c.current.y=g)},[]);return u.useEffect(()=>(n.current=requestAnimationFrame(m),()=>cancelAnimationFrame(n.current)),[m]),s.jsx("canvas",{ref:t,"aria-hidden":"true",role:"img","aria-label":"Note river animation canvas",onClick:y,onMouseMove:p,style:{display:"block",width:"100%",height:yi,marginBottom:5,cursor:"pointer",background:"transparent"}})}const th=14,nh=.9,rh=320,ah=160,sh=6,ks=8,oh=14,Ms=["♪","♫","♬","𝅘𝅥𝅮","𝅘𝅥𝅯"];function bi(){const e=u.useRef(null),t=u.useRef([]),n=u.useRef(0),r=u.useRef(0),a=u.useRef([]),o=u.useRef(null),i=u.useRef(0),l=u.useCallback((d,f)=>{for(let h=0;h<th;h++){const m=Math.random()*Math.PI*2,y=ah*(.4+Math.random()*.6),p=nh*(.6+Math.random()*.4),v=Math.random()<.15?0:-1;t.current.push({x:d,y:f,vx:Math.cos(m)*y,vy:Math.sin(m)*y-60,rot:Math.random()*Math.PI*2,vr:(Math.random()-.5)*sh*2,size:ks+Math.random()*(oh-ks),char:Ms[Math.floor(Math.random()*Ms.length)],life:p,maxLife:p,colorIdx:v})}},[]),c=u.useCallback(d=>{const f=e.current;if(!f){n.current=requestAnimationFrame(c);return}const h=f.getContext("2d");if(!h){n.current=requestAnimationFrame(c);return}const m=window.devicePixelRatio||1,y=window.innerWidth,p=window.innerHeight;(f.width!==Math.round(y*m)||f.height!==Math.round(p*m))&&(f.width=Math.round(y*m),f.height=Math.round(p*m),f.style.width=`${y}px`,f.style.height=`${p}px`,h.setTransform(m,0,0,m,0,0));const v=r.current?Math.min((d-r.current)/1e3,.05):0;r.current=d,h.clearRect(0,0,y,p),i.current++,(!o.current||i.current%60===0)&&(o.current=mi());const x=o.current;if(navigator.getGamepads){const S=navigator.getGamepads();for(let g=0;g<S.length;g++){const k=S[g];if(k)for(let M=0;M<k.buttons.length;M++){const N=g*100+M,j=k.buttons[M].pressed;j&&!a.current[N]&&l(y/2,p/2),a.current[N]=j}}}const b=[];h.textAlign="center",h.textBaseline="middle";for(const S of t.current){if(S.life-=v,S.life<=0)continue;S.vy+=rh*v,S.x+=S.vx*v,S.y+=S.vy*v,S.rot+=S.vr*v;const g=Math.max(0,S.life/S.maxLife),k=.5+.5*g;h.save(),h.globalAlpha=g,h.translate(S.x,S.y),h.rotate(S.rot),h.font=`${S.size*k}px serif`,h.lineWidth=1.4,h.strokeStyle=x.notesDark?`rgba(255,255,255,${g*.8})`:`rgba(0,0,0,${g*.55})`,h.strokeText(S.char,0,0);const M=S.colorIdx<0?x.base:x.accents[S.colorIdx%x.accents.length];h.fillStyle=M.replace(/[\d.]+\)$/,`${g})`),h.fillText(S.char,0,0),h.restore(),b.push(S)}t.current=b,n.current=requestAnimationFrame(c)},[l]);return u.useEffect(()=>{const d=h=>{l(h.clientX,h.clientY)},f=h=>{if(h.key!=="Enter")return;const m=document.activeElement;if(m){const y=m.getBoundingClientRect();l(y.left+y.width/2,y.top+y.height/2)}else l(window.innerWidth/2,window.innerHeight/2)};return window.addEventListener("click",d,!0),window.addEventListener("keydown",f,!0),n.current=requestAnimationFrame(c),()=>{window.removeEventListener("click",d,!0),window.removeEventListener("keydown",f,!0),cancelAnimationFrame(n.current)}},[c,l]),s.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 vi{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 o=this.midiToFreq(t),i=this.audioContext.createOscillator(),l=this.audioContext.createGain();i.type=a,i.frequency.value=o;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,o="sine"){const i=this.midiToFreq(t),l=this.audioContext.createOscillator(),c=this.audioContext.createGain();l.type=o,l.frequency.value=i;const d=a/127*.8;l.connect(c),c.connect(this.masterGain);const f=n;return c.gain.setValueAtTime(0,f),c.gain.linearRampToValueAtTime(d,f+.01),c.gain.exponentialRampToValueAtTime(d*.7,f+.1),c.gain.setValueAtTime(d*.7,f+r-.05),c.gain.exponentialRampToValueAtTime(.001,f+r),l.start(f),l.stop(f+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 js=nt.scoped("AudioPlaybackEngine");class ih{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){js.error("Failed to initialize AudioContext:",t)}}createEffectNode(t){if(!this.audioContext||t.bypass)return null;try{switch(t.type){case"eq3":{const n=this.audioContext.createBiquadFilter(),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 o=this.audioContext.createGain();return o.gain.value=1-(t.params.mix||.3),n.connect(r),r.connect(n),n.connect(a),{input:n,output:a,dry:o,connect:function(i){a.connect(i),o.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 o=this.audioContext.createGain();o.gain.value=t.params.mix||.3;const i=this.audioContext.createGain();return i.gain.value=1-(t.params.mix||.3),n.connect(o),{input:n,output:o,dry:i,connect:function(l){o.connect(l),i.connect(l)}}}case"distortion":{const n=this.audioContext.createWaveShaper(),r=t.params.amount||20,a=44100,o=new Float32Array(a),i=Math.PI/180;for(let d=0;d<a;d++){const f=d*2/a-1;o[d]=(3+r)*f*20*i/(Math.PI+r*Math.abs(f))}n.curve=o,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 js.error("Failed to create effect node:",t.type,n),null}}addClip(t){this.clips.set(t.id,t),this.updateDuration()}removeClip(t){this.clips.delete(t),this.stopClip(t),this.updateDuration()}updateClip(t,n){const 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 o=new vi(this.audioContext,this.masterGain);o.setVolume(a),this.synths.set(t,o)}}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 o=this.audioContext.createStereoPanner();o.pan.value=t.pan,r.connect(a);let i=a;if(t.effectChain&&t.effectChain.length>0)for(const f of t.effectChain){const h=this.createEffectNode(f);if(h)if("input"in h&&"output"in h){const m=h;i.connect(m.input),i=m.output,"dry"in h&&a.connect(m.dry)}else i.connect(h),i=h}i.connect(o),o.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 o=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-o,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 o=r[0];for(let i=1;i<r.length;++i){const l=r[i],c=o.time,d=l.time,f=o.value,h=l.value,m=o.handleType||"linear",y=Math.max(2,Math.ceil((d-c)*20));for(let p=0;p<=y;++p){const v=p/y;let x=f;if(m==="linear")x=f+(h-f)*v;else if(m==="step")x=v<1?f:h;else if(m==="exp"){const k=Math.max(f/127,.001),M=Math.max(h/127,.001);x=k*Math.pow(M/k,v)*127}const b=c+(d-c)*v,S=this.audioContext.currentTime+(b-this.currentTime);S>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(l.cc,x,S)}o=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 lh=[{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 gr(e={}){const{channelFilter:t,sysex:n=!1,onEvent:r,inputNameIncludes:a,onInputsChanged:o}=e,[i,l]=u.useState(null),[c,d]=u.useState(!1),[f,h]=u.useState([]),m=u.useRef(null),y=u.useCallback((p,v)=>{const x=p.data??new Uint8Array(0),b=x[0]??0,S=x[1]??0,g=x[2]??0,k=p.timeStamp,M=b&240,N=b&15,j=v.id,_=v.name??"MIDI Input",P=t===void 0||t===N;if((M===144||M===128)&&P){const V=M===144&&g>0;return{type:V?"noteon":"noteoff",note:S,velocity:V?g:0,channel:N,ts:k,deviceId:j,deviceName:_}}return M===176&&P?{type:"cc",controller:S,value:g,channel:N,ts:k,deviceId:j,deviceName:_}:M===208&&P?{type:"aftertouch",pressure:S,channel:N,ts:k,deviceId:j,deviceName:_}:M===224&&P?{type:"pitchbend",value:(S|g<<7)-8192,channel:N,ts:k,deviceId:j,deviceName:_}:M===192&&P?{type:"program",program:S,channel:N,ts:k,deviceId:j,deviceName:_}:{type:"unknown",status:b,data1:S,data2:g,channel:N,ts:k,deviceId:j,deviceName:_}},[t]);return u.useEffect(()=>{if(!("requestMIDIAccess"in navigator)){l(!1);return}l(!0);let p=!1;return navigator.requestMIDIAccess({sysex:n}).then(v=>{if(p)return;m.current=v,d(!0);const x=()=>{const b=Array.from(v.inputs.values()),S=a?b.filter(g=>(g.name||"").toUpperCase().includes(a.toUpperCase())):b;h(S),o==null||o(S),b.forEach(g=>g.onmidimessage=null),S.forEach(g=>{g.onmidimessage=k=>r==null?void 0:r(y(k,g))})};x(),v.onstatechange=()=>x()}),()=>{p=!0;const v=m.current;v&&(v.inputs.forEach(x=>x.onmidimessage=null),v.onstatechange=null)}},[a,r,o,y,n]),{supported:i,granted:c,inputs:f}}const Ca="nice2dev.midiLearn";function ch(){try{const e=localStorage.getItem(Ca);return e?JSON.parse(e):{}}catch{return{}}}function Rs(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(Ca,JSON.stringify(t))}function dh(e){const{parameters:t,onParameterChange:n}=e,[r,a]=u.useState(()=>{const g=ch();return t.map(k=>{const M=g[k.id];return{id:k.id,paramName:k.name,type:(M==null?void 0:M.type)??"cc",number:M==null?void 0:M.number,channel:M==null?void 0:M.channel,min:(M==null?void 0:M.min)??k.min??0,max:(M==null?void 0:M.max)??k.max??127,value:0}})}),[o,i]=u.useState({learning:!1,targetId:null}),[l,c]=u.useState(null),d=u.useRef(r);d.current=r;const f=u.useRef(n);f.current=n;const h=u.useRef(o);h.current=o;const m=u.useCallback(g=>{var M;c(g);const k=h.current;if(k.learning&&k.targetId){if(!d.current.find(_=>_.id===k.targetId))return;let j={};switch(g.type){case"cc":j={type:"cc",number:g.controller,channel:g.channel};break;case"noteon":j={type:"note",number:g.note,channel:g.channel};break;case"pitchbend":j={type:"pitchbend",channel:g.channel};break;case"aftertouch":j={type:"aftertouch",channel:g.channel};break;default:return}a(_=>{const P=_.map(V=>V.id===k.targetId?{...V,...j}:V);return Rs(P),P}),i({learning:!1,targetId:null});return}for(const N of d.current){if(N.number===void 0&&N.type!=="pitchbend"&&N.type!=="aftertouch"||N.channel!==void 0&&g.channel!==N.channel)continue;let j=null,_=127;if(N.type==="cc"&&g.type==="cc"&&g.controller===N.number?j=g.value:N.type==="note"&&g.type==="noteon"&&g.note===N.number?j=g.velocity:N.type==="pitchbend"&&g.type==="pitchbend"?(j=g.value+8192,_=16383):N.type==="aftertouch"&&g.type==="aftertouch"&&(j=g.pressure),j!==null){const P=j/_,V=N.min+P*(N.max-N.min);a(z=>z.map(A=>A.id===N.id?{...A,value:P}:A)),(M=f.current)==null||M.call(f,N.id,V,P)}}},[]),{supported:y,granted:p}=gr({onEvent:m}),v=u.useCallback(g=>{i({learning:!0,targetId:g})},[]),x=u.useCallback(()=>{i({learning:!1,targetId:null})},[]),b=u.useCallback(g=>{a(k=>{const M=k.map(N=>N.id===g?{...N,type:"cc",number:void 0,channel:void 0}:N);return Rs(M),M})},[]),S=u.useCallback(()=>{a(g=>{const k=g.map(M=>({...M,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(Ca),k})},[]);return{bindings:r,startLearn:v,cancelLearn:x,removeBinding:b,clearAll:S,learnState:o,midiSupported:y,midiGranted:p,lastEvent:l}}const uh={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function fh(e={}){const{lowerZone:t=uh,onNoteExpression:n,onNoteOn:r,onNoteOff:a}=e,[o,i]=u.useState([]),l=u.useRef(new Map),c=u.useRef(n);c.current=n;const d=u.useRef(r);d.current=r;const f=u.useRef(a);f.current=a;const h=u.useRef(new Set(t.memberChannels));u.useEffect(()=>{h.current=new Set(t.memberChannels)},[t.memberChannels]);const m=u.useCallback(v=>{var b,S,g,k,M;if(!h.current.has(v.channel??-1))return;const x=`${v.channel}`;switch(v.type){case"noteon":{const N={note:v.note,channel:v.channel,velocity:v.velocity,pitchBend:0,pressure:0,slide:0,lastUpdate:v.ts};l.current.set(x,N),i(Array.from(l.current.values())),(b=d.current)==null||b.call(d,N);break}case"noteoff":{l.current.delete(x),i(Array.from(l.current.values())),(S=f.current)==null||S.call(f,v.channel,v.note);break}case"pitchbend":{const N=l.current.get(x);N&&(N.pitchBend=v.value,N.lastUpdate=v.ts,(g=c.current)==null||g.call(c,N),i(Array.from(l.current.values())));break}case"aftertouch":{const N=l.current.get(x);N&&(N.pressure=v.pressure,N.lastUpdate=v.ts,(k=c.current)==null||k.call(c,N),i(Array.from(l.current.values())));break}case"cc":{if(v.controller===74){const N=l.current.get(x);N&&(N.slide=v.value,N.lastUpdate=v.ts,(M=c.current)==null||M.call(c,N),i(Array.from(l.current.values())))}break}}},[]),{supported:y,granted:p}=gr({onEvent:m,sysex:!1});return{activeNotes:o,midiSupported:y,midiGranted:p}}const hh={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 ph(e={},t=hh){const[n,r]=u.useState(()=>{const y=localStorage.getItem("oxygen25.layout");return y?JSON.parse(y):t}),[a,o]=u.useState([]),i=u.useRef({mode:"idle"}),l=u.useCallback(y=>{r(p=>{const v={...p,...y};return localStorage.setItem("oxygen25.layout",JSON.stringify(v)),v})},[]),c=u.useCallback(y=>{var x,b,S,g,k,M,N,j,_;const p=y.deviceName||"MIDI";o(P=>P.includes(p)?P:[...P,p]);const v=i.current;if(v.mode!=="idle"){if(v.mode==="knob"&&y.type==="cc"){const P=v.index;l({knobs:n.knobs.map(V=>V.index===P?{...V,cc:y.controller}:V)}),i.current={mode:"idle"};return}if(v.mode==="fader"&&y.type==="cc"){l({fader:{cc:y.controller,label:"Fader"}}),i.current={mode:"idle"};return}if(v.mode==="pad"&&y.type==="noteon"){const P=n.pads.slice();P[v.padIdx]={...P[v.padIdx],note:y.note},l({pads:P}),i.current={mode:"idle"};return}if(v.mode==="transport"&&y.type==="cc"){const P={...n.transport};P[v.action]=y.controller,l({transport:P}),i.current={mode:"idle"};return}}switch(y.type){case"noteon":{n.pads.findIndex(V=>V.note===y.note)>=0?(x=e.onPad)==null||x.call(e,{note:y.note,velocity:y.velocity,ts:y.ts,device:p}):(b=e.onKey)==null||b.call(e,{note:y.note,velocity:y.velocity,ts:y.ts,device:p});break}case"cc":{if(n.fader&&y.controller===n.fader.cc){(S=e.onFader)==null||S.call(e,{cc:y.controller,value:y.value,ts:y.ts,device:p});break}const P=n.knobs.find(z=>z.cc===y.controller);if(P){(g=e.onKnob)==null||g.call(e,{index:P.index,cc:y.controller,value:y.value,ts:y.ts,device:p});break}const V=Object.keys(n.transport).find(z=>n.transport[z]===y.controller);if(V){(k=e.onTransport)==null||k.call(e,{action:V,value:y.value,ts:y.ts,device:p});break}(M=e.onUnknown)==null||M.call(e,y);break}case"pitchbend":(N=e.onPitchBend)==null||N.call(e,{value:y.value,ts:y.ts,device:p});break;case"aftertouch":(j=e.onAftertouch)==null||j.call(e,{pressure:y.pressure,ts:y.ts,device:p});break;default:(_=e.onUnknown)==null||_.call(e,y)}},[l,e,n]),{supported:d,granted:f,inputs:h}=gr({inputNameIncludes:void 0,onEvent:c,sysex:!1,channelFilter:void 0,onInputsChanged:y=>o(y.map(p=>p.name||"MIDI"))}),m=u.useMemo(()=>({knob:y=>i.current={mode:"knob",index:y},fader:()=>i.current={mode:"fader"},pad:y=>i.current={mode:"pad",padIdx:y},transport:y=>i.current={mode:"transport",action:y},cancel:()=>i.current={mode:"idle"},state:()=>i.current}),[]);return{supported:d,granted:f,inputs:h,layout:n,setLayout:l,learn:m,inputsInfo:a}}const qr={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]},mh=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Hr={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]]},Gt=36,un=38,yt=42,Wt=51,yh=49,Kr={basic:[{step:0,pitch:Gt,vel:110},{step:0,pitch:yt,vel:80},{step:2,pitch:yt,vel:70},{step:4,pitch:un,vel:100},{step:4,pitch:yt,vel:80},{step:6,pitch:yt,vel:70},{step:8,pitch:Gt,vel:100},{step:10,pitch:yt,vel:70},{step:12,pitch:un,vel:100},{step:12,pitch:yt,vel:80},{step:14,pitch:yt,vel:70}],rock:[{step:0,pitch:Gt,vel:120},{step:0,pitch:yh,vel:90},{step:4,pitch:un,vel:110},{step:4,pitch:yt,vel:80},{step:8,pitch:Gt,vel:110},{step:8,pitch:yt,vel:80},{step:10,pitch:Gt,vel:90},{step:12,pitch:un,vel:110},{step:12,pitch:yt,vel:80}],swing:[{step:0,pitch:Wt,vel:90},{step:3,pitch:Wt,vel:70},{step:4,pitch:Wt,vel:80},{step:8,pitch:Wt,vel:90},{step:11,pitch:Wt,vel:70},{step:12,pitch:Wt,vel:80},{step:4,pitch:Gt,vel:80},{step:12,pitch:un,vel:70}]},xi={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function gh(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 wi=1;const Gn=()=>wi++,Si=e=>60/e,bh=e=>Si(e)/4;function Pr(e,t,n,r){const a=t.length,o=Math.floor(n/a),i=(n%a+a)%a;return e+t[i]+(r+o)*12}function Ci(e=xi){wi=1;const t=e.seed>0?gh(e.seed):Math.random,n=qr[e.scale]??qr.pentatonic,r=Hr[e.progression]??Hr.pop,a=Kr[e.drumPattern]??Kr.basic,o=Si(e.tempo),i=bh(e.tempo),l=Math.max(1,e.bars),c=16,d=[],f=[],h=[],m=[];let y=0;for(let p=0;p<l;p++){const v=p*4*o,x=p%r.length,b=r[x];for(const g of b)h.push({id:Gn(),pitch:Pr(e.root,n,g,e.octave-1),start:v,duration:4*o-.01,velocity:70+Math.floor(t()*20)});const S=b[0];for(let g=0;g<4;g++){const k=g===2?S+(t()>.5?2:0):S;f.push({id:Gn(),pitch:Pr(e.root,n,k,e.octave-2),start:v+g*o,duration:o*.9,velocity:80+Math.floor(t()*30)})}for(let g=0;g<c;g++){if(t()>e.density)continue;const k=v+g*i,M=t()>.8?t()>.5?2:-2:t()>.5?1:-1;y=Math.max(-3,Math.min(n.length+3,y+M));const N=1+Math.floor(t()*3);d.push({id:Gn(),pitch:Pr(e.root,n,y,e.octave),start:k,duration:N*i*.95,velocity:85+Math.floor(t()*30)})}for(const g of a)m.push({id:Gn(),pitch:g.pitch,start:v+g.step*i,duration:i*.8,velocity:g.vel+Math.floor(t()*10-5)})}return{melody:d,bass:f,chords:h,drums:m,config:e}}const vh=Object.keys(qr),xh=Object.keys(Hr),wh=Object.keys(Kr),Sh=Ci;function De(e,t,n){return{cc:e,paramId:n,label:`Knob ${t}`,controlType:"knob",min:0,max:127,inverted:!1}}function $n(e,t,n){return{cc:e,paramId:n,label:t,controlType:"fader",min:0,max:127,inverted:!1}}function Ut(e,t,n){return{cc:e,paramId:n,label:t,controlType:"button",min:0,max:127,inverted:!1}}const ki={id:"oxygen25",name:"M-Audio Oxygen 25 (MkIV)",deviceMatch:"OXYGEN",mappings:[De(21,1,"mixer.volume"),De(22,2,"mixer.pan"),De(23,3,"fx.reverb"),De(24,4,"fx.delay"),De(25,5,"fx.chorus"),De(26,6,"fx.filter"),De(27,7,"fx.drive"),De(28,8,"fx.eq"),$n(7,"Master Fader","mixer.master"),Ut(115,"Play","transport.play"),Ut(114,"Stop","transport.stop"),Ut(117,"Record","transport.record"),Ut(112,"Rewind","transport.rewind"),Ut(113,"Forward","transport.forward"),Ut(116,"Loop","transport.loop")]},Mi={id:"mpk-mini",name:"Akai MPK Mini",deviceMatch:"MPK",mappings:[De(1,1,"mixer.volume"),De(2,2,"mixer.pan"),De(3,3,"fx.reverb"),De(4,4,"fx.delay"),De(5,5,"fx.chorus"),De(6,6,"fx.filter"),De(7,7,"fx.drive"),De(8,8,"fx.eq")]},ji={id:"minilab",name:"Arturia MiniLab",deviceMatch:"Arturia MiniLab",mappings:[De(7,1,"mixer.volume"),De(74,2,"mixer.pan"),De(71,3,"fx.reverb"),De(76,4,"fx.delay"),De(77,5,"fx.chorus"),De(93,6,"fx.filter"),De(73,7,"fx.drive"),De(75,8,"fx.eq"),$n(1,"Mod Wheel","mixer.master")]},Ri={id:"launch-control-xl",name:"Novation Launch Control XL",deviceMatch:"Launch Control",mappings:[...Array.from({length:8},(e,t)=>De(13+t,t+1,`mixer.send${t+1}`)),...Array.from({length:8},(e,t)=>$n(77+t,`Fader ${t+1}`,`mixer.track${t+1}`))]},ka={id:"generic",name:"Generic MIDI Controller",deviceMatch:"",mappings:[De(1,1,"mixer.modWheel"),$n(7,"Volume","mixer.volume"),De(10,2,"mixer.pan"),$n(11,"Expression","mixer.expression")]},Ti=[ki,Mi,ji,Ri,ka];class Ch{constructor(t){this.ccMap=new Map,this.onChange=null,this.profile=t??ka,this.rebuildMap()}setProfile(t){this.profile=t,this.rebuildMap()}getProfile(){return this.profile}autoDetect(t){const n=t.toUpperCase(),r=Ti.find(a=>a.deviceMatch&&n.includes(a.deviceMatch.toUpperCase()));return r?(this.setProfile(r),r):null}onMappedChange(t){this.onChange=t}handleCC(t,n){var c;const r=this.ccMap.get(t);if(!r)return null;const o=(r.inverted?127-n:n)/127,i=r.min+o*(r.max-r.min),l={paramId:r.paramId,label:r.label,rawValue:n,scaledValue:i,normalizedValue:o};return(c=this.onChange)==null||c.call(this,l),l}setMapping(t,n,r,a="knob"){const o={cc:t,paramId:n,label:r,controlType:a,min:0,max:127,inverted:!1},i=this.profile.mappings.findIndex(l=>l.cc===t);i>=0?this.profile.mappings[i]=o:this.profile.mappings.push(o),this.ccMap.set(t,o)}removeMapping(t){this.profile.mappings=this.profile.mappings.filter(n=>n.cc!==t),this.ccMap.delete(t)}getMappings(){return[...this.profile.mappings]}getMapping(t){return this.ccMap.get(t)}exportConfig(){return{...this.profile,mappings:this.profile.mappings.map(t=>({...t}))}}importConfig(t){this.profile={...t,mappings:t.mappings.map(n=>({...n}))},this.rebuildMap()}static createCustomProfile(t,n){return{id:`custom-${t.toLowerCase().replace(/\s+/g,"-")}`,name:t,deviceMatch:"",mappings:n.map(r=>({...r,min:0,max:127,inverted:!1}))}}rebuildMap(){this.ccMap.clear();for(const t of this.profile.mappings)this.ccMap.set(t.cc,t)}}function $i(e){return{past:[],present:e,future:[]}}function Pi(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function Ei(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 Ai(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 Ni(e){return e.past.length>0}function Ii(e){return e.future.length>0}function Yr(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>({...n}))}function Li(e,t,n){if(t.length===0)return e;const r=Math.min(...t.map(i=>i.time)),a=n-r,o=t.map(i=>({...i,id:Date.now()+Math.floor(Math.random()*1e4)+i.id,time:i.time+a}));return[...e,...o]}function Di(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 Fi(e,t){return e.filter(n=>n.time<t.start||n.time>t.end)}function kh(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>n.id)}function Oi(e,t,n,r){const a={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:r};return[...e,a]}function _i(e,t=3){if(e.length<=2)return e;const n=[...e].sort((a,o)=>a.time-o.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 zi(e){return JSON.stringify(e,null,2)}function Bi(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 st(e,t){var n;return((n=e.find(r=>r.layerId===t))==null?void 0:n.events)??[]}function gt(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 Mh(e,t){switch(t.type){case"UNDO":return Ei(e);case"REDO":return Ai(e);default:{let n=e.present;switch(t.type){case"ADD_EVENT":{const r=[...st(n,t.layerId),t.event];n=gt(n,t.layerId,r);break}case"UPDATE_EVENT":{const r=st(n,t.layerId).map(a=>a.id===t.id?{...a,value:t.value,time:t.time,handleType:t.handleType??a.handleType}:a);n=gt(n,t.layerId,r);break}case"REMOVE_EVENT":{const r=st(n,t.layerId).filter(a=>a.id!==t.id);n=gt(n,t.layerId,r);break}case"SET_EVENTS":n=gt(n,t.layerId,t.events);break;case"PASTE":{const r=st(n,t.layerId),a=Li(r,t.clipboard,t.targetTime);n=gt(n,t.layerId,a);break}case"CUT":{const r=st(n,t.layerId),{remaining:a}=Di(r,t.range);n=gt(n,t.layerId,a);break}case"DELETE_RANGE":{const r=st(n,t.layerId),a=Fi(r,t.range);n=gt(n,t.layerId,a);break}case"RECORD":{const r=st(n,t.layerId),a=Oi(r,t.cc,t.value,t.time);n=gt(n,t.layerId,a);break}case"THIN":{const r=st(n,t.layerId),a=_i(r,t.keepEveryN);n=gt(n,t.layerId,a);break}case"IMPORT":{const r=Bi(t.json);r.length>0&&(n=gt(n,t.layerId,r));break}}return Pi(e,n)}}}function jh(e=[]){const[t,n]=u.useReducer(Mh,$i(e)),r=u.useRef([]),a=u.useCallback(g=>st(t.present,g),[t.present]),o=u.useCallback((g,k)=>n({type:"ADD_EVENT",layerId:g,event:k}),[]),i=u.useCallback((g,k,M,N,j)=>n({type:"UPDATE_EVENT",layerId:g,id:k,value:M,time:N,handleType:j}),[]),l=u.useCallback((g,k)=>n({type:"REMOVE_EVENT",layerId:g,id:k}),[]),c=u.useCallback((g,k)=>n({type:"SET_EVENTS",layerId:g,events:k}),[]),d=u.useCallback(()=>n({type:"UNDO"}),[]),f=u.useCallback(()=>n({type:"REDO"}),[]),h=u.useCallback((g,k)=>{r.current=Yr(st(t.present,g),k)},[t.present]),m=u.useCallback((g,k)=>{r.current=Yr(st(t.present,g),k),n({type:"CUT",layerId:g,range:k})},[t.present]),y=u.useCallback((g,k)=>{r.current.length>0&&n({type:"PASTE",layerId:g,clipboard:r.current,targetTime:k})},[]),p=u.useCallback((g,k)=>n({type:"DELETE_RANGE",layerId:g,range:k}),[]),v=u.useCallback((g,k,M,N)=>n({type:"RECORD",layerId:g,cc:k,value:M,time:N}),[]),x=u.useCallback((g,k)=>n({type:"THIN",layerId:g,keepEveryN:k}),[]),b=u.useCallback(g=>zi(st(t.present,g)),[t.present]),S=u.useCallback((g,k)=>n({type:"IMPORT",layerId:g,json:k}),[]);return{snapshots:t.present,getEvents:a,addEvent:o,updateEvent:i,removeEvent:l,setEvents:c,undo:d,redo:f,canUndo:Ni(t),canRedo:Ii(t),copy:h,cut:m,paste:y,clipboard:r.current,deleteRange:p,record:v,thin:x,exportLane:b,importLane:S}}function Ma(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function Dt(e="New Pattern",t=16,n=120){return{name:e,length:t,steps:Array.from({length:t},()=>Ma()),bpm:n,swing:0,rootNote:60}}function Gi(e,t){const n=e.steps.map((r,a)=>a===t?{...r,active:!r.active}:r);return{...e,steps:n}}function Wi(e,t,n){const r=e.steps.map((a,o)=>o===t?{...a,note:Math.max(0,Math.min(127,n))}:a);return{...e,steps:r}}function Ui(e,t,n){const r=e.steps.map((a,o)=>o===t?{...a,velocity:Math.max(0,Math.min(127,n))}:a);return{...e,steps:r}}function Vi(e,t,n){const r=e.steps.map((a,o)=>o===t?{...a,gate:Math.max(0,Math.min(1,n))}:a);return{...e,steps:r}}function qi(e,t,n){const r=e.steps.map((a,o)=>o===t?{...a,probability:Math.max(0,Math.min(1,n))}:a);return{...e,steps:r}}function Hi(e,t){const n=e.steps.map((r,a)=>a===t?{...r,slide:!r.slide}:r);return{...e,steps:n}}function Ki(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 Yi(e){return{...e,steps:[...e.steps].reverse()}}function Zi(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 Xi(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 Qi(e){return{...e,steps:e.steps.map(()=>Ma(e.rootNote))}}function ja(e,t=4){return 60/e/t}function Ji(e,t,n=0,r=4){const a=ja(t,r),o=e*a;return e%2===1&&n>0?o+a*n*.5:o}function el(e){return e.active&&Math.random()<e.probability}function Rh(){const e=Dt("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function Th(){const e=Dt("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function $h(){const e=Dt("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 Ph(e=60){const t=Dt("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 Eh(e=36){const t=Dt("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,o)=>{t.steps[o]={...t.steps[o],active:!!r[o],note:e+a,velocity:100,gate:.7}}),{...t,rootNote:e}}function Ah(e){return JSON.stringify(e,null,2)}function Nh(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function Ih(e={}){const{onTrigger:t,onLFOOutput:n,initialPattern:r}=e,[a,o]=u.useState(()=>r??Dt()),[i,l]=u.useState(-1),[c,d]=u.useState(!1),[f,h]=u.useState([]),m=u.useRef(a);m.current=a;const y=u.useRef(f);y.current=f;const p=u.useRef(c);p.current=c;const v=u.useRef(t);v.current=t;const x=u.useRef(n);x.current=n;const b=u.useRef(null),S=u.useRef(0),g=u.useRef(0),k=u.useCallback(()=>{var Q,J;if(!p.current)return;const R=m.current,T=S.current%R.length,C=R.steps[T];if(el(C)){const ae=Ji(S.current,R.bpm,R.swing);(Q=v.current)==null||Q.call(v,C,T,ae)}const E=(Date.now()-g.current)/1e3;for(let ae=0;ae<y.current.length;ae++){const re=y.current[ae];if(re.enabled&&re.targetCC!==void 0){const ee=ea(re,E,R.bpm);(J=x.current)==null||J.call(x,ae,re.targetCC,ee)}}l(T),S.current++;const F=ja(R.bpm)*1e3,q=T%2===0?0:F*R.swing*.5;b.current=setTimeout(k,F+q)},[]),M=u.useCallback(()=>{p.current||(S.current=0,g.current=Date.now(),d(!0),p.current=!0,k())},[k]),N=u.useCallback(()=>{d(!1),p.current=!1,l(-1),b.current&&(clearTimeout(b.current),b.current=null)},[]),j=u.useCallback(()=>{p.current?N():M()},[M,N]);u.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const _=u.useCallback(R=>o(T=>Gi(T,R)),[]),P=u.useCallback((R,T)=>o(C=>Wi(C,R,T)),[]),V=u.useCallback((R,T)=>o(C=>Ui(C,R,T)),[]),z=u.useCallback((R,T)=>o(C=>Vi(C,R,T)),[]),A=u.useCallback((R,T)=>o(C=>qi(C,R,T)),[]),I=u.useCallback(R=>o(T=>Hi(T,R)),[]),L=u.useCallback(R=>o(T=>Ki(T,R)),[]),U=u.useCallback(()=>o(R=>Yi(R)),[]),Y=u.useCallback(R=>o(T=>Zi(T,R)),[]),O=u.useCallback((R,T)=>o(C=>Xi(C,R,T)),[]),Z=u.useCallback(()=>o(R=>Qi(R)),[]),H=u.useCallback(R=>o(T=>({...T,bpm:Math.max(20,Math.min(300,R))})),[]),te=u.useCallback(R=>o(T=>({...T,swing:Math.max(0,Math.min(1,R))})),[]),G=u.useCallback(R=>{o(T=>{if(T.length===R)return T;const C=Array.from({length:R},(E,F)=>F<T.steps.length?T.steps[F]:{active:!1,note:T.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...T,length:R,steps:C}})},[]),B=u.useCallback(R=>{h(T=>[...T,R??dr()])},[]),w=u.useCallback(R=>{h(T=>T.filter((C,E)=>E!==R))},[]),$=u.useCallback((R,T)=>{h(C=>C.map((E,F)=>F===R?{...E,...T}:E))},[]);return{pattern:a,currentStep:i,playing:c,lfos:f,play:M,stop:N,togglePlayback:j,toggle:_,setNote:P,setVelocity:V,setGate:z,setProbability:A,toggleSlide:I,transpose:L,reverse:U,shift:Y,randomizeVel:O,clear:Z,setPattern:o,setBpm:H,setSwing:te,setLength:G,addLFO:B,removeLFO:w,updateLFO:$}}function Ra(e){const t=u.useRef(null),n=u.useRef(new Map),r=u.useRef(1),a=u.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.resolve(l.data))},i.onerror=l=>{console.error("[useWorker] Worker error:",l.message);for(const[c,d]of n.current)d.reject(new Error(`Worker error: ${l.message}`));n.current.clear(),i.terminate(),t.current=null},t.current=i}return t.current},[e]);return u.useEffect(()=>{const i=n.current;return()=>{var l;(l=t.current)==null||l.terminate(),t.current=null;for(const[,c]of i)c.reject(new Error("Worker terminated on unmount"));i.clear()}},[]),u.useCallback((i,l)=>{const c=r.current++,d=a();return new Promise((f,h)=>{n.current.set(c,{resolve:f,reject:h}),d.postMessage({...i,id:c},l??[])})},[a])}function Lh(){const e=Ra(u.useCallback(()=>new Worker(new URL("/assets/pitchWorker-BgAp5Z97.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return u.useCallback(async(n,r,a=.01)=>(await e({buffer:n,sampleRate:r,rmsThreshold:a})).hz,[e])}function Dh(){const e=Ra(u.useCallback(()=>new Worker(new URL("/assets/scoringWorker-B1PkYu_m.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return u.useCallback(async(n,r,a)=>(await e({notes:n,points:r,params:a})).result,[e])}const Fh={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function tl(){return`
70
+ Tame Impala - Let It Happen`,rows:10,style:{width:"100%",padding:12,borderRadius:6,border:"1px solid var(--border, #e2e8f0)",fontFamily:"monospace",fontSize:13,resize:"vertical"}}),r.jsx("button",{style:{...En,opacity:Z.trim().length===0?.5:1},disabled:Z.trim().length===0,onClick:()=>G(Z),type:"button",children:u("importWizard.parseTracks","Parse Tracks")})]}),(f!==99||k.length>0)&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[r.jsxs("p",{style:{margin:0,fontWeight:600},children:[b==null?void 0:b.name," — ",w.size,"/",k.length," ",u("importWizard.selected","selected")]}),r.jsx("button",{style:rr,onClick:C,type:"button",children:w.size===k.length?u("importWizard.deselectAll","Deselect All"):u("importWizard.selectAll","Select All")})]}),S?r.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--text-dim, #64748b)"},children:u("importWizard.loadingTracks","Loading tracks…")}):r.jsx("div",{style:{maxHeight:320,overflowY:"auto"},children:r.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[r.jsx("thead",{children:r.jsxs("tr",{style:{borderBottom:"1px solid var(--border, #e2e8f0)",textAlign:"left"},children:[r.jsx("th",{style:{padding:"4px 8px",width:32}}),r.jsx("th",{style:{padding:"4px 8px"},children:u("importWizard.title","Title")}),r.jsx("th",{style:{padding:"4px 8px"},children:u("importWizard.artist","Artist")}),r.jsx("th",{style:{padding:"4px 8px"},children:u("importWizard.album","Album")}),r.jsx("th",{style:{padding:"4px 8px",textAlign:"right"},children:u("importWizard.duration","Duration")})]})}),r.jsx("tbody",{children:k.map(H=>{const K=w.has(H.externalId);return r.jsxs("tr",{style:{borderBottom:"1px solid var(--border, #e2e8f0)",opacity:K?1:.5,cursor:"pointer"},onClick:()=>q(H.externalId),children:[r.jsx("td",{style:{padding:"6px 8px"},children:r.jsx("input",{type:"checkbox",checked:K,readOnly:!0})}),r.jsx("td",{style:{padding:"6px 8px",fontWeight:500},children:H.title}),r.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:H.artist}),r.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:H.album??"—"}),r.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--text-dim, #64748b)"},children:vf(H.duration)})]},H.externalId)})})]})}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:r.jsxs("button",{style:{...En,opacity:w.size===0?.5:1},disabled:w.size===0,onClick:()=>p("options"),type:"button",children:[u("importWizard.next","Next")," →"]})})]})]}),X=()=>r.jsxs("div",{style:{display:"grid",gap:16},children:[r.jsx("p",{style:{margin:0,fontWeight:600},children:u("importWizard.importOptions","Import options")}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:L.mergeTags,onChange:H=>W(K=>({...K,mergeTags:H.target.checked}))}),u("importWizard.mergeTags","Merge tags from source playlist")]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:L.mergeFolders,onChange:H=>W(K=>({...K,mergeFolders:H.target.checked}))}),u("importWizard.mergeFolders","Merge into existing folder structure")]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:L.overwriteExisting,onChange:H=>W(K=>({...K,overwriteExisting:H.target.checked}))}),u("importWizard.overwrite","Overwrite existing tracks (match by ISRC)")]}),l&&l.length>0&&r.jsxs("div",{style:{display:"grid",gap:4},children:[r.jsx("label",{style:{fontSize:13,fontWeight:500},children:u("importWizard.targetFolder","Target folder")}),r.jsxs("select",{style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border, #e2e8f0)"},value:L.targetFolderId??"",onChange:H=>W(K=>({...K,targetFolderId:H.target.value||void 0})),children:[r.jsx("option",{value:"",children:u("importWizard.root","— Root —")}),l.map(H=>r.jsx("option",{value:H.id,children:H.name},H.id))]})]}),r.jsx("div",{style:{marginTop:8,padding:12,borderRadius:8,background:"var(--info-bg, #eff6ff)",fontSize:13},children:u("importWizard.summary",`Ready to import ${w.size} tracks from "${(b==null?void 0:b.name)??""}"`)}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[r.jsx("button",{style:rr,onClick:P,type:"button",children:u("importWizard.back","← Back")}),r.jsx("button",{style:En,onClick:F,type:"button",children:u("importWizard.startImport","Start Import")})]})]}),ie=()=>{const H=T?Math.round(T.imported/T.total*100):0;return r.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[r.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:u("importWizard.importing","Importing…")}),r.jsx("div",{style:{height:8,borderRadius:4,background:"var(--border, #e2e8f0)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${H}%`,background:"var(--accent, #6366f1)",borderRadius:4,transition:"width 0.3s"}})}),T&&r.jsxs("div",{style:{fontSize:13,color:"var(--text-dim, #64748b)"},children:[T.imported," / ",T.total," ",u("importWizard.tracks","tracks"),T.currentTrack&&r.jsxs("div",{style:{marginTop:4},children:[r.jsx(se.NtdMusic,{size:12})," ",T.currentTrack]})]})]})},le=()=>r.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[r.jsx("span",{style:{display:"inline-flex",justifyContent:"center"},"aria-hidden":"true",children:r.jsx(se.NtdCheck,{size:48})}),r.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:u("importWizard.complete","Import Complete")}),O&&r.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[r.jsxs("div",{children:[r.jsx("strong",{children:O.imported})," ",u("importWizard.imported","imported")]}),O.skipped>0&&r.jsxs("div",{style:{color:"var(--warning, #f59e0b)"},children:[O.skipped," ",u("importWizard.skipped","skipped (duplicates)")]}),O.failed>0&&r.jsxs("div",{style:{color:"var(--error, #ef4444)"},children:[O.failed," ",u("importWizard.failed","failed")]}),O.failedTracks.length>0&&r.jsxs("details",{style:{textAlign:"left",marginTop:8,fontSize:12,color:"var(--text-dim, #64748b)"},children:[r.jsx("summary",{style:{cursor:"pointer"},children:u("importWizard.showFailed","Show failed tracks")}),r.jsx("ul",{style:{marginTop:4,paddingLeft:20},children:O.failedTracks.map((H,K)=>r.jsx("li",{children:H},K))})]})]}),r.jsx("button",{style:En,onClick:o,type:"button",children:u("importWizard.close","Done")})]}),te={connect:u("importWizard.stepConnect","Connect"),browse:u("importWizard.stepBrowse","Browse"),tracks:u("importWizard.stepTracks","Select Tracks"),options:u("importWizard.stepOptions","Options"),importing:u("importWizard.stepImporting","Importing"),done:u("importWizard.stepDone","Done")};return r.jsxs("div",{style:gf,children:[N(),r.jsxs("div",{style:yf,children:[r.jsxs("h2",{style:{margin:0,fontSize:18},children:[u("importWizard.title","Import Playlist")," — ",te[h]]}),I&&r.jsxs("button",{style:rr,onClick:P,type:"button",children:["← ",u("importWizard.back","Back")]}),h==="connect"&&r.jsx("button",{style:rr,onClick:o,type:"button","aria-label":u("importWizard.close","Close"),title:u("importWizard.close","Close"),children:r.jsx(se.NtdClose,{size:14})})]}),E&&r.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--error-bg, #fef2f2)",color:"var(--error, #ef4444)",fontSize:13},children:E}),h==="connect"&&z(),h==="browse"&&B(),h==="tracks"&&Y(),h==="options"&&X(),h==="importing"&&ie(),h==="done"&&le()]})},Sf=[{id:"concert-harp",name:"Concert Harp",description:"Warm concert harp",emoji:"🎵",dir:"concert-harp",attribution:"ConcertHarp SoundFont — source: musical-artifacts.com/artifacts/375"},{id:"celtic-harp",name:"Celtic Harp",description:"Bright celtic harp",emoji:"🍀",dir:"celtic-harp"},{id:"triangle",name:"Triangle",description:"Metallic percussion triangle",emoji:"🔺",dir:"triangle",attribution:"Triangle SoundFont — source: polyphone.io/en/soundfonts/unpitched-percussion/298-triangle"},{id:"synth",name:"Celesta",description:"Synthesized celesta / music-box",emoji:"✨",dir:"synth"},{id:"none",name:"Silent",description:"No sound on click",emoji:"🔇",dir:null}],kf="concert-harp",os=Object.fromEntries(Sf.map(e=>[e.id,e])),wf="nice2dev-note-sound-set";function jl(){try{const e=localStorage.getItem(wf);if(e&&os[e])return e}catch{}return kf}function li(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function Cl(e){if(!e)return null;const t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle=e;const n=t.fillStyle;if(n.startsWith("#")){const s=parseInt(n.slice(1),16);return{r:s>>16&255,g:s>>8&255,b:s&255}}const a=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return a?{r:+a[1],g:+a[2],b:+a[3]}:null}function Jr(e,t){const n=Cl(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function jf(e){const t=Cl(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function Ml(){const e=li("--text-primary")||"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",t=li("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",s=jf(e)<.45;return{base:Jr(e,.92),staffLine:Jr(e,.22),outline:s?"var(--nice-overlay-light-75, rgba(255, 255, 255, 0.75))":"var(--nice-overlay-55, rgba(0, 0, 0, 0.55))",accents:[Jr(t,.95)],isDark:n,notesDark:s}}const zr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),Rl=46,wt=5,pr=4,Cf=(Rl-(wt-1)*pr)/2,Mf=6,Rf=18,Nf=110,Tf=50,Or=zr?Tf:Nf,$f=zr?4:2,Pf=zr?2:4,ci=zr?1:0,Af=180,di=2.8,ui=40,Ef=14,hi=1.2,If=16,ea=[64,67,71,74,77],rn=64,In=77;function Lf(e){const t=Math.max(0,Math.min(wt-1,e)),n=Math.floor(t),a=Math.min(n+1,wt-1),s=t-n;return Math.round(ea[n]+(ea[a]-ea[n])*s)}function Df(e){return(Math.max(rn-1*(In-rn)/(wt-1),Math.min(In+1*(In-rn)/(wt-1),e))-rn)/(In-rn)*(wt-1)}const pi=2.5,fi=.72,_f=.55,Ln=new Map;let fr=null;async function Ff(e){const t=e??jl(),n=os[t];if(!n||!n.dir){Ln.clear(),fr=t;return}if(fr===t&&Ln.size>0)return;Ln.clear(),fr=t;const a=mn(),s=[];for(let i=rn;i<=In;i++)s.push(fetch(`/assets/soundfonts/notes/${n.dir}/note-${i}.mp3`).then(o=>o.arrayBuffer()).then(o=>a.decodeAudioData(o)).then(o=>{Ln.set(i,o)}).catch(()=>{}));await Promise.all(s)}function mi(e){const t=Ln.get(e);if(!t)return;const n=mn(),a=n.createBufferSource();a.buffer=t;const s=n.createGain();s.gain.value=.7,a.connect(s).connect(n.destination),a.start()}const gi=["𝅘𝅥","𝅘𝅥𝅮","𝅘𝅥𝅯","𝅘𝅥𝅰","𝅘𝅥𝅱","♪","♫","♬"];function zf(e){return()=>{e|=0,e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function Of(e){const t=zf(42),n=[];for(let a=0;a<e;a++){const i=t()<.15?0:-1;n.push({x:t(),lineIdx:t()*(wt+1)-.5,char:gi[Math.floor(t()*gi.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:i})}return n.sort((a,s)=>a.x-s.x),n}const ut=Of(Or),kn=new Float32Array(Or),ar=new Float32Array(Or),Dn=new Float32Array(Or);let ba=!1;const Bf=(wt-1)/2;function Gf(){if(!ba){ba=!0;for(let e=0;e<ut.length;e++)Dn[e]=ut[e].lineIdx}}let xa=[],yi="";function Wf(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function Uf(e){const t=Wf(e);t===yi&&xa.length===ut.length||(yi=t,xa=ut.map(n=>{const a=Math.ceil(n.size*1.6),s=a*2,i=document.createElement("canvas");i.width=s,i.height=s;const o=i.getContext("2d");return o.translate(a,a),o.rotate(n.rot*Math.PI/180),o.font=`${n.size}px serif`,o.textAlign="center",o.textBaseline="middle",o.lineWidth=1.8,o.strokeStyle=e.outline,o.strokeText(n.char,0,0),o.fillStyle=n.colorIdx<0?e.base:e.accents[n.colorIdx%e.accents.length],o.fillText(n.char,0,0),{canvas:i,ox:a,oy:a}}))}function Nl({pitchMidiRef:e}={}){const t=d.useRef(null),n=d.useRef(0),a=d.useRef(0),s=d.useRef(0),i=d.useRef(null),o=d.useRef(0),l=d.useRef(0),c=d.useRef(null),u=d.useRef(null),h=d.useRef(!1),p=d.useCallback((g,b,x)=>{const k=Cf+g*pr,v=b/x*Math.PI*2;return k+Math.sin(v)*Mf},[]),f=d.useCallback(g=>{const b=t.current;if(!b)return;if(l.current++,ci>0&&l.current%(ci+1)!==0){s.current=g,n.current=requestAnimationFrame(f);return}const x=b.getContext("2d");if(!x)return;const k=Math.min(window.devicePixelRatio||1,Pf),v=b.getBoundingClientRect(),w=v.width,M=v.height;(b.width!==Math.round(w*k)||b.height!==Math.round(M*k))&&(b.width=Math.round(w*k),b.height=Math.round(M*k),x.setTransform(k,0,0,k,0,0));const S=s.current?(g-s.current)/1e3:0;s.current=g,a.current=(a.current+Rf*S)%w,x.clearRect(0,0,w,M),o.current++,(!i.current||o.current%60===0)&&(i.current=Ml());const R=i.current;Uf(R),x.strokeStyle=R.staffLine,x.lineWidth=.7;for(let $=0;$<wt;$++){x.beginPath();for(let E=0;E<=w;E+=$f){const D=p($,E,w);E===0?x.moveTo(E,D):x.lineTo(E,D)}x.stroke()}const T=a.current,j=(e==null?void 0:e.current)??null;if(j!==null){Gf();const $=Df(j),E=pi*S;for(let D=0;D<ut.length;D++){const W=(ut[D].lineIdx-Bf)*_f,A=$*fi+($+W)*(1-fi)-Dn[D];Dn[D]+=A>0?Math.min(E,A):Math.max(-E,A)}}else if(ba){const $=pi*.4*S;for(let E=0;E<ut.length;E++){const L=ut[E].lineIdx-Dn[E];Dn[E]+=L>0?Math.min($,L):Math.max(-$,L)}}const O=c.current;O&&(O.timer-=S,O.timer<=0&&(c.current=null));for(let $=0;$<ut.length;$++){const E=ut[$];if(ar[$]>0){ar[$]-=S;const W=Math.max(0,ar[$]/di);kn[$]+=Af*W*S,kn[$]>w&&(kn[$]-=w)}const D=xa[$];if(!D)continue;const L=E.lineIdx;for(let W=0;W<2;W++){let A=((E.x*w-T-kn[$]+W*w)%w+w)%w;const _=p(Math.max(0,Math.min(wt-1,Math.round(L))),A,w),U=(L-Math.round(L))*pr;let ne=_+U;if(O&&O.timer>0){const V=A-O.x,q=ne-O.y,C=Math.sqrt(V*V+q*q);if(C<ui&&C>.1){const F=O.timer/hi,I=Ef*(1-C/ui)*F;A+=V/C*I,ne+=q/C*I}}x.drawImage(D.canvas,A-D.ox,ne-D.oy)}}n.current=requestAnimationFrame(f)},[p]),y=d.useCallback(g=>{const b=t.current;if(!b)return;const x=b.getBoundingClientRect(),k=g.clientX-x.left,v=g.clientY-x.top,w=x.width,M=a.current;let S=1/0,R=-1;for(let T=0;T<ut.length;T++){const j=ut[T],$=((j.x*w-M-kn[T])%w+w)%w,E=p(Math.max(0,Math.min(wt-1,Math.round(j.lineIdx))),$,w),D=(j.lineIdx-Math.round(j.lineIdx))*pr,L=E+D,W=$-k,Z=L-v,A=W*W+Z*Z;A<S&&(S=A,R=T)}if(R>=0&&Math.sqrt(S)<If){ar[R]=di;const T=ut[R],j=Lf(T.lineIdx);try{Bt();const O=jl(),$=os[O];$!=null&&$.dir&&(fr!==O||!h.current?(h.current=!0,Ff(O).then(()=>mi(j))):mi(j))}catch{}}c.current={x:k,y:v,timer:hi}},[p]),m=d.useCallback(g=>{const b=t.current;if(!b)return;const x=b.getBoundingClientRect(),k=g.clientX-x.left,v=g.clientY-x.top;u.current={x:k,y:v},c.current&&c.current.timer>0&&(c.current.x=k,c.current.y=v)},[]);return d.useEffect(()=>(n.current=requestAnimationFrame(f),()=>cancelAnimationFrame(n.current)),[f]),r.jsx("canvas",{ref:t,"aria-hidden":"true",role:"img","aria-label":"Note river animation canvas",onClick:y,onMouseMove:m,style:{display:"block",width:"100%",height:Rl,marginBottom:5,cursor:"pointer",background:"transparent"}})}const qf=14,Vf=.9,Hf=320,Kf=160,Yf=6,bi=8,Zf=14,xi=["♪","♫","♬","𝅘𝅥𝅮","𝅘𝅥𝅯"];function Tl(){const e=d.useRef(null),t=d.useRef([]),n=d.useRef(0),a=d.useRef(0),s=d.useRef([]),i=d.useRef(null),o=d.useRef(0),l=d.useCallback((u,h)=>{for(let p=0;p<qf;p++){const f=Math.random()*Math.PI*2,y=Kf*(.4+Math.random()*.6),m=Vf*(.6+Math.random()*.4),g=Math.random()<.15?0:-1;t.current.push({x:u,y:h,vx:Math.cos(f)*y,vy:Math.sin(f)*y-60,rot:Math.random()*Math.PI*2,vr:(Math.random()-.5)*Yf*2,size:bi+Math.random()*(Zf-bi),char:xi[Math.floor(Math.random()*xi.length)],life:m,maxLife:m,colorIdx:g})}},[]),c=d.useCallback(u=>{const h=e.current;if(!h){n.current=requestAnimationFrame(c);return}const p=h.getContext("2d");if(!p){n.current=requestAnimationFrame(c);return}const f=window.devicePixelRatio||1,y=window.innerWidth,m=window.innerHeight;(h.width!==Math.round(y*f)||h.height!==Math.round(m*f))&&(h.width=Math.round(y*f),h.height=Math.round(m*f),h.style.width=`${y}px`,h.style.height=`${m}px`,p.setTransform(f,0,0,f,0,0));const g=a.current?Math.min((u-a.current)/1e3,.05):0;a.current=u,p.clearRect(0,0,y,m),o.current++,(!i.current||o.current%60===0)&&(i.current=Ml());const b=i.current;if(navigator.getGamepads){const k=navigator.getGamepads();for(let v=0;v<k.length;v++){const w=k[v];if(w)for(let M=0;M<w.buttons.length;M++){const S=v*100+M,R=w.buttons[M].pressed;R&&!s.current[S]&&l(y/2,m/2),s.current[S]=R}}}const x=[];p.textAlign="center",p.textBaseline="middle";for(const k of t.current){if(k.life-=g,k.life<=0)continue;k.vy+=Hf*g,k.x+=k.vx*g,k.y+=k.vy*g,k.rot+=k.vr*g;const v=Math.max(0,k.life/k.maxLife),w=.5+.5*v;p.save(),p.globalAlpha=v,p.translate(k.x,k.y),p.rotate(k.rot),p.font=`${k.size*w}px serif`,p.lineWidth=1.4,p.strokeStyle=b.notesDark?`rgba(255,255,255,${v*.8})`:`rgba(0,0,0,${v*.55})`,p.strokeText(k.char,0,0);const M=k.colorIdx<0?b.base:b.accents[k.colorIdx%b.accents.length];p.fillStyle=M.replace(/[\d.]+\)$/,`${v})`),p.fillText(k.char,0,0),p.restore(),x.push(k)}t.current=x,n.current=requestAnimationFrame(c)},[l]);return d.useEffect(()=>{const u=p=>{l(p.clientX,p.clientY)},h=p=>{if(p.key!=="Enter")return;const f=document.activeElement;if(f){const y=f.getBoundingClientRect();l(y.left+y.width/2,y.top+y.height/2)}else l(window.innerWidth/2,window.innerHeight/2)};return window.addEventListener("click",u,!0),window.addEventListener("keydown",h,!0),n.current=requestAnimationFrame(c),()=>{window.removeEventListener("click",u,!0),window.removeEventListener("keydown",h,!0),cancelAnimationFrame(n.current)}},[c,l]),r.jsx("canvas",{ref:e,"aria-hidden":"true",role:"img","aria-label":"Note particles animation canvas",style:{position:"fixed",inset:0,zIndex:99999,pointerEvents:"none"}})}const mr={type:"gain",enabled:!0,mix:1,gain:0},_n={type:"compressor",enabled:!0,mix:1,threshold:-24,ratio:4,attack:10,release:100,knee:6,makeupGain:0},Fn={type:"reverb",enabled:!0,mix:.3,decay:2,preDelay:10,damping:.5,roomSize:.5},zn={type:"delay",enabled:!0,mix:.3,time:250,feedback:.4,pingPong:!1,highCut:8e3},gr={type:"chorus",enabled:!0,mix:.5,rate:1.5,depth:.5,delay:7,voices:3},yr={type:"eq",enabled:!0,mix:1,bands:[{frequency:60,gain:0,q:1,type:"lowshelf"},{frequency:250,gain:0,q:1,type:"peaking"},{frequency:1e3,gain:0,q:1,type:"peaking"},{frequency:4e3,gain:0,q:1,type:"peaking"},{frequency:12e3,gain:0,q:1,type:"highshelf"}]},br={type:"filter",enabled:!0,mix:1,filterType:"lowpass",frequency:1e3,q:1,gain:0},xr={type:"distortion",enabled:!0,mix:.5,drive:.5,tone:.5,curve:"soft"},vr={type:"tremolo",enabled:!0,mix:1,rate:5,depth:.5,waveform:"sine"},Sr={type:"phaser",enabled:!0,mix:.5,rate:.5,depth:.5,feedback:.5,stages:4,frequency:1e3},Xf={gain:{unity:{...mr,gain:0},boost:{...mr,gain:6},cut:{...mr,gain:-6}},compressor:{gentle:{..._n,threshold:-20,ratio:2,attack:30,release:200},moderate:{..._n,threshold:-24,ratio:4,attack:10,release:100},aggressive:{..._n,threshold:-30,ratio:8,attack:1,release:50},limiter:{..._n,threshold:-3,ratio:20,attack:.1,release:100}},reverb:{small_room:{...Fn,decay:.5,roomSize:.2,damping:.7},large_hall:{...Fn,decay:3,roomSize:.8,damping:.3},plate:{...Fn,decay:1.5,roomSize:.5,damping:.4},cathedral:{...Fn,decay:5,roomSize:.9,damping:.2,mix:.4}},delay:{slapback:{...zn,time:80,feedback:.1,mix:.3},quarter_note:{...zn,time:500,feedback:.4,mix:.3},dotted_eighth:{...zn,time:375,feedback:.5,mix:.3},long_ambient:{...zn,time:750,feedback:.6,highCut:3e3,mix:.4}},chorus:{subtle:{...gr,rate:.5,depth:.2,voices:2,mix:.3},vintage:{...gr,rate:1,depth:.4,voices:2,delay:10,mix:.4},ensemble:{...gr,rate:2,depth:.6,voices:4,mix:.5}},eq:{vocal_presence:{...yr,bands:[{frequency:80,gain:-3,q:1,type:"highpass"},{frequency:250,gain:-2,q:1,type:"peaking"},{frequency:3e3,gain:3,q:1.5,type:"peaking"},{frequency:8e3,gain:2,q:1,type:"highshelf"}]},bass_boost:{...yr,bands:[{frequency:60,gain:6,q:1,type:"lowshelf"},{frequency:200,gain:2,q:1,type:"peaking"}]},brightness:{...yr,bands:[{frequency:4e3,gain:3,q:1,type:"peaking"},{frequency:1e4,gain:4,q:1,type:"highshelf"}]}},filter:{low_pass_warm:{...br,filterType:"lowpass",frequency:2e3,q:.7},high_pass_clean:{...br,filterType:"highpass",frequency:100,q:.7},telephone:{...br,filterType:"bandpass",frequency:1500,q:2}},distortion:{overdrive:{...xr,drive:.3,tone:.6,curve:"soft",mix:.7},crunch:{...xr,drive:.5,tone:.5,curve:"tube",mix:.8},fuzz:{...xr,drive:.8,tone:.4,curve:"fuzz",mix:1}},tremolo:{slow:{...vr,rate:3,depth:.4,waveform:"sine"},fast:{...vr,rate:8,depth:.6,waveform:"sine"},choppy:{...vr,rate:6,depth:.9,waveform:"square"}},phaser:{subtle:{...Sr,rate:.3,depth:.3,feedback:.3,stages:4},jet:{...Sr,rate:.1,depth:.8,feedback:.7,stages:8},rotary:{...Sr,rate:1,depth:.5,feedback:.4,stages:6}}};function vi(e){return Math.pow(10,e/20)}function Qf(e,t,n,a){const s=e.sampleRate,i=Math.floor(s*t),o=e.createBuffer(2,i,s);for(let l=0;l<2;l++){const c=o.getChannelData(l);for(let u=0;u<i;u++){const h=u/s,p=Math.exp(-h/n),f=1-a*(u/i);c[u]=(Math.random()*2-1)*p*f}}return o}function Jf(e,t){const a=new Float32Array(44100),s=Math.PI/180;for(let i=0;i<44100;i++){const o=i*2/44100-1;switch(t){case"soft":a[i]=(3+e*10)*o*20*s/(Math.PI+e*10*Math.abs(o));break;case"hard":a[i]=Math.tanh(o*(1+e*5));break;case"fuzz":a[i]=Math.sign(o)*Math.pow(Math.abs(o),1/(1+e*3));break;case"tube":o>=0?a[i]=1-Math.pow(1-o,1+e*2):a[i]=-(1-Math.pow(1+o,1+e*2));break}}return a}class em{constructor(t){this.effects=[],this.bypass=!1,this.audioContext=t,this.inputNode=t.createGain(),this.outputNode=t.createGain(),this.inputNode.connect(this.outputNode)}get input(){return this.inputNode}get output(){return this.outputNode}addEffect(t,n){const a=`effect_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=this.createEffectInstance(a,t);return n!==void 0&&n>=0&&n<this.effects.length?this.effects.splice(n,0,s):this.effects.push(s),this.reconnectChain(),a}removeEffect(t){const n=this.effects.findIndex(s=>s.id===t);if(n===-1)return!1;const a=this.effects[n];for(const s of a.nodes)s.disconnect();return this.effects.splice(n,1),this.reconnectChain(),!0}updateEffect(t,n){const a=this.effects.find(l=>l.id===t);if(!a)return!1;const s={...a.params,...n},i=this.effects.indexOf(a);for(const l of a.nodes)l.disconnect();const o=this.createEffectInstance(t,s);return this.effects[i]=o,this.reconnectChain(),!0}reorderEffects(t,n){if(t<0||t>=this.effects.length||n<0||n>=this.effects.length)return!1;const[a]=this.effects.splice(t,1);return this.effects.splice(n,0,a),this.reconnectChain(),!0}setBypass(t){this.bypass=t,this.reconnectChain()}getEffects(){return[...this.effects]}clear(){for(const t of this.effects)for(const n of t.nodes)n.disconnect();this.effects=[],this.reconnectChain()}createEffectInstance(t,n){const{audioContext:a}=this,s=[];let i,o;switch(n.type){case"gain":{const l=a.createGain();l.gain.value=vi(n.gain),s.push(l),i=o=l;break}case"compressor":{const l=a.createDynamicsCompressor();l.threshold.value=n.threshold,l.ratio.value=n.ratio,l.attack.value=n.attack/1e3,l.release.value=n.release/1e3,l.knee.value=n.knee;const c=a.createGain();c.gain.value=vi(n.makeupGain),l.connect(c),s.push(l,c),i=l,o=c;break}case"reverb":{const l=a.createConvolver();l.buffer=Qf(a,n.decay,n.decay,n.damping);const c=a.createGain(),u=a.createGain(),h=a.createGain(),p=a.createGain();c.gain.value=n.mix,u.gain.value=1-n.mix,h.connect(l),h.connect(u),l.connect(c),c.connect(p),u.connect(p),s.push(h,l,c,u,p),i=h,o=p;break}case"delay":{const l=a.createDelay(5);l.delayTime.value=n.time/1e3;const c=a.createGain();c.gain.value=n.feedback;const u=a.createBiquadFilter();u.type="lowpass",u.frequency.value=n.highCut;const h=a.createGain(),p=a.createGain(),f=a.createGain(),y=a.createGain();h.gain.value=n.mix,p.gain.value=1-n.mix,f.connect(l),f.connect(p),l.connect(u),u.connect(c),c.connect(l),u.connect(h),h.connect(y),p.connect(y),s.push(f,l,u,c,h,p,y),i=f,o=y;break}case"eq":{const l=[];let c=null;for(const u of n.bands){const h=a.createBiquadFilter();h.type=u.type,h.frequency.value=u.frequency,h.Q.value=u.q,h.gain.value=u.gain,c&&c.connect(h),c=h,l.push(h)}s.push(...l),i=l[0]||a.createGain(),o=l[l.length-1]||i;break}case"filter":{const l=a.createBiquadFilter();l.type=n.filterType,l.frequency.value=n.frequency,l.Q.value=n.q,l.gain.value=n.gain,s.push(l),i=o=l;break}case"distortion":{const l=a.createWaveShaper();l.curve=Jf(n.drive,n.curve),l.oversample="4x";const c=a.createBiquadFilter();c.type="lowpass",c.frequency.value=1e3+n.tone*1e4;const u=a.createGain(),h=a.createGain(),p=a.createGain(),f=a.createGain();u.gain.value=n.mix,h.gain.value=1-n.mix,p.connect(l),p.connect(h),l.connect(c),c.connect(u),u.connect(f),h.connect(f),s.push(p,l,c,u,h,f),i=p,o=f;break}case"tremolo":{const l=a.createOscillator();l.type=n.waveform,l.frequency.value=n.rate;const c=a.createGain();c.gain.value=n.depth*.5;const u=a.createGain();u.gain.value=1-n.depth*.5,l.connect(c),c.connect(u.gain),l.start(),s.push(l,c,u),i=o=u;break}case"phaser":{const l=[],c=a.createOscillator();c.type="sine",c.frequency.value=n.rate;const u=a.createGain();u.gain.value=n.depth*n.frequency;let h=null;for(let g=0;g<n.stages;g++){const b=a.createBiquadFilter();b.type="allpass",b.frequency.value=n.frequency,b.Q.value=.5,c.connect(u),u.connect(b.frequency),h&&h.connect(b),h=b,l.push(b)}const p=a.createGain(),f=a.createGain(),y=a.createGain(),m=a.createGain();p.gain.value=n.mix,f.gain.value=1-n.mix,y.connect(l[0]),y.connect(f),l[l.length-1].connect(p),p.connect(m),f.connect(m),c.start(),s.push(c,u,...l,p,f,y,m),i=y,o=m;break}default:throw new Error(`Unknown effect type: ${n.type}`)}return{id:t,params:n,nodes:s,input:i,output:o}}reconnectChain(){this.inputNode.disconnect();for(const n of this.effects)n.output.disconnect();if(this.bypass||this.effects.length===0){this.inputNode.connect(this.outputNode);return}let t=this.inputNode;for(const n of this.effects)n.params.enabled&&(t.connect(n.input),t=n.output);t.connect(this.outputNode)}dispose(){this.clear(),this.inputNode.disconnect(),this.outputNode.disconnect()}}const $l={gain:r.jsx(se.NtdVolume,{size:16}),compressor:r.jsx(se.NtdSettings,{size:16}),reverb:r.jsx(se.NtdMountain,{size:16}),delay:r.jsx(se.NtdStopwatch,{size:16}),chorus:r.jsx(se.NtdSparkle,{size:16}),eq:r.jsx(se.NtdBarChart,{size:16}),filter:r.jsx(se.NtdFilter,{size:16}),distortion:r.jsx(se.NtdLightning,{size:16}),tremolo:r.jsx(se.NtdWave,{size:16}),phaser:r.jsx(se.NtdMagicWand,{size:16})},Pl={gain:"Gain",compressor:"Compressor",reverb:"Reverb",delay:"Delay",chorus:"Chorus",eq:"EQ",filter:"Filter",distortion:"Distortion",tremolo:"Tremolo",phaser:"Phaser"},tm={gain:mr,compressor:_n,reverb:Fn,delay:zn,chorus:gr,eq:yr,filter:br,distortion:xr,tremolo:vr,phaser:Sr},nm=["gain","compressor","reverb","delay","chorus","eq","filter","distortion","tremolo","phaser"],Le=({value:e,min:t,max:n,step:a=1,label:s,unit:i="",onChange:o,disabled:l})=>{const c=d.useRef(null),[u,h]=d.useState(!1),p=d.useRef(0),f=d.useRef(e),y=d.useCallback(g=>{l||(g.preventDefault(),h(!0),p.current=g.clientY,f.current=e)},[l,e]);d.useEffect(()=>{if(!u)return;const g=x=>{const k=p.current-x.clientY,v=n-t,M=k/200*v,S=Math.min(n,Math.max(t,f.current+M));o(a<1?S:Math.round(S/a)*a)},b=()=>{h(!1)};return document.addEventListener("mousemove",g),document.addEventListener("mouseup",b),()=>{document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",b)}},[u,t,n,a,o]);const m=(e-t)/(n-t)*270-135;return r.jsxs("div",{className:`nice-fx-knob ${l?"nice-fx-knob--disabled":""}`,ref:c,children:[r.jsx("div",{className:`nice-fx-knob__dial ${u?"nice-fx-knob__dial--active":""}`,onMouseDown:y,style:{transform:`rotate(${m}deg)`},children:r.jsx("div",{className:"nice-fx-knob__indicator"})}),r.jsx("div",{className:"nice-fx-knob__label",children:s}),r.jsxs("div",{className:"nice-fx-knob__value",children:[typeof e=="number"&&a<1?e.toFixed(2):e,i]})]})};function rm({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return r.jsx(jt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsx(Le,{value:e.gain,min:-60,max:12,step:.1,label:"Gain",unit:"dB",onChange:u=>t({...e,gain:u}),disabled:!e.enabled})})}function am({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return r.jsx(jt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(Le,{value:e.threshold,min:-60,max:0,label:"Threshold",unit:"dB",onChange:u=>t({...e,threshold:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.ratio,min:1,max:20,label:"Ratio",onChange:u=>t({...e,ratio:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.attack,min:.1,max:200,label:"Attack",unit:"ms",onChange:u=>t({...e,attack:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.release,min:10,max:1e3,label:"Release",unit:"ms",onChange:u=>t({...e,release:u}),disabled:!e.enabled}),!c&&r.jsxs(r.Fragment,{children:[r.jsx(Le,{value:e.knee,min:0,max:40,label:"Knee",unit:"dB",onChange:u=>t({...e,knee:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.makeupGain,min:0,max:24,label:"Makeup",unit:"dB",onChange:u=>t({...e,makeupGain:u}),disabled:!e.enabled})]})]})})}function sm({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return r.jsx(jt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(Le,{value:e.decay,min:.1,max:10,step:.1,label:"Decay",unit:"s",onChange:u=>t({...e,decay:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.damping,min:0,max:1,step:.01,label:"Damping",onChange:u=>t({...e,damping:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.roomSize,min:0,max:1,step:.01,label:"Room",onChange:u=>t({...e,roomSize:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:u=>t({...e,mix:u}),disabled:!e.enabled})]})})}function im({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return r.jsx(jt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(Le,{value:e.time,min:0,max:2e3,label:"Time",unit:"ms",onChange:u=>t({...e,time:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.feedback,min:0,max:1,step:.01,label:"Feedback",onChange:u=>t({...e,feedback:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.highCut,min:200,max:2e4,label:"HiCut",unit:"Hz",onChange:u=>t({...e,highCut:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:u=>t({...e,mix:u}),disabled:!e.enabled})]})})}function om({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return r.jsx(jt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(Le,{value:e.drive,min:0,max:1,step:.01,label:"Drive",onChange:u=>t({...e,drive:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.tone,min:0,max:1,step:.01,label:"Tone",onChange:u=>t({...e,tone:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:u=>t({...e,mix:u}),disabled:!e.enabled})]})})}function jt({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:u}){const[h,p]=d.useState(!1);return r.jsxs("div",{className:`nice-fx-card ${e.enabled?"":"nice-fx-card--disabled"} ${i?"nice-fx-card--drop-target":""} ${c?"nice-fx-card--compact":""}`,draggable:!0,onDragStart:a,onDragEnd:s,children:[r.jsxs("div",{className:"nice-fx-card__header",children:[r.jsx("span",{className:"nice-fx-card__icon",children:$l[e.type]}),r.jsx("span",{className:"nice-fx-card__title",children:Pl[e.type]}),r.jsx("button",{type:"button",className:`nice-fx-card__toggle ${e.enabled?"nice-fx-card__toggle--active":""}`,onClick:()=>t({...e,enabled:!e.enabled}),title:e.enabled?"Disable":"Enable","aria-pressed":e.enabled,children:r.jsx("span",{className:"nice-fx-card__toggle-dot","aria-hidden":"true"})}),l&&Object.keys(o).length>0&&r.jsxs("div",{className:"nice-fx-card__presets",children:[r.jsx("button",{type:"button",className:"nice-fx-card__preset-btn",onClick:()=>p(!h),"aria-label":"Presets",children:r.jsx(se.NtdChevronDown,{size:12})}),h&&r.jsx("div",{className:"nice-fx-card__preset-menu",children:Object.entries(o).map(([f,y])=>r.jsx("button",{type:"button",className:"nice-fx-card__preset-item",onClick:()=>{t({...y,enabled:e.enabled}),p(!1)},children:f.replace(/_/g," ")},f))})]}),r.jsx("button",{type:"button",className:"nice-fx-card__remove",onClick:n,title:"Remove",children:"×"})]}),r.jsx("div",{className:"nice-fx-card__body",children:u})]})}function lm({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return r.jsx(jt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsx("div",{className:"nice-fx-card__generic",children:r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:u=>t({...e,mix:u}),disabled:!e.enabled})})})}function cm({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return r.jsx(jt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.rate??1.5,min:.1,max:10,step:.1,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),r.jsx(Le,{value:a.depth??.5,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),r.jsx(Le,{value:a.feedback??.3,min:0,max:.95,step:.01,label:"Feedback",onChange:i=>s("feedback",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function dm({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return r.jsx(jt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.low??0,min:-12,max:12,step:.5,label:"Low",onChange:i=>s("low",i),disabled:!e.enabled}),r.jsx(Le,{value:a.mid??0,min:-12,max:12,step:.5,label:"Mid",onChange:i=>s("mid",i),disabled:!e.enabled}),r.jsx(Le,{value:a.high??0,min:-12,max:12,step:.5,label:"High",onChange:i=>s("high",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function um({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return r.jsx(jt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.frequency??1e3,min:20,max:2e4,step:1,label:"Freq",onChange:i=>s("frequency",i),disabled:!e.enabled}),r.jsx(Le,{value:a.Q??1,min:.1,max:20,step:.1,label:"Q",onChange:i=>s("Q",i),disabled:!e.enabled}),r.jsx(Le,{value:a.gain??0,min:-24,max:24,step:.5,label:"Gain",onChange:i=>s("gain",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function hm({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return r.jsx(jt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.rate??5,min:.1,max:20,step:.1,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),r.jsx(Le,{value:a.depth??.5,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function pm({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return r.jsx(jt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.rate??.5,min:.01,max:8,step:.01,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),r.jsx(Le,{value:a.depth??.7,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),r.jsx(Le,{value:a.feedback??.5,min:0,max:.95,step:.01,label:"Feedback",onChange:i=>s("feedback",i),disabled:!e.enabled}),r.jsx(Le,{value:a.stages??4,min:2,max:12,step:2,label:"Stages",onChange:i=>s("stages",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}const fm=({audioContext:e,chain:t,effects:n,onChange:a,onChainUpdate:s,maxEffects:i=10,availableEffects:o=nm,showPresets:l=!0,compact:c=!1,className:u=""})=>{const[h,p]=d.useState((n==null?void 0:n.map(T=>T.params))||[]),[f,y]=d.useState({isDragging:!1,dragIndex:-1,dropIndex:-1}),[m,g]=d.useState(!1),b=d.useMemo(()=>t||(e?new em(e):null),[e,t]),x=d.useCallback((T,j)=>{const O=[...h];O[T]=j,p(O),a==null||a(O),b&&(s==null||s(b))},[h,a,b,s]),k=d.useCallback(T=>{if(h.length>=i)return;const j={...tm[T]},O=[...h,j];p(O),a==null||a(O),g(!1)},[h,i,a]),v=d.useCallback(T=>{const j=h.filter((O,$)=>$!==T);p(j),a==null||a(j)},[h,a]),w=d.useCallback(T=>{y({isDragging:!0,dragIndex:T,dropIndex:-1})},[]),M=d.useCallback(()=>{if(f.dragIndex!==-1&&f.dropIndex!==-1&&f.dragIndex!==f.dropIndex){const T=[...h],[j]=T.splice(f.dragIndex,1);T.splice(f.dropIndex,0,j),p(T),a==null||a(T)}y({isDragging:!1,dragIndex:-1,dropIndex:-1})},[f,h,a]),S=d.useCallback((T,j)=>{T.preventDefault(),f.isDragging&&y(O=>({...O,dropIndex:j}))},[f.isDragging]),R=(T,j)=>{const O={onRemove:()=>v(j),onDragStart:()=>w(j),onDragEnd:M,isDragTarget:f.dropIndex===j,presets:Xf[T.type]||{},showPresets:l,compact:c};switch(T.type){case"gain":return r.jsx(rm,{effect:T,onChange:$=>x(j,$),...O},j);case"compressor":return r.jsx(am,{effect:T,onChange:$=>x(j,$),...O},j);case"reverb":return r.jsx(sm,{effect:T,onChange:$=>x(j,$),...O},j);case"delay":return r.jsx(im,{effect:T,onChange:$=>x(j,$),...O},j);case"distortion":return r.jsx(om,{effect:T,onChange:$=>x(j,$),...O},j);case"chorus":return r.jsx(cm,{effect:T,onChange:$=>x(j,$),...O},j);case"eq":return r.jsx(dm,{effect:T,onChange:$=>x(j,$),...O},j);case"filter":return r.jsx(um,{effect:T,onChange:$=>x(j,$),...O},j);case"tremolo":return r.jsx(hm,{effect:T,onChange:$=>x(j,$),...O},j);case"phaser":return r.jsx(pm,{effect:T,onChange:$=>x(j,$),...O},j);default:return r.jsx(lm,{effect:T,onChange:$=>x(j,$),...O},j)}};return r.jsxs("div",{className:`nice-fx-rack ${c?"nice-fx-rack--compact":""} ${u}`,children:[r.jsxs("div",{className:"nice-fx-rack__header",children:[r.jsx("h3",{className:"nice-fx-rack__title",children:"Effects Chain"}),r.jsxs("span",{className:"nice-fx-rack__count",children:[h.length,"/",i]})]}),r.jsx("div",{className:"nice-fx-rack__chain",children:h.length===0?r.jsx("div",{className:"nice-fx-rack__empty",children:"No effects. Click + to add."}):h.map((T,j)=>r.jsxs("div",{className:"nice-fx-rack__slot",onDragOver:O=>S(O,j),children:[R(T,j),j<h.length-1&&r.jsx("div",{className:"nice-fx-rack__connector","aria-hidden":"true",children:r.jsx(se.NtdArrowRight,{size:14})})]},j))}),h.length<i&&r.jsxs("div",{className:"nice-fx-rack__add",children:[r.jsx("button",{type:"button",className:"nice-fx-rack__add-btn",onClick:()=>g(!m),children:"+ Add Effect"}),m&&r.jsx("div",{className:"nice-fx-rack__add-menu",children:o.map(T=>r.jsxs("button",{type:"button",className:"nice-fx-rack__add-item",onClick:()=>k(T),children:[r.jsx("span",{className:"nice-fx-rack__add-icon",children:$l[T]}),r.jsx("span",{className:"nice-fx-rack__add-label",children:Pl[T]})]},T))})]})]})},Al=[{type:"chipmunk",enabled:!1,intensity:60,label:"Chipmunk",icon:"sparkle"},{type:"helium",enabled:!1,intensity:80,label:"Helium",icon:"sparkle"},{type:"deep",enabled:!1,intensity:50,label:"Deep Voice",icon:"music"},{type:"demon",enabled:!1,intensity:70,label:"Demon",icon:"skull"},{type:"robot",enabled:!1,intensity:50,label:"Robot",icon:"robot"},{type:"alien",enabled:!1,intensity:60,label:"Alien",icon:"ghost"},{type:"echo",enabled:!1,intensity:50,label:"Echo",icon:"mountain"},{type:"cave",enabled:!1,intensity:60,label:"Cave",icon:"mountain"},{type:"reverb",enabled:!1,intensity:50,label:"Reverb",icon:"wave"},{type:"chorus",enabled:!1,intensity:50,label:"Chorus",icon:"music"},{type:"flanger",enabled:!1,intensity:50,label:"Flanger",icon:"wave"},{type:"distortion",enabled:!1,intensity:40,label:"Distortion",icon:"lightning"},{type:"telephone",enabled:!1,intensity:80,label:"Telephone",icon:"phone"},{type:"megaphone",enabled:!1,intensity:60,label:"Megaphone",icon:"megaphone"},{type:"radio",enabled:!1,intensity:70,label:"AM Radio",icon:"wave"},{type:"underwater",enabled:!1,intensity:50,label:"Underwater",icon:"wave"},{type:"whisper",enabled:!1,intensity:60,label:"Whisper",icon:"volume-mute"},{type:"tremolo",enabled:!1,intensity:50,label:"Tremolo",icon:"wave"},{type:"autotune",enabled:!1,intensity:60,label:"Auto-Tune",icon:"microphone"},{type:"vocoder",enabled:!1,intensity:50,label:"Vocoder",icon:"volume"}];function Si(e,t,n){const a=e.sampleRate,s=Math.round(a*t),i=e.createBuffer(2,s,a);for(let o=0;o<2;o++){const l=i.getChannelData(o);for(let c=0;c<s;c++)l[c]=(Math.random()*2-1)*Math.pow(1-c/s,n)}return i}function sr(e){const t=Math.max(1,e),n=44100,a=new Float32Array(n),s=Math.PI/180;for(let i=0;i<n;i++){const o=i*2/n-1;a[i]=(3+t)*o*20*s/(Math.PI+t*Math.abs(o))}return a}class El{constructor(){this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.activeEffects=new Map,this.effectOrder=[],this.monitoring=!0,this._volume=1,this._inputVolume=1,this.started=!1,this.externalStream=!1,this.analyser=null}get isStarted(){return this.started}get context(){return this.audioCtx}get activeEffectTypes(){return[...this.effectOrder]}async start(t){this.started||(this.audioCtx=new AudioContext,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),this.sourceNode=this.audioCtx.createMediaStreamSource(this.mediaStream),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}async startWithStream(t){this.started||(this.externalStream=!0,this.audioCtx=new AudioContext,this.mediaStream=t,this.sourceNode=this.audioCtx.createMediaStreamSource(t),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}stop(){var t,n,a,s,i,o;this.clearAllEffects();try{(t=this.analyser)==null||t.disconnect()}catch{}try{(n=this.outputGain)==null||n.disconnect()}catch{}try{(a=this.inputGain)==null||a.disconnect()}catch{}try{(s=this.sourceNode)==null||s.disconnect()}catch{}try{(i=this.audioCtx)==null||i.close()}catch{}if(!this.externalStream)try{(o=this.mediaStream)==null||o.getTracks().forEach(l=>l.stop())}catch{}this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.analyser=null,this.started=!1}setMonitoring(t){this.monitoring=t,this.outputGain&&(this.outputGain.gain.value=t?this._volume:0)}setVolume(t){this._volume=Math.max(0,Math.min(2,t)),this.outputGain&&this.monitoring&&(this.outputGain.gain.value=this._volume)}setInputGain(t){this._inputVolume=Math.max(0,Math.min(3,t)),this.inputGain&&(this.inputGain.gain.value=this._inputVolume)}getLevel(){if(!this.analyser)return 0;const t=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(t);let n=0;for(let a=0;a<t.length;a++){const s=(t[a]-128)/128;n+=s*s}return Math.sqrt(n/t.length)}addEffect(t,n=50){if(!this.audioCtx||!this.inputGain||!this.outputGain||this.activeEffects.has(t))return;const a=this.buildEffectChain(t,n);a&&(this.activeEffects.set(t,a),this.effectOrder.push(t),this.reconnectChain())}removeEffect(t){const n=this.activeEffects.get(t);if(n){for(const a of n.nodes)try{a.disconnect()}catch{}this.activeEffects.delete(t),this.effectOrder=this.effectOrder.filter(a=>a!==t),this.reconnectChain()}}toggleEffect(t,n=50){return this.activeEffects.has(t)?(this.removeEffect(t),!1):(this.addEffect(t,n),!0)}updateIntensity(t,n){this.activeEffects.has(t)&&(this.removeEffect(t),this.addEffect(t,n))}clearAllEffects(){for(const[t]of this.activeEffects){const n=this.activeEffects.get(t);if(n)for(const a of n.nodes)try{a.disconnect()}catch{}}this.activeEffects.clear(),this.effectOrder=[],this.reconnectChain()}reconnectChain(){if(!this.inputGain||!this.outputGain)return;try{this.inputGain.disconnect()}catch{}for(const[,n]of this.activeEffects)try{n.output.disconnect()}catch{}if(this.effectOrder.length===0){this.inputGain.connect(this.outputGain);return}let t=this.inputGain;for(const n of this.effectOrder){const a=this.activeEffects.get(n);a&&(t.connect(a.input),t=a.output)}t.connect(this.outputGain)}buildEffectChain(t,n){const a=this.audioCtx,s=n/100;switch(t){case"chipmunk":return this.buildPitchShift(a,1+s*.8,s);case"helium":return this.buildPitchShift(a,1.5+s*1,s);case"deep":return this.buildPitchShift(a,1/(1+s*.5),s);case"demon":return this.buildDemon(a,s);case"robot":return this.buildRobot(a,s);case"alien":return this.buildAlien(a,s);case"echo":return this.buildDelay(a,.15+s*.35,.3+s*.4,s);case"cave":return this.buildCave(a,s);case"reverb":return this.buildReverb(a,1.5+s*3,2+s*4,s);case"chorus":return this.buildChorus(a,s);case"flanger":return this.buildFlanger(a,s);case"distortion":return this.buildDistortion(a,20+s*100,s);case"telephone":return this.buildBandpass(a,400,3500,s);case"megaphone":return this.buildMegaphone(a,s);case"radio":return this.buildRadio(a,s);case"underwater":return this.buildUnderwater(a,s);case"whisper":return this.buildWhisper(a,s);case"tremolo":return this.buildTremolo(a,s);case"autotune":return this.buildAutotune(a,s);case"vocoder":return this.buildVocoder(a,s);default:return null}}buildPitchShift(t,n,a){const s=t.createGain();s.gain.value=1;const i=t.createGain();i.gain.value=1;const o=t.createGain();o.gain.value=.7+a*.3;const l=t.createGain();l.gain.value=1-a*.5;const c=t.createDelay(1),u=t.createDelay(1),h=t.createOscillator(),p=t.createOscillator(),f=t.createGain(),y=t.createGain(),m=n-1,g=Math.abs(m)*5+2,b=Math.abs(m)*.015;h.type="sawtooth",h.frequency.value=g,f.gain.value=b,h.connect(f),f.connect(c.delayTime),c.delayTime.value=.02,p.type="sawtooth",p.frequency.value=g,y.gain.value=b,p.connect(y),y.connect(u.delayTime),u.delayTime.value=.02+b;const x=t.createGain();x.gain.value=.5;const k=t.createGain();return k.gain.value=.5,s.connect(c),s.connect(u),c.connect(x),u.connect(k),x.connect(o),k.connect(o),s.connect(l),o.connect(i),l.connect(i),h.start(),p.start(),{type:"chipmunk",nodes:[s,c,u,h,p,f,y,x,k,o,l,i],input:s,output:i}}buildRobot(t,n){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=.6+n*.4;const o=t.createGain();o.gain.value=1-n*.6;const l=t.createOscillator();l.type="square",l.frequency.value=50+n*200;const c=t.createGain();return c.gain.value=0,l.connect(c.gain),a.connect(c),c.connect(i),a.connect(o),i.connect(s),o.connect(s),l.start(),{type:"robot",nodes:[a,l,c,i,o,s],input:a,output:s}}buildAlien(t,n){const a=t.createGain(),s=t.createGain(),i=t.createOscillator();i.type="sine",i.frequency.value=300+n*700;const o=t.createGain();o.gain.value=0,i.connect(o.gain),a.connect(o);const l=t.createDelay(.1);l.delayTime.value=.005;const c=t.createOscillator();c.type="sine",c.frequency.value=3+n*10;const u=t.createGain();u.gain.value=.004,c.connect(u),u.connect(l.delayTime),o.connect(l),l.connect(s);const h=t.createGain();return h.gain.value=.3,a.connect(h),h.connect(s),i.start(),c.start(),{type:"alien",nodes:[a,i,o,l,c,u,h,s],input:a,output:s}}buildDelay(t,n,a,s){const i=t.createGain(),o=t.createGain(),l=t.createDelay(2);l.delayTime.value=n;const c=t.createGain();c.gain.value=Math.min(.85,a);const u=t.createGain();u.gain.value=.5+s*.5;const h=t.createGain();return h.gain.value=1,i.connect(l),l.connect(c),c.connect(l),l.connect(u),i.connect(h),u.connect(o),h.connect(o),{type:"echo",nodes:[i,l,c,u,h,o],input:i,output:o}}buildCave(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(2);i.delayTime.value=.2+n*.3;const o=t.createDelay(2);o.delayTime.value=.35+n*.25;const l=t.createDelay(2);l.delayTime.value=.55+n*.3;const c=t.createGain();c.gain.value=.5;const u=t.createGain();u.gain.value=.35;const h=t.createGain();h.gain.value=.25;const p=t.createConvolver();p.buffer=Si(t,2+n*3,3);const f=t.createGain();f.gain.value=.3+n*.3,a.connect(i),i.connect(c),c.connect(i),a.connect(o),o.connect(u),u.connect(o),a.connect(l),l.connect(h),h.connect(l),i.connect(f),o.connect(f),l.connect(f),a.connect(p),p.connect(f);const y=t.createGain();return y.gain.value=.7,a.connect(y),y.connect(s),f.connect(s),{type:"cave",nodes:[a,i,o,l,c,u,h,p,f,y,s],input:a,output:s}}buildReverb(t,n,a,s){const i=t.createGain(),o=t.createGain(),l=t.createConvolver();l.buffer=Si(t,n,a);const c=t.createGain();c.gain.value=.4+s*.5;const u=t.createGain();return u.gain.value=1,i.connect(l),l.connect(c),i.connect(u),c.connect(o),u.connect(o),{type:"reverb",nodes:[i,l,c,u,o],input:i,output:o}}buildChorus(t,n){const a=t.createGain(),s=t.createGain(),i=[{delayMs:20,lfoFreq:.5,depth:.003},{delayMs:25,lfoFreq:.7,depth:.004},{delayMs:30,lfoFreq:1.1,depth:.005}],o=[a,s],l=t.createGain();l.gain.value=.7,a.connect(l),l.connect(s),o.push(l);for(const c of i){const u=t.createDelay(.1);u.delayTime.value=c.delayMs/1e3;const h=t.createOscillator();h.type="sine",h.frequency.value=c.lfoFreq;const p=t.createGain();p.gain.value=c.depth*(.5+n),h.connect(p),p.connect(u.delayTime);const f=t.createGain();f.gain.value=.3+n*.2,a.connect(u),u.connect(f),f.connect(s),h.start(),o.push(u,h,p,f)}return{type:"chorus",nodes:o,input:a,output:s}}buildFlanger(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.02);i.delayTime.value=.005;const o=t.createOscillator();o.type="sine",o.frequency.value=.2+n*2;const l=t.createGain();l.gain.value=.003+n*.002,o.connect(l),l.connect(i.delayTime);const c=t.createGain();c.gain.value=.5+n*.35;const u=t.createGain();u.gain.value=.5+n*.3;const h=t.createGain();return h.gain.value=1,a.connect(i),i.connect(c),c.connect(i),i.connect(u),a.connect(h),u.connect(s),h.connect(s),o.start(),{type:"flanger",nodes:[a,i,o,l,c,u,h,s],input:a,output:s}}buildDistortion(t,n,a){const s=t.createGain(),i=t.createGain(),o=t.createWaveShaper();o.curve=sr(n),o.oversample="4x";const l=t.createGain();l.gain.value=.6+a*.4;const c=t.createGain();return c.gain.value=1-a*.4,s.connect(o),o.connect(l),s.connect(c),l.connect(i),c.connect(i),{type:"distortion",nodes:[s,o,l,c,i],input:s,output:i}}buildBandpass(t,n,a,s){const i=t.createGain(),o=t.createGain(),l=t.createBiquadFilter();l.type="highpass",l.frequency.value=n,l.Q.value=.7;const c=t.createBiquadFilter();return c.type="lowpass",c.frequency.value=a,c.Q.value=.7,i.connect(l),l.connect(c),c.connect(o),{type:"telephone",nodes:[i,l,c,o],input:i,output:o}}buildMegaphone(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500;const o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=4e3;const l=t.createWaveShaper();l.curve=sr(15+n*30),l.oversample="2x";const c=t.createBiquadFilter();return c.type="peaking",c.frequency.value=2e3,c.gain.value=6+n*6,c.Q.value=1,a.connect(i),i.connect(o),o.connect(l),l.connect(c),c.connect(s),{type:"megaphone",nodes:[a,i,o,l,c,s],input:a,output:s}}buildRadio(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=300+n*200;const o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=3e3-n*500;const l=t.createBiquadFilter();l.type="peaking",l.frequency.value=1500,l.gain.value=8,l.Q.value=2;const c=t.createWaveShaper();return c.curve=sr(10),a.connect(i),i.connect(o),o.connect(l),l.connect(c),c.connect(s),{type:"radio",nodes:[a,i,o,l,c,s],input:a,output:s}}buildUnderwater(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="lowpass",i.frequency.value=300+(1-n)*400,i.Q.value=5+n*10;const o=t.createOscillator();o.type="sine",o.frequency.value=.5+n*2;const l=t.createGain();l.gain.value=100+n*200,o.connect(l),l.connect(i.frequency);const c=t.createGain();c.gain.value=.7+n*.3;const u=t.createGain();return u.gain.value=.3-n*.2,a.connect(i),i.connect(c),a.connect(u),c.connect(s),u.connect(s),o.start(),{type:"underwater",nodes:[a,i,o,l,c,u,s],input:a,output:s}}buildWhisper(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500+n*500,i.Q.value=.5;const o=t.createWaveShaper(),l=new Float32Array(256);for(let u=0;u<256;u++){const h=u/255*2-1;l[u]=Math.sign(h)*Math.pow(Math.abs(h),.3+n*.5)}o.curve=l;const c=t.createBiquadFilter();return c.type="highshelf",c.frequency.value=3e3,c.gain.value=6+n*6,a.connect(i),i.connect(o),o.connect(c),c.connect(s),{type:"whisper",nodes:[a,i,o,c,s],input:a,output:s}}buildDemon(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.1);i.delayTime.value=.03;const o=t.createOscillator();o.type="sawtooth",o.frequency.value=2+n*3;const l=t.createGain();l.gain.value=.02+n*.015,o.connect(l),l.connect(i.delayTime);const c=t.createWaveShaper();c.curve=sr(20+n*50),c.oversample="2x";const u=t.createBiquadFilter();u.type="lowshelf",u.frequency.value=200,u.gain.value=8+n*8;const h=t.createGain();h.gain.value=.7+n*.3;const p=t.createGain();return p.gain.value=.3,a.connect(i),i.connect(c),c.connect(u),u.connect(h),a.connect(p),h.connect(s),p.connect(s),o.start(),{type:"demon",nodes:[a,i,o,l,c,u,h,p,s],input:a,output:s}}buildTremolo(t,n){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=1;const o=t.createOscillator();o.type="sine",o.frequency.value=3+n*12;const l=t.createGain();return l.gain.value=.3+n*.5,o.connect(l),l.connect(i.gain),a.connect(i),i.connect(s),o.start(),{type:"tremolo",nodes:[a,i,o,l,s],input:a,output:s}}buildAutotune(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.05);i.delayTime.value=.005;const o=t.createOscillator();o.type="sine",o.frequency.value=6+n*8;const l=t.createGain();l.gain.value=.002+n*.002,o.connect(l),l.connect(i.delayTime);const c=[],u=[261.6,293.7,329.6,349.2,392,440,493.9,523.3],h=t.createGain();h.gain.value=.15;for(const y of u){const m=t.createBiquadFilter();m.type="peaking",m.frequency.value=y,m.Q.value=8+n*15,m.gain.value=4+n*8,a.connect(m),m.connect(h),c.push(m)}const p=t.createGain();p.gain.value=.7;const f=t.createGain();return f.gain.value=.5+n*.3,a.connect(i),i.connect(f),h.connect(f),a.connect(p),f.connect(s),p.connect(s),o.start(),{type:"autotune",nodes:[a,i,o,l,...c,h,f,p,s],input:a,output:s}}buildVocoder(t,n){const a=t.createGain(),s=t.createGain(),i=t.createOscillator();i.type="sawtooth",i.frequency.value=110+n*110;const o=t.createGain();o.gain.value=0;const l=8,c=[a,s,i,o],u=t.createGain();u.gain.value=.5+n*.5,c.push(u);for(let p=0;p<l;p++){const f=200*Math.pow(2,p*.5),y=t.createBiquadFilter();y.type="bandpass",y.frequency.value=f,y.Q.value=4;const m=t.createBiquadFilter();m.type="bandpass",m.frequency.value=f,m.Q.value=4;const g=t.createGain();g.gain.value=0,a.connect(y),y.connect(g.gain),i.connect(m),m.connect(g),g.connect(u),c.push(y,m,g)}u.connect(s);const h=t.createGain();return h.gain.value=.3-n*.2,a.connect(h),h.connect(s),c.push(h),i.start(),{type:"vocoder",nodes:c,input:a,output:s}}}const mm={sparkle:se.NtdSparkle,music:se.NtdMusic,skull:se.NtdSkull,robot:se.NtdRobot,ghost:se.NtdGhost,mountain:se.NtdMountain,wave:se.NtdWave,lightning:se.NtdLightning,phone:se.NtdPhone,megaphone:se.NtdMegaphone,"volume-mute":se.NtdVolumeMute,microphone:se.NtdMicrophone,volume:se.NtdVolume},gm=({deviceId:e,mediaStream:t,compact:n=!1,t:a,className:s,style:i,id:o,accessMode:l,"data-testid":c})=>{const{t:u}=Te(),h=a??u,p=d.useRef(null),[f,y]=d.useState(!1),[m,g]=d.useState(()=>Al.map(A=>({...A}))),[b,x]=d.useState(!0),[k,v]=d.useState(80),[w,M]=d.useState(100),[S,R]=d.useState(0),T=d.useRef(0),j=d.useCallback(()=>{const A=()=>{var _;(_=p.current)!=null&&_.isStarted&&(R(p.current.getLevel()),T.current=requestAnimationFrame(A))};T.current=requestAnimationFrame(A)},[]),O=d.useCallback(()=>{T.current&&cancelAnimationFrame(T.current)},[]),$=d.useCallback(async()=>{const A=new El;p.current=A;try{t?await A.startWithStream(t):await A.start(e),A.setMonitoring(b),A.setVolume(k/100),A.setInputGain(w/100);for(const _ of m)_.enabled&&A.addEffect(_.type,_.intensity);y(!0),j()}catch(_){typeof console<"u"&&console.warn("[VocalEffectsRack] start error",_)}},[e,t,b,k,w,m,j]),E=d.useCallback(()=>{var A;O(),(A=p.current)==null||A.stop(),p.current=null,y(!1),R(0)},[O]);d.useEffect(()=>()=>{var A;O(),(A=p.current)==null||A.stop(),p.current=null},[O]);const D=d.useCallback(A=>{g(_=>_.map(U=>{var V;if(U.type!==A)return U;const ne={...U,enabled:!U.enabled};return(V=p.current)!=null&&V.isStarted&&(ne.enabled?p.current.addEffect(A,ne.intensity):p.current.removeEffect(A)),ne}))},[]),L=d.useCallback((A,_)=>{g(U=>U.map(ne=>{var V;return ne.type!==A?ne:(ne.enabled&&((V=p.current)!=null&&V.isStarted)&&p.current.updateIntensity(A,_),{...ne,intensity:_})}))},[]);d.useEffect(()=>{var A;(A=p.current)==null||A.setVolume(k/100)},[k]),d.useEffect(()=>{var A;(A=p.current)==null||A.setInputGain(w/100)},[w]),d.useEffect(()=>{var A;(A=p.current)==null||A.setMonitoring(b)},[b]);const W=d.useCallback(()=>{var A;(A=p.current)==null||A.clearAllEffects(),g(_=>_.map(U=>({...U,enabled:!1})))},[]),Z=m.filter(A=>A.enabled).length;return l==="hidden"?null:r.jsxs("div",{className:`nice-vocal-effects-rack${s?` ${s}`:""}`,style:{border:"1px solid var(--nice-border, #e2e8f0)",borderRadius:12,padding:n?12:20,background:"var(--bg-secondary)",color:"var(--nice-text, inherit)",...i},id:o,"data-testid":c,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16,gap:8},children:[r.jsxs("h3",{style:{margin:0,fontSize:n?16:20,display:"flex",alignItems:"center",gap:8},children:[r.jsx(se.NtdMicrophone,{size:n?16:20})," ",h("vocalEffects.title","Vocal effects")]}),r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[Z>0&&r.jsxs(we.NiceBadge,{variant:"primary",children:[Z," ",h("vocalEffects.active","active")]}),f?r.jsx(we.NiceButton,{variant:"danger",size:"sm",onClick:E,children:h("vocalEffects.stop","Stop")}):r.jsx(we.NiceButton,{variant:"primary",size:"sm",onClick:$,children:h("vocalEffects.start","Start mic")})]})]}),r.jsxs("div",{style:{display:"flex",gap:16,alignItems:"center",marginBottom:16,flexWrap:"wrap"},children:[r.jsx(we.NiceToggle,{checked:b,onChange:x,label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(se.NtdVolume,{size:14})," ",h("vocalEffects.monitor","Monitor")]})}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[h("vocalEffects.volume","Vol"),r.jsx("div",{style:{width:100},children:r.jsx(we.NiceSlider,{value:k,onChange:v,min:0,max:200})}),r.jsxs("span",{style:{minWidth:36,fontSize:12},children:[k,"%"]})]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[h("vocalEffects.gain","Gain"),r.jsx("div",{style:{width:100},children:r.jsx(we.NiceSlider,{value:w,onChange:M,min:0,max:300})}),r.jsxs("span",{style:{minWidth:36,fontSize:12},children:[w,"%"]})]}),f&&r.jsx("div",{style:{width:80,height:8,borderRadius:4,background:"var(--bg-tertiary)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${Math.min(100,S*300)}%`,background:S>.5?"var(--nice-danger, #ef4444)":S>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})}),Z>0&&r.jsx(we.NiceButton,{variant:"ghost",size:"sm",onClick:W,children:h("vocalEffects.clearAll","Clear all")})]}),r.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(auto-fill, minmax(${n?130:160}px, 1fr))`,gap:n?6:10},children:m.map(A=>r.jsxs("div",{style:{border:A.enabled?"2px solid var(--nice-accent, #3b82f6)":"1px solid var(--nice-border, #e2e8f0)",borderRadius:10,padding:n?"6px 8px":"10px 12px",background:A.enabled?"var(--nice-accent-tint-10, rgba(59,130,246,0.08))":"transparent",transition:"all 0.15s ease"},children:[r.jsxs("button",{type:"button",onClick:()=>D(A.type),style:{display:"flex",alignItems:"center",gap:6,width:"100%",marginBottom:A.enabled?6:0,background:"transparent",border:"none",cursor:"pointer",color:"inherit",textAlign:"left"},children:[(()=>{const _=mm[A.icon]??se.NtdMusic;return r.jsx(_,{size:n?18:22})})(),r.jsx("span",{style:{fontSize:n?12:14,fontWeight:A.enabled?700:500,color:A.enabled?"var(--nice-accent, #3b82f6)":"inherit"},children:A.label})]}),A.enabled&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},onClick:_=>_.stopPropagation(),children:[r.jsx("div",{style:{flex:1},children:r.jsx(we.NiceSlider,{value:A.intensity,onChange:_=>L(A.type,_),min:0,max:100})}),r.jsx("span",{style:{fontSize:11,minWidth:24,color:"var(--nice-text-muted, #64748b)"},children:A.intensity})]})]},A.type))}),r.jsx("div",{style:{marginTop:12,fontSize:12,color:"var(--nice-text-muted, #94a3b8)",textAlign:"center"},children:h("vocalEffects.hint","Click effects to toggle. Multiple effects can be active at once — adjust intensity with the slider.")})]})},Il={algorithm:"pitchy",gain:1,rmsThreshold:.02,pitchThreshold:.6,smoothingWindow:3,hysteresisFrames:2,useHanning:!1,offsetMs:0},ym=[{value:"pitchy",label:"Pitchy (fast)"},{value:"autocorrelation",label:"Autocorrelation"},{value:"librosa",label:"Librosa (server)"},{value:"crepe",label:"CREPE (AI, server)"}],bm=({deviceId:e,onDeviceChange:t,settings:n,onSettingsChange:a,audioInputs:s,algorithms:i=ym,showLevelMeter:o=!0,onCalibrate:l,compact:c=!1,t:u})=>{const{t:h}=Te(),p=u??h,f=d.useMemo(()=>({...Il,...n}),[n]),y=$=>a==null?void 0:a({...f,...$}),[m,g]=d.useState([]);d.useEffect(()=>{var D,L,W;if(s||!((D=navigator.mediaDevices)!=null&&D.enumerateDevices))return;let $=!1;const E=()=>navigator.mediaDevices.enumerateDevices().then(Z=>!$&&g(Z.filter(A=>A.kind==="audioinput"))).catch(()=>{});return E(),(W=(L=navigator.mediaDevices).addEventListener)==null||W.call(L,"devicechange",E),()=>{var Z,A;$=!0,(A=(Z=navigator.mediaDevices).removeEventListener)==null||A.call(Z,"devicechange",E)}},[s]);const b=s??m,x=d.useMemo(()=>b.map(($,E)=>({value:$.deviceId,label:$.label||`${p("audioInput.microphone","Microphone")} ${E+1}`})),[b,p]),[k,v]=d.useState(!1),[w,M]=d.useState(0),S=d.useRef(null),R=()=>{const $=S.current;$&&(cancelAnimationFrame($.raf),$.stream.getTracks().forEach(E=>E.stop()),$.ctx.close().catch(()=>{}),S.current=null),v(!1),M(0)},T=async()=>{try{const $=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0}}),E=new AudioContext,D=E.createMediaStreamSource($),L=E.createAnalyser();L.fftSize=1024,D.connect(L);const W=new Float32Array(L.fftSize),Z=()=>{L.getFloatTimeDomainData(W);let A=0;for(let _=0;_<W.length;_++)A+=W[_]*W[_];M(Math.sqrt(A/W.length)*(f.gain||1)),S.current.raf=requestAnimationFrame(Z)};S.current={ctx:E,stream:$,raf:requestAnimationFrame(Z)},v(!0)}catch{}};d.useEffect(()=>()=>R(),[]);const j={fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:4,display:"block"},O=($,E,D)=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[r.jsx("span",{style:{flex:"0 0 120px",fontSize:13},children:$}),r.jsx("div",{style:{flex:1},children:E}),r.jsx("span",{style:{flex:"0 0 48px",textAlign:"right",fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:D})]});return r.jsxs("div",{className:"nice-audio-input-picker",style:{display:"flex",flexDirection:"column",gap:c?8:12,border:"1px solid var(--nice-border, #e2e8f0)",borderRadius:12,padding:c?12:16,color:"var(--nice-text, inherit)"},children:[r.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap"},children:[r.jsxs("div",{style:{flex:"1 1 220px",minWidth:180},children:[r.jsxs("label",{style:{...j,display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(se.NtdMicrophone,{size:13})," ",p("audioInput.device","Microphone")]}),r.jsx(we.NiceSelect,{options:x,value:e??"",onChange:$=>t==null?void 0:t(typeof $=="string"?$:$[0]),placeholder:p("audioInput.selectDevice","Select microphone"),size:"sm"})]}),r.jsxs("div",{style:{flex:"1 1 200px",minWidth:160},children:[r.jsx("label",{style:j,children:p("audioInput.algorithm","Pitch algorithm")}),r.jsx(we.NiceSelect,{options:i,value:f.algorithm,onChange:$=>y({algorithm:typeof $=="string"?$:$[0]}),size:"sm"})]})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[O(p("audioInput.gain","Gain"),r.jsx(we.NiceSlider,{value:Math.round(f.gain*100),onChange:$=>y({gain:$/100}),min:0,max:300}),`${Math.round(f.gain*100)}%`),O(p("audioInput.rmsThreshold","RMS gate"),r.jsx(we.NiceSlider,{value:Math.round(f.rmsThreshold*1e3),onChange:$=>y({rmsThreshold:$/1e3}),min:0,max:200}),f.rmsThreshold.toFixed(3)),O(p("audioInput.pitchThreshold","Pitch clarity"),r.jsx(we.NiceSlider,{value:Math.round(f.pitchThreshold*100),onChange:$=>y({pitchThreshold:$/100}),min:0,max:100}),f.pitchThreshold.toFixed(2)),!c&&O(p("audioInput.smoothing","Smoothing"),r.jsx(we.NiceSlider,{value:f.smoothingWindow,onChange:$=>y({smoothingWindow:$}),min:0,max:12}),`${f.smoothingWindow}`),!c&&O(p("audioInput.hysteresis","Hysteresis"),r.jsx(we.NiceSlider,{value:f.hysteresisFrames,onChange:$=>y({hysteresisFrames:$}),min:0,max:12}),`${f.hysteresisFrames}`),!c&&O(p("audioInput.offset","Latency"),r.jsx(we.NiceSlider,{value:f.offsetMs,onChange:$=>y({offsetMs:$}),min:-200,max:500}),`${f.offsetMs}ms`)]}),r.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap"},children:[r.jsx(we.NiceToggle,{checked:f.useHanning,onChange:$=>y({useHanning:$}),label:p("audioInput.hanning","Hanning window")}),o&&r.jsxs(r.Fragment,{children:[r.jsx(we.NiceButton,{variant:k?"danger":"secondary",size:"sm",onClick:k?R:T,children:k?p("audioInput.stopTest","Stop test"):p("audioInput.testMic","Test mic")}),r.jsx("div",{style:{width:100,height:8,borderRadius:4,background:"var(--bg-tertiary)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${Math.min(100,w*300)}%`,background:w>.5?"var(--nice-danger, #ef4444)":w>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})})]}),l&&e&&r.jsxs(we.NiceButton,{variant:"ghost",size:"sm",onClick:()=>l(e),children:[r.jsx(se.NtdSettings,{size:14})," ",p("audioInput.calibrate","Calibrate latency")]})]})]})};class Ll{constructor(t,n){this.activeNotes=new Map,this.audioContext=t,this.masterGain=t.createGain(),this.masterGain.gain.value=.3,this.masterGain.connect(n)}applyCC(t,n,a){}midiToFreq(t){return 440*Math.pow(2,(t-69)/12)}playNote(t,n=100,a=1,s="sine"){const i=this.midiToFreq(t),o=this.audioContext.createOscillator(),l=this.audioContext.createGain();o.type=s,o.frequency.value=i;const c=n/127*.8;l.gain.value=c,o.connect(l),l.connect(this.masterGain);const u=this.audioContext.currentTime;return l.gain.setValueAtTime(0,u),l.gain.linearRampToValueAtTime(c,u+.01),l.gain.exponentialRampToValueAtTime(c*.7,u+.1),l.gain.setValueAtTime(c*.7,u+a-.05),l.gain.exponentialRampToValueAtTime(.001,u+a),o.start(u),o.stop(u+a),o.onended=()=>{l.disconnect(),o.disconnect()},{osc:o,gain:l}}scheduleNote(t,n,a,s=100,i="sine"){const o=this.midiToFreq(t),l=this.audioContext.createOscillator(),c=this.audioContext.createGain();l.type=i,l.frequency.value=o;const u=s/127*.8;l.connect(c),c.connect(this.masterGain);const h=n;return c.gain.setValueAtTime(0,h),c.gain.linearRampToValueAtTime(u,h+.01),c.gain.exponentialRampToValueAtTime(u*.7,h+.1),c.gain.setValueAtTime(u*.7,h+a-.05),c.gain.exponentialRampToValueAtTime(.001,h+a),l.start(h),l.stop(h+a),l.onended=()=>{c.disconnect(),l.disconnect()},{osc:l,gain:c}}setVolume(t){this.masterGain.gain.value=Math.max(0,Math.min(1,t))}stopAll(){this.activeNotes.forEach(({osc:t,gain:n})=>{try{t.stop(),n.disconnect(),t.disconnect()}catch{}}),this.activeNotes.clear()}dispose(){this.stopAll(),this.masterGain.disconnect()}}const ki=it.scoped("AudioPlaybackEngine");class xm{constructor(){this.audioContext=null,this.masterGain=null,this.masterFilter=null,this.clips=new Map,this.scheduledSources=new Map,this.midiTracks=new Map,this.synths=new Map,this.isPlaying=!1,this.startTimeOffset=0,this.audioContextStartTime=0,this.currentTime=0,this.loopRegion={start:0,end:0,enabled:!1},this.bpm=120,this.duration=0,this.initAudioContext()}setMidiCCEvents(t,n){const a=this.midiTracks.get(t);a&&(a.ccEvents=n)}getMidiCCEvents(t){const n=this.midiTracks.get(t);return(n==null?void 0:n.ccEvents)||[]}addMidiCCEvent(t,n){const a=this.midiTracks.get(t);a&&(a.ccEvents||(a.ccEvents=[]),a.ccEvents.push(n))}removeMidiCCEvent(t,n){const a=this.midiTracks.get(t);a&&a.ccEvents&&(a.ccEvents=a.ccEvents.filter(s=>s.id!==n))}initAudioContext(){try{this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.masterGain=this.audioContext.createGain(),this.masterFilter=this.audioContext.createBiquadFilter(),this.masterFilter.type="peaking",this.masterFilter.frequency.value=1200,this.masterFilter.Q.value=.7,this.masterFilter.gain.value=0,this.masterGain.connect(this.masterFilter),this.masterFilter.connect(this.audioContext.destination),this.masterGain.gain.value=.8,this.audioContext.state==="suspended"&&this.audioContext.resume()}catch(t){ki.error("Failed to initialize AudioContext:",t)}}createEffectNode(t){if(!this.audioContext||t.bypass)return null;try{switch(t.type){case"eq3":{const n=this.audioContext.createBiquadFilter(),a=this.audioContext.createBiquadFilter(),s=this.audioContext.createBiquadFilter();return n.type="lowshelf",n.frequency.value=t.params.lowFreq||250,n.gain.value=t.params.lowGain||0,a.type="peaking",a.frequency.value=1e3,a.Q.value=1,a.gain.value=t.params.midGain||0,s.type="highshelf",s.frequency.value=t.params.highFreq||4e3,s.gain.value=t.params.highGain||0,n.connect(a),a.connect(s),{input:n,output:s}}case"compressor":{const n=this.audioContext.createDynamicsCompressor();return n.threshold.value=t.params.threshold||-24,n.ratio.value=t.params.ratio||4,n.attack.value=t.params.attack||.003,n.release.value=t.params.release||.25,n.knee.value=t.params.knee||30,n}case"delay":{const n=this.audioContext.createDelay(5);n.delayTime.value=t.params.time||.25;const a=this.audioContext.createGain();a.gain.value=t.params.feedback||.3;const s=this.audioContext.createGain();s.gain.value=t.params.mix||.3;const i=this.audioContext.createGain();return i.gain.value=1-(t.params.mix||.3),n.connect(a),a.connect(n),n.connect(s),{input:n,output:s,dry:i,connect:function(o){s.connect(o),i.connect(o)}}}case"reverb":{const n=this.audioContext.createConvolver(),a=this.audioContext.sampleRate*(t.params.decay||2),s=this.audioContext.createBuffer(2,a,this.audioContext.sampleRate);for(let l=0;l<2;l++){const c=s.getChannelData(l);for(let u=0;u<a;u++)c[u]=(Math.random()*2-1)*Math.pow(1-u/a,2)}n.buffer=s;const i=this.audioContext.createGain();i.gain.value=t.params.mix||.3;const o=this.audioContext.createGain();return o.gain.value=1-(t.params.mix||.3),n.connect(i),{input:n,output:i,dry:o,connect:function(l){i.connect(l),o.connect(l)}}}case"distortion":{const n=this.audioContext.createWaveShaper(),a=t.params.amount||20,s=44100,i=new Float32Array(s),o=Math.PI/180;for(let u=0;u<s;u++){const h=u*2/s-1;i[u]=(3+a)*h*20*o/(Math.PI+a*Math.abs(h))}n.curve=i,n.oversample="4x";const l=this.audioContext.createGain();l.gain.value=t.params.mix||.5;const c=this.audioContext.createGain();return c.gain.value=1-(t.params.mix||.5),n.connect(l),{input:n,output:l,dry:c,connect:function(u){l.connect(u),c.connect(u)}}}default:return null}}catch(n){return ki.error("Failed to create effect node:",t.type,n),null}}addClip(t){this.clips.set(t.id,t),this.updateDuration()}removeClip(t){this.clips.delete(t),this.stopClip(t),this.updateDuration()}updateClip(t,n){const a=this.clips.get(t);a&&(Object.assign(a,n),this.updateDuration())}getClipsByLayer(t){return Array.from(this.clips.values()).filter(n=>n.layerId===t)}setMidiTrack(t,n,a="sine",s=.5){if(this.midiTracks.set(t,{layerId:t,notes:n,instrument:a,volume:s}),!this.synths.has(t)&&this.audioContext&&this.masterGain){const i=new Ll(this.audioContext,this.masterGain);i.setVolume(s),this.synths.set(t,i)}}removeMidiTrack(t){this.midiTracks.delete(t);const n=this.synths.get(t);n&&(n.dispose(),this.synths.delete(t))}updateMidiTrackVolume(t,n){const a=this.midiTracks.get(t);a&&(a.volume=n);const s=this.synths.get(t);s&&s.setVolume(n)}updateDuration(){let t=0;this.clips.forEach(n=>{const a=n.startTime+n.duration;a>t&&(t=a)}),this.duration=t}play(){!this.audioContext||this.isPlaying||(this.audioContext.state==="suspended"&&this.audioContext.resume(),this.isPlaying=!0,this.audioContextStartTime=this.audioContext.currentTime,this.startTimeOffset=this.currentTime,this.scheduleClips(),this.scheduleMidiNotes(),this.startTimeTracking(),this.onPlayStateChange&&this.onPlayStateChange(!0))}pause(){this.isPlaying&&(this.isPlaying=!1,this.stopAllSources(),this.onPlayStateChange&&this.onPlayStateChange(!1))}stop(){this.pause(),this.seek(0)}seek(t){const n=this.isPlaying;n&&this.pause(),this.currentTime=Math.max(0,Math.min(t,this.duration)),this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),n&&this.play()}scheduleClips(){!this.audioContext||!this.masterGain||this.clips.forEach(t=>{if(t.startTime+t.duration<=this.currentTime)return;const a=this.audioContext.createBufferSource();a.buffer=t.buffer,t.stretchFactor&&t.stretchFactor!==1&&(a.playbackRate.value=1/t.stretchFactor);const s=this.audioContext.createGain();s.gain.value=t.volume;const i=this.audioContext.createStereoPanner();i.pan.value=t.pan,a.connect(s);let o=s;if(t.effectChain&&t.effectChain.length>0)for(const h of t.effectChain){const p=this.createEffectNode(h);if(p)if("input"in p&&"output"in p){const f=p;o.connect(f.input),o=f.output,"dry"in p&&s.connect(f.dry)}else o.connect(p),o=p}o.connect(i),i.connect(this.masterGain);const l=t.startTime,c=Math.max(0,this.currentTime-l),u=this.audioContext.currentTime+(l-this.currentTime);u>=this.audioContext.currentTime&&(a.start(u,t.offset+c,t.duration-c),this.scheduledSources.set(t.id,a),a.onended=()=>{this.scheduledSources.delete(t.id)})})}stopClip(t){const n=this.scheduledSources.get(t);if(n){try{n.stop()}catch{}this.scheduledSources.delete(t)}}stopAllSources(){this.scheduledSources.forEach(t=>{try{t.stop()}catch{}}),this.scheduledSources.clear(),this.synths.forEach(t=>t.stopAll())}scheduleMidiNotes(){this.audioContext&&this.midiTracks.forEach(t=>{const n=this.synths.get(t.layerId);if(n&&(t.notes.forEach(a=>{if(a.start+a.duration<=this.currentTime)return;const i=Math.max(0,this.currentTime-a.start),o=this.audioContext.currentTime+(a.start-this.currentTime);o>=this.audioContext.currentTime&&n.scheduleNote(a.pitch,o,a.duration-i,a.velocity,t.instrument)}),t.ccEvents&&Array.isArray(t.ccEvents)&&t.ccEvents.length>0)){const a=[...t.ccEvents].sort((o,l)=>o.time-l.time);let i=a[0];for(let o=1;o<a.length;++o){const l=a[o],c=i.time,u=l.time,h=i.value,p=l.value,f=i.handleType||"linear",y=Math.max(2,Math.ceil((u-c)*20));for(let m=0;m<=y;++m){const g=m/y;let b=h;if(f==="linear")b=h+(p-h)*g;else if(f==="step")b=g<1?h:p;else if(f==="exp"){const w=Math.max(h/127,.001),M=Math.max(p/127,.001);b=w*Math.pow(M/w,g)*127}const x=c+(u-c)*g,k=this.audioContext.currentTime+(x-this.currentTime);k>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(l.cc,b,k)}i=l}}})}startTimeTracking(){if(!this.audioContext)return;const t=()=>{if(!this.isPlaying||!this.audioContext)return;const n=this.audioContext.currentTime-this.audioContextStartTime;if(this.currentTime=this.startTimeOffset+n,this.loopRegion.enabled&&this.currentTime>=this.loopRegion.end){this.seek(this.loopRegion.start);return}if(this.currentTime>=this.duration){this.stop();return}this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),requestAnimationFrame(t)};requestAnimationFrame(t)}setLoopRegion(t,n,a){this.loopRegion={start:t,end:n,enabled:a}}setBPM(t){this.bpm=Math.max(20,Math.min(300,t))}getBPM(){return this.bpm}setMasterVolume(t){this.masterGain&&(this.masterGain.gain.value=Math.max(0,Math.min(1,t)))}setMasterFilter(t){this.masterFilter&&(t.type&&(this.masterFilter.type=t.type),t.frequency!=null&&(this.masterFilter.frequency.value=Math.max(20,Math.min(2e4,t.frequency))),t.q!=null&&(this.masterFilter.Q.value=Math.max(.1,Math.min(18,t.q))),t.gain!=null&&"gain"in this.masterFilter&&(this.masterFilter.gain.value=Math.max(-40,Math.min(40,t.gain))))}getCurrentTime(){return this.currentTime}getDuration(){return this.duration}getIsPlaying(){return this.isPlaying}setOnTimeUpdate(t){this.onTimeUpdate=t}setOnPlayStateChange(t){this.onPlayStateChange=t}dispose(){this.stop(),this.audioContext&&this.audioContext.close(),this.clips.clear()}}const vm=[{name:"Grand Piano",waveform:"sawtooth",attack:.02,sustain:.7,release:1.2,eq:{C:2,D:1,E:1,F:0,G:0,A:-1,B:-2,C2:-3},category:"Keyboard"},{name:"Electric Piano",waveform:"triangle",attack:.03,sustain:.8,release:1,eq:{C:0,D:1,E:2,F:3,G:1,A:-1,B:-2,C2:-2},category:"Keyboard"},{name:"Harpsichord",waveform:"square",attack:.01,sustain:.5,release:.6,eq:{C:-1,D:-1,E:0,F:2,G:3,A:1,B:0,C2:-1},category:"Keyboard"},{name:"Violin",waveform:"triangle",attack:.3,sustain:1,release:1.5,eq:{C:3,D:2,E:2,F:1,G:-1,A:-2,B:-3,C2:-3},category:"String"},{name:"Acoustic Guitar",waveform:"sawtooth",attack:.2,sustain:.6,release:.9,eq:{C:-1,D:-2,E:0,F:1,G:3,A:2,B:0,C2:-2},category:"String"},{name:"Electric Guitar",waveform:"square",attack:.05,sustain:.7,release:1.2,eq:{C:-2,D:1,E:2,F:2,G:1,A:0,B:-1,C2:-3},category:"String"},{name:"Kick Drum",waveform:"sine",attack:.005,sustain:.1,release:.2,eq:{C:5,D:3,E:0,F:-3,G:-5,A:-7,B:-9,C2:-10},category:"Percussion"},{name:"Snare Drum",waveform:"triangle",attack:.01,sustain:.2,release:.3,eq:{C:-2,D:-1,E:1,F:2,G:3,A:2,B:0,C2:-2},category:"Percussion"},{name:"Hi-Hat",waveform:"square",attack:.002,sustain:.05,release:.1,eq:{C:-5,D:-3,E:0,F:2,G:5,A:7,B:9,C2:10},category:"Percussion"},{name:"Acoustic Bass",waveform:"sine",attack:.08,sustain:.8,release:1.2,eq:{C:4,D:3,E:2,F:1,G:0,A:-1,B:-2,C2:-3},category:"Bass"},{name:"Electric Bass",waveform:"square",attack:.05,sustain:.9,release:1.3,eq:{C:3,D:2,E:1,F:0,G:-1,A:-2,B:-3,C2:-4},category:"Bass"},{name:"Trumpet",waveform:"sawtooth",attack:.1,sustain:.9,release:1.5,eq:{C:2,D:3,E:4,F:5,G:3,A:1,B:-1,C2:-3},category:"Brass"},{name:"Trombone",waveform:"triangle",attack:.2,sustain:1,release:1.7,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-2,C2:-4},category:"Brass"},{name:"Saxophone",waveform:"sawtooth",attack:.15,sustain:.8,release:1.3,eq:{C:2,D:3,E:4,F:3,G:1,A:-1,B:-2,C2:-3},category:"Woodwind"},{name:"Clarinet",waveform:"triangle",attack:.18,sustain:.9,release:1.6,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-1,C2:-2},category:"Woodwind"},{name:"Saw Synth",waveform:"sawtooth",attack:.05,sustain:.9,release:1.2,eq:{C:2,D:3,E:4,F:3,G:2,A:0,B:-1,C2:-2},category:"Synth"},{name:"Square Lead",waveform:"square",attack:.04,sustain:.85,release:1.1,eq:{C:2,D:3,E:4,F:3,G:1,A:0,B:-1,C2:-3},category:"Synth"}];function Br(e={}){const{channelFilter:t,sysex:n=!1,onEvent:a,inputNameIncludes:s,onInputsChanged:i}=e,[o,l]=d.useState(null),[c,u]=d.useState(!1),[h,p]=d.useState([]),f=d.useRef(null),y=d.useCallback((m,g)=>{const b=m.data??new Uint8Array(0),x=b[0]??0,k=b[1]??0,v=b[2]??0,w=m.timeStamp,M=x&240,S=x&15,R=g.id,T=g.name??"MIDI Input",j=t===void 0||t===S;if((M===144||M===128)&&j){const O=M===144&&v>0;return{type:O?"noteon":"noteoff",note:k,velocity:O?v:0,channel:S,ts:w,deviceId:R,deviceName:T}}return M===176&&j?{type:"cc",controller:k,value:v,channel:S,ts:w,deviceId:R,deviceName:T}:M===208&&j?{type:"aftertouch",pressure:k,channel:S,ts:w,deviceId:R,deviceName:T}:M===224&&j?{type:"pitchbend",value:(k|v<<7)-8192,channel:S,ts:w,deviceId:R,deviceName:T}:M===192&&j?{type:"program",program:k,channel:S,ts:w,deviceId:R,deviceName:T}:{type:"unknown",status:x,data1:k,data2:v,channel:S,ts:w,deviceId:R,deviceName:T}},[t]);return d.useEffect(()=>{if(!("requestMIDIAccess"in navigator)){l(!1);return}l(!0);let m=!1;return navigator.requestMIDIAccess({sysex:n}).then(g=>{if(m)return;f.current=g,u(!0);const b=()=>{const x=Array.from(g.inputs.values()),k=s?x.filter(v=>(v.name||"").toUpperCase().includes(s.toUpperCase())):x;p(k),i==null||i(k),x.forEach(v=>v.onmidimessage=null),k.forEach(v=>{v.onmidimessage=w=>a==null?void 0:a(y(w,v))})};b(),g.onstatechange=()=>b()}),()=>{m=!0;const g=f.current;g&&(g.inputs.forEach(b=>b.onmidimessage=null),g.onstatechange=null)}},[s,a,i,y,n]),{supported:o,granted:c,inputs:h}}const ls="nice2dev.midiLearn";function Sm(){try{const e=localStorage.getItem(ls);return e?JSON.parse(e):{}}catch{return{}}}function wi(e){const t={};for(const n of e)t[n.id]={id:n.id,type:n.type,number:n.number,channel:n.channel,min:n.min,max:n.max};localStorage.setItem(ls,JSON.stringify(t))}function km(e){const{parameters:t,onParameterChange:n}=e,[a,s]=d.useState(()=>{const v=Sm();return t.map(w=>{const M=v[w.id];return{id:w.id,paramName:w.name,type:(M==null?void 0:M.type)??"cc",number:M==null?void 0:M.number,channel:M==null?void 0:M.channel,min:(M==null?void 0:M.min)??w.min??0,max:(M==null?void 0:M.max)??w.max??127,value:0}})}),[i,o]=d.useState({learning:!1,targetId:null}),[l,c]=d.useState(null),u=d.useRef(a);u.current=a;const h=d.useRef(n);h.current=n;const p=d.useRef(i);p.current=i;const f=d.useCallback(v=>{var M;c(v);const w=p.current;if(w.learning&&w.targetId){if(!u.current.find(T=>T.id===w.targetId))return;let R={};switch(v.type){case"cc":R={type:"cc",number:v.controller,channel:v.channel};break;case"noteon":R={type:"note",number:v.note,channel:v.channel};break;case"pitchbend":R={type:"pitchbend",channel:v.channel};break;case"aftertouch":R={type:"aftertouch",channel:v.channel};break;default:return}s(T=>{const j=T.map(O=>O.id===w.targetId?{...O,...R}:O);return wi(j),j}),o({learning:!1,targetId:null});return}for(const S of u.current){if(S.number===void 0&&S.type!=="pitchbend"&&S.type!=="aftertouch"||S.channel!==void 0&&v.channel!==S.channel)continue;let R=null,T=127;if(S.type==="cc"&&v.type==="cc"&&v.controller===S.number?R=v.value:S.type==="note"&&v.type==="noteon"&&v.note===S.number?R=v.velocity:S.type==="pitchbend"&&v.type==="pitchbend"?(R=v.value+8192,T=16383):S.type==="aftertouch"&&v.type==="aftertouch"&&(R=v.pressure),R!==null){const j=R/T,O=S.min+j*(S.max-S.min);s($=>$.map(E=>E.id===S.id?{...E,value:j}:E)),(M=h.current)==null||M.call(h,S.id,O,j)}}},[]),{supported:y,granted:m}=Br({onEvent:f}),g=d.useCallback(v=>{o({learning:!0,targetId:v})},[]),b=d.useCallback(()=>{o({learning:!1,targetId:null})},[]),x=d.useCallback(v=>{s(w=>{const M=w.map(S=>S.id===v?{...S,type:"cc",number:void 0,channel:void 0}:S);return wi(M),M})},[]),k=d.useCallback(()=>{s(v=>{const w=v.map(M=>({...M,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(ls),w})},[]);return{bindings:a,startLearn:g,cancelLearn:b,removeBinding:x,clearAll:k,learnState:i,midiSupported:y,midiGranted:m,lastEvent:l}}const wm={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function jm(e={}){const{lowerZone:t=wm,onNoteExpression:n,onNoteOn:a,onNoteOff:s}=e,[i,o]=d.useState([]),l=d.useRef(new Map),c=d.useRef(n);c.current=n;const u=d.useRef(a);u.current=a;const h=d.useRef(s);h.current=s;const p=d.useRef(new Set(t.memberChannels));d.useEffect(()=>{p.current=new Set(t.memberChannels)},[t.memberChannels]);const f=d.useCallback(g=>{var x,k,v,w,M;if(!p.current.has(g.channel??-1))return;const b=`${g.channel}`;switch(g.type){case"noteon":{const S={note:g.note,channel:g.channel,velocity:g.velocity,pitchBend:0,pressure:0,slide:0,lastUpdate:g.ts};l.current.set(b,S),o(Array.from(l.current.values())),(x=u.current)==null||x.call(u,S);break}case"noteoff":{l.current.delete(b),o(Array.from(l.current.values())),(k=h.current)==null||k.call(h,g.channel,g.note);break}case"pitchbend":{const S=l.current.get(b);S&&(S.pitchBend=g.value,S.lastUpdate=g.ts,(v=c.current)==null||v.call(c,S),o(Array.from(l.current.values())));break}case"aftertouch":{const S=l.current.get(b);S&&(S.pressure=g.pressure,S.lastUpdate=g.ts,(w=c.current)==null||w.call(c,S),o(Array.from(l.current.values())));break}case"cc":{if(g.controller===74){const S=l.current.get(b);S&&(S.slide=g.value,S.lastUpdate=g.ts,(M=c.current)==null||M.call(c,S),o(Array.from(l.current.values())))}break}}},[]),{supported:y,granted:m}=Br({onEvent:f,sysex:!1});return{activeNotes:i,midiSupported:y,midiGranted:m}}const Cm={name:"M-Audio Oxygen 25 (MKIV)",deviceMatch:"OXYGEN",knobs:[{index:1,cc:21,label:"Knob 1"},{index:2,cc:22,label:"Knob 2"},{index:3,cc:23,label:"Knob 3"},{index:4,cc:24,label:"Knob 4"},{index:5,cc:25,label:"Knob 5"},{index:6,cc:26,label:"Knob 6"},{index:7,cc:27,label:"Knob 7"},{index:8,cc:28,label:"Knob 8"}],fader:{cc:7,label:"Fader (Channel Volume)"},pads:[{note:36,label:"Kick C1"},{note:38,label:"Snare D1"},{note:42,label:"HH Closed F#1"},{note:46,label:"HH Open A#1"},{note:48,label:"Tom1 C2"},{note:45,label:"Tom2 A1"},{note:43,label:"Floor G1"},{note:49,label:"Crash C#2"}],transport:{play:115,stop:114,record:117,rew:112,ff:113,loop:116}};function Mm(e={},t=Cm){const[n,a]=d.useState(()=>{const y=localStorage.getItem("oxygen25.layout");return y?JSON.parse(y):t}),[s,i]=d.useState([]),o=d.useRef({mode:"idle"}),l=d.useCallback(y=>{a(m=>{const g={...m,...y};return localStorage.setItem("oxygen25.layout",JSON.stringify(g)),g})},[]),c=d.useCallback(y=>{var b,x,k,v,w,M,S,R,T;const m=y.deviceName||"MIDI";i(j=>j.includes(m)?j:[...j,m]);const g=o.current;if(g.mode!=="idle"){if(g.mode==="knob"&&y.type==="cc"){const j=g.index;l({knobs:n.knobs.map(O=>O.index===j?{...O,cc:y.controller}:O)}),o.current={mode:"idle"};return}if(g.mode==="fader"&&y.type==="cc"){l({fader:{cc:y.controller,label:"Fader"}}),o.current={mode:"idle"};return}if(g.mode==="pad"&&y.type==="noteon"){const j=n.pads.slice();j[g.padIdx]={...j[g.padIdx],note:y.note},l({pads:j}),o.current={mode:"idle"};return}if(g.mode==="transport"&&y.type==="cc"){const j={...n.transport};j[g.action]=y.controller,l({transport:j}),o.current={mode:"idle"};return}}switch(y.type){case"noteon":{n.pads.findIndex(O=>O.note===y.note)>=0?(b=e.onPad)==null||b.call(e,{note:y.note,velocity:y.velocity,ts:y.ts,device:m}):(x=e.onKey)==null||x.call(e,{note:y.note,velocity:y.velocity,ts:y.ts,device:m});break}case"cc":{if(n.fader&&y.controller===n.fader.cc){(k=e.onFader)==null||k.call(e,{cc:y.controller,value:y.value,ts:y.ts,device:m});break}const j=n.knobs.find($=>$.cc===y.controller);if(j){(v=e.onKnob)==null||v.call(e,{index:j.index,cc:y.controller,value:y.value,ts:y.ts,device:m});break}const O=Object.keys(n.transport).find($=>n.transport[$]===y.controller);if(O){(w=e.onTransport)==null||w.call(e,{action:O,value:y.value,ts:y.ts,device:m});break}(M=e.onUnknown)==null||M.call(e,y);break}case"pitchbend":(S=e.onPitchBend)==null||S.call(e,{value:y.value,ts:y.ts,device:m});break;case"aftertouch":(R=e.onAftertouch)==null||R.call(e,{pressure:y.pressure,ts:y.ts,device:m});break;default:(T=e.onUnknown)==null||T.call(e,y)}},[l,e,n]),{supported:u,granted:h,inputs:p}=Br({inputNameIncludes:void 0,onEvent:c,sysex:!1,channelFilter:void 0,onInputsChanged:y=>i(y.map(m=>m.name||"MIDI"))}),f=d.useMemo(()=>({knob:y=>o.current={mode:"knob",index:y},fader:()=>o.current={mode:"fader"},pad:y=>o.current={mode:"pad",padIdx:y},transport:y=>o.current={mode:"transport",action:y},cancel:()=>o.current={mode:"idle"},state:()=>o.current}),[]);return{supported:u,granted:h,inputs:p,layout:n,setLayout:l,learn:f,inputsInfo:s}}const va={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],mixolydian:[0,2,4,5,7,9,10],pentatonic:[0,2,4,7,9],minorPenta:[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11]},Rm=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Sa={pop:[[0,4,7],[5,9,0],[7,11,2],[5,9,0]],rock:[[0,4,7],[5,9,0],[3,7,10],[5,9,0]],jazz:[[0,4,7,11],[2,5,9,0],[5,9,0,4],[0,4,7,11]],blues12:[[0,4,7],[0,4,7],[0,4,7],[0,4,7],[5,9,0],[5,9,0],[0,4,7],[0,4,7],[7,11,2],[5,9,0],[0,4,7],[7,11,2]]},Qt=36,wn=38,Rt=42,Jt=51,Nm=49,ka={basic:[{step:0,pitch:Qt,vel:110},{step:0,pitch:Rt,vel:80},{step:2,pitch:Rt,vel:70},{step:4,pitch:wn,vel:100},{step:4,pitch:Rt,vel:80},{step:6,pitch:Rt,vel:70},{step:8,pitch:Qt,vel:100},{step:10,pitch:Rt,vel:70},{step:12,pitch:wn,vel:100},{step:12,pitch:Rt,vel:80},{step:14,pitch:Rt,vel:70}],rock:[{step:0,pitch:Qt,vel:120},{step:0,pitch:Nm,vel:90},{step:4,pitch:wn,vel:110},{step:4,pitch:Rt,vel:80},{step:8,pitch:Qt,vel:110},{step:8,pitch:Rt,vel:80},{step:10,pitch:Qt,vel:90},{step:12,pitch:wn,vel:110},{step:12,pitch:Rt,vel:80}],swing:[{step:0,pitch:Jt,vel:90},{step:3,pitch:Jt,vel:70},{step:4,pitch:Jt,vel:80},{step:8,pitch:Jt,vel:90},{step:11,pitch:Jt,vel:70},{step:12,pitch:Jt,vel:80},{step:4,pitch:Qt,vel:80},{step:12,pitch:wn,vel:70}]},Dl={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function Tm(e){let t=e|0;return()=>{t=t+1831565813|0;let n=Math.imul(t^t>>>15,1|t);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}let _l=1;const ir=()=>_l++,Fl=e=>60/e,$m=e=>Fl(e)/4;function ta(e,t,n,a){const s=t.length,i=Math.floor(n/s),o=(n%s+s)%s;return e+t[o]+(a+i)*12}function zl(e=Dl){_l=1;const t=e.seed>0?Tm(e.seed):Math.random,n=va[e.scale]??va.pentatonic,a=Sa[e.progression]??Sa.pop,s=ka[e.drumPattern]??ka.basic,i=Fl(e.tempo),o=$m(e.tempo),l=Math.max(1,e.bars),c=16,u=[],h=[],p=[],f=[];let y=0;for(let m=0;m<l;m++){const g=m*4*i,b=m%a.length,x=a[b];for(const v of x)p.push({id:ir(),pitch:ta(e.root,n,v,e.octave-1),start:g,duration:4*i-.01,velocity:70+Math.floor(t()*20)});const k=x[0];for(let v=0;v<4;v++){const w=v===2?k+(t()>.5?2:0):k;h.push({id:ir(),pitch:ta(e.root,n,w,e.octave-2),start:g+v*i,duration:i*.9,velocity:80+Math.floor(t()*30)})}for(let v=0;v<c;v++){if(t()>e.density)continue;const w=g+v*o,M=t()>.8?t()>.5?2:-2:t()>.5?1:-1;y=Math.max(-3,Math.min(n.length+3,y+M));const S=1+Math.floor(t()*3);u.push({id:ir(),pitch:ta(e.root,n,y,e.octave),start:w,duration:S*o*.95,velocity:85+Math.floor(t()*30)})}for(const v of s)f.push({id:ir(),pitch:v.pitch,start:g+v.step*o,duration:o*.8,velocity:v.vel+Math.floor(t()*10-5)})}return{melody:u,bass:h,chords:p,drums:f,config:e}}const Pm=Object.keys(va),Am=Object.keys(Sa),Em=Object.keys(ka),Im=zl;function He(e,t,n){return{cc:e,paramId:n,label:`Knob ${t}`,controlType:"knob",min:0,max:127,inverted:!1}}function Un(e,t,n){return{cc:e,paramId:n,label:t,controlType:"fader",min:0,max:127,inverted:!1}}function en(e,t,n){return{cc:e,paramId:n,label:t,controlType:"button",min:0,max:127,inverted:!1}}const Ol={id:"oxygen25",name:"M-Audio Oxygen 25 (MkIV)",deviceMatch:"OXYGEN",mappings:[He(21,1,"mixer.volume"),He(22,2,"mixer.pan"),He(23,3,"fx.reverb"),He(24,4,"fx.delay"),He(25,5,"fx.chorus"),He(26,6,"fx.filter"),He(27,7,"fx.drive"),He(28,8,"fx.eq"),Un(7,"Master Fader","mixer.master"),en(115,"Play","transport.play"),en(114,"Stop","transport.stop"),en(117,"Record","transport.record"),en(112,"Rewind","transport.rewind"),en(113,"Forward","transport.forward"),en(116,"Loop","transport.loop")]},Bl={id:"mpk-mini",name:"Akai MPK Mini",deviceMatch:"MPK",mappings:[He(1,1,"mixer.volume"),He(2,2,"mixer.pan"),He(3,3,"fx.reverb"),He(4,4,"fx.delay"),He(5,5,"fx.chorus"),He(6,6,"fx.filter"),He(7,7,"fx.drive"),He(8,8,"fx.eq")]},Gl={id:"minilab",name:"Arturia MiniLab",deviceMatch:"Arturia MiniLab",mappings:[He(7,1,"mixer.volume"),He(74,2,"mixer.pan"),He(71,3,"fx.reverb"),He(76,4,"fx.delay"),He(77,5,"fx.chorus"),He(93,6,"fx.filter"),He(73,7,"fx.drive"),He(75,8,"fx.eq"),Un(1,"Mod Wheel","mixer.master")]},Wl={id:"launch-control-xl",name:"Novation Launch Control XL",deviceMatch:"Launch Control",mappings:[...Array.from({length:8},(e,t)=>He(13+t,t+1,`mixer.send${t+1}`)),...Array.from({length:8},(e,t)=>Un(77+t,`Fader ${t+1}`,`mixer.track${t+1}`))]},cs={id:"generic",name:"Generic MIDI Controller",deviceMatch:"",mappings:[He(1,1,"mixer.modWheel"),Un(7,"Volume","mixer.volume"),He(10,2,"mixer.pan"),Un(11,"Expression","mixer.expression")]},Ul=[Ol,Bl,Gl,Wl,cs];class Lm{constructor(t){this.ccMap=new Map,this.onChange=null,this.profile=t??cs,this.rebuildMap()}setProfile(t){this.profile=t,this.rebuildMap()}getProfile(){return this.profile}autoDetect(t){const n=t.toUpperCase(),a=Ul.find(s=>s.deviceMatch&&n.includes(s.deviceMatch.toUpperCase()));return a?(this.setProfile(a),a):null}onMappedChange(t){this.onChange=t}handleCC(t,n){var c;const a=this.ccMap.get(t);if(!a)return null;const i=(a.inverted?127-n:n)/127,o=a.min+i*(a.max-a.min),l={paramId:a.paramId,label:a.label,rawValue:n,scaledValue:o,normalizedValue:i};return(c=this.onChange)==null||c.call(this,l),l}setMapping(t,n,a,s="knob"){const i={cc:t,paramId:n,label:a,controlType:s,min:0,max:127,inverted:!1},o=this.profile.mappings.findIndex(l=>l.cc===t);o>=0?this.profile.mappings[o]=i:this.profile.mappings.push(i),this.ccMap.set(t,i)}removeMapping(t){this.profile.mappings=this.profile.mappings.filter(n=>n.cc!==t),this.ccMap.delete(t)}getMappings(){return[...this.profile.mappings]}getMapping(t){return this.ccMap.get(t)}exportConfig(){return{...this.profile,mappings:this.profile.mappings.map(t=>({...t}))}}importConfig(t){this.profile={...t,mappings:t.mappings.map(n=>({...n}))},this.rebuildMap()}static createCustomProfile(t,n){return{id:`custom-${t.toLowerCase().replace(/\s+/g,"-")}`,name:t,deviceMatch:"",mappings:n.map(a=>({...a,min:0,max:127,inverted:!1}))}}rebuildMap(){this.ccMap.clear();for(const t of this.profile.mappings)this.ccMap.set(t.cc,t)}}function ql(e){return{past:[],present:e,future:[]}}function Vl(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function Hl(e){if(e.past.length===0)return e;const t=e.past[e.past.length-1];return{past:e.past.slice(0,-1),present:t,future:[e.present,...e.future]}}function Kl(e){if(e.future.length===0)return e;const t=e.future[0];return{past:[...e.past,e.present],present:t,future:e.future.slice(1)}}function Yl(e){return e.past.length>0}function Zl(e){return e.future.length>0}function wa(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>({...n}))}function Xl(e,t,n){if(t.length===0)return e;const a=Math.min(...t.map(o=>o.time)),s=n-a,i=t.map(o=>({...o,id:Date.now()+Math.floor(Math.random()*1e4)+o.id,time:o.time+s}));return[...e,...i]}function Ql(e,t){const n=[],a=[];for(const s of e)s.time>=t.start&&s.time<=t.end?n.push({...s}):a.push(s);return{remaining:a,cut:n}}function Jl(e,t){return e.filter(n=>n.time<t.start||n.time>t.end)}function Dm(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>n.id)}function ec(e,t,n,a){const s={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:a};return[...e,s]}function tc(e,t=3){if(e.length<=2)return e;const n=[...e].sort((s,i)=>s.time-i.time),a=[n[0]];for(let s=1;s<n.length-1;s++)s%t===0&&a.push(n[s]);return a.push(n[n.length-1]),a}function nc(e){return JSON.stringify(e,null,2)}function rc(e){try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&"id"in n&&"cc"in n&&"value"in n&&"time"in n):[]}catch{return[]}}function yt(e,t){var n;return((n=e.find(a=>a.layerId===t))==null?void 0:n.events)??[]}function Nt(e,t,n){return e.find(s=>s.layerId===t)?e.map(s=>s.layerId===t?{...s,events:n}:s):[...e,{layerId:t,events:n}]}function _m(e,t){switch(t.type){case"UNDO":return Hl(e);case"REDO":return Kl(e);default:{let n=e.present;switch(t.type){case"ADD_EVENT":{const a=[...yt(n,t.layerId),t.event];n=Nt(n,t.layerId,a);break}case"UPDATE_EVENT":{const a=yt(n,t.layerId).map(s=>s.id===t.id?{...s,value:t.value,time:t.time,handleType:t.handleType??s.handleType}:s);n=Nt(n,t.layerId,a);break}case"REMOVE_EVENT":{const a=yt(n,t.layerId).filter(s=>s.id!==t.id);n=Nt(n,t.layerId,a);break}case"SET_EVENTS":n=Nt(n,t.layerId,t.events);break;case"PASTE":{const a=yt(n,t.layerId),s=Xl(a,t.clipboard,t.targetTime);n=Nt(n,t.layerId,s);break}case"CUT":{const a=yt(n,t.layerId),{remaining:s}=Ql(a,t.range);n=Nt(n,t.layerId,s);break}case"DELETE_RANGE":{const a=yt(n,t.layerId),s=Jl(a,t.range);n=Nt(n,t.layerId,s);break}case"RECORD":{const a=yt(n,t.layerId),s=ec(a,t.cc,t.value,t.time);n=Nt(n,t.layerId,s);break}case"THIN":{const a=yt(n,t.layerId),s=tc(a,t.keepEveryN);n=Nt(n,t.layerId,s);break}case"IMPORT":{const a=rc(t.json);a.length>0&&(n=Nt(n,t.layerId,a));break}}return Vl(e,n)}}}function Fm(e=[]){const[t,n]=d.useReducer(_m,ql(e)),a=d.useRef([]),s=d.useCallback(v=>yt(t.present,v),[t.present]),i=d.useCallback((v,w)=>n({type:"ADD_EVENT",layerId:v,event:w}),[]),o=d.useCallback((v,w,M,S,R)=>n({type:"UPDATE_EVENT",layerId:v,id:w,value:M,time:S,handleType:R}),[]),l=d.useCallback((v,w)=>n({type:"REMOVE_EVENT",layerId:v,id:w}),[]),c=d.useCallback((v,w)=>n({type:"SET_EVENTS",layerId:v,events:w}),[]),u=d.useCallback(()=>n({type:"UNDO"}),[]),h=d.useCallback(()=>n({type:"REDO"}),[]),p=d.useCallback((v,w)=>{a.current=wa(yt(t.present,v),w)},[t.present]),f=d.useCallback((v,w)=>{a.current=wa(yt(t.present,v),w),n({type:"CUT",layerId:v,range:w})},[t.present]),y=d.useCallback((v,w)=>{a.current.length>0&&n({type:"PASTE",layerId:v,clipboard:a.current,targetTime:w})},[]),m=d.useCallback((v,w)=>n({type:"DELETE_RANGE",layerId:v,range:w}),[]),g=d.useCallback((v,w,M,S)=>n({type:"RECORD",layerId:v,cc:w,value:M,time:S}),[]),b=d.useCallback((v,w)=>n({type:"THIN",layerId:v,keepEveryN:w}),[]),x=d.useCallback(v=>nc(yt(t.present,v)),[t.present]),k=d.useCallback((v,w)=>n({type:"IMPORT",layerId:v,json:w}),[]);return{snapshots:t.present,getEvents:s,addEvent:i,updateEvent:o,removeEvent:l,setEvents:c,undo:u,redo:h,canUndo:Yl(t),canRedo:Zl(t),copy:p,cut:f,paste:y,clipboard:a.current,deleteRange:m,record:g,thin:b,exportLane:x,importLane:k}}function ds(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function Ht(e="New Pattern",t=16,n=120){return{name:e,length:t,steps:Array.from({length:t},()=>ds()),bpm:n,swing:0,rootNote:60}}function ac(e,t){const n=e.steps.map((a,s)=>s===t?{...a,active:!a.active}:a);return{...e,steps:n}}function sc(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,note:Math.max(0,Math.min(127,n))}:s);return{...e,steps:a}}function ic(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,velocity:Math.max(0,Math.min(127,n))}:s);return{...e,steps:a}}function oc(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,gate:Math.max(0,Math.min(1,n))}:s);return{...e,steps:a}}function lc(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,probability:Math.max(0,Math.min(1,n))}:s);return{...e,steps:a}}function cc(e,t){const n=e.steps.map((a,s)=>s===t?{...a,slide:!a.slide}:a);return{...e,steps:n}}function dc(e,t){const n=e.steps.map(a=>a.active?{...a,note:Math.max(0,Math.min(127,a.note+t))}:a);return{...e,steps:n,rootNote:Math.max(0,Math.min(127,e.rootNote+t))}}function uc(e){return{...e,steps:[...e.steps].reverse()}}function hc(e,t){const n=e.steps.length,a=(t%n+n)%n,s=[...e.steps.slice(a),...e.steps.slice(0,a)];return{...e,steps:s}}function pc(e,t=60,n=127){const a=e.steps.map(s=>s.active?{...s,velocity:Math.floor(t+Math.random()*(n-t+1))}:s);return{...e,steps:a}}function fc(e){return{...e,steps:e.steps.map(()=>ds(e.rootNote))}}function us(e,t=4){return 60/e/t}function mc(e,t,n=0,a=4){const s=us(t,a),i=e*s;return e%2===1&&n>0?i+s*n*.5:i}function gc(e){return e.active&&Math.random()<e.probability}function zm(){const e=Ht("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function Om(){const e=Ht("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function Bm(){const e=Ht("Hi-Hat",16);for(let t=0;t<16;t+=2)e.steps[t]={...e.steps[t],active:!0,note:42,velocity:80};return e}function Gm(e=60){const t=Ht("Arp",16,120);return[0,4,7,12,7,4,0,-5,0,3,7,12,7,3,0,-5].forEach((a,s)=>{t.steps[s]={...t.steps[s],active:!0,note:e+a,velocity:90,gate:.5}}),{...t,rootNote:e}}function Wm(e=36){const t=Ht("Bassline",16,120),n=[0,0,7,0,5,5,3,0,0,0,7,12,5,5,3,0],a=[1,0,1,0,1,0,1,1,1,0,1,1,1,0,1,0];return n.forEach((s,i)=>{t.steps[i]={...t.steps[i],active:!!a[i],note:e+s,velocity:100,gate:.7}}),{...t,rootNote:e}}function Um(e){return JSON.stringify(e,null,2)}function qm(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function Vm(e={}){const{onTrigger:t,onLFOOutput:n,initialPattern:a}=e,[s,i]=d.useState(()=>a??Ht()),[o,l]=d.useState(-1),[c,u]=d.useState(!1),[h,p]=d.useState([]),f=d.useRef(s);f.current=s;const y=d.useRef(h);y.current=h;const m=d.useRef(c);m.current=c;const g=d.useRef(t);g.current=t;const b=d.useRef(n);b.current=n;const x=d.useRef(null),k=d.useRef(0),v=d.useRef(0),w=d.useCallback(()=>{var Y,X;if(!m.current)return;const I=f.current,P=k.current%I.length,N=I.steps[P];if(gc(N)){const ie=mc(k.current,I.bpm,I.swing);(Y=g.current)==null||Y.call(g,N,P,ie)}const z=(Date.now()-v.current)/1e3;for(let ie=0;ie<y.current.length;ie++){const le=y.current[ie];if(le.enabled&&le.targetCC!==void 0){const te=Aa(le,z,I.bpm);(X=b.current)==null||X.call(b,ie,le.targetCC,te)}}l(P),k.current++;const B=us(I.bpm)*1e3,G=P%2===0?0:B*I.swing*.5;x.current=setTimeout(w,B+G)},[]),M=d.useCallback(()=>{m.current||(k.current=0,v.current=Date.now(),u(!0),m.current=!0,w())},[w]),S=d.useCallback(()=>{u(!1),m.current=!1,l(-1),x.current&&(clearTimeout(x.current),x.current=null)},[]),R=d.useCallback(()=>{m.current?S():M()},[M,S]);d.useEffect(()=>()=>{x.current&&clearTimeout(x.current)},[]);const T=d.useCallback(I=>i(P=>ac(P,I)),[]),j=d.useCallback((I,P)=>i(N=>sc(N,I,P)),[]),O=d.useCallback((I,P)=>i(N=>ic(N,I,P)),[]),$=d.useCallback((I,P)=>i(N=>oc(N,I,P)),[]),E=d.useCallback((I,P)=>i(N=>lc(N,I,P)),[]),D=d.useCallback(I=>i(P=>cc(P,I)),[]),L=d.useCallback(I=>i(P=>dc(P,I)),[]),W=d.useCallback(()=>i(I=>uc(I)),[]),Z=d.useCallback(I=>i(P=>hc(P,I)),[]),A=d.useCallback((I,P)=>i(N=>pc(N,I,P)),[]),_=d.useCallback(()=>i(I=>fc(I)),[]),U=d.useCallback(I=>i(P=>({...P,bpm:Math.max(20,Math.min(300,I))})),[]),ne=d.useCallback(I=>i(P=>({...P,swing:Math.max(0,Math.min(1,I))})),[]),V=d.useCallback(I=>{i(P=>{if(P.length===I)return P;const N=Array.from({length:I},(z,B)=>B<P.steps.length?P.steps[B]:{active:!1,note:P.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...P,length:I,steps:N}})},[]),q=d.useCallback(I=>{p(P=>[...P,I??Er()])},[]),C=d.useCallback(I=>{p(P=>P.filter((N,z)=>z!==I))},[]),F=d.useCallback((I,P)=>{p(N=>N.map((z,B)=>B===I?{...z,...P}:z))},[]);return{pattern:s,currentStep:o,playing:c,lfos:h,play:M,stop:S,togglePlayback:R,toggle:T,setNote:j,setVelocity:O,setGate:$,setProbability:E,toggleSlide:D,transpose:L,reverse:W,shift:Z,randomizeVel:A,clear:_,setPattern:i,setBpm:U,setSwing:ne,setLength:V,addLFO:q,removeLFO:C,updateLFO:F}}function hs(e){const t=d.useRef(null),n=d.useRef(new Map),a=d.useRef(1),s=d.useCallback(()=>{if(!t.current){const o=e();o.onmessage=l=>{const{id:c}=l.data,u=n.current.get(c);u&&(n.current.delete(c),u.resolve(l.data))},o.onerror=l=>{console.error("[useWorker] Worker error:",l.message);for(const[c,u]of n.current)u.reject(new Error(`Worker error: ${l.message}`));n.current.clear(),o.terminate(),t.current=null},t.current=o}return t.current},[e]);return d.useEffect(()=>{const o=n.current;return()=>{var l;(l=t.current)==null||l.terminate(),t.current=null;for(const[,c]of o)c.reject(new Error("Worker terminated on unmount"));o.clear()}},[]),d.useCallback((o,l)=>{const c=a.current++,u=s();return new Promise((h,p)=>{n.current.set(c,{resolve:h,reject:p}),u.postMessage({...o,id:c},l??[])})},[s])}function Hm(){const e=hs(d.useCallback(()=>new Worker(new URL("/assets/pitchWorker-BgAp5Z97.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:xt&&xt.tagName.toUpperCase()==="SCRIPT"&&xt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return d.useCallback(async(n,a,s=.01)=>(await e({buffer:n,sampleRate:a,rmsThreshold:s})).hz,[e])}function Km(){const e=hs(d.useCallback(()=>new Worker(new URL("/assets/scoringWorker-B1PkYu_m.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:xt&&xt.tagName.toUpperCase()==="SCRIPT"&&xt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return d.useCallback(async(n,a,s)=>(await e({notes:n,points:a,params:s})).result,[e])}const Ym={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function yc(){return`
54
71
  /**
55
72
  * NiceAudioProcessor — Main audio analysis processor.
56
73
  */
@@ -386,7 +403,7 @@ registerProcessor('nice-audio-processor', NiceAudioProcessor);
386
403
  registerProcessor('nice-gain-processor', NiceGainProcessor);
387
404
  registerProcessor('nice-compressor-processor', NiceCompressorProcessor);
388
405
  registerProcessor('nice-vocoder-processor', NiceVocoderProcessor);
389
- `}let Ts=!1,Wn=null;async function nl(e){if(!Ts)return Wn||(Wn=(async()=>{const t=tl(),n=new Blob([t],{type:"application/javascript"}),r=URL.createObjectURL(n);try{await e.audioWorklet.addModule(r),Ts=!0}finally{URL.revokeObjectURL(r)}})(),Wn)}function rl(e,t,n){const r=new AudioWorkletNode(e,"nice-audio-processor",{processorOptions:{...Fh,...t}});return n&&(r.port.onmessage=a=>{a.data.type==="analysis"&&n(a.data.payload)}),r}function al(e,t=1){const n=new AudioWorkletNode(e,"nice-gain-processor");return n.parameters.get("gain").value=t,n}function sl(e,t){const n=new AudioWorkletNode(e,"nice-compressor-processor");return(t==null?void 0:t.threshold)!==void 0&&(n.parameters.get("threshold").value=t.threshold),(t==null?void 0:t.ratio)!==void 0&&(n.parameters.get("ratio").value=t.ratio),(t==null?void 0:t.attack)!==void 0&&(n.parameters.get("attack").value=t.attack),(t==null?void 0:t.release)!==void 0&&(n.parameters.get("release").value=t.release),(t==null?void 0:t.makeupGain)!==void 0&&(n.parameters.get("makeupGain").value=t.makeupGain),n}function ol(e,t){const n=new AudioWorkletNode(e,"nice-vocoder-processor");return(t==null?void 0:t.pitchShift)!==void 0&&(n.parameters.get("pitchShift").value=t.pitchShift),(t==null?void 0:t.formantShift)!==void 0&&(n.parameters.get("formantShift").value=t.formantShift),(t==null?void 0:t.mix)!==void 0&&(n.parameters.get("mix").value=t.mix),n}function Oh(e={}){const{enableAnalysis:t=!0,analysisOptions:n,enableGain:r=!1,initialGain:a=1,enableCompressor:o=!1,compressorOptions:i,enableVocoder:l=!1,vocoderOptions:c,onAnalysis:d}=e,[f,h]=u.useState(!1),[m,y]=u.useState(null),[p,v]=u.useState(null),x=u.useRef(null),b=u.useRef(null),S=u.useRef(null),g=u.useRef(null),k=u.useRef(null),M=u.useRef(null),N=u.useRef(null),j=u.useRef(null);u.useEffect(()=>{let L=!0;return(async()=>{try{const Y=new AudioContext;if(x.current=Y,await nl(Y),!L){Y.close();return}const O=[];if(t){const Z=rl(Y,n,H=>{L&&(v(H),d==null||d(H))});b.current=Z,O.push(Z)}if(r){const Z=al(Y,a);S.current=Z,O.push(Z)}if(o){const Z=sl(Y,i);g.current=Z,O.push(Z)}if(l){const Z=ol(Y,c);k.current=Z,O.push(Z)}if(O.length>0){N.current=O[0],j.current=O[O.length-1];for(let Z=0;Z<O.length-1;Z++)O[Z].connect(O[Z+1])}h(!0)}catch(Y){L&&y(Y)}})(),()=>{var Y,O,Z,H,te;L=!1,(Y=b.current)==null||Y.disconnect(),(O=S.current)==null||O.disconnect(),(Z=g.current)==null||Z.disconnect(),(H=k.current)==null||H.disconnect(),(te=x.current)==null||te.close()}},[t,r,o,l]);const _=u.useCallback(L=>{M.current&&M.current.disconnect(),M.current=L,N.current&&L.connect(N.current)},[]),P=u.useCallback(()=>{M.current&&(M.current.disconnect(),M.current=null)},[]),V=u.useCallback(()=>j.current,[]),z=u.useCallback(L=>{var Y;const U=(Y=S.current)==null?void 0:Y.parameters.get("gain");U&&(U.value=Math.max(0,Math.min(2,L)))},[]),A=u.useCallback((L,U)=>{var O;const Y=(O=g.current)==null?void 0:O.parameters.get(L);Y&&(Y.value=U)},[]),I=u.useCallback((L,U)=>{var O;const Y=(O=k.current)==null?void 0:O.parameters.get(L);Y&&(Y.value=U)},[]);return{isReady:f,error:m,analysis:p,connectSource:_,disconnectSource:P,getOutputNode:V,setGain:z,setCompressorParam:A,setVocoderParam:I,audioContext:x.current}}function il(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function ll(e){return e>=50?3:e>=30?2.5:e>=20?2:e>=10?1.5:1}function _h(e,t,n){const{semitoneTolerance:r,preWindow:a,postExtra:o}=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,f=!!n.disableGoldNotes;let h=0,m=0,y=0;const p=[];let v=0,x=0,b=0;const S=new Map;e.forEach((P,V)=>{const z=P.startTime,A=P.startTime+P.duration,I=z-a,L=A+o,U=t.filter(w=>w.t>=I&&w.t<=L&&w.hz>0);if(!U||U.length===0)return;const Y=Math.max(1,Math.ceil((P.duration||.25)/i)),O=Math.max(10,Math.round(100*(P.duration||1))),Z=Math.max(1,Math.round(O/Y));let H=0;const te=[];for(let w=0;w<Y;w++){const $=z+w*(P.duration/Y),R=z+(w+1)*(P.duration/Y),T=Math.min(.06,P.duration/Y*.2),C=$-T,E=R+T,F=t.filter(ee=>ee.t>=C&&ee.t<=E&&ee.hz>0);if(!F||F.length===0)continue;let q=0;F.forEach(ee=>{let K=((12*Math.log2(ee.hz/440)+69)%12+12)%12;for(;K-P.pitch>6;)K-=12;for(;K-P.pitch<-6;)K+=12;const se=Math.abs(K-P.pitch);q+=se});const Q=q/F.length;let J=0;if(r<=0)J=Q===0?1:0;else{const ee=r*2;J=Math.max(0,1-Math.min(Q/ee,1))}if(J<=0)continue;const ae=!f&&P.isGold?2:1,re=Math.round(Z*ae*J);re>0&&(h+=re,H+=re,te.push({segIndex:w,frac:J,add:re,segStart:C,segEnd:E,visualStart:$,visualEnd:R}))}const G=P.line??0;S.has(G)||S.set(G,{total:0,hit:0,comboBonus:0});const B=S.get(G);if(B.total++,H>0){v++,v>x&&(x=v),B.hit++;const w=ll(v),$=w>1?Math.round(H*(w-1)):0;b+=$,B.comboBonus+=$;const R=Math.max(1,Math.ceil((P.duration||.25)/i)),C=te.length>=R,E=C?Math.round(Math.max(10,Math.round(100*(P.duration||1)))*l*(!f&&P.isGold?1.5:1)*d):0,F=C&&!f&&P.isGold?Math.round(Math.max(10,Math.round(100*(P.duration||1)))*c*d):0;m+=E,y+=F,p.push({noteKey:`${P.line??0}-${P.idx??0}`,segments:te,totalAdded:H,completed:C,completionBonus:E,goldFullBonus:F})}else v=0});const g=[];for(const[P,V]of S.entries()){const z=V.total>0?V.hit/V.total:0;g.push({verseIndex:P,hitFraction:z,label:il(z),comboBonus:V.comboBonus})}const k={maxCombo:x,currentCombo:0,totalComboBonus:b},M=b+m+y,N=p.length,j=p.filter(P=>P.completed).length,_={hits:N,misses:e.length-N,good:N-j,perfect:j,maxCombo:x};return{classicScore:h,bonusScore:M,totalScore:h+M,total:h,perNote:p,combo:k,verseRatings:g,noteStats:_}}function cl(e,t){let n=0;for(const r of e){const a=Math.max(10,Math.round(100*(r.duration||1))),o=!t&&r.isGold?2:1;n+=a*o}return n}function dl(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function zh(e,t,n){const r=cl(t,n);if(r<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0,total:0};const a=dl(e.classicScore,r),o=Math.round(e.bonusScore/r*1e4);return{...e,classicScore:a,bonusScore:o,totalScore:a+o,total:a}}function ul(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 Bh(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 Gh(e,t="/backgrounds"){return e.backgroundImage?`${t}/${e.backgroundImage}`:""}function Wh(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,o=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>o&&(o=l,a=i)}return a>0?t/a:0}function Uh(e,t){const n=[];return e.forEach((r,a)=>{r.forEach((o,i)=>{n.push({startTime:o.startTime+t,duration:o.duration,pitch:o.pitch,isGold:o.isGold,line:a,idx:i})})}),n}function Vh(e,t,n){const r=[];return e.forEach(a=>{var c;const[o,i]=a.noteKey.split("-").map(Number),l=(c=t[o])==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 qh(e,t=120){let n=e;if(e.length>t){const r=e.length/t,a=[];for(let o=0;o<t;o++)a.push(e[Math.floor(o*r)]);n=a}return n.map(r=>({t:Math.round(r.t*1e3)/1e3,hz:Math.round(r.hz)}))}function Hh(e,t,n){const a=Date.parse(e)-n;return Math.max(0,Math.round(t-a))}const fl={crepe:"var(--nice-accent, #a78bfa)",librosa:"var(--nice-success-light, #34d399)",pitchy:"var(--nice-primary-light, #60a5fa)",autocorr:"var(--nice-text-secondary, #555555)"};function Kh(e){return e==="autocorr"?"Ultrastar":e.charAt(0).toUpperCase()+e.slice(1)}function Yh(e){return fl[e]??"var(--nice-text-secondary, #555555)"}function Zh(e){const t=fl[e]??"var(--nice-text-secondary, #555555)";return`var(--algo-${e}, ${t})`}function Xh(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 o=e.videoPath;if(o.startsWith("v=")){const i=ul(o);i.youtubeId&&(o=`https://www.youtube.com/watch?v=${i.youtubeId}`)}/youtu(\.be|be\.com)/i.test(o)?a.push({kind:"youtube",url:o}):/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(e.videoPath)&&a.push({kind:"audio",url:e.videoPath})}if(a.length===0){const o=r?e.instrumentalPath:e.audioPath;o&&/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(o)&&a.push({kind:"audio",url:o})}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 Qh(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 Jh(e,t,n){const o={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)||[],o]}}})}function ep(e,t,n){e(r=>{var a,o;return{...r,[t]:{...r[t],effectChain:((o=(a=r[t])==null?void 0:a.effectChain)==null?void 0:o.filter(i=>i.id!==n))||[]}}})}function tp(e,t,n){e(r=>{var a,o;return{...r,[t]:{...r[t],effectChain:((o=(a=r[t])==null?void 0:a.effectChain)==null?void 0:o.map(i=>i.id===n?{...i,bypass:!i.bypass}:i))||[]}}})}function np(e,t,n,r){e(a=>{var o,i;return{...a,[t]:{...a[t],effectChain:((i=(o=a[t])==null?void 0:o.effectChain)==null?void 0:i.map(l=>l.id===n?{...l,params:{...l.params,...r}}:l))||[]}}})}function rp(e,t,n,r,a,o,i=.5,l=100){const c={id:Date.now()+Math.floor(Math.random()*1e3),pitch:a,start:o,duration:i,velocity:l};t(d=>({...d,[r]:[...d[r]||[],c]})),n({layerId:r,noteId:c.id})}function ap(e,t,n,r){e(a=>({...a,[n]:(a[n]||[]).filter(o=>o.id!==r)})),t(null)}function sp(e,t,n){e(r=>({...r,[n]:[]})),t(null)}function op(e,t,n){e(r=>({...r,[t]:n}))}function ip(e,t,n,r,a){const o={id:Date.now()+Math.floor(Math.random()*1e3),cc:n,value:r,time:a};e(i=>({...i,[t]:[...i[t]||[],o]}))}function lp(e,t,n,r,a,o){e(i=>({...i,[t]:(i[t]||[]).map(l=>l.id===n?{...l,value:r,time:a,handleType:o??l.handleType}:l)}))}function cp(e,t,n){e(r=>({...r,[t]:(r[t]||[]).filter(a=>a.id!==n)}))}function Un(e){if(!e||e<=0)return null;const t=12*Math.log2(e/440)+69;return Math.round(t-12)}function dp(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 up(e,t,n=.01){const r=Math.floor(t/50);let a=-1,o=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 f=0;f<r;f++)d+=Math.abs(e[f]-e[f+c]);d=1-d/r,d>o&&d>.9&&d>l&&(o=d,a=c),l=d}return a===-1?0:t/a}async function fp(e,t,n){const{signal:r,onProgress:a,rmsThreshold:o,useHanning:i,postPitch:l,postLibrosaPitchTrack:c}=n||{},d=await e.arrayBuffer();if(r!=null&&r.aborted)throw new Error("aborted");const h=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(d),m=h.getChannelData(0),y=h.sampleRate,p=Math.floor(y*.1),v=p,x=[];if(t==="pitchy"){const b=Nr.PitchDetector.forFloat32Array(p),S=Math.max(1,Math.floor((m.length-p)/v));let g=0;for(let k=0;k<m.length-p;k+=v){if(r!=null&&r.aborted)throw new Error("aborted");const M=m.slice(k,k+p);if(i)for(let z=0;z<M.length;z++)M[z]*=.5*(1-Math.cos(2*Math.PI*z/(M.length-1)));const[N,j]=b.findPitch(M,y),_=Un(N);let P=0;for(let z=0;z<M.length;z++)P+=M[z]*M[z];P=Math.sqrt(P/M.length);const V=typeof o=="number"?o:.01;_&&N>50&&N<2e3&&j>.7&&P>V&&x.push({start:k/y,duration:p/y,pitch:_,freq:N}),g++,a&&a(g/S)}}else if(t==="crepe"){if(a&&a(.05),!l)throw new Error("CREPE backend callback (postPitch) is required for crepe algorithm");const b=await l(e);if(r!=null&&r.aborted)throw new Error("aborted");const S=Array.isArray(b.track)?b.track:[];S.length>0&&S.forEach((g,k)=>{var N;const M=Un(g.hz);if(M&&g.hz>50&&g.hz<2e3){const j=((N=S[k+1])==null?void 0:N.t)??g.t+.1;x.push({start:g.t,duration:k<S.length-1?j-g.t:.1,pitch:M,freq:g.hz})}}),a&&a(1)}else if(t==="ultrastar-wp"){const b=Math.max(1,Math.floor((m.length-p)/v));let S=0;for(let g=0;g<m.length-p;g+=v){if(r!=null&&r.aborted)throw new Error("aborted");const k=m.slice(g,g+p);if(i)for(let _=0;_<k.length;_++)k[_]*=.5*(1-Math.cos(2*Math.PI*_/(k.length-1)));const N=up(k,y,typeof o=="number"?o:.01),j=Un(N);j&&N>50&&N<2e3&&x.push({start:g/y,duration:p/y,pitch:j,freq:N}),S++,a&&a(S/b)}}if(t==="librosa"){if(a&&a(.05),!c)throw new Error("Librosa backend callback (postLibrosaPitchTrack) is required for librosa algorithm");const b=await c(e);if(r!=null&&r.aborted)throw new Error("aborted");const S=Array.isArray(b.track)?b.track:[];S.length>0&&S.forEach((g,k)=>{var N;const M=Un(g.hz);if(M&&g.hz>50&&g.hz<2e3){const j=((N=S[k+1])==null?void 0:N.t)??g.t+.1;x.push({start:g.t,duration:k<S.length-1?j-g.t:.1,pitch:M,freq:g.hz})}}),a&&a(1)}return dp(x)}function hp(e){switch(e){case"pitchy":return`#TITLE:Analyzed Song
406
+ `}let ji=!1,or=null;async function bc(e){if(!ji)return or||(or=(async()=>{const t=yc(),n=new Blob([t],{type:"application/javascript"}),a=URL.createObjectURL(n);try{await e.audioWorklet.addModule(a),ji=!0}finally{URL.revokeObjectURL(a)}})(),or)}function xc(e,t,n){const a=new AudioWorkletNode(e,"nice-audio-processor",{processorOptions:{...Ym,...t}});return n&&(a.port.onmessage=s=>{s.data.type==="analysis"&&n(s.data.payload)}),a}function vc(e,t=1){const n=new AudioWorkletNode(e,"nice-gain-processor");return n.parameters.get("gain").value=t,n}function Sc(e,t){const n=new AudioWorkletNode(e,"nice-compressor-processor");return(t==null?void 0:t.threshold)!==void 0&&(n.parameters.get("threshold").value=t.threshold),(t==null?void 0:t.ratio)!==void 0&&(n.parameters.get("ratio").value=t.ratio),(t==null?void 0:t.attack)!==void 0&&(n.parameters.get("attack").value=t.attack),(t==null?void 0:t.release)!==void 0&&(n.parameters.get("release").value=t.release),(t==null?void 0:t.makeupGain)!==void 0&&(n.parameters.get("makeupGain").value=t.makeupGain),n}function kc(e,t){const n=new AudioWorkletNode(e,"nice-vocoder-processor");return(t==null?void 0:t.pitchShift)!==void 0&&(n.parameters.get("pitchShift").value=t.pitchShift),(t==null?void 0:t.formantShift)!==void 0&&(n.parameters.get("formantShift").value=t.formantShift),(t==null?void 0:t.mix)!==void 0&&(n.parameters.get("mix").value=t.mix),n}function Zm(e={}){const{enableAnalysis:t=!0,analysisOptions:n,enableGain:a=!1,initialGain:s=1,enableCompressor:i=!1,compressorOptions:o,enableVocoder:l=!1,vocoderOptions:c,onAnalysis:u}=e,[h,p]=d.useState(!1),[f,y]=d.useState(null),[m,g]=d.useState(null),b=d.useRef(null),x=d.useRef(null),k=d.useRef(null),v=d.useRef(null),w=d.useRef(null),M=d.useRef(null),S=d.useRef(null),R=d.useRef(null);d.useEffect(()=>{let L=!0;return(async()=>{try{const Z=new AudioContext;if(b.current=Z,await bc(Z),!L){Z.close();return}const A=[];if(t){const _=xc(Z,n,U=>{L&&(g(U),u==null||u(U))});x.current=_,A.push(_)}if(a){const _=vc(Z,s);k.current=_,A.push(_)}if(i){const _=Sc(Z,o);v.current=_,A.push(_)}if(l){const _=kc(Z,c);w.current=_,A.push(_)}if(A.length>0){S.current=A[0],R.current=A[A.length-1];for(let _=0;_<A.length-1;_++)A[_].connect(A[_+1])}p(!0)}catch(Z){L&&y(Z)}})(),()=>{var Z,A,_,U,ne;L=!1,(Z=x.current)==null||Z.disconnect(),(A=k.current)==null||A.disconnect(),(_=v.current)==null||_.disconnect(),(U=w.current)==null||U.disconnect(),(ne=b.current)==null||ne.close()}},[t,a,i,l]);const T=d.useCallback(L=>{M.current&&M.current.disconnect(),M.current=L,S.current&&L.connect(S.current)},[]),j=d.useCallback(()=>{M.current&&(M.current.disconnect(),M.current=null)},[]),O=d.useCallback(()=>R.current,[]),$=d.useCallback(L=>{var Z;const W=(Z=k.current)==null?void 0:Z.parameters.get("gain");W&&(W.value=Math.max(0,Math.min(2,L)))},[]),E=d.useCallback((L,W)=>{var A;const Z=(A=v.current)==null?void 0:A.parameters.get(L);Z&&(Z.value=W)},[]),D=d.useCallback((L,W)=>{var A;const Z=(A=w.current)==null?void 0:A.parameters.get(L);Z&&(Z.value=W)},[]);return{isReady:h,error:f,analysis:m,connectSource:T,disconnectSource:j,getOutputNode:O,setGain:$,setCompressorParam:E,setVocoderParam:D,audioContext:b.current}}function Xm(e,t,n){const i={id:`${t}-${n}-${Date.now()}`,type:n,bypass:!1,params:{eq3:{lowGain:0,midGain:0,highGain:0,lowFreq:250,highFreq:4e3},compressor:{threshold:-24,ratio:4,attack:.003,release:.25,knee:30},delay:{time:.25,feedback:.3,mix:.3},reverb:{decay:2,mix:.3},distortion:{amount:20,mix:.5}}[n]};e(o=>{var l;return{...o,[t]:{...o[t],effectChain:[...((l=o[t])==null?void 0:l.effectChain)||[],i]}}})}function Qm(e,t,n){e(a=>{var s,i;return{...a,[t]:{...a[t],effectChain:((i=(s=a[t])==null?void 0:s.effectChain)==null?void 0:i.filter(o=>o.id!==n))||[]}}})}function Jm(e,t,n){e(a=>{var s,i;return{...a,[t]:{...a[t],effectChain:((i=(s=a[t])==null?void 0:s.effectChain)==null?void 0:i.map(o=>o.id===n?{...o,bypass:!o.bypass}:o))||[]}}})}function e0(e,t,n,a){e(s=>{var i,o;return{...s,[t]:{...s[t],effectChain:((o=(i=s[t])==null?void 0:i.effectChain)==null?void 0:o.map(l=>l.id===n?{...l,params:{...l.params,...a}}:l))||[]}}})}function t0(e,t,n,a,s,i,o=.5,l=100){const c={id:Date.now()+Math.floor(Math.random()*1e3),pitch:s,start:i,duration:o,velocity:l};t(u=>({...u,[a]:[...u[a]||[],c]})),n({layerId:a,noteId:c.id})}function n0(e,t,n,a){e(s=>({...s,[n]:(s[n]||[]).filter(i=>i.id!==a)})),t(null)}function r0(e,t,n){e(a=>({...a,[n]:[]})),t(null)}function a0(e,t,n){e(a=>({...a,[t]:n}))}function s0(e,t,n,a,s){const i={id:Date.now()+Math.floor(Math.random()*1e3),cc:n,value:a,time:s};e(o=>({...o,[t]:[...o[t]||[],i]}))}function i0(e,t,n,a,s,i){e(o=>({...o,[t]:(o[t]||[]).map(l=>l.id===n?{...l,value:a,time:s,handleType:i??l.handleType}:l)}))}function o0(e,t,n){e(a=>({...a,[t]:(a[t]||[]).filter(s=>s.id!==n)}))}function lr(e){if(!e||e<=0)return null;const t=12*Math.log2(e/440)+69;return Math.round(t-12)}function l0(e){if(e.length===0)return[];const t=[];let n=e[0];for(let a=1;a<e.length;a++){const s=e[a];s.pitch===n.pitch&&Math.abs(s.freq-n.freq)<1?n.duration+=s.duration:(t.push(n),n=s)}return t.push(n),t}function c0(e,t,n=.01){const a=Math.floor(t/50);let s=-1,i=0,o=0;for(let c=0;c<e.length;c++)o+=e[c]*e[c];if(o=Math.sqrt(o/e.length),o<n)return 0;let l=1;for(let c=50;c<a;c++){let u=0;for(let h=0;h<a;h++)u+=Math.abs(e[h]-e[h+c]);u=1-u/a,u>i&&u>.9&&u>l&&(i=u,s=c),l=u}return s===-1?0:t/s}async function d0(e,t,n){const{signal:a,onProgress:s,rmsThreshold:i,useHanning:o,postPitch:l,postLibrosaPitchTrack:c}=n||{},u=await e.arrayBuffer();if(a!=null&&a.aborted)throw new Error("aborted");const p=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(u),f=p.getChannelData(0),y=p.sampleRate,m=Math.floor(y*.1),g=m,b=[];if(t==="pitchy"){const x=ra.PitchDetector.forFloat32Array(m),k=Math.max(1,Math.floor((f.length-m)/g));let v=0;for(let w=0;w<f.length-m;w+=g){if(a!=null&&a.aborted)throw new Error("aborted");const M=f.slice(w,w+m);if(o)for(let $=0;$<M.length;$++)M[$]*=.5*(1-Math.cos(2*Math.PI*$/(M.length-1)));const[S,R]=x.findPitch(M,y),T=lr(S);let j=0;for(let $=0;$<M.length;$++)j+=M[$]*M[$];j=Math.sqrt(j/M.length);const O=typeof i=="number"?i:.01;T&&S>50&&S<2e3&&R>.7&&j>O&&b.push({start:w/y,duration:m/y,pitch:T,freq:S}),v++,s&&s(v/k)}}else if(t==="crepe"){if(s&&s(.05),!l)throw new Error("CREPE backend callback (postPitch) is required for crepe algorithm");const x=await l(e);if(a!=null&&a.aborted)throw new Error("aborted");const k=Array.isArray(x.track)?x.track:[];k.length>0&&k.forEach((v,w)=>{var S;const M=lr(v.hz);if(M&&v.hz>50&&v.hz<2e3){const R=((S=k[w+1])==null?void 0:S.t)??v.t+.1;b.push({start:v.t,duration:w<k.length-1?R-v.t:.1,pitch:M,freq:v.hz})}}),s&&s(1)}else if(t==="ultrastar-wp"){const x=Math.max(1,Math.floor((f.length-m)/g));let k=0;for(let v=0;v<f.length-m;v+=g){if(a!=null&&a.aborted)throw new Error("aborted");const w=f.slice(v,v+m);if(o)for(let T=0;T<w.length;T++)w[T]*=.5*(1-Math.cos(2*Math.PI*T/(w.length-1)));const S=c0(w,y,typeof i=="number"?i:.01),R=lr(S);R&&S>50&&S<2e3&&b.push({start:v/y,duration:m/y,pitch:R,freq:S}),k++,s&&s(k/x)}}if(t==="librosa"){if(s&&s(.05),!c)throw new Error("Librosa backend callback (postLibrosaPitchTrack) is required for librosa algorithm");const x=await c(e);if(a!=null&&a.aborted)throw new Error("aborted");const k=Array.isArray(x.track)?x.track:[];k.length>0&&k.forEach((v,w)=>{var S;const M=lr(v.hz);if(M&&v.hz>50&&v.hz<2e3){const R=((S=k[w+1])==null?void 0:S.t)??v.t+.1;b.push({start:v.t,duration:w<k.length-1?R-v.t:.1,pitch:M,freq:v.hz})}}),s&&s(1)}return l0(b)}function u0(e){switch(e){case"pitchy":return`#TITLE:Analyzed Song
390
407
  #ARTIST:AI
391
408
  #ALGO:Pitchy
392
409
  : 0 4 40 Pitchy
@@ -409,30 +426,4 @@ E`;case"ultrastarws":return`#TITLE:Analyzed Song
409
426
  E`;default:return`#TITLE:Analyzed Song
410
427
  #ARTIST:AI
411
428
  : 0 2 40 Test
412
- E`}}function pp(e,t){return`${e}:${t}`}function mp(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 o=a*4;return Math.round(e/o)*o}return e}function yp(e){return e.length===0?[]:e.flat()}function gp(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const Ta=[{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 bp(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function hl(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 pl(e,t){const n=t.seed!=null?bp(t.seed):Math.random;return e.map(r=>{const a=(n()-.5)*2*t.timingAmount,o=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+o)),duration:Math.max(.01,r.duration+i)}})}function ml(e,t,n=1){const r=4/t.stepsPerBar;return e.map(a=>{const o=a.time/r,i=Math.round(o)%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 vp(e,t){let n=[...e.map(r=>({...r}))];return t.template&&t.grooveStrength>0&&(n=ml(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=hl(n,t.swing)),t.humanize&&(n=pl(n,t.humanize)),n}function xp(e){return Ta.find(t=>t.id===e)}function wp(){return Ta.map(({id:e,name:t})=>({id:e,name:t}))}const Sp=[{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 $s(e,t,n){const r=e.sampleRate,a=Math.round(r*t),o=e.createBuffer(2,a,r);for(let i=0;i<2;i++){const l=o.getChannelData(i);for(let c=0;c<a;c++)l[c]=(Math.random()*2-1)*Math.pow(1-c/a,n)}return o}function Vn(e){const t=Math.max(1,e),n=44100,r=new Float32Array(n),a=Math.PI/180;for(let o=0;o<n;o++){const i=o*2/n-1;r[o]=(3+t)*i*20*a/(Math.PI+t*Math.abs(i))}return r}class Cp{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,o,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{(o=this.audioCtx)==null||o.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 o=t.createGain();o.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),f=t.createOscillator(),h=t.createOscillator(),m=t.createGain(),y=t.createGain(),p=n-1,v=Math.abs(p)*5+2,x=Math.abs(p)*.015;f.type="sawtooth",f.frequency.value=v,m.gain.value=x,f.connect(m),m.connect(c.delayTime),c.delayTime.value=.02,h.type="sawtooth",h.frequency.value=v,y.gain.value=x,h.connect(y),y.connect(d.delayTime),d.delayTime.value=.02+x;const b=t.createGain();b.gain.value=.5;const S=t.createGain();return S.gain.value=.5,a.connect(c),a.connect(d),c.connect(b),d.connect(S),b.connect(i),S.connect(i),a.connect(l),i.connect(o),l.connect(o),f.start(),h.start(),{type:"chipmunk",nodes:[a,c,d,f,h,m,y,b,S,i,l,o],input:a,output:o}}buildRobot(t,n){const r=t.createGain(),a=t.createGain(),o=t.createGain();o.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(o),r.connect(i),o.connect(a),i.connect(a),l.start(),{type:"robot",nodes:[r,l,c,o,i,a],input:r,output:a}}buildAlien(t,n){const r=t.createGain(),a=t.createGain(),o=t.createOscillator();o.type="sine",o.frequency.value=300+n*700;const i=t.createGain();i.gain.value=0,o.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 f=t.createGain();return f.gain.value=.3,r.connect(f),f.connect(a),o.start(),c.start(),{type:"alien",nodes:[r,o,i,l,c,d,f,a],input:r,output:a}}buildDelay(t,n,r,a){const o=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 f=t.createGain();return f.gain.value=1,o.connect(l),l.connect(c),c.connect(l),l.connect(d),o.connect(f),d.connect(i),f.connect(i),{type:"echo",nodes:[o,l,c,d,f,i],input:o,output:i}}buildCave(t,n){const r=t.createGain(),a=t.createGain(),o=t.createDelay(2);o.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 f=t.createGain();f.gain.value=.25;const h=t.createConvolver();h.buffer=$s(t,2+n*3,3);const m=t.createGain();m.gain.value=.3+n*.3,r.connect(o),o.connect(c),c.connect(o),r.connect(i),i.connect(d),d.connect(i),r.connect(l),l.connect(f),f.connect(l),o.connect(m),i.connect(m),l.connect(m),r.connect(h),h.connect(m);const y=t.createGain();return y.gain.value=.7,r.connect(y),y.connect(a),m.connect(a),{type:"cave",nodes:[r,o,i,l,c,d,f,h,m,y,a],input:r,output:a}}buildReverb(t,n,r,a){const o=t.createGain(),i=t.createGain(),l=t.createConvolver();l.buffer=$s(t,n,r);const c=t.createGain();c.gain.value=.4+a*.5;const d=t.createGain();return d.gain.value=1,o.connect(l),l.connect(c),o.connect(d),c.connect(i),d.connect(i),{type:"reverb",nodes:[o,l,c,d,i],input:o,output:i}}buildChorus(t,n){const r=t.createGain(),a=t.createGain(),o=[{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 o){const d=t.createDelay(.1);d.delayTime.value=c.delayMs/1e3;const f=t.createOscillator();f.type="sine",f.frequency.value=c.lfoFreq;const h=t.createGain();h.gain.value=c.depth*(.5+n),f.connect(h),h.connect(d.delayTime);const m=t.createGain();m.gain.value=.3+n*.2,r.connect(d),d.connect(m),m.connect(a),f.start(),i.push(d,f,h,m)}return{type:"chorus",nodes:i,input:r,output:a}}buildFlanger(t,n){const r=t.createGain(),a=t.createGain(),o=t.createDelay(.02);o.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(o.delayTime);const c=t.createGain();c.gain.value=.5+n*.35;const d=t.createGain();d.gain.value=.5+n*.3;const f=t.createGain();return f.gain.value=1,r.connect(o),o.connect(c),c.connect(o),o.connect(d),r.connect(f),d.connect(a),f.connect(a),i.start(),{type:"flanger",nodes:[r,o,i,l,c,d,f,a],input:r,output:a}}buildDistortion(t,n,r){const a=t.createGain(),o=t.createGain(),i=t.createWaveShaper();i.curve=Vn(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(o),c.connect(o),{type:"distortion",nodes:[a,i,l,c,o],input:a,output:o}}buildBandpass(t,n,r,a){const o=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,o.connect(l),l.connect(c),c.connect(i),{type:"telephone",nodes:[o,l,c,i],input:o,output:i}}buildMegaphone(t,n){const r=t.createGain(),a=t.createGain(),o=t.createBiquadFilter();o.type="highpass",o.frequency.value=500;const i=t.createBiquadFilter();i.type="lowpass",i.frequency.value=4e3;const l=t.createWaveShaper();l.curve=Vn(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(o),o.connect(i),i.connect(l),l.connect(c),c.connect(a),{type:"megaphone",nodes:[r,o,i,l,c,a],input:r,output:a}}buildRadio(t,n){const r=t.createGain(),a=t.createGain(),o=t.createBiquadFilter();o.type="highpass",o.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=Vn(10),r.connect(o),o.connect(i),i.connect(l),l.connect(c),c.connect(a),{type:"radio",nodes:[r,o,i,l,c,a],input:r,output:a}}buildUnderwater(t,n){const r=t.createGain(),a=t.createGain(),o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=300+(1-n)*400,o.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(o.frequency);const c=t.createGain();c.gain.value=.7+n*.3;const d=t.createGain();return d.gain.value=.3-n*.2,r.connect(o),o.connect(c),r.connect(d),c.connect(a),d.connect(a),i.start(),{type:"underwater",nodes:[r,o,i,l,c,d,a],input:r,output:a}}buildWhisper(t,n){const r=t.createGain(),a=t.createGain(),o=t.createBiquadFilter();o.type="highpass",o.frequency.value=500+n*500,o.Q.value=.5;const i=t.createWaveShaper(),l=new Float32Array(256);for(let d=0;d<256;d++){const f=d/255*2-1;l[d]=Math.sign(f)*Math.pow(Math.abs(f),.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(o),o.connect(i),i.connect(c),c.connect(a),{type:"whisper",nodes:[r,o,i,c,a],input:r,output:a}}buildDemon(t,n){const r=t.createGain(),a=t.createGain(),o=t.createDelay(.1);o.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(o.delayTime);const c=t.createWaveShaper();c.curve=Vn(20+n*50),c.oversample="2x";const d=t.createBiquadFilter();d.type="lowshelf",d.frequency.value=200,d.gain.value=8+n*8;const f=t.createGain();f.gain.value=.7+n*.3;const h=t.createGain();return h.gain.value=.3,r.connect(o),o.connect(c),c.connect(d),d.connect(f),r.connect(h),f.connect(a),h.connect(a),i.start(),{type:"demon",nodes:[r,o,i,l,c,d,f,h,a],input:r,output:a}}buildTremolo(t,n){const r=t.createGain(),a=t.createGain(),o=t.createGain();o.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(o.gain),r.connect(o),o.connect(a),i.start(),{type:"tremolo",nodes:[r,o,i,l,a],input:r,output:a}}buildAutotune(t,n){const r=t.createGain(),a=t.createGain(),o=t.createDelay(.05);o.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(o.delayTime);const c=[],d=[261.6,293.7,329.6,349.2,392,440,493.9,523.3],f=t.createGain();f.gain.value=.15;for(const y of d){const p=t.createBiquadFilter();p.type="peaking",p.frequency.value=y,p.Q.value=8+n*15,p.gain.value=4+n*8,r.connect(p),p.connect(f),c.push(p)}const h=t.createGain();h.gain.value=.7;const m=t.createGain();return m.gain.value=.5+n*.3,r.connect(o),o.connect(m),f.connect(m),r.connect(h),m.connect(a),h.connect(a),i.start(),{type:"autotune",nodes:[r,o,i,l,...c,f,m,h,a],input:r,output:a}}buildVocoder(t,n){const r=t.createGain(),a=t.createGain(),o=t.createOscillator();o.type="sawtooth",o.frequency.value=110+n*110;const i=t.createGain();i.gain.value=0;const l=8,c=[r,a,o,i],d=t.createGain();d.gain.value=.5+n*.5,c.push(d);for(let h=0;h<l;h++){const m=200*Math.pow(2,h*.5),y=t.createBiquadFilter();y.type="bandpass",y.frequency.value=m,y.Q.value=4;const p=t.createBiquadFilter();p.type="bandpass",p.frequency.value=m,p.Q.value=4;const v=t.createGain();v.gain.value=0,r.connect(y),y.connect(v.gain),o.connect(p),p.connect(v),v.connect(d),c.push(y,p,v)}d.connect(a);const f=t.createGain();return f.gain.value=.3-n*.2,r.connect(f),f.connect(a),c.push(f),o.start(),{type:"vocoder",nodes:c,input:r,output:a}}}const yl=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Ht(e){return 12*Math.log2(e/440)+69}function qn(e){const t=yl[Math.round(e)%12],n=Math.floor(Math.round(e)/12)-1;return`${t}${n}`}function Er(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 kp(e){const{playerName:t,playerColor:n,songTitle:r,songArtist:a,songBpm:o,difficulty:i,pitchPoints:l,notes:c,verseRatings:d,combo:f,classicScore:h,bonusScore:m,totalScore:y,micSettings:p}=e,v=l.filter(ne=>ne.hz>0),x=v.map(ne=>Ht(ne.hz)),b=[],S=[],g=[],k=[...c].sort((ne,oe)=>ne.startTime-oe.startTime);function M(ne){let oe=0,Ie=k.length-1;for(;oe<=Ie;){const Oe=oe+Ie>>>1,Ee=k[Oe];if(ne<Ee.startTime)Ie=Oe-1;else if(ne>Ee.startTime+Ee.duration)oe=Oe+1;else return Ee.pitch}return 0}for(const ne of l){const oe=ne.hz>0?Ht(ne.hz):0,Ie=M(ne.t);if(S.push({t:ne.t,sung:oe,expected:Ie}),oe>0&&Ie>0){const Oe=(oe-Ie)*100;b.push(Oe)}}let N=0;for(const ne of k){const oe=ne.startTime-.3,Ie=ne.startTime+ne.duration;for(;N<v.length&&v[N].t<oe;)N++;N<v.length&&v[N].t<=Ie&&g.push((v[N].t-ne.startTime)*1e3)}const j=b.map(Math.abs),_=[...j].sort((ne,oe)=>ne-oe),P=j.length>0?j.reduce((ne,oe)=>ne+oe,0)/j.length:0,V=Er(_,50),z=j.length>1?Math.sqrt(j.reduce((ne,oe)=>ne+(oe-P)**2,0)/(j.length-1)):0,A=j.filter(ne=>ne<=50).length,I=j.filter(ne=>ne<=15).length,L=j.length>0?A/j.length*100:0,U=j.length>0?I/j.length*100:0,Y=["< −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"],O=new Array(10).fill(0);for(const ne of b){const oe=ne<-100?0:ne<-50?1:ne<-25?2:ne<-15?3:ne<0?4:ne<15?5:ne<25?6:ne<50?7:ne<100?8:9;O[oe]++}const Z=Y.map((ne,oe)=>({centRange:ne,count:O[oe],pct:b.length>0?O[oe]/b.length*100:0})),H=v.map(ne=>ne.hz).sort((ne,oe)=>ne-oe),te=H.length>0?H[0]:0,G=H.length>0?H[H.length-1]:0,B=te>0?Ht(te):0,w=G>0?Ht(G):0,$=w-B,R=[...x].sort((ne,oe)=>ne-oe),T=Er(R,10),C=Er(R,90),E=new Array(12).fill(0);for(const ne of x){const oe=Math.round(ne)%12;oe>=0&&oe<12&&E[oe]++}const F=E.reduce((ne,oe)=>ne+oe,0),q=yl.map((ne,oe)=>({note:ne,count:E[oe],pct:F>0?E[oe]/F*100:0})),Q=Mp(v),J=g.length>0?g.reduce((ne,oe)=>ne+oe,0)/g.length:0,ae=g.length>1?Math.sqrt(g.reduce((ne,oe)=>ne+(oe-J)**2,0)/(g.length-1)):0,re=ae>0?Math.max(0,Math.min(100,100-ae/2)):100;let ee=0,D=0;for(let ne=1;ne<x.length;ne++){const oe=Math.abs(x[ne]-x[ne-1]);ee+=oe,D++}const K=D>0?ee/D*100/12:0,se=l.filter(ne=>ne.hz<=0).length,ce=l.length>0?(1-se/l.length)*100:0,pe=new Map;for(const ne of c){const oe=ne.line??0;pe.has(oe)||pe.set(oe,[]),pe.get(oe).push(ne)}const X=new Map;for(const ne of v){const oe=M(ne.t);if(oe<=0)continue;let Ie=0,Oe=k.length-1,Ee=-1;for(;Ie<=Oe;){const Ce=Ie+Oe>>>1,ft=k[Ce];if(ne.t<ft.startTime)Oe=Ce-1;else if(ne.t>ft.startTime+ft.duration)Ie=Ce+1;else{Ee=ft.line??0;break}}if(Ee<0)continue;const rt=Math.abs((Ht(ne.hz)-oe)*100);X.has(Ee)||X.set(Ee,[]),X.get(Ee).push(rt)}const fe=d.map(ne=>{const oe=pe.get(ne.verseIndex)??[],Ie=X.get(ne.verseIndex)??[],Oe=Ie.length>0?Ie.reduce((Ee,rt)=>Ee+rt,0)/Ie.length:0;return{verseIndex:ne.verseIndex,label:ne.label,hitFraction:ne.hitFraction,avgCentDeviation:Math.round(Oe*10)/10,noteCount:oe.length,notesHit:Math.round(ne.hitFraction*oe.length),comboBonus:ne.comboBonus}}),be=2,Re=.5,Fe=l.length>0?l[l.length-1].t:0,Te=[],Se=S.filter(ne=>ne.sung>0&&ne.expected>0);if(Se.length>0){let ne=0,oe=0,Ie=0;for(let Oe=0;Oe<=Fe;Oe+=Re){const Ee=Oe-be/2,rt=Oe+be/2;for(;oe<Se.length&&Se[oe].t<rt;)Math.abs(Se[oe].sung-Se[oe].expected)<=.5&&Ie++,oe++;for(;ne<oe&&Se[ne].t<Ee;)Math.abs(Se[ne].sung-Se[ne].expected)<=.5&&Ie--,ne++;const Ce=oe-ne;Te.push({t:Oe,accuracy:Ce>0?Ie/Ce*100:0})}}else for(let ne=0;ne<=Fe;ne+=Re)Te.push({t:ne,accuracy:0});return{playerName:t,playerColor:n,songTitle:r,songArtist:a,songBpm:o,difficulty:i,timestamp:new Date().toISOString(),classicScore:h,bonusScore:m,totalScore:y,maxCombo:(f==null?void 0:f.maxCombo)??0,totalComboBonus:(f==null?void 0:f.totalComboBonus)??0,totalPitchPoints:l.length,avgCentDeviation:Math.round(P*10)/10,medianCentDeviation:Math.round(V*10)/10,stdDevCents:Math.round(z*10)/10,intonationAccuracyPct:Math.round(L*10)/10,perfectHitPct:Math.round(U*10)/10,pitchDeviationHistogram:Z,lowestHz:Math.round(te*10)/10,highestHz:Math.round(G*10)/10,lowestNote:B>0?qn(B):"—",highestNote:w>0?qn(w):"—",rangeInSemitones:Math.round($*10)/10,tessituraLow:T>0?qn(T):"—",tessituraHigh:C>0?qn(C):"—",pitchClassDistribution:q,vibrato:Q,avgOnsetDeviationMs:Math.round(J*10)/10,rhythmStabilityPct:Math.round(re*10)/10,jitterPct:Math.round(K*100)/100,shimmerProxy:Math.round(ce*10)/10,verseMetrics:fe,micSettings:p,pitchOverTime:S,accuracyOverTime:Te}}function Mp(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(y=>Ht(y.hz)),n=e.map(y=>y.t),r=.5,a=[],o=[];let i=0,l=0,c=0;for(let y=0;y<e.length;y++){for(l+=t[y],c++;i<y&&n[y]-n[i]>=r;)l-=t[i],c--,i++;if(c<6||(y-i)%10!==0)continue;const p=l/c;let v=0,x=t[i]-p,b=Math.abs(x);for(let k=i+1;k<=y;k++){const M=t[k]-p;M*x<0&&v++,x=M;const N=Math.abs(M);N>b&&(b=N)}const S=n[y]-n[i];if(S<=0)continue;const g=v/2/S;g>=3&&g<=12&&(a.push(g),o.push(b*100))}if(a.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const d=a.reduce((y,p)=>y+p,0)/a.length,f=o.reduce((y,p)=>y+p,0)/o.length,h=Math.sqrt(a.reduce((y,p)=>y+(p-d)**2,0)/a.length),m=Math.max(0,Math.min(100,100-h*20));return{detected:!0,avgRateHz:Math.round(d*10)/10,avgExtentCents:Math.round(f*10)/10,regularityPct:Math.round(m)}}function gl(e,t,n=50,r=30){const a=Math.round(e/1e3*t),o=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))),f=o+c-Math.floor(i/2);f>=0&&f<a&&(l[f]=d)}return l}function Ps(e,t,n=1e3){const r=Math.max(1,Math.round(t/n)),a=Math.ceil(e.length/r),o=new Float32Array(a);for(let l=0;l<a;l++){const c=l*r,d=Math.min(e.length,c+r);let f=0;for(let h=c;h<d;h++)f+=Math.abs(e[h]);o[l]=f/(d-c||1)}let i=0;for(let l=0;l<o.length;l++)o[l]>i&&(i=o[l]);if(i>0)for(let l=0;l<o.length;l++)o[l]=o[l]/i;return{env:o,factor:r}}function jp(e,t){const n=e.length,r=t.length;if(n===0||r===0)return 0;let a={lag:0,score:-1/0};const o=Math.min(2e3,r);for(let i=-o;i<=o;i++){let l=0,c=0,d=0;for(let m=0;m<n;m++){const y=m+i+Math.floor((r-n)/2);if(y<0||y>=r)continue;const p=e[m],v=t[y];l+=p*v,c+=p*p,d+=v*v}const f=Math.sqrt(Math.max(1e-9,c*d)),h=l/f;h>a.score&&(a={lag:i,score:h})}return a.lag}function Rp(e,t,n=50,r=30){try{const a=Math.max(300,Math.round(e.length/t*1e3)),o=gl(a,t,n,r),i=Ps(e,t,1e3),l=Ps(o,t,1e3),d=jp(l.env,i.env)*1e3/1e3;return Math.round(d)}catch{return null}}function bl(e){switch(e){case"1/4":return 1;case"1/8":return .5;case"1/16":return .25;case"1/32":return .125;case"1/4T":return 2/3;case"1/8T":return 1/3;case"1/16T":return 1/6}}function $a(e,t){return bl(e)*60/t}function Zr(e,t,n){const r=$a(t,n);return Math.round(e/r)*r}function Tp(e,t){const{value:n,bpm:r,strength:a=1,quantizeStarts:o=!0,quantizeDurations:i=!1}=t,l=$a(n,r);return e.map(c=>{let{start:d,duration:f}=c;if(o){const h=Math.round(d/l)*l;d=d+(h-d)*a}if(i){const h=Math.max(l,Math.round(f/l)*l);f=f+(h-f)*a}return d===c.start&&f===c.duration?c:{...c,start:d,duration:f}})}function $p(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function Pp(e,t={}){const{timingRange:n=.02,velocityRange:r=10,seed:a}=t,o=a!=null?$p(a):Math.random;return e.map(i=>{const l=(o()*2-1)*n,c=Math.round((o()*2-1)*r);return{...i,start:Math.max(0,i.start+l),velocity:i.velocity!=null?Math.max(1,Math.min(127,(i.velocity??100)+c)):void 0}})}function Ep(){return{start:0,end:0,enabled:!1}}function Ap(e,t){return{...e<t?{start:e,end:t}:{start:t,end:e},enabled:!0}}function Np(e,t,n){return{start:Zr(e.start,t,n),end:Zr(e.end,t,n),enabled:e.enabled}}function Ip(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function Lp(e,t){if(!t.enabled||t.end<=t.start||e<t.start)return e;if(e>=t.end){const n=t.end-t.start;return t.start+(e-t.start)%n}return e}function Xr(e){return e.length===1?e.toLowerCase():e}function Qn(e){var n,r,a,o;const t=[];return(n=e.modifiers)!=null&&n.ctrl&&t.push("Ctrl"),(r=e.modifiers)!=null&&r.shift&&t.push("Shift"),(a=e.modifiers)!=null&&a.alt&&t.push("Alt"),(o=e.modifiers)!=null&&o.meta&&t.push("Meta"),t.push(Xr(e.key)),t.join("+")}function Dp(e,t){var l,c,d,f;const n=Xr(e.key)===Xr(t.key),r=!!e.ctrlKey==!!((l=t.modifiers)!=null&&l.ctrl),a=!!e.shiftKey==!!((c=t.modifiers)!=null&&c.shift),o=!!e.altKey==!!((d=t.modifiers)!=null&&d.alt),i=!!e.metaKey==!!((f=t.modifiers)!=null&&f.meta);return n&&r&&a&&o&&i}class vl{constructor(){this.actions=new Map,this.activeScopes=new Set(["global"]),this.enabled=!0,this.listener=null}register(t){this.actions.set(t.id,{...t,enabled:t.enabled??!0})}unregister(t){this.actions.delete(t)}rebind(t,n){const r=this.actions.get(t);r&&(r.binding=n)}setActiveScopes(t){this.activeScopes.clear(),this.activeScopes.add("global");for(const n of t)this.activeScopes.add(n)}setEnabled(t){this.enabled=t}setActionEnabled(t,n){const r=this.actions.get(t);r&&(r.enabled=n)}findConflicts(){const t=[],n=[...this.actions.values()];for(let r=0;r<n.length;r++)for(let a=r+1;a<n.length;a++){const o=n[r],i=n[a];Qn(o.binding)===Qn(i.binding)&&(o.scope===i.scope||o.scope==="global"||i.scope==="global")&&t.push([o,i])}return t}getGrouped(){const t={};for(const n of this.actions.values())t[n.group]||(t[n.group]=[]),t[n.group].push(n);return t}getAll(){return[...this.actions.values()]}exportConfig(){return[...this.actions.values()].map(t=>({id:t.id,binding:t.binding}))}importConfig(t){for(const n of t)this.rebind(n.id,n.binding)}formatBinding(t){const n=this.actions.get(t);return n?Qn(n.binding):""}handleKeyDown(t){if(!this.enabled)return!1;for(const n of this.actions.values())if(n.enabled&&this.activeScopes.has(n.scope)&&Dp(t,n.binding))return t.preventDefault(),t.stopPropagation(),n.callback(),!0;return!1}attach(){this.listener||(this.listener=t=>{const n=t.target;n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable||this.handleKeyDown(t)},window.addEventListener("keydown",this.listener,!0))}detach(){this.listener&&(window.removeEventListener("keydown",this.listener,!0),this.listener=null)}destroy(){this.detach(),this.actions.clear()}}function Fp(e={}){const t=new vl,n=()=>{},r=[{id:"transport.play",label:"Play / Pause",group:"Transport",scope:"global",binding:{key:" "}},{id:"transport.stop",label:"Stop",group:"Transport",scope:"global",binding:{key:"Escape"}},{id:"transport.record",label:"Record",group:"Transport",scope:"global",binding:{key:"r",modifiers:{ctrl:!0}}},{id:"transport.rewind",label:"Rewind",group:"Transport",scope:"global",binding:{key:"Home"}},{id:"transport.forward",label:"Forward",group:"Transport",scope:"global",binding:{key:"End"}},{id:"transport.loopToggle",label:"Toggle Loop",group:"Transport",scope:"global",binding:{key:"l"}},{id:"edit.undo",label:"Undo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0}}},{id:"edit.redo",label:"Redo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0,shift:!0}}},{id:"edit.cut",label:"Cut",group:"Edit",scope:"editor",binding:{key:"x",modifiers:{ctrl:!0}}},{id:"edit.copy",label:"Copy",group:"Edit",scope:"editor",binding:{key:"c",modifiers:{ctrl:!0}}},{id:"edit.paste",label:"Paste",group:"Edit",scope:"editor",binding:{key:"v",modifiers:{ctrl:!0}}},{id:"edit.delete",label:"Delete",group:"Edit",scope:"editor",binding:{key:"Delete"}},{id:"edit.selectAll",label:"Select All",group:"Edit",scope:"editor",binding:{key:"a",modifiers:{ctrl:!0}}},{id:"edit.duplicate",label:"Duplicate",group:"Edit",scope:"editor",binding:{key:"d",modifiers:{ctrl:!0}}},{id:"view.zoomIn",label:"Zoom In",group:"View",scope:"global",binding:{key:"=",modifiers:{ctrl:!0}}},{id:"view.zoomOut",label:"Zoom Out",group:"View",scope:"global",binding:{key:"-",modifiers:{ctrl:!0}}},{id:"view.zoomFit",label:"Zoom to Fit",group:"View",scope:"global",binding:{key:"0",modifiers:{ctrl:!0}}},{id:"view.toggleMixer",label:"Toggle Mixer",group:"View",scope:"global",binding:{key:"m"}},{id:"view.togglePianoRoll",label:"Toggle Piano Roll",group:"View",scope:"global",binding:{key:"p"}},{id:"pianoRoll.quantize",label:"Quantize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"q"}},{id:"pianoRoll.humanize",label:"Humanize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"h"}},{id:"pianoRoll.velocityUp",label:"Velocity +10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{shift:!0}}},{id:"pianoRoll.velocityDown",label:"Velocity -10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{shift:!0}}},{id:"pianoRoll.octaveUp",label:"Octave Up",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{ctrl:!0,shift:!0}}},{id:"pianoRoll.octaveDown",label:"Octave Down",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{ctrl:!0,shift:!0}}},{id:"timeline.split",label:"Split at Cursor",group:"Timeline",scope:"timeline",binding:{key:"s"}},{id:"timeline.mute",label:"Mute Track",group:"Timeline",scope:"timeline",binding:{key:"m",modifiers:{ctrl:!0}}},{id:"timeline.solo",label:"Solo Track",group:"Timeline",scope:"timeline",binding:{key:"s",modifiers:{ctrl:!0}}},{id:"timeline.addTrack",label:"Add Track",group:"Timeline",scope:"timeline",binding:{key:"t",modifiers:{ctrl:!0}}},{id:"mixer.resetFader",label:"Reset Fader",group:"Mixer",scope:"mixer",binding:{key:"0"}},{id:"mixer.bypassFx",label:"Bypass All FX",group:"Mixer",scope:"mixer",binding:{key:"b"}}];for(const a of r)t.register({...a,callback:e[a.id]??n});return t}function Op(e){return Qn(e)}const _p=["audio/mpeg","audio/wav","audio/ogg","audio/flac","audio/aac","audio/webm","audio/mp4","audio/x-m4a","audio/x-wav","audio/x-aiff","audio/aiff","audio/midi","audio/x-midi"],zp=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],Bp=500*1024*1024,Gp=20;function Tt(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function Wp(e,t){return!!(e.type&&t.some(n=>e.type.startsWith(n.replace("*","")))||e.type.startsWith("audio/"))}function Up(e,t){const n=Tt(e.name);return n!==""&&t.includes(n)}function Pa(e,t={}){const n=t.maxSize??Bp,r=t.allowedTypes??_p,a=t.allowedExtensions??zp,o=t.maxFiles??Gp,i=[],l=[];for(let c=0;c<e.length;c++){const d=e[c];if(c>=o){l.push({file:d,reason:"limit",message:`Exceeded maximum of ${o} files`});continue}if(d.size>n){l.push({file:d,reason:"size",message:`File exceeds ${Math.round(n/1024/1024)}MB limit`});continue}if(!Wp(d,r)&&!Up(d,a)){l.push({file:d,reason:"type",message:`Unsupported file type: ${d.type||Tt(d.name)}`});continue}i.push(d)}return{valid:i,errors:l}}async function xl(e){const t={file:e,name:e.name.replace(/\.[^.]+$/,""),extension:Tt(e.name),sizeBytes:e.size,mimeType:e.type||`audio/${Tt(e.name)}`};try{const n=await e.arrayBuffer(),a=await new OfflineAudioContext(1,1,44100).decodeAudioData(n);t.duration=a.duration,t.sampleRate=a.sampleRate,t.channels=a.numberOfChannels}catch{}return t}function Vp(e){let t=0;return{onDragEnter:n=>{var r;n.preventDefault(),n.stopPropagation(),t++,t===1&&((r=e.onDragEnter)==null||r.call(e))},onDragOver:n=>{n.preventDefault(),n.stopPropagation(),(n instanceof DragEvent&&n.dataTransfer||"dataTransfer"in n&&n.dataTransfer)&&(n.dataTransfer.dropEffect="copy")},onDragLeave:n=>{var r;n.preventDefault(),n.stopPropagation(),t--,t===0&&((r=e.onDragLeave)==null||r.call(e))},onDrop:async n=>{var d,f;n.preventDefault(),n.stopPropagation(),t=0,(d=e.onDragLeave)==null||d.call(e);const r="dataTransfer"in n?n.dataTransfer:null;if(!((f=r==null?void 0:r.files)!=null&&f.length))return;const a=Array.from(r.files),{valid:o,errors:i}=Pa(a,e.validation),l=[],c=[...i];for(const h of o)if(e.probe)try{l.push(await xl(h))}catch{c.push({file:h,reason:"decode",message:"Failed to decode audio"})}else l.push({file:h,name:h.name.replace(/\.[^.]+$/,""),extension:Tt(h.name),sizeBytes:h.size,mimeType:h.type||`audio/${Tt(h.name)}`});e.onDrop({accepted:l,rejected:c})}}}function qp(e={}){return new Promise(t=>{const n=document.createElement("input");n.type="file",n.accept="audio/*,.mid,.midi",n.multiple=e.multiple??!0,n.onchange=async()=>{var l;if(!((l=n.files)!=null&&l.length)){t({accepted:[],rejected:[]});return}const r=Array.from(n.files),{valid:a,errors:o}=Pa(r,e.validation),i=a.map(c=>({file:c,name:c.name.replace(/\.[^.]+$/,""),extension:Tt(c.name),sizeBytes:c.size,mimeType:c.type||`audio/${Tt(c.name)}`}));t({accepted:i,rejected:o})},n.click()})}var wl=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(wl||{}),jt=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(jt||{}),Sl=(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))(Sl||{}),Cl=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(Cl||{});const Hp=["var(--nice-success, #4caf50)","var(--nice-primary, #2196f3)","var(--nice-warning, #ff9800)","var(--nice-accent-pink, #e91e63)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-success, #8bc34a)","var(--nice-warning, #ffc107)"],Nt=["var(--nice-primary, #2196f3)","var(--nice-danger, #e53935)","var(--nice-warning, #ffeb3b)","var(--nice-success, #43a047)","var(--nice-warning, #ff9800)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-warning, #ffc107)","var(--nice-success, #8bc34a)","var(--nice-danger, #f44336)","var(--nice-accent, #3f51b5)","var(--nice-text-secondary, #607d8b)","var(--nice-warning-dark, #795548)","var(--nice-warning, #cddc39)","var(--nice-accent, #673ab7)","#009688"];function Kp(e){for(const t of Nt)if(!e.includes(t))return t;return Nt[Math.floor(Math.random()*Nt.length)]}const Jn=Nt.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function Yp(e){for(let t=0;t<Nt.length;t++){const n=Nt[t],r=Jn[t];if(!e.includes(n)&&!e.includes(r))return r}return Jn[Math.floor(Math.random()*Jn.length)]}const Zp=(e,t)=>t,Xp=u.createContext(Zp);function Qp(){return{t:u.useContext(Xp)}}u.createContext({dir:"ltr",isRTL:!1,flip:e=>e,value:e=>e.ltr});u.createContext(null);u.createContext(null);const Jp={radius:"md",shadow:"md",fill:"solid",buttonStyle:"flat",inputStyle:"bordered",cardStyle:"elevated",badgeStyle:"solid",tabStyle:"underline",toggleStyle:"default",tooltipStyle:"dark",modalStyle:"default",tableStyle:"default",menuStyle:"default",animation:"normal",density:"normal"};u.createContext({displayStyle:"default",variantConfig:Jp,setDisplayStyle:()=>{}});u.createContext({});u.createContext({direction:"ltr",isRTL:!1,flip:e=>e,flipStyle:(e,t)=>({[e]:t})});u.createContext({permissions:{},getAccessMode:()=>"full"});u.createContext(null);const e0=process.env.NODE_ENV==="development";let kl={enabled:e0,slowRenderThreshold:16};const Ml=[],Ea=new Map,jl=new Map;function t0(){Ml.length=0,Ea.clear(),jl.clear()}function n0(e){const t=kl.slowRenderThreshold;return Ml.filter(n=>n.actualDuration>t)}function Pt(e){return e<1?`${(e*1e3).toFixed(0)}μs`:e<1e3?`${e.toFixed(2)}ms`:`${(e/1e3).toFixed(2)}s`}function r0(){const e=Array.from(Ea.values()),t=n0(),n=e.reduce((o,i)=>o+i.renderCount,0),r=e.length>0?e.reduce((o,i)=>o+i.avgRenderTime,0)/e.length:0,a=Array.from(jl.values());return{stats:e,slowRenders:t,totalRenders:n,avgRenderTime:r,marks:a}}function a0(){const e=r0();console.group("%c[Nice2Dev Performance Report]","color: var(--nice-info, #6366f1); font-weight: bold; font-size: 14px"),console.log(`Total renders: ${e.totalRenders}`),console.log(`Average render time: ${Pt(e.avgRenderTime)}`),console.log(`Slow renders: ${e.slowRenders.length}`),console.group("Component Stats"),console.table(e.stats.sort((t,n)=>n.totalRenderTime-t.totalRenderTime).map(t=>({Name:t.componentName,Renders:t.renderCount,"Avg Time":Pt(t.avgRenderTime),"Max Time":Pt(t.maxRenderTime),"Total Time":Pt(t.totalRenderTime),"Slow Renders":t.slowRenderCount}))),console.groupEnd(),e.slowRenders.length>0&&(console.group("Slow Renders (last 10)"),console.table(e.slowRenders.slice(-10).map(t=>({Component:t.componentName,Phase:t.phase,Duration:Pt(t.actualDuration),Time:new Date(t.timestamp).toLocaleTimeString()}))),console.groupEnd()),e.marks.length>0&&(console.group("Custom Marks"),console.table(e.marks.filter(t=>t.duration).map(t=>({Name:t.name,Duration:Pt(t.duration)}))),console.groupEnd()),console.groupEnd()}const s0=u.memo(({position:e="bottom-right",defaultCollapsed:t=!0})=>{const[n,r]=u.useState(t),[a,o]=u.useState([]),[i,l]=u.useState({used:0,total:0});if(u.useEffect(()=>{const d=()=>{const h=Array.from(Ea.values());o(h.sort((y,p)=>p.totalRenderTime-y.totalRenderTime).slice(0,10));const m=window.performance;m.memory&&l({used:m.memory.usedJSHeapSize/1024/1024,total:m.memory.totalJSHeapSize/1024/1024})};d();const f=setInterval(d,2e3);return()=>clearInterval(f)},[]),!kl.enabled)return null;const c={position:"fixed",zIndex:99999,...e.includes("top")?{top:8}:{bottom:8},...e.includes("left")?{left:8}:{right:8}};return s.jsxs("div",{style:{...c,background:"var(--nice-overlay-85, rgba(0, 0, 0, 0.85))",color:"var(--bg-primary, #fff)",borderRadius:8,fontSize:11,fontFamily:"Monaco, Consolas, monospace",padding:n?"4px 8px":8,maxWidth:n?"auto":300,maxHeight:n?"auto":400,overflow:"auto"},children:[s.jsxs("div",{style:{cursor:"pointer",display:"flex",alignItems:"center",gap:8},onClick:()=>r(d=>!d),children:[s.jsx("span",{style:{color:"var(--color-success, #22c55e)"},children:"●"}),s.jsx("span",{children:"Profiler"}),i.used>0&&s.jsxs("span",{style:{color:i.used>100?"var(--color-warning, #f59e0b)":"var(--text-muted, #64748b)"},children:[i.used.toFixed(0),"MB"]}),s.jsx("span",{style:{marginLeft:"auto",opacity:.5},children:n?"▼":"▲"})]}),!n&&s.jsxs("div",{style:{marginTop:8},children:[s.jsx("div",{style:{borderBottom:"1px solid var(--border-color, #333)",paddingBottom:4,marginBottom:8},children:s.jsx("strong",{children:"Top Components"})}),a.map(d=>s.jsxs("div",{style:{marginBottom:4,display:"flex",gap:8},children:[s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:d.componentName}),s.jsx("span",{style:{color:d.avgRenderTime>16?"var(--color-warning, #f59e0b)":"var(--color-success, #22c55e)"},children:Pt(d.avgRenderTime)}),s.jsxs("span",{style:{color:"var(--text-muted, #64748b)",minWidth:30,textAlign:"right"},children:["x",d.renderCount]})]},d.componentName)),s.jsxs("div",{style:{marginTop:8,display:"flex",gap:8},children:[s.jsx("button",{onClick:a0,style:{flex:1,padding:"4px 8px",background:"var(--bg-tertiary, #333)",border:"none",borderRadius:4,color:"var(--bg-primary, #fff)",cursor:"pointer",fontSize:10},children:"Print Report"}),s.jsx("button",{onClick:t0,style:{flex:1,padding:"4px 8px",background:"var(--bg-tertiary, #333)",border:"none",borderRadius:4,color:"var(--bg-primary, #fff)",cursor:"pointer",fontSize:10},children:"Clear"})]})]})]})});s0.displayName="ProfilerOverlay";process.env.NODE_ENV;u.createContext(null);const o0=u.createContext({enabled:!0,active:!1,run:()=>{}});function i0(){return u.useContext(o0)}function l0(e,t){if(!e)return null;if(e===!0)return t&&t.length>0?t:null;if(Array.isArray(e))return e.length>0?e:null;const n=e.steps??t;return n&&n.length>0?n:null}function c0(e,t){return e.map(n=>({target:n.target,title:n.titleKey?t(n.titleKey,n.title??""):n.title??"",content:n.contentKey?t(n.contentKey,n.content??""):n.content??"",placement:n.placement,highlightPadding:n.highlightPadding,showArrow:n.showArrow,scrollIntoView:n.scrollIntoView,disableInteraction:n.disableInteraction}))}const d0=({steps:e,autoStart:t,label:n,size:r="md",className:a,style:o,"data-testid":i})=>{const{enabled:l,run:c}=i0(),{t:d}=Qp();if(!l||!e||e.length===0)return null;const f=n??d("tutorial.startAria","Start tutorial");return s.jsx("button",{type:"button",className:`nice-tutorial-button nice-tutorial-button--${r}`+(a?` ${a}`:""),style:o,"data-testid":i,"aria-label":f,title:f,onClick:()=>c(c0(e,d),{autoStart:t}),children:"?"})},Es="nice-tutorial-button-styles";if(typeof document<"u"&&!document.getElementById(Es)){const e=document.createElement("style");e.id=Es,e.textContent=`
413
- .nice-tutorial-button {
414
- display: inline-flex;
415
- align-items: center;
416
- justify-content: center;
417
- border: 1px solid var(--nice-border, #cbd5e1);
418
- background: var(--nice-bg, #fff);
419
- color: var(--nice-text-secondary, #475569);
420
- border-radius: var(--nice-radius-full, 9999px);
421
- cursor: help;
422
- font-weight: 700;
423
- line-height: 1;
424
- padding: 0;
425
- transition: background var(--nice-transition, 200ms ease), color var(--nice-transition, 200ms ease), border-color var(--nice-transition, 200ms ease);
426
- }
427
- .nice-tutorial-button:hover {
428
- background: var(--nice-primary, #2563eb);
429
- border-color: var(--nice-primary, #2563eb);
430
- color: var(--nice-text-inverse, #fff);
431
- }
432
- .nice-tutorial-button:focus-visible {
433
- outline: none;
434
- box-shadow: 0 0 0 2px var(--nice-bg, #fff), 0 0 0 4px var(--nice-primary, #2563eb);
435
- }
436
- .nice-tutorial-button--sm { width: 16px; height: 16px; font-size: 11px; }
437
- .nice-tutorial-button--md { width: 20px; height: 20px; font-size: 12px; }
438
- `,document.head.appendChild(e)}u.createContext(null);u.createContext(null);u.createContext(null);const Rl={space1:"4px",space2:"8px",space3:"12px",space4:"16px",space5:"20px",space6:"24px",space8:"32px"},Tl={fontFamily:"'Inter', system-ui, -apple-system, sans-serif",fontSizeXs:"0.75rem",fontSizeSm:"0.8125rem",fontSizeMd:"0.875rem",fontSizeLg:"1rem",fontSizeXl:"1.125rem",fontWeightNormal:400,fontWeightMedium:500,fontWeightSemibold:600,fontWeightBold:700,lineHeight:1.5},$l={fast:"120ms ease",normal:"200ms ease",slow:"300ms ease"},Pl=e=>({color:e,radiusSm:"4px",radiusMd:"6px",radiusLg:"8px",radiusXl:"12px",radiusFull:"9999px"}),u0={sm:"0 1px 2px rgba(0,0,0,0.05)",md:"0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -2px rgba(0,0,0,0.1)",lg:"0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -4px rgba(0,0,0,0.1)",xl:"0 20px 25px -5px rgba(0,0,0,0.1), 0 8px 10px -6px rgba(0,0,0,0.1)"},f0={sm:"0 1px 2px rgba(0,0,0,0.3)",md:"0 4px 6px -1px rgba(0,0,0,0.4)",lg:"0 10px 15px -3px rgba(0,0,0,0.4)",xl:"0 20px 25px -5px rgba(0,0,0,0.4)"};function de(e,t,n,r,a){return{name:e,darkMode:"light",colors:{...t,surface:t.surface??n.primary,surfaceHover:t.surfaceHover??n.secondary},backgrounds:{...n,elevated:n.elevated??n.primary,inset:n.inset??n.tertiary,canvas:n.canvas??n.primary},text:{...r,inverse:r.inverse??"#ffffff"},borders:Pl(a),shadows:u0,spacing:Rl,typography:Tl,transitions:$l}}function Be(e,t,n,r,a){return{name:e,darkMode:"dark",colors:{...t,surface:t.surface??n.secondary,surfaceHover:t.surfaceHover??n.tertiary},backgrounds:{...n,elevated:n.elevated??n.secondary,inset:n.inset??n.primary,canvas:n.canvas??n.primary},text:{...r,inverse:r.inverse??"#0f172a"},borders:Pl(a),shadows:f0,spacing:Rl,typography:Tl,transitions:$l}}de("Slate",{primary:"#64748b",primaryHover:"#475569",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#f8fafc",secondary:"#f1f5f9",tertiary:"#e2e8f0",hover:"#e2e8f0"},{primary:"#1e293b",secondary:"#475569",muted:"#94a3b8"},"#cbd5e1");de("Zinc",{primary:"#71717a",primaryHover:"#52525b",success:"#22c55e",warning:"#eab308",error:"#ef4444",info:"#06b6d4"},{primary:"#fafafa",secondary:"#f4f4f5",tertiary:"#e4e4e7",hover:"#e4e4e7"},{primary:"#18181b",secondary:"#3f3f46",muted:"#a1a1aa"},"#d4d4d8");de("Stone",{primary:"#78716c",primaryHover:"#57534e",success:"#16a34a",warning:"#ca8a04",error:"#dc2626",info:"#0891b2"},{primary:"#fafaf9",secondary:"#f5f5f4",tertiary:"#e7e5e4",hover:"#e7e5e4"},{primary:"#1c1917",secondary:"#44403c",muted:"#a8a29e"},"#d6d3d1");de("Cool Gray",{primary:"#6b7280",primaryHover:"#4b5563",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#3b82f6"},{primary:"#f9fafb",secondary:"#f3f4f6",tertiary:"#e5e7eb",hover:"#e5e7eb"},{primary:"#111827",secondary:"#374151",muted:"#9ca3af"},"#d1d5db");de("Warm Gray",{primary:"#7c7568",primaryHover:"#5c564c",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#faf9f7",secondary:"#f5f4f0",tertiary:"#e8e6e1",hover:"#e8e6e1"},{primary:"#1f1d19",secondary:"#4a463d",muted:"#a09888"},"#d4d0c8");de("Silver",{primary:"#94a3b8",primaryHover:"#64748b",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#38bdf8"},{primary:"#f8fafc",secondary:"#f1f5f9",tertiary:"#e2e8f0",hover:"#e2e8f0"},{primary:"#334155",secondary:"#64748b",muted:"#94a3b8"},"#cbd5e1");de("Charcoal",{primary:"#374151",primaryHover:"#1f2937",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0284c7"},{primary:"#f9fafb",secondary:"#f3f4f6",tertiary:"#e5e7eb",hover:"#e5e7eb"},{primary:"#111827",secondary:"#374151",muted:"#6b7280"},"#d1d5db");de("Ivory",{primary:"#92876d",primaryHover:"#7a6f55",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#fffef7",secondary:"#faf6eb",tertiary:"#f0ead6",hover:"#f0ead6"},{primary:"#2b2517",secondary:"#5c5340",muted:"#9c9280"},"#ddd8c4");de("Rose",{primary:"#e11d48",primaryHover:"#be123c",success:"#16a34a",warning:"#ea580c",error:"#dc2626",info:"#0891b2"},{primary:"#fff1f2",secondary:"#ffe4e6",tertiary:"#fecdd3",hover:"#ffe4e6"},{primary:"#4c0519",secondary:"#881337",muted:"#f43f5e"},"#fda4af");de("Emerald",{primary:"#059669",primaryHover:"#047857",success:"#16a34a",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#ecfdf5",secondary:"#d1fae5",tertiary:"#a7f3d0",hover:"#d1fae5"},{primary:"#064e3b",secondary:"#065f46",muted:"#34d399"},"#6ee7b7");de("Amber",{primary:"#d97706",primaryHover:"#b45309",success:"#16a34a",warning:"#ca8a04",error:"#dc2626",info:"#0284c7"},{primary:"#fffbeb",secondary:"#fef3c7",tertiary:"#fde68a",hover:"#fef3c7"},{primary:"#451a03",secondary:"#78350f",muted:"#f59e0b"},"#fcd34d");de("Violet",{primary:"#7c3aed",primaryHover:"#6d28d9",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#f5f3ff",secondary:"#ede9fe",tertiary:"#ddd6fe",hover:"#ede9fe"},{primary:"#2e1065",secondary:"#4c1d95",muted:"#a78bfa"},"#c4b5fd");de("Teal",{primary:"#0d9488",primaryHover:"#0f766e",success:"#16a34a",warning:"#d97706",error:"#dc2626",info:"#0284c7"},{primary:"#f0fdfa",secondary:"#ccfbf1",tertiary:"#99f6e4",hover:"#ccfbf1"},{primary:"#134e4a",secondary:"#115e59",muted:"#2dd4bf"},"#5eead4");de("Indigo",{primary:"#4f46e5",primaryHover:"#4338ca",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#eef2ff",secondary:"#e0e7ff",tertiary:"#c7d2fe",hover:"#e0e7ff"},{primary:"#1e1b4b",secondary:"#312e81",muted:"#818cf8"},"#a5b4fc");de("Cyan",{primary:"#0891b2",primaryHover:"#0e7490",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#0284c7"},{primary:"#ecfeff",secondary:"#cffafe",tertiary:"#a5f3fc",hover:"#cffafe"},{primary:"#164e63",secondary:"#155e75",muted:"#22d3ee"},"#67e8f9");de("Lime",{primary:"#65a30d",primaryHover:"#4d7c0f",success:"#16a34a",warning:"#ca8a04",error:"#dc2626",info:"#0891b2"},{primary:"#f7fee7",secondary:"#ecfccb",tertiary:"#d9f99d",hover:"#ecfccb"},{primary:"#1a2e05",secondary:"#365314",muted:"#84cc16"},"#bef264");de("Pink",{primary:"#db2777",primaryHover:"#be185d",success:"#10b981",warning:"#f59e0b",error:"#dc2626",info:"#06b6d4"},{primary:"#fdf2f8",secondary:"#fce7f3",tertiary:"#fbcfe8",hover:"#fce7f3"},{primary:"#500724",secondary:"#831843",muted:"#f472b6"},"#f9a8d4");de("Orange",{primary:"#ea580c",primaryHover:"#c2410c",success:"#16a34a",warning:"#ca8a04",error:"#dc2626",info:"#0891b2"},{primary:"#fff7ed",secondary:"#ffedd5",tertiary:"#fed7aa",hover:"#ffedd5"},{primary:"#431407",secondary:"#7c2d12",muted:"#fb923c"},"#fdba74");de("Fuchsia",{primary:"#c026d3",primaryHover:"#a21caf",success:"#10b981",warning:"#eab308",error:"#ef4444",info:"#06b6d4"},{primary:"#fdf4ff",secondary:"#fae8ff",tertiary:"#f5d0fe",hover:"#fae8ff"},{primary:"#4a044e",secondary:"#701a75",muted:"#d946ef"},"#e879f9");de("Sky",{primary:"#0284c7",primaryHover:"#0369a1",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#f0f9ff",secondary:"#e0f2fe",tertiary:"#bae6fd",hover:"#e0f2fe"},{primary:"#0c4a6e",secondary:"#075985",muted:"#38bdf8"},"#7dd3fc");de("Ruby",{primary:"#be123c",primaryHover:"#9f1239",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0284c7"},{primary:"#fff1f2",secondary:"#ffe4e6",tertiary:"#fecdd3",hover:"#ffe4e6"},{primary:"#4c0519",secondary:"#881337",muted:"#fb7185"},"#fda4af");de("Coral",{primary:"#f97316",primaryHover:"#ea580c",success:"#10b981",warning:"#eab308",error:"#ef4444",info:"#06b6d4"},{primary:"#fff7ed",secondary:"#ffedd5",tertiary:"#fed7aa",hover:"#ffedd5"},{primary:"#431407",secondary:"#9a3412",muted:"#fb923c"},"#fdba74");Be("Midnight",{primary:"#818cf8",primaryHover:"#6366f1",success:"#34d399",warning:"#fbbf24",error:"#f87171",info:"#22d3ee"},{primary:"#020617",secondary:"#0f172a",tertiary:"#1e293b",hover:"#1e293b"},{primary:"#f1f5f9",secondary:"#94a3b8",muted:"#475569"},"#1e293b");Be("Obsidian",{primary:"#a78bfa",primaryHover:"#8b5cf6",success:"#4ade80",warning:"#facc15",error:"#fb7185",info:"#38bdf8"},{primary:"#09090b",secondary:"#18181b",tertiary:"#27272a",hover:"#27272a"},{primary:"#fafafa",secondary:"#a1a1aa",muted:"#52525b"},"#3f3f46");Be("Eclipse",{primary:"#c084fc",primaryHover:"#a855f7",success:"#34d399",warning:"#fbbf24",error:"#f87171",info:"#67e8f9"},{primary:"#0c0a1d",secondary:"#1a1533",tertiary:"#2a2248",hover:"#2a2248"},{primary:"#f5f3ff",secondary:"#a78bfa",muted:"#6d5eac"},"#3b3266");Be("Onyx",{primary:"#60a5fa",primaryHover:"#3b82f6",success:"#4ade80",warning:"#fbbf24",error:"#f87171",info:"#22d3ee"},{primary:"#000000",secondary:"#0a0a0a",tertiary:"#171717",hover:"#171717"},{primary:"#ffffff",secondary:"#a3a3a3",muted:"#525252"},"#262626");Be("Carbon",{primary:"#38bdf8",primaryHover:"#0ea5e9",success:"#4ade80",warning:"#facc15",error:"#f87171",info:"#67e8f9"},{primary:"#161616",secondary:"#262626",tertiary:"#393939",hover:"#393939"},{primary:"#f4f4f4",secondary:"#c6c6c6",muted:"#6f6f6f"},"#525252");Be("Cosmos",{primary:"#6366f1",primaryHover:"#4f46e5",success:"#34d399",warning:"#fbbf24",error:"#f87171",info:"#22d3ee"},{primary:"#030712",secondary:"#111827",tertiary:"#1f2937",hover:"#1f2937"},{primary:"#e5e7eb",secondary:"#9ca3af",muted:"#4b5563"},"#374151");Be("Nebula",{primary:"#e879f9",primaryHover:"#d946ef",success:"#4ade80",warning:"#fbbf24",error:"#fb7185",info:"#67e8f9"},{primary:"#0d0117",secondary:"#1a0533",tertiary:"#2d0a52",hover:"#2d0a52"},{primary:"#fae8ff",secondary:"#d8b4fe",muted:"#7c3aed"},"#581c87");Be("Abyss",{primary:"#22d3ee",primaryHover:"#06b6d4",success:"#34d399",warning:"#fbbf24",error:"#f87171",info:"#38bdf8"},{primary:"#001219",secondary:"#002a3a",tertiary:"#003e54",hover:"#003e54"},{primary:"#e0f2fe",secondary:"#7dd3fc",muted:"#0369a1"},"#075985");Be("Shadow",{primary:"#a3a3a3",primaryHover:"#737373",success:"#4ade80",warning:"#facc15",error:"#f87171",info:"#38bdf8"},{primary:"#171717",secondary:"#1f1f1f",tertiary:"#2a2a2a",hover:"#2a2a2a"},{primary:"#e5e5e5",secondary:"#a3a3a3",muted:"#525252"},"#404040");Be("Emerald Dark",{primary:"#34d399",primaryHover:"#10b981",success:"#4ade80",warning:"#fbbf24",error:"#f87171",info:"#22d3ee"},{primary:"#022c22",secondary:"#064e3b",tertiary:"#065f46",hover:"#065f46"},{primary:"#ecfdf5",secondary:"#6ee7b7",muted:"#047857"},"#047857");de("Forest",{primary:"#166534",primaryHover:"#14532d",success:"#22c55e",warning:"#ca8a04",error:"#dc2626",info:"#0891b2"},{primary:"#f0fdf4",secondary:"#dcfce7",tertiary:"#bbf7d0",hover:"#dcfce7"},{primary:"#052e16",secondary:"#166534",muted:"#4ade80"},"#86efac");de("Ocean",{primary:"#0369a1",primaryHover:"#075985",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0284c7"},{primary:"#f0f9ff",secondary:"#e0f2fe",tertiary:"#bae6fd",hover:"#e0f2fe"},{primary:"#0c4a6e",secondary:"#0369a1",muted:"#38bdf8"},"#7dd3fc");de("Desert",{primary:"#b45309",primaryHover:"#92400e",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#fefce8",secondary:"#fef9c3",tertiary:"#fef08a",hover:"#fef9c3"},{primary:"#422006",secondary:"#713f12",muted:"#ca8a04"},"#fde047");de("Sunset",{primary:"#ea580c",primaryHover:"#c2410c",success:"#16a34a",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#fff7ed",secondary:"#ffedd5",tertiary:"#fed7aa",hover:"#ffedd5"},{primary:"#431407",secondary:"#9a3412",muted:"#f97316"},"#fdba74");de("Aurora",{primary:"#0d9488",primaryHover:"#0f766e",success:"#22c55e",warning:"#eab308",error:"#ef4444",info:"#06b6d4"},{primary:"#f0fdfa",secondary:"#ccfbf1",tertiary:"#99f6e4",hover:"#ccfbf1"},{primary:"#134e4a",secondary:"#115e59",muted:"#2dd4bf"},"#5eead4");de("Lavender",{primary:"#7e22ce",primaryHover:"#6b21a8",success:"#16a34a",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#faf5ff",secondary:"#f3e8ff",tertiary:"#e9d5ff",hover:"#f3e8ff"},{primary:"#3b0764",secondary:"#581c87",muted:"#a855f7"},"#d8b4fe");de("Autumn",{primary:"#c2410c",primaryHover:"#9a3412",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#fef2f2",secondary:"#fee2e2",tertiary:"#fecaca",hover:"#fee2e2"},{primary:"#450a0a",secondary:"#7f1d1d",muted:"#f87171"},"#fca5a5");de("Spring",{primary:"#16a34a",primaryHover:"#15803d",success:"#22c55e",warning:"#eab308",error:"#ef4444",info:"#06b6d4"},{primary:"#f0fdf4",secondary:"#dcfce7",tertiary:"#bbf7d0",hover:"#dcfce7"},{primary:"#14532d",secondary:"#166534",muted:"#4ade80"},"#86efac");de("Arctic",{primary:"#0ea5e9",primaryHover:"#0284c7",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#f0f9ff",secondary:"#e0f2fe",tertiary:"#bae6fd",hover:"#e0f2fe"},{primary:"#0c4a6e",secondary:"#0369a1",muted:"#7dd3fc"},"#bae6fd");de("Tropical",{primary:"#0d9488",primaryHover:"#0f766e",success:"#16a34a",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#ecfdf5",secondary:"#d1fae5",tertiary:"#a7f3d0",hover:"#d1fae5"},{primary:"#064e3b",secondary:"#065f46",muted:"#6ee7b7"},"#a7f3d0");de("Pastel Rose",{primary:"#f472b6",primaryHover:"#ec4899",success:"#4ade80",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#fdf2f8",secondary:"#fce7f3",tertiary:"#fbcfe8",hover:"#fce7f3"},{primary:"#831843",secondary:"#9d174d",muted:"#f9a8d4"},"#f9a8d4");de("Pastel Sky",{primary:"#38bdf8",primaryHover:"#0ea5e9",success:"#4ade80",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#f0f9ff",secondary:"#e0f2fe",tertiary:"#bae6fd",hover:"#e0f2fe"},{primary:"#075985",secondary:"#0369a1",muted:"#7dd3fc"},"#bae6fd");de("Pastel Mint",{primary:"#34d399",primaryHover:"#10b981",success:"#4ade80",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#ecfdf5",secondary:"#d1fae5",tertiary:"#a7f3d0",hover:"#d1fae5"},{primary:"#065f46",secondary:"#047857",muted:"#6ee7b7"},"#a7f3d0");de("Pastel Peach",{primary:"#fb923c",primaryHover:"#f97316",success:"#4ade80",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#fff7ed",secondary:"#ffedd5",tertiary:"#fed7aa",hover:"#ffedd5"},{primary:"#7c2d12",secondary:"#9a3412",muted:"#fdba74"},"#fed7aa");de("Pastel Lavender",{primary:"#a78bfa",primaryHover:"#8b5cf6",success:"#4ade80",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#f5f3ff",secondary:"#ede9fe",tertiary:"#ddd6fe",hover:"#ede9fe"},{primary:"#4c1d95",secondary:"#5b21b6",muted:"#c4b5fd"},"#ddd6fe");de("Pastel Lemon",{primary:"#facc15",primaryHover:"#eab308",success:"#4ade80",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#fefce8",secondary:"#fef9c3",tertiary:"#fef08a",hover:"#fef9c3"},{primary:"#713f12",secondary:"#854d0e",muted:"#fde047"},"#fef08a");de("Pastel Sage",{primary:"#86efac",primaryHover:"#4ade80",success:"#22c55e",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#f0fdf4",secondary:"#dcfce7",tertiary:"#bbf7d0",hover:"#dcfce7"},{primary:"#166534",secondary:"#15803d",muted:"#86efac"},"#bbf7d0");de("Pastel Coral",{primary:"#fb7185",primaryHover:"#f43f5e",success:"#4ade80",warning:"#fcd34d",error:"#ef4444",info:"#67e8f9"},{primary:"#fff1f2",secondary:"#ffe4e6",tertiary:"#fecdd3",hover:"#ffe4e6"},{primary:"#881337",secondary:"#9f1239",muted:"#fda4af"},"#fecdd3");de("Banking",{primary:"#1e3a5f",primaryHover:"#152c4a",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#f8fafc",secondary:"#f1f5f9",tertiary:"#e2e8f0",hover:"#e2e8f0"},{primary:"#0f172a",secondary:"#334155",muted:"#94a3b8"},"#cbd5e1");de("Healthcare",{primary:"#0891b2",primaryHover:"#0e7490",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0284c7"},{primary:"#f0fdfa",secondary:"#e0f7fa",tertiary:"#b2ebf2",hover:"#e0f7fa"},{primary:"#134e4a",secondary:"#1a6b6a",muted:"#80cbc4"},"#b2dfdb");de("Legal",{primary:"#1e293b",primaryHover:"#0f172a",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0284c7"},{primary:"#fafaf9",secondary:"#f5f5f4",tertiary:"#e7e5e4",hover:"#e7e5e4"},{primary:"#0f172a",secondary:"#44403c",muted:"#a8a29e"},"#d6d3d1");de("Tech Startup",{primary:"#7c3aed",primaryHover:"#6d28d9",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#faf5ff",secondary:"#f3e8ff",tertiary:"#e9d5ff",hover:"#f3e8ff"},{primary:"#1e1b4b",secondary:"#4c1d95",muted:"#a78bfa"},"#c4b5fd");de("Enterprise",{primary:"#1e40af",primaryHover:"#1e3a8a",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#eff6ff",secondary:"#dbeafe",tertiary:"#bfdbfe",hover:"#dbeafe"},{primary:"#1e3a5f",secondary:"#1e40af",muted:"#60a5fa"},"#93c5fd");de("Government",{primary:"#1d4ed8",primaryHover:"#1e40af",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#f8fafc",secondary:"#f1f5f9",tertiary:"#e2e8f0",hover:"#e2e8f0"},{primary:"#0f172a",secondary:"#1e293b",muted:"#64748b"},"#cbd5e1");de("Education",{primary:"#059669",primaryHover:"#047857",success:"#16a34a",warning:"#f59e0b",error:"#ef4444",info:"#0891b2"},{primary:"#f0fdf9",secondary:"#d1fae5",tertiary:"#a7f3d0",hover:"#d1fae5"},{primary:"#064e3b",secondary:"#065f46",muted:"#6ee7b7"},"#a7f3d0");de("Real Estate",{primary:"#92400e",primaryHover:"#78350f",success:"#059669",warning:"#b45309",error:"#dc2626",info:"#0891b2"},{primary:"#fffbeb",secondary:"#fef3c7",tertiary:"#fde68a",hover:"#fef3c7"},{primary:"#422006",secondary:"#713f12",muted:"#d97706"},"#fcd34d");de("Nord",{primary:"#5e81ac",primaryHover:"#4c6b90",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",info:"#88c0d0"},{primary:"#eceff4",secondary:"#e5e9f0",tertiary:"#d8dee9",hover:"#d8dee9"},{primary:"#2e3440",secondary:"#3b4252",muted:"#4c566a"},"#d8dee9");Be("Dracula",{primary:"#bd93f9",primaryHover:"#9d79d9",success:"#50fa7b",warning:"#f1fa8c",error:"#ff5555",info:"#8be9fd"},{primary:"#282a36",secondary:"#343746",tertiary:"#44475a",hover:"#44475a"},{primary:"#f8f8f2",secondary:"#c0c0c0",muted:"#6272a4"},"#44475a");de("Solarized Light",{primary:"#268bd2",primaryHover:"#1a6da0",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#2aa198"},{primary:"#fdf6e3",secondary:"#eee8d5",tertiary:"#e0dbc7",hover:"#eee8d5"},{primary:"#073642",secondary:"#586e75",muted:"#93a1a1"},"#eee8d5");Be("Solarized Dark",{primary:"#268bd2",primaryHover:"#3d98db",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#2aa198"},{primary:"#002b36",secondary:"#073642",tertiary:"#0a4858",hover:"#073642"},{primary:"#eee8d5",secondary:"#93a1a1",muted:"#586e75"},"#073642");Be("Monokai",{primary:"#66d9ef",primaryHover:"#45c0d6",success:"#a6e22e",warning:"#e6db74",error:"#f92672",info:"#66d9ef"},{primary:"#272822",secondary:"#34352e",tertiary:"#3e3d32",hover:"#3e3d32"},{primary:"#f8f8f2",secondary:"#cfcfc2",muted:"#75715e"},"#3e3d32");Be("One Dark",{primary:"#61afef",primaryHover:"#4b9ee0",success:"#98c379",warning:"#e5c07b",error:"#e06c75",info:"#56b6c2"},{primary:"#282c34",secondary:"#2c313a",tertiary:"#353b45",hover:"#353b45"},{primary:"#abb2bf",secondary:"#828997",muted:"#545862"},"#3e4452");Be("Synthwave",{primary:"#ff7edb",primaryHover:"#e660c2",success:"#72f1b8",warning:"#fede5d",error:"#fe4450",info:"#36f9f6"},{primary:"#241b2f",secondary:"#2d2140",tertiary:"#362a50",hover:"#362a50"},{primary:"#f0e4fc",secondary:"#b4a0cc",muted:"#6c5c84"},"#4a3866");de("Vaporwave",{primary:"#ff71ce",primaryHover:"#e655b5",success:"#78dcca",warning:"#ffb86c",error:"#ff5555",info:"#76e8fc"},{primary:"#fce4f7",secondary:"#e8d0f4",tertiary:"#d4bcf0",hover:"#e8d0f4"},{primary:"#4a1a4e",secondary:"#7b3f7d",muted:"#c080c0"},"#d8a8e8");Be("Terminal Green",{primary:"#00ff41",primaryHover:"#00cc34",success:"#00ff41",warning:"#ffff00",error:"#ff0000",info:"#00ffff"},{primary:"#0a0a0a",secondary:"#0d1a0d",tertiary:"#1a2e1a",hover:"#1a2e1a"},{primary:"#00ff41",secondary:"#00cc33",muted:"#008822"},"#003300");de("Sepia",{primary:"#8b6914",primaryHover:"#704f10",success:"#6b8e23",warning:"#cd853f",error:"#b22222",info:"#5f9ea0"},{primary:"#faf0e6",secondary:"#f5e6d3",tertiary:"#eddcc7",hover:"#f5e6d3"},{primary:"#3e2723",secondary:"#5d4037",muted:"#a1887f"},"#d7ccc8");de("Vintage",{primary:"#8d6e63",primaryHover:"#6d4c41",success:"#66bb6a",warning:"#ffb300",error:"#e53935",info:"#29b6f6"},{primary:"#efebe9",secondary:"#d7ccc8",tertiary:"#bcaaa4",hover:"#d7ccc8"},{primary:"#3e2723",secondary:"#5d4037",muted:"#a1887f"},"#bcaaa4");Be("Cyberpunk",{primary:"#00f0ff",primaryHover:"#00c8d4",success:"#39ff14",warning:"#ffff00",error:"#ff003c",info:"#bf00ff"},{primary:"#0a0e17",secondary:"#131824",tertiary:"#1c2333",hover:"#1c2333"},{primary:"#e0fbfc",secondary:"#80d4dd",muted:"#3a6b72"},"#1c3a44");Be("Neon",{primary:"#ff00ff",primaryHover:"#cc00cc",success:"#00ff00",warning:"#ffff00",error:"#ff0000",info:"#00ffff"},{primary:"#0d0d0d",secondary:"#1a1a1a",tertiary:"#262626",hover:"#262626"},{primary:"#ffffff",secondary:"#cccccc",muted:"#666666"},"#333333");Be("Retrowave",{primary:"#f77fbe",primaryHover:"#e462a3",success:"#72f1b8",warning:"#ffe261",error:"#ff4444",info:"#79e8fb"},{primary:"#1b0a2e",secondary:"#261440",tertiary:"#321e52",hover:"#321e52"},{primary:"#ffe6f7",secondary:"#c9a0c9",muted:"#6b4c7a"},"#4a2d66");de("Christmas",{primary:"#c41e3a",primaryHover:"#a01830",success:"#228b22",warning:"#ffd700",error:"#dc2626",info:"#0891b2"},{primary:"#fef2f2",secondary:"#fde8e8",tertiary:"#f8d0d0",hover:"#fde8e8"},{primary:"#3b0a0a",secondary:"#7f1d1d",muted:"#dc6868"},"#e8a0a0");Be("Halloween",{primary:"#ff6600",primaryHover:"#e05500",success:"#4ade80",warning:"#fbbf24",error:"#ff0000",info:"#9333ea"},{primary:"#1a0a00",secondary:"#2d1500",tertiary:"#402000",hover:"#402000"},{primary:"#ffedd5",secondary:"#fdba74",muted:"#9a5c28"},"#5c3400");de("Valentine",{primary:"#e11d48",primaryHover:"#be123c",success:"#10b981",warning:"#f59e0b",error:"#dc2626",info:"#ec4899"},{primary:"#fff1f2",secondary:"#ffe4e6",tertiary:"#fecdd3",hover:"#ffe4e6"},{primary:"#4c0519",secondary:"#881337",muted:"#f9a8d4"},"#fda4af");de("Easter",{primary:"#a78bfa",primaryHover:"#8b5cf6",success:"#4ade80",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#fef9ff",secondary:"#f3e8ff",tertiary:"#e8d5ff",hover:"#f3e8ff"},{primary:"#581c87",secondary:"#6d28d9",muted:"#c4b5fd"},"#ddd6fe");de("Summer Beach",{primary:"#0ea5e9",primaryHover:"#0284c7",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#fffbeb",secondary:"#fef3c7",tertiary:"#fde68a",hover:"#fef3c7"},{primary:"#0c4a6e",secondary:"#0369a1",muted:"#7dd3fc"},"#fcd34d");de("Winter Frost",{primary:"#3b82f6",primaryHover:"#2563eb",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#f0f9ff",secondary:"#e0f2fe",tertiary:"#bae6fd",hover:"#e0f2fe"},{primary:"#1e3a5f",secondary:"#1e40af",muted:"#93c5fd"},"#bfdbfe");de("Cherry Blossom",{primary:"#ec4899",primaryHover:"#db2777",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#fdf2f8",secondary:"#fce7f3",tertiary:"#fbcfe8",hover:"#fce7f3"},{primary:"#831843",secondary:"#9d174d",muted:"#f9a8d4"},"#fbcfe8");de("Harvest",{primary:"#b45309",primaryHover:"#92400e",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#fffbeb",secondary:"#fef3c7",tertiary:"#fde68a",hover:"#fef3c7"},{primary:"#451a03",secondary:"#78350f",muted:"#d97706"},"#fcd34d");de("Japanese Zen",{primary:"#6b7280",primaryHover:"#4b5563",success:"#6b8e23",warning:"#d4a017",error:"#c0392b",info:"#5f9ea0"},{primary:"#faf9f6",secondary:"#f0ece3",tertiary:"#e6e0d4",hover:"#f0ece3"},{primary:"#2c2c2c",secondary:"#5c5c5c",muted:"#a0998a"},"#d5cec0");de("Moroccan",{primary:"#c2410c",primaryHover:"#9a3412",success:"#15803d",warning:"#ca8a04",error:"#b91c1c",info:"#0e7490"},{primary:"#fffbf0",secondary:"#fef3e0",tertiary:"#fde6c4",hover:"#fef3e0"},{primary:"#3a1a00",secondary:"#7c2d12",muted:"#d97706"},"#f5d0a0");de("Scandinavian",{primary:"#4b5563",primaryHover:"#374151",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#ffffff",secondary:"#f9fafb",tertiary:"#f3f4f6",hover:"#f3f4f6"},{primary:"#111827",secondary:"#374151",muted:"#9ca3af"},"#e5e7eb");de("Mediterranean",{primary:"#1e40af",primaryHover:"#1e3a8a",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#eff6ff",secondary:"#dbeafe",tertiary:"#bfdbfe",hover:"#dbeafe"},{primary:"#1e3a5f",secondary:"#2563eb",muted:"#93c5fd"},"#bfdbfe");de("Chinese New Year",{primary:"#dc2626",primaryHover:"#b91c1c",success:"#16a34a",warning:"#d4a017",error:"#ef4444",info:"#0891b2"},{primary:"#fef2f2",secondary:"#fee2e2",tertiary:"#fecaca",hover:"#fee2e2"},{primary:"#450a0a",secondary:"#991b1b",muted:"#f87171"},"#fca5a5");de("Indian Festive",{primary:"#d97706",primaryHover:"#b45309",success:"#16a34a",warning:"#ca8a04",error:"#dc2626",info:"#7c3aed"},{primary:"#fffbeb",secondary:"#fef3c7",tertiary:"#fde68a",hover:"#fef3c7"},{primary:"#451a03",secondary:"#92400e",muted:"#f59e0b"},"#fcd34d");de("Brazilian Carnival",{primary:"#16a34a",primaryHover:"#15803d",success:"#22c55e",warning:"#facc15",error:"#ef4444",info:"#0ea5e9"},{primary:"#f0fdf4",secondary:"#dcfce7",tertiary:"#bbf7d0",hover:"#dcfce7"},{primary:"#052e16",secondary:"#166534",muted:"#4ade80"},"#86efac");de("African Earth",{primary:"#92400e",primaryHover:"#78350f",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#faf5f0",secondary:"#f0e6d6",tertiary:"#e6d5bb",hover:"#f0e6d6"},{primary:"#2b1a0e",secondary:"#5c3d1e",muted:"#a08060"},"#d4b896");Be("High Contrast Dark",{primary:"#ffff00",primaryHover:"#cccc00",success:"#00ff00",warning:"#ff8c00",error:"#ff0000",info:"#00ffff"},{primary:"#000000",secondary:"#1a1a1a",tertiary:"#333333",hover:"#333333"},{primary:"#ffffff",secondary:"#ffffff",muted:"#cccccc"},"#ffffff");de("Monochrome",{primary:"#404040",primaryHover:"#262626",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#fafafa",secondary:"#f0f0f0",tertiary:"#e0e0e0",hover:"#e0e0e0"},{primary:"#1a1a1a",secondary:"#404040",muted:"#808080"},"#c0c0c0");de("Enhanced Contrast",{primary:"#0050b3",primaryHover:"#003d8c",success:"#006400",warning:"#cc7000",error:"#cc0000",info:"#006680"},{primary:"#ffffff",secondary:"#f5f5f5",tertiary:"#ebebeb",hover:"#ebebeb"},{primary:"#000000",secondary:"#1a1a1a",muted:"#595959"},"#8c8c8c");de("Minimalist",{primary:"#18181b",primaryHover:"#27272a",success:"#22c55e",warning:"#eab308",error:"#ef4444",info:"#3b82f6"},{primary:"#ffffff",secondary:"#fafafa",tertiary:"#f5f5f5",hover:"#f5f5f5"},{primary:"#0a0a0a",secondary:"#404040",muted:"#a3a3a3"},"#e5e5e5");Be("Warm Dark",{primary:"#f59e0b",primaryHover:"#d97706",success:"#10b981",warning:"#fbbf24",error:"#f87171",info:"#38bdf8"},{primary:"#1c1917",secondary:"#292524",tertiary:"#44403c",hover:"#44403c"},{primary:"#fafaf9",secondary:"#d6d3d1",muted:"#78716c"},"#57534e");Be("Soft Dark",{primary:"#a78bfa",primaryHover:"#8b5cf6",success:"#34d399",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#1e1e2e",secondary:"#262637",tertiary:"#313147",hover:"#313147"},{primary:"#e8e8f0",secondary:"#a0a0b8",muted:"#5c5c74"},"#3e3e58");de("Coffee",{primary:"#6f4e37",primaryHover:"#5c3d28",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#faf6f1",secondary:"#f0e8dc",tertiary:"#e6d8c6",hover:"#f0e8dc"},{primary:"#2c1a0e",secondary:"#5c3d28",muted:"#a08868"},"#d4c4a8");de("Wine",{primary:"#7f1d1d",primaryHover:"#641717",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#fef2f2",secondary:"#fde8e8",tertiary:"#f8d0d0",hover:"#fde8e8"},{primary:"#3b0a0a",secondary:"#7f1d1d",muted:"#dc6868"},"#e8a0a0");u.createContext(null);const cr=["off","no function","brak"],h0=e=>e.segments.some(t=>t.isOff||cr.some(n=>t.name.toLowerCase().includes(n))),p0=e=>e.segments.find(t=>t.isOff||cr.some(n=>t.name.toLowerCase().includes(n))),El=e=>Math.floor((e.valueFrom+e.valueTo)/2),m0=e=>{const t=p0(e);return t?El(t):0},y0=(e,t)=>e.segments.find(n=>t>=n.valueFrom&&t<=n.valueTo),fn=(e,t=0,n=255)=>Math.max(t,Math.min(n,Math.round(e))),Rn=({channel:e,value:t,onChange:n,onCommit:r,showDirectionHint:a})=>{const[o,i]=u.useState(fn(t)),l=u.useMemo(()=>y0(e,o),[e,o]);u.useEffect(()=>i(fn(t)),[t]);const c=d=>{const f=fn(d);i(f),n(f),r==null||r(f)};return s.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:6},children:[s.jsxs("strong",{children:[e.channel,". ",e.name]}),a&&l&&s.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:l.name})]}),s.jsx("input",{type:"range",min:0,max:255,value:o,onChange:d=>{const f=fn(Number(d.target.value));i(f),n(f)},onMouseUp:()=>r==null?void 0:r(o),onTouchEnd:()=>r==null?void 0:r(o),style:{width:"100%"}}),s.jsx("div",{style:{marginTop:6},children:s.jsx("input",{type:"number",min:0,max:255,value:o,onChange:d=>{const f=fn(Number(d.target.value));i(f),n(f)},onBlur:()=>r==null?void 0:r(o),style:{width:80,padding:6,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:6}})}),h0(e)&&s.jsx("button",{type:"button",onClick:()=>c(m0(e)),style:{width:"100%",marginTop:8,padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)",cursor:"pointer"},children:"OFF"})]})},Aa=({channel:e,value:t,onChange:n,onCommit:r})=>{const a=u.useMemo(()=>{const i=[...e.segments];return i.sort((l,c)=>{const d=(l.isOff?-1:0)+(cr.some(h=>l.name.toLowerCase().includes(h))?-1:0),f=(c.isOff?-1:0)+(cr.some(h=>c.name.toLowerCase().includes(h))?-1:0);return d!==f?d-f:l.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),i},[e]),o=i=>{const l=El(i);n(l),r==null||r(l)};return s.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[s.jsxs("strong",{children:[e.channel,". ",e.name]}),s.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 s.jsx("button",{type:"button",onClick:()=>o(i),style:{padding:"8px 10px",borderRadius:8,border:c?"2px solid var(--nice-primary-hover, #2563eb)":"1px solid var(--nice-border, #d1d5db)",background:c?"var(--nice-primary-bg, #eff6ff)":"var(--nice-bg, #fff)",textAlign:"left",cursor:"pointer",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:`${i.name} [${i.valueFrom}..${i.valueTo}]`,children:i.name},`${i.name}-${l}`)})})]})},Na=e=>{switch(e.channel.type){case jt.Dimmer:case jt.DimmerWithOff:return s.jsx(Rn,{...e});case jt.RotationWithOff:case jt.RotationWithOffAndCcw:return s.jsx(Rn,{...e,showDirectionHint:!0});case jt.Options:return s.jsx(Aa,{...e});default:return s.jsx(Rn,{...e})}},Ar=e=>Math.max(0,Math.min(255,Math.round(e))),g0=[{target:".ntd-dmx-editor",titleKey:"tutorial.dmxEditor.intro.title",title:"DMX editor",contentKey:"tutorial.dmxEditor.intro.content",content:"Pick the FTDI device and port, then set each DMX channel’s value with the sliders to control your lighting fixtures live.",placement:"auto"}];function Al({service:e,pollInterval:t=500,className:n,style:r,channels:a,onChannelChange:o,fixtures:i,tutorial:l}){if(!e)return s.jsx("div",{className:n,style:r,children:s.jsx("small",{children:"Provide a `service` prop (DmxService) to control hardware."})});const[c,d]=u.useState([]),[f,h]=u.useState(null),[m,y]=u.useState(()=>Array(513).fill(0)),[p,v]=u.useState(30),[x,b]=u.useState(0),[S,g]=u.useState(!1),k=u.useRef(null);u.useEffect(()=>{let I=!1;return e.getDevices().then(L=>{I||(d(L),L.length>0&&h(L[0]))}).catch(()=>{}),()=>{I=!0}},[e]),u.useEffect(()=>{if(k.current&&window.clearInterval(k.current),!(t<=0))return k.current=window.setInterval(async()=>{try{const I=await e.getState();Array.isArray(I.frontSnapshot)&&I.frontSnapshot.length>=513&&y(I.frontSnapshot.slice(0,513)),typeof I.fps=="number"&&v(I.fps),typeof I.startCode=="number"&&b(I.startCode)}catch{}},t),()=>{k.current&&window.clearInterval(k.current)}},[e,t]);const M=async()=>{f&&(await e.openPort(f.serialNumber||f.description),g(!0))},N=async()=>{await e.closePort(),g(!1)},j=async()=>{await e.blackout(),y(I=>{const L=[...I];for(let U=1;U<L.length;U++)L[U]=0;return L})},_=()=>e.configure(p,x),P=(I,L)=>{const U=Ar(L);y(Y=>{const O=[...Y];return O[I]=U,O})},V=(I,L)=>e.setChannel(I,Ar(L)),z=(f==null?void 0:f.deviceInfo)??null,A=u.useMemo(()=>{var I;return(I=z==null?void 0:z.channels)!=null&&I.length?z.channels:Array.from({length:16},(L,U)=>({channel:U+1,name:`Channel ${U+1}`,type:jt.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[z]);return s.jsxs("div",{className:`ntd-dmx-editor ${n??""}`,style:{position:"relative",padding:16,display:"grid",gap:16,...r},children:[s.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:s.jsx(d0,{steps:l0(l,g0)})}),s.jsxs("section",{style:{display:"grid",gap:12,gridTemplateColumns:"1fr auto auto auto",alignItems:"end"},children:[s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FTDI Device"}),s.jsx("select",{value:(f==null?void 0:f.serialNumber)||"",onChange:I=>h(c.find(L=>L.serialNumber===I.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"},children:c.map(I=>{var L,U;return s.jsxs("option",{value:I.serialNumber,children:[((L=I.deviceInfo)==null?void 0:L.manufacturer)??""," ",((U=I.deviceInfo)==null?void 0:U.model)??I.description," (",I.serialNumber||I.description,")"]},I.serialNumber||I.description)})}),z&&s.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:["Mode: ",s.jsx("b",{children:z.modeName}),", footprint: ",s.jsx("b",{children:z.footprint})]})]}),s.jsx("button",{onClick:M,disabled:!f||S,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-success, #10b981)",background:"var(--nice-success-bg, #ecfdf5)",cursor:"pointer"},children:"Open port"}),s.jsx("button",{onClick:N,disabled:!S,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-danger, #ef4444)",background:"var(--nice-danger-bg, #fef2f2)",cursor:"pointer"},children:"Close port"}),s.jsx("button",{onClick:j,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-text-secondary, #4b5563)",background:"var(--nice-bg-secondary, #f3f4f6)",cursor:"pointer"},children:"Blackout"})]}),s.jsxs("section",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(160px, 100%), 1fr))",gap:12,alignItems:"end"},children:[s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FPS"}),s.jsx("input",{type:"number",min:10,max:44,value:p,onChange:I=>v(Number(I.target.value)),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"Start Code"}),s.jsx("input",{type:"number",min:0,max:255,value:x,onChange:I=>b(Ar(Number(I.target.value))),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),s.jsx("div",{children:s.jsx("button",{onClick:_,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-primary, #3b82f6)",background:"var(--nice-primary-bg, #eff6ff)",cursor:"pointer"},children:"Apply configuration"})})]}),s.jsxs("section",{children:[s.jsx("h3",{style:{margin:"8px 0 12px",fontSize:16},children:"Channels"}),s.jsx("div",{style:{display:"grid",gap:12,gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))"},children:A.map(I=>s.jsx(Na,{channel:I,value:m[I.channel]??0,onChange:L=>P(I.channel,L),onCommit:L=>V(I.channel,L)},I.channel))})]})]})}const Nl=[{id:"generic-dimmer-1ch",name:"Generic Dimmer",manufacturer:"Generic",type:"dimmer",channelCount:1,channels:[{name:"Dimmer",type:"dimmer",defaultValue:0}]},{id:"generic-rgb-3ch",name:"Generic RGB",manufacturer:"Generic",type:"rgb",channelCount:3,channels:[{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0}]},{id:"generic-rgbw-4ch",name:"Generic RGBW",manufacturer:"Generic",type:"rgbw",channelCount:4,channels:[{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0}]},{id:"generic-rgbw-dimmer-5ch",name:"Generic RGBW+D",manufacturer:"Generic",type:"rgbw",channelCount:5,channels:[{name:"Dimmer",type:"dimmer",defaultValue:255},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0}]},{id:"generic-par-7ch",name:"Generic PAR 7ch",manufacturer:"Generic",type:"par",channelCount:7,channels:[{name:"Dimmer",type:"dimmer",defaultValue:255},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0},{name:"Strobe",type:"strobe",defaultValue:0},{name:"Function",type:"function",defaultValue:0}]},{id:"generic-moving-head-16ch",name:"Generic Moving Head 16ch",manufacturer:"Generic",type:"moving_head",channelCount:16,channels:[{name:"Pan",type:"pan",defaultValue:128,min:0,max:255},{name:"Pan Fine",type:"pan",defaultValue:0},{name:"Tilt",type:"tilt",defaultValue:128,min:0,max:255},{name:"Tilt Fine",type:"tilt",defaultValue:0},{name:"Pan/Tilt Speed",type:"speed",defaultValue:0},{name:"Dimmer",type:"dimmer",defaultValue:0},{name:"Strobe",type:"strobe",defaultValue:0},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0},{name:"Color Wheel",type:"function",defaultValue:0},{name:"Gobo",type:"gobo",defaultValue:0},{name:"Gobo Rotation",type:"speed",defaultValue:128},{name:"Prism",type:"function",defaultValue:0},{name:"Function",type:"function",defaultValue:0}]},{id:"generic-strobe-2ch",name:"Generic Strobe",manufacturer:"Generic",type:"strobe",channelCount:2,channels:[{name:"Dimmer",type:"dimmer",defaultValue:0},{name:"Strobe Speed",type:"strobe",defaultValue:0}]},{id:"generic-fog-2ch",name:"Generic Fog Machine",manufacturer:"Generic",type:"fog",channelCount:2,channels:[{name:"Output",type:"dimmer",defaultValue:0},{name:"Fan",type:"speed",defaultValue:128}]}];class Il{constructor(){this.universes=new Map,this.fixtures=new Map,this.profiles=new Map,this.outputCallback=null,this.running=!1,this.frameRate=44,this.intervalId=null,Nl.forEach(t=>this.profiles.set(t.id,t)),this.createUniverse(1,"Universe 1")}createUniverse(t,n){const r={id:String(t),name:n,channels:new Uint8Array(512)};return this.universes.set(t,r),r}getUniverse(t){return this.universes.get(t)}addFixture(t){this.fixtures.set(t.id,t)}removeFixture(t){this.fixtures.delete(t)}getFixture(t){return this.fixtures.get(t)}getAllFixtures(){return Array.from(this.fixtures.values())}getProfile(t){return this.profiles.get(t)}registerProfile(t){this.profiles.set(t.id,t)}setChannel(t,n,r){const a=this.universes.get(t);a&&n>=1&&n<=512&&(a.channels[n-1]=Math.max(0,Math.min(255,r)))}getChannel(t,n){const r=this.universes.get(t);return r&&n>=1&&n<=512?r.channels[n-1]:0}setFixtureValues(t,n){const r=this.fixtures.get(t);if(!r)return;const a=this.profiles.get(r.profileId);if(a)for(let o=0;o<Math.min(n.length,a.channelCount);o++)r.values[o]=n[o],this.setChannel(r.universe,r.startChannel+o,n[o])}setFixtureColor(t,n,r,a,o=0){const i=this.fixtures.get(t);if(!i)return;const l=this.profiles.get(i.profileId);if(!l)return;const c=[...i.values];l.channels.forEach((d,f)=>{d.name.toLowerCase().includes("red")?c[f]=n:d.name.toLowerCase().includes("green")?c[f]=r:d.name.toLowerCase().includes("blue")?c[f]=a:d.name.toLowerCase().includes("white")&&(c[f]=o)}),this.setFixtureValues(t,c)}setFixtureDimmer(t,n){const r=this.fixtures.get(t);if(!r)return;const a=this.profiles.get(r.profileId);a&&a.channels.forEach((o,i)=>{o.type==="dimmer"&&(r.values[i]=Math.max(0,Math.min(255,Math.round(n*255))),this.setChannel(r.universe,r.startChannel+i,r.values[i]))})}fadeFixture(t,n,r,a="linear"){return new Promise(o=>{const i=this.fixtures.get(t);if(!i){o();return}const l=[...i.values],c=performance.now(),d=()=>{const f=performance.now()-c,h=Math.min(1,f/r);let m=h;switch(a){case"ease-in":m=h*h;break;case"ease-out":m=1-(1-h)*(1-h);break;case"ease-in-out":m=h<.5?2*h*h:1-Math.pow(-2*h+2,2)/2;break}const y=l.map((p,v)=>{const x=n[v]??p;return Math.round(p+(x-p)*m)});this.setFixtureValues(t,y),h<1?requestAnimationFrame(d):o()};d()})}setOutputCallback(t){this.outputCallback=t}start(){this.running||(this.running=!0,this.intervalId=window.setInterval(()=>{this.sendOutput()},1e3/this.frameRate))}stop(){this.running=!1,this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null)}sendOutput(){this.outputCallback&&this.universes.forEach((t,n)=>{this.outputCallback(n,t.channels)})}blackout(){this.universes.forEach(t=>{t.channels.fill(0)}),this.fixtures.forEach(t=>{t.values.fill(0)})}fullOn(){this.fixtures.forEach(t=>{this.setFixtureDimmer(t.id,1)})}}const b0=6454,v0=new Uint8Array([65,114,116,45,78,101,116,0]);function x0(e,t){const n=new Uint8Array(18+t.length);return n.set(v0,0),n[8]=0,n[9]=80,n[10]=0,n[11]=14,n[12]=0,n[13]=0,n[14]=e&255,n[15]=e>>8&255,n[16]=t.length>>8&255,n[17]=t.length&255,n.set(t.slice(0,512),18),n}const w0=5568;function S0(e,t,n,r=100,a="Nice2Dev DMX"){const o=Math.min(t.length,512),i=126+o,l=new Uint8Array(i),c=new DataView(l.buffer);c.setUint16(0,16,!1),c.setUint16(2,0,!1);const d=[65,83,67,45,69,49,46,49,55,0,0,0];for(let p=0;p<d.length;p++)l[4+p]=d[p];const f=i-16;c.setUint16(16,28672|f&4095,!1),c.setUint32(18,4,!1);for(let p=0;p<16;p++)l[22+p]=p+1;const h=i-38;c.setUint16(38,28672|h&4095,!1),c.setUint32(40,2,!1);const m=new TextEncoder().encode(a.slice(0,63));l.set(m,44),l[108]=r,c.setUint16(109,0,!1),l[111]=n&255,l[112]=0,c.setUint16(113,e,!1);const y=o+11;return c.setUint16(115,28672|y&4095,!1),l[117]=2,l[118]=161,c.setUint16(119,0,!1),c.setUint16(121,1,!1),c.setUint16(123,o+1,!1),l[125]=0,l.set(t.slice(0,o),126),l}function C0(e){const t=e>>8&255,n=e&255;return`239.255.${t}.${n}`}class k0{constructor(t,n){this.config=t,this.scenes=n,this.currentStep=0,this.direction=1,this.isRunning=!1,this.timer=null,this.fadeStartTime=0,this.fadeFromValues=new Uint8Array(512),this.fadeToValues=new Uint8Array(512),this.onOutput=null}setOutputCallback(t){this.onOutput=t}start(){this.isRunning||(this.isRunning=!0,this.currentStep=this.config.direction==="backward"?this.config.steps.length-1:0,this.direction=this.config.direction==="backward"?-1:1,this.executeStep())}stop(){this.isRunning=!1,this.timer&&(clearTimeout(this.timer),this.timer=null)}executeStep(){var i;if(!this.isRunning)return;const t=this.config.steps[this.currentStep];if(!t)return;const n=this.scenes.get(t.sceneId);if(!n){this.advanceStep();return}const r=new Uint8Array(512);if(n.channels)for(const l of n.channels)l.channel>=1&&l.channel<=512&&(r[l.channel-1]=l.value);this.fadeFromValues.set(this.fadeToValues),this.fadeToValues.set(r),this.fadeStartTime=performance.now();const a=t.fadeTime/this.config.speed,o=t.holdTime/this.config.speed;a>0?this.runFade(a,()=>{var l;(l=this.onOutput)==null||l.call(this,this.fadeToValues),this.timer=setTimeout(()=>this.advanceStep(),o)}):((i=this.onOutput)==null||i.call(this,r),this.timer=setTimeout(()=>this.advanceStep(),o))}runFade(t,n){const r=performance.now(),a=new Uint8Array(512),o=()=>{var c;if(!this.isRunning)return;const i=performance.now()-r,l=Math.min(i/t,1);for(let d=0;d<512;d++)a[d]=Math.round(this.fadeFromValues[d]+(this.fadeToValues[d]-this.fadeFromValues[d])*l);(c=this.onOutput)==null||c.call(this,a),l<1?requestAnimationFrame(o):n()};requestAnimationFrame(o)}advanceStep(){if(!this.isRunning)return;const{steps:t,loop:n,direction:r}=this.config;if(this.currentStep+=this.direction,r==="bounce"){if(this.currentStep>=t.length?(this.direction=-1,this.currentStep=t.length-2):this.currentStep<0&&(this.direction=1,this.currentStep=1),this.currentStep<0||this.currentStep>=t.length){if(!n){this.stop();return}this.currentStep=0,this.direction=1}}else if(this.currentStep>=t.length||this.currentStep<0){if(!n){this.stop();return}this.currentStep=r==="backward"?t.length-1:0}this.executeStep()}}const M0=({engine:e,tracks:t=[],scenes:n=[],duration:r=3e5,currentTime:a=0,bpm:o=120,onTimeChange:i,onCueAdd:l,onCueUpdate:c,onCueDelete:d,onTrackAdd:f,onTrackUpdate:h,onPlay:m,onPause:y,onStop:p,className:v=""})=>{const[x,b]=u.useState(1),[S,g]=u.useState(0),[k,M]=u.useState(!1),[N,j]=u.useState(null),[_,P]=u.useState(null),[V,z]=u.useState(!0),[A,I]=u.useState(1e3),L=u.useRef(null),U=u.useRef(null),Y=u.useRef(0),O=u.useMemo(()=>.1*x,[x]),Z=u.useCallback(C=>C*O,[O]),H=u.useCallback(C=>C/O,[O]),te=u.useCallback(C=>{if(!V)return C;const E=6e4/o;return Math.round(C/E)*E},[V,o]);u.useEffect(()=>{if(k){const C=performance.now(),E=a,F=()=>{const q=performance.now()-C,Q=E+q;if(Q>=r){M(!1),i==null||i(0),p==null||p();return}G(Q),i==null||i(Q),U.current=requestAnimationFrame(F)};U.current=requestAnimationFrame(F),m==null||m()}else U.current!==null&&(cancelAnimationFrame(U.current),U.current=null),y==null||y();return()=>{U.current!==null&&cancelAnimationFrame(U.current)}},[k,a,r,i,m,y,p]);const G=u.useCallback(C=>{t.forEach(E=>{E.muted||E.cues.forEach(F=>{const q=F.startTime,Q=q+F.duration;if(C>=q&&C<Q&&Y.current<q){const J=n.find(ae=>ae.id===F.sceneId);J&&J.fixtures.forEach(ae=>{F.fadeIn&&F.fadeIn>0?e.fadeFixture(ae.fixtureId,ae.values,F.fadeIn):e.setFixtureValues(ae.fixtureId,ae.values)})}if(Y.current<Q&&C>=Q){const J=n.find(ae=>ae.id===F.sceneId);J&&J.fixtures.forEach(ae=>{if(e.getFixture(ae.fixtureId)&&F.fadeOut&&F.fadeOut>0){const ee=new Array(ae.values.length).fill(0);e.fadeFixture(ae.fixtureId,ee,F.fadeOut)}})}})}),Y.current=C},[t,n,e]),B=C=>{const E=Math.floor(C/1e3),F=Math.floor(E/60),q=E%60,Q=Math.floor(C%1e3/(1e3/30));return`${F}:${q.toString().padStart(2,"0")}:${Q.toString().padStart(2,"0")}`},w=u.useCallback(C=>{if(!L.current)return;const E=L.current.getBoundingClientRect(),F=C.clientX-E.left+S,q=te(H(F));i==null||i(Math.max(0,Math.min(r,q)))},[S,H,te,r,i]),$=u.useCallback((C,E,F)=>{const q=t.find(ae=>ae.id===E),Q=q==null?void 0:q.cues.find(ae=>ae.id===C);if(!Q)return;const J=te(Math.max(0,Q.startTime+H(F)));c==null||c({...Q,startTime:J})},[t,H,te,c]),R=()=>{const C=6e4/o,E=Math.ceil(r/C),F=[];for(let q=0;q<=E;q++){const Q=q*C,J=Z(Q),ae=q%4===0;F.push(s.jsx("div",{className:`nice-dmx-timeline__beat ${ae?"nice-dmx-timeline__beat--measure":""}`,style:{left:J},children:ae&&s.jsx("span",{className:"nice-dmx-timeline__beat-label",children:q/4+1})},q))}return F},T=(C,E)=>{const F=Z(C.startTime),q=Z(C.duration),Q=n.find(J=>J.id===C.sceneId);return s.jsxs("div",{className:`nice-dmx-timeline__cue ${N===C.id?"nice-dmx-timeline__cue--selected":""}`,style:{left:F,width:q,backgroundColor:(Q==null?void 0:Q.color)||E.color||"var(--nice-accent, #8b5cf6)"},onClick:J=>{J.stopPropagation(),j(C.id)},draggable:!E.locked,onDragEnd:J=>{var re;const ae=(re=J.target.parentElement)==null?void 0:re.getBoundingClientRect();ae&&$(C.id,E.id,J.clientX-ae.left-F)},children:[s.jsx("span",{className:"nice-dmx-timeline__cue-name",children:C.name||(Q==null?void 0:Q.name)}),C.fadeIn&&C.fadeIn>0&&s.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--in",style:{width:Z(C.fadeIn)}}),C.fadeOut&&C.fadeOut>0&&s.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--out",style:{width:Z(C.fadeOut)}})]},C.id)};return s.jsxs("div",{className:`nice-dmx-timeline ${v}`,children:[s.jsxs("div",{className:"nice-dmx-timeline__toolbar",children:[s.jsxs("div",{className:"nice-dmx-timeline__transport",children:[s.jsx("button",{type:"button",onClick:()=>i==null?void 0:i(0),title:"Go to start",children:"⏮"}),s.jsx("button",{type:"button",onClick:()=>M(!k),title:k?"Pause":"Play",children:k?"⏸":"▶"}),s.jsx("button",{type:"button",onClick:()=>{M(!1),i==null||i(0),e.blackout(),p==null||p()},title:"Stop",children:"⏹"})]}),s.jsx("div",{className:"nice-dmx-timeline__time",children:B(a)}),s.jsxs("div",{className:"nice-dmx-timeline__tools",children:[s.jsx("button",{type:"button",className:V?"active":"",onClick:()=>z(!V),title:"Snap to grid",children:"⊞"}),s.jsx("button",{type:"button",onClick:()=>b(Math.max(.25,x-.25)),title:"Zoom out",children:"−"}),s.jsxs("span",{className:"nice-dmx-timeline__zoom",children:[Math.round(x*100),"%"]}),s.jsx("button",{type:"button",onClick:()=>b(Math.min(4,x+.25)),title:"Zoom in",children:"+"})]}),s.jsxs("div",{className:"nice-dmx-timeline__bpm",children:[s.jsx("label",{children:"BPM:"}),s.jsx("span",{children:o})]}),s.jsx("button",{type:"button",className:"nice-dmx-timeline__blackout",onClick:()=>e.blackout(),title:"Blackout",children:"⬛"})]}),s.jsxs("div",{className:"nice-dmx-timeline__content",children:[s.jsxs("div",{className:"nice-dmx-timeline__headers",children:[t.map(C=>s.jsxs("div",{className:`nice-dmx-timeline__header ${_===C.id?"nice-dmx-timeline__header--selected":""}`,onClick:()=>P(C.id),children:[s.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:C.color||"var(--nice-accent, #8b5cf6)"}}),s.jsx("span",{className:"nice-dmx-timeline__track-name",children:C.name}),s.jsxs("div",{className:"nice-dmx-timeline__track-controls",children:[s.jsx("button",{type:"button",className:C.muted?"active":"",onClick:E=>{E.stopPropagation(),h==null||h({...C,muted:!C.muted})},title:"Mute",children:"M"}),s.jsx("button",{type:"button",className:C.locked?"active":"",onClick:E=>{E.stopPropagation(),h==null||h({...C,locked:!C.locked})},title:"Lock",children:"🔒"})]})]},C.id)),s.jsx("button",{type:"button",className:"nice-dmx-timeline__add-track",onClick:()=>{f==null||f({id:`track-${Date.now()}`,name:`Track ${t.length+1}`,fixtureIds:[],cues:[]})},children:"+ Add Track"})]}),s.jsxs("div",{className:"nice-dmx-timeline__tracks",ref:L,onClick:w,onScroll:C=>g(C.currentTarget.scrollLeft),children:[s.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:Z(r)},children:R()}),t.map(C=>s.jsx("div",{className:`nice-dmx-timeline__track ${C.muted?"nice-dmx-timeline__track--muted":""}`,style:{width:Z(r)},children:C.cues.map(E=>T(E,C))},C.id)),s.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:Z(a)}})]})]})]})};function j0(){const[e]=u.useState(()=>new Il);return u.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function R0(e,t,n=120){const[r,a]=u.useState(0),o=u.useRef(0);return u.useEffect(()=>{if(!t)return;const i=60/n,l=()=>{const c=t.currentTime,d=Math.floor(c/i);d!==o.current&&(o.current=d,a(d))};return t.addEventListener("timeupdate",l),()=>t.removeEventListener("timeupdate",l)},[t,n]),{currentBeat:r}}const T0=[{name:"Flat",bands:[{frequency:60,gain:0},{frequency:250,gain:0},{frequency:1e3,gain:0},{frequency:4e3,gain:0},{frequency:16e3,gain:0}]},{name:"Bass Boost",bands:[{frequency:60,gain:8},{frequency:250,gain:4},{frequency:1e3,gain:0},{frequency:4e3,gain:-2},{frequency:16e3,gain:-4}]},{name:"Treble Boost",bands:[{frequency:60,gain:-4},{frequency:250,gain:-2},{frequency:1e3,gain:0},{frequency:4e3,gain:4},{frequency:16e3,gain:8}]},{name:"Voice",bands:[{frequency:60,gain:-6},{frequency:250,gain:2},{frequency:1e3,gain:6},{frequency:4e3,gain:4},{frequency:16e3,gain:-2}]},{name:"Rock",bands:[{frequency:60,gain:4},{frequency:250,gain:2},{frequency:1e3,gain:-2},{frequency:4e3,gain:4},{frequency:16e3,gain:6}]}];function Ll(){const[e,t]=u.useState(!1),[n,r]=u.useState(.8),[a,o]=u.useState(!1),[i,l]=u.useState(null),[c,d]=u.useState(null),[f,h]=u.useState(null),m=u.useRef(null),y=u.useRef(null),p=u.useRef(null),v=u.useRef(null),x=u.useRef([]),b=u.useRef(null),S=u.useRef(null),g=u.useCallback(()=>{if(y.current)return;const L=new AudioContext;y.current=L;const U=L.createGain();U.gain.value=n,v.current=U;const Y=L.createAnalyser();Y.fftSize=256,b.current=Y,U.connect(Y).connect(L.destination)},[]),k=u.useCallback(()=>{const L=m.current,U=y.current,Y=v.current;if(!L||!U||!Y||p.current)return;const O=U.createMediaElementSource(L);p.current=O,x.current.length>0?(O.connect(x.current[0]),x.current[x.current.length-1].connect(Y)):O.connect(Y)},[]),M=u.useCallback(()=>{var U;const L=m.current;!L||!S.current||(It(),g(),k(),((U=y.current)==null?void 0:U.state)==="suspended"&&y.current.resume(),L.play().catch(Y=>d(String(Y))))},[g,k]),N=u.useCallback(()=>{var L;(L=m.current)==null||L.pause()},[]),j=u.useCallback(()=>{e?N():M()},[e,M,N]),_=u.useCallback(L=>{const U=Math.max(0,Math.min(1,L));r(U),v.current&&(v.current.gain.value=U),m.current&&(m.current.volume=U)},[]),P=u.useCallback(L=>{S.current=L,d(null),l(null),o(!0),p.current&&(p.current.disconnect(),p.current=null),m.current||(m.current=new Audio,m.current.crossOrigin="anonymous",m.current.addEventListener("playing",()=>{t(!0),o(!1)}),m.current.addEventListener("pause",()=>t(!1)),m.current.addEventListener("waiting",()=>o(!0)),m.current.addEventListener("canplay",()=>o(!1)),m.current.addEventListener("error",()=>d("Failed to load stream"))),m.current.src=L.streamUrl,m.current.load(),l({genre:L.genre,bitrate:L.bitrate})},[]),V=u.useCallback(L=>{y.current||g();const Y=y.current;x.current.forEach(Z=>Z.disconnect());const O=L.bands.map(Z=>{const H=Y.createBiquadFilter();return H.type="peaking",H.frequency.value=Z.frequency,H.gain.value=Z.gain,H.Q.value=Z.Q??1.4,H});for(let Z=0;Z<O.length-1;Z++)O[Z].connect(O[Z+1]);x.current=O,p.current&&v.current&&(p.current.disconnect(),p.current.connect(O[0]),O[O.length-1].connect(v.current)),h(L.name)},[g]),z=u.useCallback(()=>{x.current.forEach(L=>L.disconnect()),x.current=[],p.current&&v.current&&(p.current.disconnect(),p.current.connect(v.current)),h(null)},[]);return u.useEffect(()=>()=>{var L,U,Y;(L=m.current)==null||L.pause(),m.current=null,x.current.forEach(O=>O.disconnect()),(U=p.current)==null||U.disconnect(),(Y=y.current)==null||Y.close()},[]),[{isPlaying:e,volume:n,isBuffering:a,metadata:i,error:c,activePreset:f},{play:M,pause:N,toggle:j,setVolume:_,setStation:P,applyEQPreset:V,clearEQ:z}]}function Dl({stations:e,activeStationId:t,onSelect:n,onToggleFavorite:r,className:a}){const{t:o}=we(),[i,l]=u.useState(""),[c,d]=u.useState(null),[f,h]=u.useState(!1),m=u.useMemo(()=>[...new Set(e.map(p=>p.genre).filter(Boolean))],[e]),y=u.useMemo(()=>e.filter(p=>{var v,x;if(f&&!p.isFavorite||c&&p.genre!==c)return!1;if(i){const b=i.toLowerCase();return p.name.toLowerCase().includes(b)||(((v=p.genre)==null?void 0:v.toLowerCase().includes(b))??!1)||(((x=p.country)==null?void 0:x.toLowerCase().includes(b))??!1)}return!0}),[e,i,c,f]);return s.jsxs("div",{className:`nice-station-browser${a?` ${a}`:""}`,children:[s.jsxs("div",{className:"nice-station-browser__toolbar",children:[s.jsx("input",{type:"text",className:"nice-station-browser__search",placeholder:(o==null?void 0:o("search_stations"))??"Search stations...",value:i,onChange:p=>l(p.target.value)}),s.jsxs("select",{className:"nice-station-browser__genre-filter",value:c??"",onChange:p=>d(p.target.value||null),children:[s.jsx("option",{value:"",children:(o==null?void 0:o("all_genres"))??"All Genres"}),m.map(p=>s.jsx("option",{value:p,children:p},p))]}),s.jsx("button",{className:`nice-station-browser__fav-toggle${f?" nice-station-browser__fav-toggle--active":""}`,onClick:()=>h(!f),title:(o==null?void 0:o("favorites"))??"Favorites",children:"★"})]}),s.jsxs("div",{className:"nice-station-browser__list",children:[y.map(p=>s.jsxs("div",{className:`nice-station-browser__item${p.id===t?" nice-station-browser__item--active":""}`,onClick:()=>n(p),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&n(p)},children:[p.logoUrl&&s.jsx("img",{className:"nice-station-browser__logo",src:p.logoUrl,alt:p.name,loading:"lazy"}),s.jsxs("div",{className:"nice-station-browser__info",children:[s.jsx("span",{className:"nice-station-browser__name",children:p.name}),p.genre&&s.jsx("span",{className:"nice-station-browser__genre",children:p.genre}),p.country&&s.jsx("span",{className:"nice-station-browser__country",children:p.country})]}),p.bitrate&&s.jsxs("span",{className:"nice-station-browser__bitrate",children:[p.bitrate,"kbps"]}),r&&s.jsx("button",{className:`nice-station-browser__fav${p.isFavorite?" nice-station-browser__fav--active":""}`,onClick:v=>{v.stopPropagation(),r(p.id)},children:p.isFavorite?"★":"☆"})]},p.id)),y.length===0&&s.jsx("div",{className:"nice-station-browser__empty",children:(o==null?void 0:o("no_stations_found"))??"No stations found"})]})]})}function $0({stations:e,initialStationId:t,autoPlay:n=!1,eqPresets:r=T0,onStationChange:a,onPlayingChange:o,onMetadata:i,onToggleFavorite:l,onRecordingStart:c,onRecordingStop:d,showBrowser:f=!0,showEqualizer:h=!1,showVisualizer:m=!1,showMetadataHistory:y=!1,showRecording:p=!1,showSleepTimer:v=!1,className:x,style:b}){var T,C;const{t:S}=we(),[g,k]=Ll(),[M,N]=u.useState(()=>t?e.find(E=>E.id===t)??null:null),[j,_]=u.useState(h),P=u.useRef(null),V=u.useRef(0),[z,A]=u.useState([]),[I,L]=u.useState(!1),U=u.useRef(null),Y=u.useRef([]),[O,Z]=u.useState(0),H=u.useRef(null),[te,G]=u.useState(0),[B,w]=u.useState(null),$=u.useRef(null);u.useEffect(()=>{o==null||o(g.isPlaying)},[g.isPlaying,o]),u.useEffect(()=>{g.metadata&&(i==null||i(g.metadata),(g.metadata.title||g.metadata.artist)&&A(E=>[{time:new Date,meta:g.metadata},...E.slice(0,49)]))},[g.metadata,i]);const R=u.useCallback(E=>{N(E),k.setStation(E),a==null||a(E),n&&setTimeout(()=>k.play(),100)},[k,a,n]);return u.useEffect(()=>{if(t&&!M){const E=e.find(F=>F.id===t);E&&R(E)}},[t,e]),u.useEffect(()=>{if(!m||!P.current)return;const E=P.current,F=E.getContext("2d");if(!F)return;const q=()=>{V.current=requestAnimationFrame(q),F.clearRect(0,0,E.width,E.height);const Q=F.createLinearGradient(0,E.height,0,0);if(Q.addColorStop(0,"var(--nice-accent-tint-80, rgba(99, 102, 241, 0.8))"),Q.addColorStop(.5,"rgba(168,85,247,0.6)"),Q.addColorStop(1,"rgba(236,72,153,0.4)"),!g.isPlaying){const ee=E.width/32;for(let D=0;D<32;D++){const K=4+Math.sin(Date.now()/1e3+D*.3)*3;F.fillStyle=Q,F.fillRect(D*ee+1,E.height-K,ee-2,K)}return}const J=32,ae=E.width/J;for(let re=0;re<J;re++){const ee=re/J,K=(Math.sin(Date.now()/200+re*.5)*.3+.5)*E.height*(1-ee*.5)*(.5+Math.random()*.5);F.fillStyle=Q,F.fillRect(re*ae+1,E.height-K,ae-2,K)}};return q(),()=>cancelAnimationFrame(V.current)},[m,g.isPlaying]),u.useCallback(()=>{if(g.isPlaying)try{const F=new AudioContext().createMediaStreamDestination();Y.current=[];const q=new MediaRecorder(F.stream,{mimeType:"audio/webm"});q.ondataavailable=Q=>{Q.data.size>0&&Y.current.push(Q.data)},q.onstop=()=>{const Q=new Blob(Y.current,{type:"audio/webm"});d==null||d(Q),Z(0),H.current&&window.clearInterval(H.current)},q.start(1e3),U.current=q,L(!0),Z(0),H.current=window.setInterval(()=>{Z(Q=>Q+1)},1e3),c==null||c()}catch{}},[g.isPlaying,c,d]),u.useCallback(()=>{U.current&&I&&(U.current.stop(),L(!1),H.current&&window.clearInterval(H.current))},[I]),u.useCallback(E=>{$.current&&window.clearInterval($.current),G(E),w(E*60),$.current=window.setInterval(()=>{w(F=>!F||F<=1?($.current&&window.clearInterval($.current),$.current=null,k.pause(),null):F-1)},1e3)},[k]),u.useCallback(()=>{$.current&&window.clearInterval($.current),$.current=null,w(null),G(0)},[]),u.useEffect(()=>()=>{H.current&&window.clearInterval(H.current),$.current&&window.clearInterval($.current),cancelAnimationFrame(V.current)},[]),s.jsxs("div",{className:`nice-radio-player${x?` ${x}`:""}`,style:b,children:[s.jsx("div",{className:"nice-radio-player__now-playing",children:M?s.jsxs(s.Fragment,{children:[M.logoUrl&&s.jsx("img",{className:"nice-radio-player__cover",src:M.logoUrl,alt:M.name}),s.jsxs("div",{className:"nice-radio-player__info",children:[s.jsx("span",{className:"nice-radio-player__station-name",children:M.name}),((T=g.metadata)==null?void 0:T.title)&&s.jsx("span",{className:"nice-radio-player__track",children:g.metadata.artist?`${g.metadata.artist} — ${g.metadata.title}`:g.metadata.title}),((C=g.metadata)==null?void 0:C.genre)&&s.jsx("span",{className:"nice-radio-player__genre",children:g.metadata.genre}),g.isBuffering&&s.jsx("span",{className:"nice-radio-player__buffering",children:(S==null?void 0:S("buffering"))??"Buffering..."})]})]}):s.jsx("div",{className:"nice-radio-player__placeholder",children:(S==null?void 0:S("select_station"))??"Select a station"})}),s.jsxs("div",{className:"nice-radio-player__controls",children:[s.jsx("button",{className:"nice-radio-player__play-btn",onClick:k.toggle,disabled:!M,"aria-label":g.isPlaying?"Pause":"Play",children:g.isPlaying?"⏸":"▶"}),s.jsxs("div",{className:"nice-radio-player__volume",children:[s.jsx("span",{className:"nice-radio-player__volume-icon",children:"🔊"}),s.jsx("input",{type:"range",min:0,max:1,step:.01,value:g.volume,onChange:E=>k.setVolume(parseFloat(E.target.value)),className:"nice-radio-player__volume-slider","aria-label":"Volume"})]}),s.jsx("button",{className:`nice-radio-player__eq-btn${j?" nice-radio-player__eq-btn--active":""}`,onClick:()=>_(!j),title:"Equalizer",children:"EQ"})]}),g.error&&s.jsx("div",{className:"nice-radio-player__error",children:g.error}),j&&s.jsx("div",{className:"nice-radio-player__equalizer",children:s.jsxs("div",{className:"nice-radio-player__eq-presets",children:[r.map(E=>s.jsx("button",{className:`nice-radio-player__eq-preset${g.activePreset===E.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>k.applyEQPreset(E),children:E.name},E.name)),g.activePreset&&s.jsx("button",{className:"nice-radio-player__eq-preset",onClick:k.clearEQ,children:(S==null?void 0:S("clear"))??"Clear"})]})}),f&&s.jsx(Dl,{stations:e,activeStationId:M==null?void 0:M.id,onSelect:R})]})}const P0=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],E0={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class Fl{constructor(t,n={}){this.localStream=null,this.peers=new Map,this.onRemoteStream=null,this.onPeerStateChange=null,this.onSignalingMessage=null,this.localUserId=t,this.config={iceServers:n.iceServers??P0,audioConstraints:{...E0,echoCancellation:n.echoCancellation??!0,noiseSuppression:n.noiseSuppression??!0,autoGainControl:n.autoGainControl??!0}}}async initialize(){return this.localStream?this.localStream:(this.localStream=await navigator.mediaDevices.getUserMedia({audio:this.config.audioConstraints,video:!1}),this.localStream)}getLocalStream(){return this.localStream}getPeerIds(){return Array.from(this.peers.keys())}getPeerState(t){var n;return((n=this.peers.get(t))==null?void 0:n.state)??null}async createOffer(t){if(!this.localStream)throw new Error("WebRTCAudioManager not initialized. Call initialize() first.");const n=this.createPeerConnection(t),r=await n.createOffer();await n.setLocalDescription(r),this.sendSignalingMessage({type:"offer",from:this.localUserId,to:t,payload:r})}async handleSignalingMessage(t){if(t.to===this.localUserId)switch(t.type){case"offer":await this.handleOffer(t.from,t.payload);break;case"answer":await this.handleAnswer(t.from,t.payload);break;case"ice-candidate":await this.handleIceCandidate(t.from,t.payload);break;case"leave":this.removePeer(t.from);break}}removePeer(t){const n=this.peers.get(t);n&&(n.pc.close(),this.peers.delete(t))}disconnect(){for(const t of this.peers.keys())this.sendSignalingMessage({type:"leave",from:this.localUserId,to:t,payload:null});for(const t of this.peers.values())t.pc.close();this.peers.clear(),this.localStream&&(this.localStream.getTracks().forEach(t=>t.stop()),this.localStream=null)}setMuted(t){this.localStream&&this.localStream.getAudioTracks().forEach(n=>{n.enabled=!t})}isMuted(){if(!this.localStream)return!0;const t=this.localStream.getAudioTracks()[0];return t?!t.enabled:!0}createPeerConnection(t){const n=new RTCPeerConnection({iceServers:this.config.iceServers}),r={id:t,pc:n,remoteStream:null,state:n.connectionState};return this.peers.set(t,r),this.localStream&&this.localStream.getTracks().forEach(a=>{n.addTrack(a,this.localStream)}),n.onicecandidate=a=>{a.candidate&&this.sendSignalingMessage({type:"ice-candidate",from:this.localUserId,to:t,payload:a.candidate.toJSON()})},n.ontrack=a=>{var i;const[o]=a.streams;o&&(r.remoteStream=o,(i=this.onRemoteStream)==null||i.call(this,t,o))},n.onconnectionstatechange=()=>{var a;r.state=n.connectionState,(a=this.onPeerStateChange)==null||a.call(this,t,n.connectionState),(n.connectionState==="failed"||n.connectionState==="disconnected")&&this.removePeer(t)},n}async handleOffer(t,n){this.localStream||await this.initialize();const r=this.createPeerConnection(t);await r.setRemoteDescription(new RTCSessionDescription(n));const a=await r.createAnswer();await r.setLocalDescription(a),this.sendSignalingMessage({type:"answer",from:this.localUserId,to:t,payload:a})}async handleAnswer(t,n){const r=this.peers.get(t);r&&await r.pc.setRemoteDescription(new RTCSessionDescription(n))}async handleIceCandidate(t,n){const r=this.peers.get(t);r&&n&&await r.pc.addIceCandidate(new RTCIceCandidate(n))}sendSignalingMessage(t){var n;(n=this.onSignalingMessage)==null||n.call(this,t)}}function A0(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function N0(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function I0(){return new AudioContext({sampleRate:48e3,latencyHint:"interactive"})}const Ia=u.forwardRef(function(t,n){const{mode:r="bars",width:a=300,height:o=100,barCount:i=32,barColor:l="var(--nice-primary, #3b82f6)",backgroundColor:c="transparent",fftSize:d=256,smoothing:f=.8,minDecibels:h=-90,maxDecibels:m=-10,deviceId:y,autoStart:p=!1,onStart:v,onStop:x,onAudioLevel:b,onError:S,className:g,style:k,barBorderRadius:M=2,barGap:N=2,lineWidth:j=2}=t,_=u.useRef(null),P=u.useRef(null),V=u.useRef(null),z=u.useRef(null),A=u.useRef(0),I=u.useRef(null),L=u.useRef(0),[U,Y]=u.useState(!1),O=u.useCallback((R,T,C=!0)=>{const E=C?R.createLinearGradient(0,o,0,0):R.createLinearGradient(0,0,a,0);return T.forEach((F,q)=>{E.addColorStop(q/(T.length-1),F)}),E},[a,o]),Z=u.useCallback((R,T)=>{const E=(a-(i-1)*N)/i,F=Math.floor(T.length/i),q=Array.isArray(l)?l:[l],Q=q.length>1?O(R,q):q[0];R.fillStyle=Q;for(let J=0;J<i;J++){const re=T[J*F]/255*o,ee=J*(E+N),D=o-re;M>0?(R.beginPath(),R.roundRect(ee,D,E,re,M),R.fill()):R.fillRect(ee,D,E,re)}},[i,l,N,M,a,o,O]),H=u.useCallback((R,T)=>{const C=o/2,F=(a-(i-1)*N)/i,q=Math.floor(T.length/i),Q=Array.isArray(l)?l:[l],J=Q.length>1?O(R,Q):Q[0];R.fillStyle=J;for(let ae=0;ae<i;ae++){const ee=T[ae*q]/255*C,D=ae*(F+N);M>0?(R.beginPath(),R.roundRect(D,C-ee,F,ee,M),R.fill(),R.beginPath(),R.roundRect(D,C,F,ee,M),R.fill()):(R.fillRect(D,C-ee,F,ee),R.fillRect(D,C,F,ee))}},[i,l,N,M,a,o,O]),te=u.useCallback((R,T)=>{const C=Array.isArray(l)?l:[l];R.strokeStyle=C.length>1?O(R,C,!1):C[0],R.lineWidth=j,R.lineCap="round",R.lineJoin="round",R.beginPath();const E=a/T.length;let F=0;for(let q=0;q<T.length;q++){const J=T[q]/128*o/2;q===0?R.moveTo(F,J):R.lineTo(F,J),F+=E}R.stroke()},[l,j,a,o,O]),G=u.useCallback((R,T)=>{const C=a/2,E=o/2,F=Math.min(a,o)/3,q=Array.isArray(l)?l:[l];R.strokeStyle=q.length>1?O(R,q):q[0],R.lineWidth=j;const Q=Math.floor(T.length/64),J=Math.PI*2/64;R.beginPath();for(let ae=0;ae<64;ae++){const re=T[ae*Q]/255,ee=F+re*F*.5,D=ae*J-Math.PI/2,K=C+Math.cos(D)*ee,se=E+Math.sin(D)*ee;ae===0?R.moveTo(K,se):R.lineTo(K,se)}R.closePath(),R.stroke()},[l,j,a,o,O]),B=u.useCallback(()=>{const R=_.current,T=V.current,C=I.current;if(!R||!T||!C)return;const E=R.getContext("2d");if(!E)return;r==="waveform"?T.getByteTimeDomainData(C):T.getByteFrequencyData(C);let F=0;for(let q=0;q<C.length;q++)F+=C[q];switch(L.current=F/(C.length*255),b==null||b(L.current),E.clearRect(0,0,a,o),c!=="transparent"&&(E.fillStyle=c,E.fillRect(0,0,a,o)),r){case"bars":Z(E,C);break;case"mirror-bars":H(E,C);break;case"waveform":te(E,C);break;case"circle":G(E,C);break}A.current=requestAnimationFrame(B)},[r,a,o,c,Z,H,te,G,b]),w=u.useCallback(async()=>{try{if(U)return;const R=await navigator.mediaDevices.getUserMedia({audio:y?{deviceId:{exact:y}}:!0,video:!1});z.current=R;const T=new AudioContext;P.current=T;const C=T.createMediaStreamSource(R),E=T.createAnalyser();E.fftSize=d,E.smoothingTimeConstant=f,E.minDecibels=h,E.maxDecibels=m,C.connect(E),V.current=E,I.current=new Uint8Array(E.frequencyBinCount),Y(!0),v==null||v(),B()}catch(R){S==null||S(R instanceof Error?R:new Error(String(R)))}},[U,y,d,f,h,m,v,S,B]),$=u.useCallback(()=>{cancelAnimationFrame(A.current),z.current&&(z.current.getTracks().forEach(T=>T.stop()),z.current=null),P.current&&(P.current.close(),P.current=null),V.current=null,I.current=null,L.current=0,Y(!1),x==null||x();const R=_.current;if(R){const T=R.getContext("2d");T&&(T.clearRect(0,0,a,o),c!=="transparent"&&(T.fillStyle=c,T.fillRect(0,0,a,o)))}},[a,o,c,x]);return u.useImperativeHandle(n,()=>({start:w,stop:$,isCapturing:()=>U,getAudioLevel:()=>L.current}),[w,$,U]),u.useEffect(()=>(p&&w(),()=>{$()}),[p]),s.jsx("canvas",{ref:_,width:a,height:o,className:g,style:{display:"block",...k},"aria-label":"Audio visualizer"})}),As=e=>{switch(e){case"top-left":return{top:16,left:16};case"top-right":return{top:16,right:16};case"bottom-left":return{bottom:16,left:16};case"bottom-right":default:return{bottom:16,right:16}}},L0={position:"fixed",display:"flex",flexDirection:"column",gap:8,padding:12,borderRadius:12,boxShadow:"0 4px 20px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:14,minWidth:200,maxWidth:280,transition:"all 0.2s ease"},D0={background:"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",text:"var(--nice-bg, #1a1a1a)",textSecondary:"var(--nice-text-secondary, #666)",border:"var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-bg, #fee2e2)",mutedIcon:"var(--nice-danger, #ef4444)",activeBg:"var(--nice-success-bg, #dcfce7)",activeIcon:"var(--nice-success, #22c55e)",hoverBg:"var(--nice-overlay-5, rgba(0, 0, 0, 0.05))"},F0={background:"rgba(30, 30, 30, 0.95)",text:"var(--nice-bg, #fff)",textSecondary:"var(--nice-text-muted, #a0a0a0)",border:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-dark, #7f1d1d)",mutedIcon:"var(--nice-danger-bg, #fca5a5)",activeBg:"#14532d",activeIcon:"var(--nice-success-light, #86efac)",hoverBg:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))"},Ol=u.forwardRef(function(t,n){const{userId:r,userName:a,userAvatarUrl:o,participants:i=[],rtcConfig:l,position:c="bottom-right",expanded:d=!0,onSignalingMessage:f,onMuteToggle:h,onLeave:m,onSpeakingChange:y,speakingThreshold:p=.1,theme:v="auto",className:x,style:b,zIndex:S=1e3}=t,g=u.useRef(null),k=u.useRef(null),M=u.useRef(new Map);u.useRef(new Map);const[N,j]=u.useState(!1),[_,P]=u.useState(!1),[V,z]=u.useState(!1),[A,I]=u.useState(d),U=u.useMemo(()=>v==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":v,[v])==="dark"?F0:D0;u.useEffect(()=>{const B=new Fl(r,l);return B.onRemoteStream=(w,$)=>{let R=M.current.get(w);R||(R=new Audio,R.autoplay=!0,M.current.set(w,R)),R.srcObject=$},B.onSignalingMessage=w=>{f==null||f(w)},B.onPeerStateChange=(w,$)=>{$==="connected"&&P(!0)},g.current=B,B.initialize().then(()=>{var w;(w=k.current)==null||w.start()}),()=>{B.disconnect();const w=M.current;w.forEach($=>{$.srcObject=null}),w.clear()}},[r,l,f]);const Y=u.useCallback(()=>{var w;const B=!N;j(B),(w=g.current)==null||w.setMuted(B),h==null||h(B)},[N,h]),O=u.useCallback(()=>{var B,w;(B=g.current)==null||B.disconnect(),(w=k.current)==null||w.stop(),P(!1),m==null||m()},[m]),Z=u.useCallback(B=>{const w=B>p;w!==V&&(z(w),y==null||y(r,w))},[p,V,r,y]),H=u.useCallback(async B=>{var w;await((w=g.current)==null?void 0:w.createOffer(B))},[]),te=u.useCallback(async B=>{var w;await((w=g.current)==null?void 0:w.handleSignalingMessage(B))},[]);u.useImperativeHandle(n,()=>({connectToPeer:H,handleSignalingMessage:te,toggleMute:Y,isMuted:()=>N,leave:O,getManager:()=>g.current}),[H,te,Y,N,O]);const G=({participant:B,isLocal:w,isSpeaking:$})=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 0"},children:[s.jsx("div",{style:{width:32,height:32,borderRadius:"50%",backgroundColor:U.hoverBg,border:`2px solid ${$?U.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:U.text,transition:"border-color 0.15s ease"},children:B.avatarUrl?s.jsx("img",{src:B.avatarUrl,alt:B.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):B.name.charAt(0).toUpperCase()}),s.jsx("div",{style:{flex:1,minWidth:0},children:s.jsxs("div",{style:{color:U.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[B.name,w&&s.jsx("span",{style:{color:U.textSecondary,fontWeight:400},children:" (You)"})]})}),B.isMuted&&s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:U.mutedIcon,strokeWidth:"2",children:[s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),s.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),s.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),s.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),s.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})]});return A?s.jsxs("div",{className:x,style:{...L0,...As(c),backgroundColor:U.background,border:`1px solid ${U.border}`,zIndex:S,...b},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${U.border}`},children:[s.jsx("span",{style:{color:U.text,fontWeight:600},children:"Voice Chat"}),s.jsx("button",{onClick:()=>I(!1),style:{background:"none",border:"none",cursor:"pointer",padding:4,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:4},"aria-label":"Collapse",children:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:U.textSecondary,strokeWidth:"2",children:[s.jsx("polyline",{points:"4 14 10 14 10 20"}),s.jsx("polyline",{points:"20 10 14 10 14 4"}),s.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),s.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx(G,{participant:{id:r,name:a,avatarUrl:o,isMuted:N},isLocal:!0,isSpeaking:V&&!N}),i.map(B=>s.jsx(G,{participant:B,isSpeaking:B.isSpeaking},B.id))]}),s.jsx(Ia,{ref:k,mode:"bars",width:256,height:32,barCount:24,barColor:N?"var(--nice-text-muted, #9ca3af)":["var(--nice-primary, #3b82f6)","var(--nice-accent, #8b5cf6)"],barGap:3,barBorderRadius:2,autoStart:!1,onAudioLevel:Z,style:{borderRadius:4,opacity:N?.5:1}}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{onClick:Y,style:{flex:1,padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:N?U.mutedBg:U.activeBg,color:N?U.mutedIcon:U.activeIcon,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":N?"Unmute":"Mute",children:N?s.jsxs(s.Fragment,{children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),s.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),s.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),s.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),s.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Muted"]}):s.jsxs(s.Fragment,{children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),s.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),s.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),s.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Mic On"]})}),s.jsx("button",{onClick:O,style:{padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:"var(--nice-danger-bg, #fef2f2)",color:"var(--nice-danger-dark, #dc2626)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":"Leave voice chat",children:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),s.jsx("polyline",{points:"16 17 21 12 16 7"}),s.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]})]}):s.jsx("div",{className:x,style:{position:"fixed",...As(c),zIndex:S,...b},children:s.jsxs("button",{onClick:()=>I(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:U.background,boxShadow:"0 4px 12px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":"Expand voice chat",children:[s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:U.text,strokeWidth:"2",children:[s.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),s.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),s.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),s.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),i.length>0&&s.jsx("span",{style:{position:"absolute",top:-4,right:-4,width:20,height:20,borderRadius:"50%",backgroundColor:U.speakingRing,color:"var(--nice-bg, #fff)",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:i.length+1})]})})});function O0(e,t){const n={...t,id:`op_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now()},r=e.operations.slice(0,e.undoIndex+1);return r.push(n),{...e,operations:r,undoIndex:r.length-1}}function _0(e){return e.undoIndex<0?e:{...e,undoIndex:e.undoIndex-1}}function z0(e){return e.undoIndex>=e.operations.length-1?e:{...e,undoIndex:e.undoIndex+1}}function B0(e,t,n){const a=({"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":.6666666666666666,"1/8T":.3333333333333333,"1/16T":.16666666666666666,"1/4D":1.5,"1/8D":.75}[t.grid]??1)*n,o=t.strength/100;return e.map(i=>{const l=Math.round(i.startTick/a)*a,c=i.startTick+(l-i.startTick)*o,d=(Math.random()-.5)*2*t.humanize;return{...i,startTick:Math.max(0,Math.round(c+d))}})}function G0(e){if(e.length<2)return null;const t=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],n=[...new Set(e.map(a=>a%12))].sort((a,o)=>a-o),r=[{intervals:[0,4,7],quality:"maj"},{intervals:[0,3,7],quality:"min"},{intervals:[0,4,7,11],quality:"maj7"},{intervals:[0,3,7,10],quality:"min7"},{intervals:[0,4,7,10],quality:"7"},{intervals:[0,3,6],quality:"dim"},{intervals:[0,4,8],quality:"aug"},{intervals:[0,3,6,9],quality:"dim7"},{intervals:[0,2,7],quality:"sus2"},{intervals:[0,5,7],quality:"sus4"},{intervals:[0,4,7,9],quality:"6"},{intervals:[0,3,7,9],quality:"min6"}];for(const a of n){const o=n.map(i=>(i-a+12)%12).sort((i,l)=>i-l);for(const i of r)if(i.intervals.length===o.length&&i.intervals.every((l,c)=>l===o[c])){const l=t[a],c=t[e[0]%12];return{root:l,quality:i.quality,bass:c!==l?c:void 0,symbol:`${l}${i.quality==="maj"?"":i.quality}${c!==l?`/${c}`:""}`,intervals:i.intervals}}}return null}const _l={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],aeolian:[0,2,3,5,7,8,10],locrian:[0,1,3,5,6,8,10],"harmonic-minor":[0,2,3,5,7,8,11],"melodic-minor":[0,2,3,5,7,9,11],"pentatonic-major":[0,2,4,7,9],"pentatonic-minor":[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11],"whole-tone":[0,2,4,6,8,10]};function W0(e,t,n){const r=_l[n],a=(e-t+120)%12;let o=r[0],i=999;for(const c of r){const d=Math.min(Math.abs(a-c),12-Math.abs(a-c));d<i&&(i=d,o=c)}const l=Math.floor((e-t)/12);return t+l*12+o}function U0(e,t){switch(t.type){case"transpose":return e.map(n=>({...n,pitch:Math.max(0,Math.min(127,n.pitch+(t.params.semitones??0)))}));case"invert":{const n=t.params.axis??60;return e.map(r=>({...r,pitch:Math.max(0,Math.min(127,Math.round(2*n-r.pitch)))}))}case"retrograde":{if(e.length===0)return e;const n=Math.max(...e.map(r=>r.startTick+r.durationTicks));return e.map(r=>({...r,startTick:n-r.startTick-r.durationTicks}))}case"randomize-velocity":return e.map(n=>({...n,velocity:Math.max(1,Math.min(127,n.velocity+Math.round((Math.random()-.5)*2*(t.params.range??20))))}));default:return e}}function V0(e){return e>=95?"S":e>=85?"A":e>=70?"B":e>=55?"C":e>=40?"D":"F"}const q0={"guitar-standard":{instrument:"guitar-6",stringPitches:[40,45,50,55,59,64]},"guitar-drop-d":{instrument:"guitar-6",stringPitches:[38,45,50,55,59,64]},"bass-standard":{instrument:"bass-4",stringPitches:[28,33,38,43]},"ukulele-standard":{instrument:"ukulele",stringPitches:[67,60,64,69]}},H0={"Bass Drum":{staffLine:4,noteHead:"normal",stem:"down"},Snare:{staffLine:2,noteHead:"normal",stem:"up"},"Hi-Hat Closed":{staffLine:0,noteHead:"x",stem:"up"},"Hi-Hat Open":{staffLine:0,noteHead:"diamond",stem:"up"},Ride:{staffLine:-1,noteHead:"x",stem:"up"},Crash:{staffLine:-2,noteHead:"x",stem:"up"},"High Tom":{staffLine:1,noteHead:"normal",stem:"up"},"Mid Tom":{staffLine:2,noteHead:"normal",stem:"down"},"Low Tom":{staffLine:3,noteHead:"normal",stem:"down"}};exports.ALL_CAP_STYLES=jn;exports.ALL_EFFECTS=Sp;exports.ALL_TEXTURES=$o;exports.ARTNET_PORT=b0;exports.ASYMMETRIC_CAPS=vo;exports.ArpeggiatorPanel=Zs;exports.AudioEffectType=Sl;exports.AudioPitchAnalyzer=Eo;exports.AudioPlaybackEngine=ih;exports.AudioRecorder=ao;exports.AudioTimeline=zs;exports.AutoSavePanel=Js;exports.BarFillEditor=Po;exports.CCAutomationLaneEditor=Vs;exports.CCLane=Ds;exports.CONTROLLER_PROFILES=Ti;exports.ChaseRunner=k0;exports.CollaboratorPermission=Cl;exports.DEFAULT_ARP_CONFIG=Lr;exports.DEFAULT_BAR_FILL=Lt;exports.DEFAULT_CAP_STYLE=wo;exports.DEFAULT_EMPTY_BAR_FILL=ur;exports.DEFAULT_FONT_SETTINGS=pr;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=fr;exports.DEFAULT_GOLD_FILLED_BAR_FILL=hr;exports.DEFAULT_KARAOKE_SETTINGS=So;exports.DEFAULT_PLAYER_BAR_STYLE=en;exports.DEFAULT_SEED_CONFIG=xi;exports.DMXEngine=Il;exports.DRUM_PATTERN_NAMES=wh;exports.DefaultScoringPresets=aa;exports.DmxChannelControl=Na;exports.DmxChannelType=jt;exports.DmxEditor=Al;exports.DmxOptionsControl=Aa;exports.DmxSliderControl=Rn;exports.DynamicRuleEditor=ti;exports.DynamicRuleField=Xe;exports.DynamicRuleOperator=Qe;exports.EditorTrackProvider=ta;exports.EditorUndoManager=fd;exports.FIXTURE_PROFILES=Nl;exports.GENERIC_PROFILE=ka;exports.GM_DRUM_MAP=H0;exports.GRADIENT_PRESETS=Ao;exports.GROOVE_TEMPLATES=Ta;exports.GenericPlayer=Go;exports.GenericPlayerControls=Uo;exports.GenericPlayerStage=Vo;exports.GenericPlayerStageVisualizer=qo;exports.GenericPlaylist=Ko;exports.GenericPlaylistItem=ga;exports.KARAOKE_FONT_OPTIONS=su;exports.KEY_MAPS=Lo;exports.KaraokeEditorManager=_o;exports.KaraokeFormat=wl;exports.KaraokeLyrics=co;exports.KaraokePhaserRenderer=zo;exports.KaraokeTimeline=Ro;exports.LANE_COLORS=xn;exports.LAUNCH_CONTROL_PROFILE=Ri;exports.LAYER_COLORS=Hp;exports.LFOPanel=Xs;exports.MINILAB_PROFILE=ji;exports.MPK_MINI_PROFILE=Mi;exports.MasterFXPanel=no;exports.MidiCCMapper=Ch;exports.ModeSwitcher=ma;exports.NOTE_NAMES=mh;exports.NiceArpeggiatorPanel=Zs;exports.NiceAudioErrorBoundary=Zl;exports.NiceAudioPitchAnalyzer=Eo;exports.NiceAudioTimeline=zs;exports.NiceAutoSavePanel=Js;exports.NiceBarFillEditor=Po;exports.NiceCCAutomationLaneEditor=Vs;exports.NiceCCLane=Ds;exports.NiceDMXTimeline=M0;exports.NiceDmxChannelControl=Na;exports.NiceDmxEditor=Al;exports.NiceDmxOptionsControl=Aa;exports.NiceDmxSliderControl=Rn;exports.NiceDynamicRuleEditor=ti;exports.NiceEditorTrackProvider=ta;exports.NiceGenericPlayer=Go;exports.NiceGenericPlayerControls=Uo;exports.NiceGenericPlayerStage=Vo;exports.NiceGenericPlayerStageVisualizer=qo;exports.NiceGenericPlaylist=Ko;exports.NiceGenericPlaylistItem=ga;exports.NiceI18nProvider=Yl;exports.NiceKaraokeEditorManager=_o;exports.NiceKaraokeLyrics=co;exports.NiceKaraokePhaserRenderer=zo;exports.NiceKaraokeTimeline=Ro;exports.NiceLFOPanel=Xs;exports.NiceMasterFXPanel=no;exports.NiceModeSwitcher=ma;exports.NiceNoteParticles=bi;exports.NiceNoteRiver=gi;exports.NicePianoRoll=Ls;exports.NicePlaylistBrowser=si;exports.NicePlaylistDualPane=ni;exports.NicePlaylistGridView=li;exports.NicePlaylistImportWizard=fi;exports.NicePlaylistList=wa;exports.NicePlaylistOverview=ci;exports.NicePlaylistSearchBar=di;exports.NicePlaylistSidebar=ii;exports.NicePlaylistTagEditor=Yo;exports.NicePlaylistTrackList=va;exports.NiceRadioPlayer=$0;exports.NiceRecordingOptionsPanel=ro;exports.NiceStageVisualizer=ya;exports.NiceStationBrowser=Dl;exports.NiceStepSequencerPanel=Qs;exports.NiceStreamingVisualizer=Ia;exports.NiceUndoRedoPanel=eo;exports.NiceVoiceChatOverlay=Ol;exports.NiceWaveform=Is;exports.NiceYouTubePlayer=Ho;exports.NiceZoomSnapControls=to;exports.NoteParticles=bi;exports.NoteRiver=gi;exports.OVERLAY_PATTERNS=sr;exports.OXYGEN25_PROFILE=ki;exports.PLAYER_COLORS=Nt;exports.PLAYER_COLOR_VARS=Jn;exports.PROGRESSION_NAMES=xh;exports.PadNotePlayer=cu;exports.PaneSide=Xo;exports.PianoRoll=Ls;exports.PlaylistBrowser=si;exports.PlaylistDualPane=ni;exports.PlaylistGridView=li;exports.PlaylistImportWizard=fi;exports.PlaylistList=wa;exports.PlaylistOverview=ci;exports.PlaylistSearchBar=di;exports.PlaylistSidebar=ii;exports.PlaylistTagEditor=Yo;exports.PlaylistTrackList=va;exports.PlaylistType=ba;exports.RecordingOptionsPanel=ro;exports.SACN_PORT=w0;exports.SCALE_INTERVALS=_l;exports.SCALE_NAMES=vh;exports.SKEW_CAPS=xo;exports.STANDARD_TUNINGS=q0;exports.SYMMETRIC_CAPS=da;exports.ShortcutManager=vl;exports.SimpleSynth=vi;exports.SortDirection=Yt;exports.SortField=Qo;exports.StageVisualizer=ya;exports.StepSequencerPanel=Qs;exports.StreamingVisualizer=Ia;exports.TEXTURE_CATEGORIES=fa;exports.TrackSource=dt;exports.UndoRedoPanel=eo;exports.ViewMode=Zo;exports.VocalEffectsEngine=Cp;exports.VoiceChatOverlay=Ol;exports.Waveform=Is;exports.WebRTCAudioManager=Fl;exports.YouTubePlayer=Ho;exports.ZoomSnapControls=to;exports.addEffectToLayer=Jh;exports.addMidiNote=rp;exports.analyzeAudioFileWithAlgorithm=fp;exports.applyGroove=vp;exports.applyGrooveTemplate=ml;exports.applyHumanize=pl;exports.applyKaraokeDisplayVars=pa;exports.applyMidiTransform=U0;exports.applySwing=hl;exports.arrow_L=Rt;exports.arrow_R=bt;exports.autoCorrelate=Wh;exports.bracket_L=oa;exports.bracket_R=go;exports.buildArpSequence=Hs;exports.buildLanes=Do;exports.buildNoteDescriptors=Uh;exports.buildPadNoteEvents=Oo;exports.buildSegmentScores=Vh;exports.canRedo=Ii;exports.canUndo=Ni;exports.chamfer_L=tr;exports.chamfer_R=Jt;exports.clearMidiNotes=sp;exports.clearPattern=Qi;exports.computeGrade=V0;exports.computeTheoreticalMax=cl;exports.computeVocalPerformanceReport=kp;exports.convertBrowserSongToKaraokeSongFile=Qh;exports.copyCCEvents=Yr;exports.createAnalyserNode=rl;exports.createArpPattern=Ph;exports.createArtNetPacket=x0;exports.createBasslinePattern=Eh;exports.createCCHistory=$i;exports.createCompressorNode=sl;exports.createDefaultLFO=dr;exports.createDefaultShortcuts=Fp;exports.createDropZoneHandlers=Vp;exports.createEmptyPattern=Dt;exports.createEmptyStep=Ma;exports.createGainNode=al;exports.createHiHatPattern=$h;exports.createKickPattern=Rh;exports.createLoopRegion=Ep;exports.createSACNPacket=S0;exports.createSnarePattern=Th;exports.createVocoderNode=ol;exports.createVoiceChatAudioContext=I0;exports.cutCCEvents=Di;exports.deleteCCEventsInRange=Fi;exports.deserializeLFO=Sc;exports.deserializePattern=Nh;exports.detectChord=G0;exports.downsampleAndQuantizePitchPoints=qh;exports.drawGlossyBarOnCanvas=mn;exports.drawTimeline=zr;exports.estimateLatencyMs=Hh;exports.estimateLatencyMsFromRecording=Rp;exports.evaluateLFO=Jr;exports.evaluateLFOAsCC=ea;exports.exportCCLane=zi;exports.extractBpmFromNotes=uo;exports.findTextureByUrl=nu;exports.formatShortcut=Op;exports.generateArpEvents=Mc;exports.generatePlaceholderWaveform=gp;exports.generateSeed=Ci;exports.generateUltrastarText=hp;exports.getActiveGradient=Io;exports.getActiveLyrics=bd;exports.getActiveWords=vd;exports.getAlgorithmColor=Yh;exports.getAlgorithmCssVar=Zh;exports.getAlgorithmLabel=Kh;exports.getArpModes=Ks;exports.getArpRates=Ys;exports.getAudioContext=an;exports.getAudioInputDevices=N0;exports.getAudioWorkletProcessorCode=tl;exports.getBackgroundUrl=Gh;exports.getCachedImage=Jd;exports.getCapStyleByName=hn;exports.getComboMultiplier=ll;exports.getCoverUrl=Bh;exports.getGrooveTemplate=xp;exports.getGrooveTemplateNames=wp;exports.getLaneForPitch=Fo;exports.getNextPlayerColor=Kp;exports.getNextPlayerColorCss=Yp;exports.getOverlayCanvasPattern=vn;exports.getPatternByName=pn;exports.getSACNMulticastAddress=C0;exports.getScoringPreset=po;exports.getTexturePattern=gn;exports.getVerseRatingLabel=il;exports.handleAddCCEvent=ip;exports.handleRedo=ud;exports.handleRemoveCCEvent=cp;exports.handleSelectCCLane=op;exports.handleUndo=dd;exports.handleUpdateCCEvent=lp;exports.hexToHsl=or;exports.humanizeMidiNotes=Pp;exports.hydrateKaraokeDisplayFromBackend=ou;exports.hydratePlayerKaraokeSettingsFromBackend=Ed;exports.hzToUltrastarPitch=fo;exports.importCCLane=Bi;exports.initKaraokeDisplaySettings=lu;exports.instrumentPresets=lh;exports.isAudioContextRunning=Fs;exports.isInLoopRegion=Ip;exports.isWebRTCSupported=A0;exports.loadAllKaraokeSettings=Ad;exports.loadAudioWorkletModule=nl;exports.loadKaraokeDisplaySettings=No;exports.loadKaraokeSettings=Co;exports.loadPlayerBarStyle=ko;exports.loadPlayerBarStyles=Id;exports.loadRemoteScoringPresets=Rd;exports.makeClickReference=gl;exports.makeClipSelectionId=pp;exports.mergeWaveforms=yp;exports.midiSeedGenerator=Sh;exports.midiToHz=Br;exports.normalizeHex=ir;exports.openAudioFilePicker=qp;exports.ornate_L=la;exports.ornate_R=ar;exports.parseLyrics=yd;exports.parseNotes=ra;exports.parseVersesWithSyllables=lo;exports.parseVersesWithWords=gd;exports.parseVideoMetadata=ul;exports.pasteCCEvents=Li;exports.pill_L=Et;exports.pill_R=Mt;exports.preloadTexture=ua;exports.preloadTextures=eu;exports.probeAudioFile=xl;exports.pushCCState=Pi;exports.pushOperation=O0;exports.quantizeMidiNotes=Tp;exports.quantizeNotes=B0;exports.quantizeStepInBeats=bl;exports.quantizeStepInSeconds=$a;exports.randomizeVelocity=Xi;exports.recordCCEvent=Oi;exports.redoCC=Ai;exports.redoOperation=z0;exports.removeEffectFromLayer=ep;exports.removeMidiNote=ap;exports.renderGlossyBarSvg=Mo;exports.resumeAudioContext=It;exports.reversePattern=Yi;exports.sampleLFOForDisplay=Us;exports.sampleLFOToCCEvents=Ws;exports.saveKaraokeDisplaySettings=iu;exports.saveKaraokeSettings=Pd;exports.savePlayerBarStyle=Nd;exports.scaleResult=zh;exports.scaleTo10k=dl;exports.scoreNotesWithPitchPoints=_h;exports.selectCCEventsInRange=kh;exports.serializeLFO=wc;exports.serializePattern=Ah;exports.setLoopFromSelection=Ap;exports.setProjectWithUndo=oo;exports.setStepGate=Vi;exports.setStepNote=Wi;exports.setStepProbability=qi;exports.setStepVelocity=Ui;exports.sharp_L=Xt;exports.sharp_R=Qt;exports.shield_L=nr;exports.shield_R=yo;exports.shiftPattern=Zi;exports.shouldTrigger=el;exports.skewTL_L=Hn;exports.skewTL_R=_r;exports.skewTR_L=Or;exports.skewTR_R=Kn;exports.snapLoopToGrid=Np;exports.snapTimeToQuantize=Zr;exports.snapToGrid=mp;exports.snapToScale=W0;exports.soft_L=sa;exports.soft_R=mo;exports.stepDuration=ja;exports.stepTimeOffset=Ji;exports.syncDivisionToHz=Bs;exports.tab_L=ia;exports.tab_R=bo;exports.thinCCEvents=_i;exports.toTrack=Xh;exports.toggleEffectBypass=tp;exports.toggleStep=Gi;exports.toggleStepSlide=Hi;exports.transposePattern=Ki;exports.undoCC=Ei;exports.undoOperation=_0;exports.updateEffectParams=np;exports.useAudioWorklet=Oh;exports.useAutoSave=od;exports.useCCAutomation=jh;exports.useDMXAudioSync=R0;exports.useDMXEngine=j0;exports.useEditorTrack=md;exports.useLocalPlaylists=xa;exports.useMPE=fh;exports.useMidiLearn=dh;exports.useNiceTranslation=we;exports.useOxygen25=ph;exports.usePitchWorker=Lh;exports.usePlaybackEngine=id;exports.useProjectCRUD=pd;exports.useRadioStream=Ll;exports.useRecording=ld;exports.useScoringWorker=Dh;exports.useStepSequencer=Ih;exports.useWebMidi=gr;exports.useWorker=Ra;exports.validateAudioFiles=Pa;exports.wave_L=rr;exports.wave_R=ca;exports.waveformValue=Gs;exports.wrapTimeInLoop=Lp;
429
+ E`}}function h0(e,t){return`${e}:${t}`}function p0(e,t,n,a=1){if(t==="off")return e;const s=60/n;if(t==="beat")return Math.round(e/(s/a))*(s/a);if(t==="bar"){const i=s*4;return Math.round(e/i)*i}return e}function f0(e){return e.length===0?[]:e.flat()}function m0(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const ps=[{id:"mpc-60-tight",name:"MPC 60 Tight",stepsPerBar:16,timingOffsets:[0,.02,0,.01,0,.03,0,.01,0,.02,0,.01,0,.03,0,.01],velocityScales:[1.1,.85,.95,.8,1.05,.85,.9,.8,1.1,.85,.95,.8,1.05,.85,.9,.8],durationScales:[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]},{id:"mpc-60-swing",name:"MPC 60 Swing",stepsPerBar:16,timingOffsets:[0,.06,0,.04,0,.07,0,.04,0,.06,0,.04,0,.07,0,.04],velocityScales:[1.15,.7,.9,.75,1.1,.7,.85,.75,1.15,.7,.9,.75,1.1,.7,.85,.75],durationScales:[1.05,.9,1,.95,1.05,.9,1,.95,1.05,.9,1,.95,1.05,.9,1,.95]},{id:"hip-hop-lazy",name:"Hip-Hop Lazy",stepsPerBar:16,timingOffsets:[0,.04,.01,.05,0,.04,.02,.06,0,.04,.01,.05,0,.04,.02,.06],velocityScales:[1.2,.65,.85,.6,1.1,.65,.8,.6,1.2,.65,.85,.6,1.1,.65,.8,.6],durationScales:[1.1,1,1,.9,1.1,1,1,.9,1.1,1,1,.9,1.1,1,1,.9]},{id:"funk-pocket",name:"Funk Pocket",stepsPerBar:16,timingOffsets:[0,-.01,.03,0,0,-.01,.04,0,0,-.01,.03,0,0,-.01,.04,0],velocityScales:[1.2,.9,.7,1.05,.85,.9,.7,1,1.15,.9,.7,1.05,.85,.9,.7,1],durationScales:[1,.95,1.1,1,1,.95,1.1,1,1,.95,1.1,1,1,.95,1.1,1]},{id:"shuffle-blues",name:"Shuffle / Blues",stepsPerBar:8,timingOffsets:[0,.11,0,.11,0,.11,0,.11],velocityScales:[1.2,.8,1.1,.8,1.2,.8,1.1,.8],durationScales:[1.1,.8,1.1,.8,1.1,.8,1.1,.8]},{id:"reggaeton",name:"Reggaeton",stepsPerBar:16,timingOffsets:[0,0,0,.03,0,0,0,.03,0,0,0,.03,0,0,0,.03],velocityScales:[1.3,.6,.9,1.1,.7,.6,.9,1.1,1.3,.6,.9,1.1,.7,.6,.9,1.1],durationScales:[1,1,1,.9,1,1,1,.9,1,1,1,.9,1,1,1,.9]}];function g0(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function wc(e,t){return t.amount===0?e:e.map(n=>{const a=n.time/t.grid;if(Math.round(a)%2===1){const o=t.grid*t.amount*.5;return{...n,time:n.time+o}}return{...n}})}function jc(e,t){const n=t.seed!=null?g0(t.seed):Math.random;return e.map(a=>{const s=(n()-.5)*2*t.timingAmount,i=Math.round((n()-.5)*2*t.velocityAmount),o=(n()-.5)*2*t.durationAmount;return{...a,time:Math.max(0,a.time+s),velocity:Math.max(1,Math.min(127,a.velocity+i)),duration:Math.max(.01,a.duration+o)}})}function Cc(e,t,n=1){const a=4/t.stepsPerBar;return e.map(s=>{const i=s.time/a,o=Math.round(i)%t.stepsPerBar,l=t.timingOffsets[o]*a*n,c=1+(t.velocityScales[o]-1)*n,u=1+(t.durationScales[o]-1)*n;return{...s,time:Math.max(0,s.time+l),velocity:Math.max(1,Math.min(127,Math.round(s.velocity*c))),duration:Math.max(.01,s.duration*u)}})}function y0(e,t){let n=[...e.map(a=>({...a}))];return t.template&&t.grooveStrength>0&&(n=Cc(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=wc(n,t.swing)),t.humanize&&(n=jc(n,t.humanize)),n}function b0(e){return ps.find(t=>t.id===e)}function x0(){return ps.map(({id:e,name:t})=>({id:e,name:t}))}function Mc(e){switch(e){case"1/4":return 1;case"1/8":return .5;case"1/16":return .25;case"1/32":return .125;case"1/4T":return 2/3;case"1/8T":return 1/3;case"1/16T":return 1/6}}function fs(e,t){return Mc(e)*60/t}function ja(e,t,n){const a=fs(t,n);return Math.round(e/a)*a}function v0(e,t){const{value:n,bpm:a,strength:s=1,quantizeStarts:i=!0,quantizeDurations:o=!1}=t,l=fs(n,a);return e.map(c=>{let{start:u,duration:h}=c;if(i){const p=Math.round(u/l)*l;u=u+(p-u)*s}if(o){const p=Math.max(l,Math.round(h/l)*l);h=h+(p-h)*s}return u===c.start&&h===c.duration?c:{...c,start:u,duration:h}})}function S0(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function k0(e,t={}){const{timingRange:n=.02,velocityRange:a=10,seed:s}=t,i=s!=null?S0(s):Math.random;return e.map(o=>{const l=(i()*2-1)*n,c=Math.round((i()*2-1)*a);return{...o,start:Math.max(0,o.start+l),velocity:o.velocity!=null?Math.max(1,Math.min(127,(o.velocity??100)+c)):void 0}})}function w0(){return{start:0,end:0,enabled:!1}}function j0(e,t){return{...e<t?{start:e,end:t}:{start:t,end:e},enabled:!0}}function C0(e,t,n){return{start:ja(e.start,t,n),end:ja(e.end,t,n),enabled:e.enabled}}function M0(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function R0(e,t){if(!t.enabled||t.end<=t.start||e<t.start)return e;if(e>=t.end){const n=t.end-t.start;return t.start+(e-t.start)%n}return e}function Ca(e){return e.length===1?e.toLowerCase():e}function kr(e){var n,a,s,i;const t=[];return(n=e.modifiers)!=null&&n.ctrl&&t.push("Ctrl"),(a=e.modifiers)!=null&&a.shift&&t.push("Shift"),(s=e.modifiers)!=null&&s.alt&&t.push("Alt"),(i=e.modifiers)!=null&&i.meta&&t.push("Meta"),t.push(Ca(e.key)),t.join("+")}function N0(e,t){var l,c,u,h;const n=Ca(e.key)===Ca(t.key),a=!!e.ctrlKey==!!((l=t.modifiers)!=null&&l.ctrl),s=!!e.shiftKey==!!((c=t.modifiers)!=null&&c.shift),i=!!e.altKey==!!((u=t.modifiers)!=null&&u.alt),o=!!e.metaKey==!!((h=t.modifiers)!=null&&h.meta);return n&&a&&s&&i&&o}class Rc{constructor(){this.actions=new Map,this.activeScopes=new Set(["global"]),this.enabled=!0,this.listener=null}register(t){this.actions.set(t.id,{...t,enabled:t.enabled??!0})}unregister(t){this.actions.delete(t)}rebind(t,n){const a=this.actions.get(t);a&&(a.binding=n)}setActiveScopes(t){this.activeScopes.clear(),this.activeScopes.add("global");for(const n of t)this.activeScopes.add(n)}setEnabled(t){this.enabled=t}setActionEnabled(t,n){const a=this.actions.get(t);a&&(a.enabled=n)}findConflicts(){const t=[],n=[...this.actions.values()];for(let a=0;a<n.length;a++)for(let s=a+1;s<n.length;s++){const i=n[a],o=n[s];kr(i.binding)===kr(o.binding)&&(i.scope===o.scope||i.scope==="global"||o.scope==="global")&&t.push([i,o])}return t}getGrouped(){const t={};for(const n of this.actions.values())t[n.group]||(t[n.group]=[]),t[n.group].push(n);return t}getAll(){return[...this.actions.values()]}exportConfig(){return[...this.actions.values()].map(t=>({id:t.id,binding:t.binding}))}importConfig(t){for(const n of t)this.rebind(n.id,n.binding)}formatBinding(t){const n=this.actions.get(t);return n?kr(n.binding):""}handleKeyDown(t){if(!this.enabled)return!1;for(const n of this.actions.values())if(n.enabled&&this.activeScopes.has(n.scope)&&N0(t,n.binding))return t.preventDefault(),t.stopPropagation(),n.callback(),!0;return!1}attach(){this.listener||(this.listener=t=>{const n=t.target;n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable||this.handleKeyDown(t)},window.addEventListener("keydown",this.listener,!0))}detach(){this.listener&&(window.removeEventListener("keydown",this.listener,!0),this.listener=null)}destroy(){this.detach(),this.actions.clear()}}function T0(e={}){const t=new Rc,n=()=>{},a=[{id:"transport.play",label:"Play / Pause",group:"Transport",scope:"global",binding:{key:" "}},{id:"transport.stop",label:"Stop",group:"Transport",scope:"global",binding:{key:"Escape"}},{id:"transport.record",label:"Record",group:"Transport",scope:"global",binding:{key:"r",modifiers:{ctrl:!0}}},{id:"transport.rewind",label:"Rewind",group:"Transport",scope:"global",binding:{key:"Home"}},{id:"transport.forward",label:"Forward",group:"Transport",scope:"global",binding:{key:"End"}},{id:"transport.loopToggle",label:"Toggle Loop",group:"Transport",scope:"global",binding:{key:"l"}},{id:"edit.undo",label:"Undo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0}}},{id:"edit.redo",label:"Redo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0,shift:!0}}},{id:"edit.cut",label:"Cut",group:"Edit",scope:"editor",binding:{key:"x",modifiers:{ctrl:!0}}},{id:"edit.copy",label:"Copy",group:"Edit",scope:"editor",binding:{key:"c",modifiers:{ctrl:!0}}},{id:"edit.paste",label:"Paste",group:"Edit",scope:"editor",binding:{key:"v",modifiers:{ctrl:!0}}},{id:"edit.delete",label:"Delete",group:"Edit",scope:"editor",binding:{key:"Delete"}},{id:"edit.selectAll",label:"Select All",group:"Edit",scope:"editor",binding:{key:"a",modifiers:{ctrl:!0}}},{id:"edit.duplicate",label:"Duplicate",group:"Edit",scope:"editor",binding:{key:"d",modifiers:{ctrl:!0}}},{id:"view.zoomIn",label:"Zoom In",group:"View",scope:"global",binding:{key:"=",modifiers:{ctrl:!0}}},{id:"view.zoomOut",label:"Zoom Out",group:"View",scope:"global",binding:{key:"-",modifiers:{ctrl:!0}}},{id:"view.zoomFit",label:"Zoom to Fit",group:"View",scope:"global",binding:{key:"0",modifiers:{ctrl:!0}}},{id:"view.toggleMixer",label:"Toggle Mixer",group:"View",scope:"global",binding:{key:"m"}},{id:"view.togglePianoRoll",label:"Toggle Piano Roll",group:"View",scope:"global",binding:{key:"p"}},{id:"pianoRoll.quantize",label:"Quantize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"q"}},{id:"pianoRoll.humanize",label:"Humanize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"h"}},{id:"pianoRoll.velocityUp",label:"Velocity +10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{shift:!0}}},{id:"pianoRoll.velocityDown",label:"Velocity -10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{shift:!0}}},{id:"pianoRoll.octaveUp",label:"Octave Up",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{ctrl:!0,shift:!0}}},{id:"pianoRoll.octaveDown",label:"Octave Down",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{ctrl:!0,shift:!0}}},{id:"timeline.split",label:"Split at Cursor",group:"Timeline",scope:"timeline",binding:{key:"s"}},{id:"timeline.mute",label:"Mute Track",group:"Timeline",scope:"timeline",binding:{key:"m",modifiers:{ctrl:!0}}},{id:"timeline.solo",label:"Solo Track",group:"Timeline",scope:"timeline",binding:{key:"s",modifiers:{ctrl:!0}}},{id:"timeline.addTrack",label:"Add Track",group:"Timeline",scope:"timeline",binding:{key:"t",modifiers:{ctrl:!0}}},{id:"mixer.resetFader",label:"Reset Fader",group:"Mixer",scope:"mixer",binding:{key:"0"}},{id:"mixer.bypassFx",label:"Bypass All FX",group:"Mixer",scope:"mixer",binding:{key:"b"}}];for(const s of a)t.register({...s,callback:e[s.id]??n});return t}function $0(e){return kr(e)}const P0=["audio/mpeg","audio/wav","audio/ogg","audio/flac","audio/aac","audio/webm","audio/mp4","audio/x-m4a","audio/x-wav","audio/x-aiff","audio/aiff","audio/midi","audio/x-midi"],A0=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],E0=500*1024*1024,I0=20;function Ot(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function L0(e,t){return!!(e.type&&t.some(n=>e.type.startsWith(n.replace("*","")))||e.type.startsWith("audio/"))}function D0(e,t){const n=Ot(e.name);return n!==""&&t.includes(n)}function ms(e,t={}){const n=t.maxSize??E0,a=t.allowedTypes??P0,s=t.allowedExtensions??A0,i=t.maxFiles??I0,o=[],l=[];for(let c=0;c<e.length;c++){const u=e[c];if(c>=i){l.push({file:u,reason:"limit",message:`Exceeded maximum of ${i} files`});continue}if(u.size>n){l.push({file:u,reason:"size",message:`File exceeds ${Math.round(n/1024/1024)}MB limit`});continue}if(!L0(u,a)&&!D0(u,s)){l.push({file:u,reason:"type",message:`Unsupported file type: ${u.type||Ot(u.name)}`});continue}o.push(u)}return{valid:o,errors:l}}async function Nc(e){const t={file:e,name:e.name.replace(/\.[^.]+$/,""),extension:Ot(e.name),sizeBytes:e.size,mimeType:e.type||`audio/${Ot(e.name)}`};try{const n=await e.arrayBuffer(),s=await new OfflineAudioContext(1,1,44100).decodeAudioData(n);t.duration=s.duration,t.sampleRate=s.sampleRate,t.channels=s.numberOfChannels}catch{}return t}function _0(e){let t=0;return{onDragEnter:n=>{var a;n.preventDefault(),n.stopPropagation(),t++,t===1&&((a=e.onDragEnter)==null||a.call(e))},onDragOver:n=>{n.preventDefault(),n.stopPropagation(),(n instanceof DragEvent&&n.dataTransfer||"dataTransfer"in n&&n.dataTransfer)&&(n.dataTransfer.dropEffect="copy")},onDragLeave:n=>{var a;n.preventDefault(),n.stopPropagation(),t--,t===0&&((a=e.onDragLeave)==null||a.call(e))},onDrop:async n=>{var u,h;n.preventDefault(),n.stopPropagation(),t=0,(u=e.onDragLeave)==null||u.call(e);const a="dataTransfer"in n?n.dataTransfer:null;if(!((h=a==null?void 0:a.files)!=null&&h.length))return;const s=Array.from(a.files),{valid:i,errors:o}=ms(s,e.validation),l=[],c=[...o];for(const p of i)if(e.probe)try{l.push(await Nc(p))}catch{c.push({file:p,reason:"decode",message:"Failed to decode audio"})}else l.push({file:p,name:p.name.replace(/\.[^.]+$/,""),extension:Ot(p.name),sizeBytes:p.size,mimeType:p.type||`audio/${Ot(p.name)}`});e.onDrop({accepted:l,rejected:c})}}}function F0(e={}){return new Promise(t=>{const n=document.createElement("input");n.type="file",n.accept="audio/*,.mid,.midi",n.multiple=e.multiple??!0,n.onchange=async()=>{var l;if(!((l=n.files)!=null&&l.length)){t({accepted:[],rejected:[]});return}const a=Array.from(n.files),{valid:s,errors:i}=ms(a,e.validation),o=s.map(c=>({file:c,name:c.name.replace(/\.[^.]+$/,""),extension:Ot(c.name),sizeBytes:c.size,mimeType:c.type||`audio/${Ot(c.name)}`}));t({accepted:o,rejected:i})},n.click()})}var Ft=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(Ft||{}),Tc=(e=>(e[e.Equalizer=0]="Equalizer",e[e.Compressor=1]="Compressor",e[e.Reverb=2]="Reverb",e[e.Delay=3]="Delay",e[e.Distortion=4]="Distortion",e[e.Chorus=5]="Chorus",e[e.Flanger=6]="Flanger",e[e.Phaser=7]="Phaser",e))(Tc||{}),$c=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))($c||{});const z0=["var(--nice-success, #4caf50)","var(--nice-primary, #2196f3)","var(--nice-warning, #ff9800)","var(--nice-accent-pink, #e91e63)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-success, #8bc34a)","var(--nice-warning, #ffc107)"],Ar=["off","no function","brak"],O0=e=>e.segments.some(t=>t.isOff||Ar.some(n=>t.name.toLowerCase().includes(n))),B0=e=>e.segments.find(t=>t.isOff||Ar.some(n=>t.name.toLowerCase().includes(n))),Pc=e=>Math.floor((e.valueFrom+e.valueTo)/2),G0=e=>{const t=B0(e);return t?Pc(t):0},W0=(e,t)=>e.segments.find(n=>t>=n.valueFrom&&t<=n.valueTo),jn=(e,t=0,n=255)=>Math.max(t,Math.min(n,Math.round(e))),Gn=({channel:e,value:t,onChange:n,onCommit:a,showDirectionHint:s})=>{const[i,o]=d.useState(jn(t)),l=d.useMemo(()=>W0(e,i),[e,i]);d.useEffect(()=>o(jn(t)),[t]);const c=u=>{const h=jn(u);o(h),n(h),a==null||a(h)};return r.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:6},children:[r.jsxs("strong",{children:[e.channel,". ",e.name]}),s&&l&&r.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:l.name})]}),r.jsx("input",{type:"range",min:0,max:255,value:i,onChange:u=>{const h=jn(Number(u.target.value));o(h),n(h)},onMouseUp:()=>a==null?void 0:a(i),onTouchEnd:()=>a==null?void 0:a(i),style:{width:"100%"}}),r.jsx("div",{style:{marginTop:6},children:r.jsx("input",{type:"number",min:0,max:255,value:i,onChange:u=>{const h=jn(Number(u.target.value));o(h),n(h)},onBlur:()=>a==null?void 0:a(i),style:{width:80,padding:6,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:6}})}),O0(e)&&r.jsx("button",{type:"button",onClick:()=>c(G0(e)),style:{width:"100%",marginTop:8,padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)",cursor:"pointer"},children:"OFF"})]})},gs=({channel:e,value:t,onChange:n,onCommit:a})=>{const s=d.useMemo(()=>{const o=[...e.segments];return o.sort((l,c)=>{const u=(l.isOff?-1:0)+(Ar.some(p=>l.name.toLowerCase().includes(p))?-1:0),h=(c.isOff?-1:0)+(Ar.some(p=>c.name.toLowerCase().includes(p))?-1:0);return u!==h?u-h:l.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),o},[e]),i=o=>{const l=Pc(o);n(l),a==null||a(l)};return r.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[r.jsxs("strong",{children:[e.channel,". ",e.name]}),r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(120px, 1fr))",gap:8,marginTop:8,maxHeight:220,overflowY:"auto"},children:s.map((o,l)=>{const c=t>=o.valueFrom&&t<=o.valueTo;return r.jsx("button",{type:"button",onClick:()=>i(o),style:{padding:"8px 10px",borderRadius:8,border:c?"2px solid var(--nice-primary-hover, #2563eb)":"1px solid var(--nice-border, #d1d5db)",background:c?"var(--nice-primary-bg, #eff6ff)":"var(--nice-bg, #fff)",textAlign:"left",cursor:"pointer",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:`${o.name} [${o.valueFrom}..${o.valueTo}]`,children:o.name},`${o.name}-${l}`)})})]})},ys=e=>{switch(e.channel.type){case Ft.Dimmer:case Ft.DimmerWithOff:return r.jsx(Gn,{...e});case Ft.RotationWithOff:case Ft.RotationWithOffAndCcw:return r.jsx(Gn,{...e,showDirectionHint:!0});case Ft.Options:return r.jsx(gs,{...e});default:return r.jsx(Gn,{...e})}},na=e=>Math.max(0,Math.min(255,Math.round(e))),U0=[{target:".ntd-dmx-editor",titleKey:"tutorial.dmxEditor.intro.title",title:"DMX editor",contentKey:"tutorial.dmxEditor.intro.content",content:"Pick the FTDI device and port, then set each DMX channel’s value with the sliders to control your lighting fixtures live.",placement:"auto"}];function Ac({service:e,pollInterval:t=500,className:n,style:a,channels:s,onChannelChange:i,fixtures:o,tutorial:l}){if(!e)return r.jsx("div",{className:n,style:a,children:r.jsx("small",{children:"Provide a `service` prop (DmxService) to control hardware."})});const[c,u]=d.useState([]),[h,p]=d.useState(null),[f,y]=d.useState(()=>Array(513).fill(0)),[m,g]=d.useState(30),[b,x]=d.useState(0),[k,v]=d.useState(!1),w=d.useRef(null);d.useEffect(()=>{let D=!1;return e.getDevices().then(L=>{D||(u(L),L.length>0&&p(L[0]))}).catch(()=>{}),()=>{D=!0}},[e]),d.useEffect(()=>{if(w.current&&window.clearInterval(w.current),!(t<=0))return w.current=window.setInterval(async()=>{try{const D=await e.getState();Array.isArray(D.frontSnapshot)&&D.frontSnapshot.length>=513&&y(D.frontSnapshot.slice(0,513)),typeof D.fps=="number"&&g(D.fps),typeof D.startCode=="number"&&x(D.startCode)}catch{}},t),()=>{w.current&&window.clearInterval(w.current)}},[e,t]);const M=async()=>{h&&(await e.openPort(h.serialNumber||h.description),v(!0))},S=async()=>{await e.closePort(),v(!1)},R=async()=>{await e.blackout(),y(D=>{const L=[...D];for(let W=1;W<L.length;W++)L[W]=0;return L})},T=()=>e.configure(m,b),j=(D,L)=>{const W=na(L);y(Z=>{const A=[...Z];return A[D]=W,A})},O=(D,L)=>e.setChannel(D,na(L)),$=(h==null?void 0:h.deviceInfo)??null,E=d.useMemo(()=>{var D;return(D=$==null?void 0:$.channels)!=null&&D.length?$.channels:Array.from({length:16},(L,W)=>({channel:W+1,name:`Channel ${W+1}`,type:Ft.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[$]);return r.jsxs("div",{className:`ntd-dmx-editor ${n??""}`,style:{position:"relative",padding:16,display:"grid",gap:16,...a},children:[r.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:r.jsx(aa.NiceTutorialButton,{steps:aa.resolveTutorial(l,U0)})}),r.jsxs("section",{style:{display:"grid",gap:12,gridTemplateColumns:"1fr auto auto auto",alignItems:"end"},children:[r.jsxs("div",{children:[r.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FTDI Device"}),r.jsx("select",{value:(h==null?void 0:h.serialNumber)||"",onChange:D=>p(c.find(L=>L.serialNumber===D.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"},children:c.map(D=>{var L,W;return r.jsxs("option",{value:D.serialNumber,children:[((L=D.deviceInfo)==null?void 0:L.manufacturer)??""," ",((W=D.deviceInfo)==null?void 0:W.model)??D.description," (",D.serialNumber||D.description,")"]},D.serialNumber||D.description)})}),$&&r.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:["Mode: ",r.jsx("b",{children:$.modeName}),", footprint: ",r.jsx("b",{children:$.footprint})]})]}),r.jsx("button",{onClick:M,disabled:!h||k,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-success, #10b981)",background:"var(--nice-success-bg, #ecfdf5)",cursor:"pointer"},children:"Open port"}),r.jsx("button",{onClick:S,disabled:!k,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-danger, #ef4444)",background:"var(--nice-danger-bg, #fef2f2)",cursor:"pointer"},children:"Close port"}),r.jsx("button",{onClick:R,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-text-secondary, #4b5563)",background:"var(--nice-bg-secondary, #f3f4f6)",cursor:"pointer"},children:"Blackout"})]}),r.jsxs("section",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(160px, 100%), 1fr))",gap:12,alignItems:"end"},children:[r.jsxs("div",{children:[r.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FPS"}),r.jsx("input",{type:"number",min:10,max:44,value:m,onChange:D=>g(Number(D.target.value)),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),r.jsxs("div",{children:[r.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"Start Code"}),r.jsx("input",{type:"number",min:0,max:255,value:b,onChange:D=>x(na(Number(D.target.value))),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),r.jsx("div",{children:r.jsx("button",{onClick:T,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-primary, #3b82f6)",background:"var(--nice-primary-bg, #eff6ff)",cursor:"pointer"},children:"Apply configuration"})})]}),r.jsxs("section",{children:[r.jsx("h3",{style:{margin:"8px 0 12px",fontSize:16},children:"Channels"}),r.jsx("div",{style:{display:"grid",gap:12,gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))"},children:E.map(D=>r.jsx(ys,{channel:D,value:f[D.channel]??0,onChange:L=>j(D.channel,L),onCommit:L=>O(D.channel,L)},D.channel))})]})]})}const Ec=[{id:"generic-dimmer-1ch",name:"Generic Dimmer",manufacturer:"Generic",type:"dimmer",channelCount:1,channels:[{name:"Dimmer",type:"dimmer",defaultValue:0}]},{id:"generic-rgb-3ch",name:"Generic RGB",manufacturer:"Generic",type:"rgb",channelCount:3,channels:[{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0}]},{id:"generic-rgbw-4ch",name:"Generic RGBW",manufacturer:"Generic",type:"rgbw",channelCount:4,channels:[{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0}]},{id:"generic-rgbw-dimmer-5ch",name:"Generic RGBW+D",manufacturer:"Generic",type:"rgbw",channelCount:5,channels:[{name:"Dimmer",type:"dimmer",defaultValue:255},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0}]},{id:"generic-par-7ch",name:"Generic PAR 7ch",manufacturer:"Generic",type:"par",channelCount:7,channels:[{name:"Dimmer",type:"dimmer",defaultValue:255},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0},{name:"Strobe",type:"strobe",defaultValue:0},{name:"Function",type:"function",defaultValue:0}]},{id:"generic-moving-head-16ch",name:"Generic Moving Head 16ch",manufacturer:"Generic",type:"moving_head",channelCount:16,channels:[{name:"Pan",type:"pan",defaultValue:128,min:0,max:255},{name:"Pan Fine",type:"pan",defaultValue:0},{name:"Tilt",type:"tilt",defaultValue:128,min:0,max:255},{name:"Tilt Fine",type:"tilt",defaultValue:0},{name:"Pan/Tilt Speed",type:"speed",defaultValue:0},{name:"Dimmer",type:"dimmer",defaultValue:0},{name:"Strobe",type:"strobe",defaultValue:0},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0},{name:"Color Wheel",type:"function",defaultValue:0},{name:"Gobo",type:"gobo",defaultValue:0},{name:"Gobo Rotation",type:"speed",defaultValue:128},{name:"Prism",type:"function",defaultValue:0},{name:"Function",type:"function",defaultValue:0}]},{id:"generic-strobe-2ch",name:"Generic Strobe",manufacturer:"Generic",type:"strobe",channelCount:2,channels:[{name:"Dimmer",type:"dimmer",defaultValue:0},{name:"Strobe Speed",type:"strobe",defaultValue:0}]},{id:"generic-fog-2ch",name:"Generic Fog Machine",manufacturer:"Generic",type:"fog",channelCount:2,channels:[{name:"Output",type:"dimmer",defaultValue:0},{name:"Fan",type:"speed",defaultValue:128}]}];class Ic{constructor(){this.universes=new Map,this.fixtures=new Map,this.profiles=new Map,this.outputCallback=null,this.running=!1,this.frameRate=44,this.intervalId=null,Ec.forEach(t=>this.profiles.set(t.id,t)),this.createUniverse(1,"Universe 1")}createUniverse(t,n){const a={id:String(t),name:n,channels:new Uint8Array(512)};return this.universes.set(t,a),a}getUniverse(t){return this.universes.get(t)}addFixture(t){this.fixtures.set(t.id,t)}removeFixture(t){this.fixtures.delete(t)}getFixture(t){return this.fixtures.get(t)}getAllFixtures(){return Array.from(this.fixtures.values())}getProfile(t){return this.profiles.get(t)}registerProfile(t){this.profiles.set(t.id,t)}setChannel(t,n,a){const s=this.universes.get(t);s&&n>=1&&n<=512&&(s.channels[n-1]=Math.max(0,Math.min(255,a)))}getChannel(t,n){const a=this.universes.get(t);return a&&n>=1&&n<=512?a.channels[n-1]:0}setFixtureValues(t,n){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);if(s)for(let i=0;i<Math.min(n.length,s.channelCount);i++)a.values[i]=n[i],this.setChannel(a.universe,a.startChannel+i,n[i])}setFixtureColor(t,n,a,s,i=0){const o=this.fixtures.get(t);if(!o)return;const l=this.profiles.get(o.profileId);if(!l)return;const c=[...o.values];l.channels.forEach((u,h)=>{u.name.toLowerCase().includes("red")?c[h]=n:u.name.toLowerCase().includes("green")?c[h]=a:u.name.toLowerCase().includes("blue")?c[h]=s:u.name.toLowerCase().includes("white")&&(c[h]=i)}),this.setFixtureValues(t,c)}setFixtureDimmer(t,n){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);s&&s.channels.forEach((i,o)=>{i.type==="dimmer"&&(a.values[o]=Math.max(0,Math.min(255,Math.round(n*255))),this.setChannel(a.universe,a.startChannel+o,a.values[o]))})}fadeFixture(t,n,a,s="linear"){return new Promise(i=>{const o=this.fixtures.get(t);if(!o){i();return}const l=[...o.values],c=performance.now(),u=()=>{const h=performance.now()-c,p=Math.min(1,h/a);let f=p;switch(s){case"ease-in":f=p*p;break;case"ease-out":f=1-(1-p)*(1-p);break;case"ease-in-out":f=p<.5?2*p*p:1-Math.pow(-2*p+2,2)/2;break}const y=l.map((m,g)=>{const b=n[g]??m;return Math.round(m+(b-m)*f)});this.setFixtureValues(t,y),p<1?requestAnimationFrame(u):i()};u()})}setOutputCallback(t){this.outputCallback=t}start(){this.running||(this.running=!0,this.intervalId=window.setInterval(()=>{this.sendOutput()},1e3/this.frameRate))}stop(){this.running=!1,this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null)}sendOutput(){this.outputCallback&&this.universes.forEach((t,n)=>{this.outputCallback(n,t.channels)})}blackout(){this.universes.forEach(t=>{t.channels.fill(0)}),this.fixtures.forEach(t=>{t.values.fill(0)})}fullOn(){this.fixtures.forEach(t=>{this.setFixtureDimmer(t.id,1)})}}const q0=6454,V0=new Uint8Array([65,114,116,45,78,101,116,0]);function H0(e,t){const n=new Uint8Array(18+t.length);return n.set(V0,0),n[8]=0,n[9]=80,n[10]=0,n[11]=14,n[12]=0,n[13]=0,n[14]=e&255,n[15]=e>>8&255,n[16]=t.length>>8&255,n[17]=t.length&255,n.set(t.slice(0,512),18),n}const K0=5568;function Y0(e,t,n,a=100,s="Nice2Dev DMX"){const i=Math.min(t.length,512),o=126+i,l=new Uint8Array(o),c=new DataView(l.buffer);c.setUint16(0,16,!1),c.setUint16(2,0,!1);const u=[65,83,67,45,69,49,46,49,55,0,0,0];for(let m=0;m<u.length;m++)l[4+m]=u[m];const h=o-16;c.setUint16(16,28672|h&4095,!1),c.setUint32(18,4,!1);for(let m=0;m<16;m++)l[22+m]=m+1;const p=o-38;c.setUint16(38,28672|p&4095,!1),c.setUint32(40,2,!1);const f=new TextEncoder().encode(s.slice(0,63));l.set(f,44),l[108]=a,c.setUint16(109,0,!1),l[111]=n&255,l[112]=0,c.setUint16(113,e,!1);const y=i+11;return c.setUint16(115,28672|y&4095,!1),l[117]=2,l[118]=161,c.setUint16(119,0,!1),c.setUint16(121,1,!1),c.setUint16(123,i+1,!1),l[125]=0,l.set(t.slice(0,i),126),l}function Z0(e){const t=e>>8&255,n=e&255;return`239.255.${t}.${n}`}class X0{constructor(t,n){this.config=t,this.scenes=n,this.currentStep=0,this.direction=1,this.isRunning=!1,this.timer=null,this.fadeStartTime=0,this.fadeFromValues=new Uint8Array(512),this.fadeToValues=new Uint8Array(512),this.onOutput=null}setOutputCallback(t){this.onOutput=t}start(){this.isRunning||(this.isRunning=!0,this.currentStep=this.config.direction==="backward"?this.config.steps.length-1:0,this.direction=this.config.direction==="backward"?-1:1,this.executeStep())}stop(){this.isRunning=!1,this.timer&&(clearTimeout(this.timer),this.timer=null)}executeStep(){var o;if(!this.isRunning)return;const t=this.config.steps[this.currentStep];if(!t)return;const n=this.scenes.get(t.sceneId);if(!n){this.advanceStep();return}const a=new Uint8Array(512);if(n.channels)for(const l of n.channels)l.channel>=1&&l.channel<=512&&(a[l.channel-1]=l.value);this.fadeFromValues.set(this.fadeToValues),this.fadeToValues.set(a),this.fadeStartTime=performance.now();const s=t.fadeTime/this.config.speed,i=t.holdTime/this.config.speed;s>0?this.runFade(s,()=>{var l;(l=this.onOutput)==null||l.call(this,this.fadeToValues),this.timer=setTimeout(()=>this.advanceStep(),i)}):((o=this.onOutput)==null||o.call(this,a),this.timer=setTimeout(()=>this.advanceStep(),i))}runFade(t,n){const a=performance.now(),s=new Uint8Array(512),i=()=>{var c;if(!this.isRunning)return;const o=performance.now()-a,l=Math.min(o/t,1);for(let u=0;u<512;u++)s[u]=Math.round(this.fadeFromValues[u]+(this.fadeToValues[u]-this.fadeFromValues[u])*l);(c=this.onOutput)==null||c.call(this,s),l<1?requestAnimationFrame(i):n()};requestAnimationFrame(i)}advanceStep(){if(!this.isRunning)return;const{steps:t,loop:n,direction:a}=this.config;if(this.currentStep+=this.direction,a==="bounce"){if(this.currentStep>=t.length?(this.direction=-1,this.currentStep=t.length-2):this.currentStep<0&&(this.direction=1,this.currentStep=1),this.currentStep<0||this.currentStep>=t.length){if(!n){this.stop();return}this.currentStep=0,this.direction=1}}else if(this.currentStep>=t.length||this.currentStep<0){if(!n){this.stop();return}this.currentStep=a==="backward"?t.length-1:0}this.executeStep()}}const Q0=({engine:e,tracks:t=[],scenes:n=[],duration:a=3e5,currentTime:s=0,bpm:i=120,onTimeChange:o,onCueAdd:l,onCueUpdate:c,onCueDelete:u,onTrackAdd:h,onTrackUpdate:p,onPlay:f,onPause:y,onStop:m,className:g=""})=>{const[b,x]=d.useState(1),[k,v]=d.useState(0),[w,M]=d.useState(!1),[S,R]=d.useState(null),[T,j]=d.useState(null),[O,$]=d.useState(!0),[E,D]=d.useState(1e3),L=d.useRef(null),W=d.useRef(null),Z=d.useRef(0),A=d.useMemo(()=>.1*b,[b]),_=d.useCallback(N=>N*A,[A]),U=d.useCallback(N=>N/A,[A]),ne=d.useCallback(N=>{if(!O)return N;const z=6e4/i;return Math.round(N/z)*z},[O,i]);d.useEffect(()=>{if(w){const N=performance.now(),z=s,B=()=>{const G=performance.now()-N,Y=z+G;if(Y>=a){M(!1),o==null||o(0),m==null||m();return}V(Y),o==null||o(Y),W.current=requestAnimationFrame(B)};W.current=requestAnimationFrame(B),f==null||f()}else W.current!==null&&(cancelAnimationFrame(W.current),W.current=null),y==null||y();return()=>{W.current!==null&&cancelAnimationFrame(W.current)}},[w,s,a,o,f,y,m]);const V=d.useCallback(N=>{t.forEach(z=>{z.muted||z.cues.forEach(B=>{const G=B.startTime,Y=G+B.duration;if(N>=G&&N<Y&&Z.current<G){const X=n.find(ie=>ie.id===B.sceneId);X&&X.fixtures.forEach(ie=>{B.fadeIn&&B.fadeIn>0?e.fadeFixture(ie.fixtureId,ie.values,B.fadeIn):e.setFixtureValues(ie.fixtureId,ie.values)})}if(Z.current<Y&&N>=Y){const X=n.find(ie=>ie.id===B.sceneId);X&&X.fixtures.forEach(ie=>{if(e.getFixture(ie.fixtureId)&&B.fadeOut&&B.fadeOut>0){const te=new Array(ie.values.length).fill(0);e.fadeFixture(ie.fixtureId,te,B.fadeOut)}})}})}),Z.current=N},[t,n,e]),q=N=>{const z=Math.floor(N/1e3),B=Math.floor(z/60),G=z%60,Y=Math.floor(N%1e3/(1e3/30));return`${B}:${G.toString().padStart(2,"0")}:${Y.toString().padStart(2,"0")}`},C=d.useCallback(N=>{if(!L.current)return;const z=L.current.getBoundingClientRect(),B=N.clientX-z.left+k,G=ne(U(B));o==null||o(Math.max(0,Math.min(a,G)))},[k,U,ne,a,o]),F=d.useCallback((N,z,B)=>{const G=t.find(ie=>ie.id===z),Y=G==null?void 0:G.cues.find(ie=>ie.id===N);if(!Y)return;const X=ne(Math.max(0,Y.startTime+U(B)));c==null||c({...Y,startTime:X})},[t,U,ne,c]),I=()=>{const N=6e4/i,z=Math.ceil(a/N),B=[];for(let G=0;G<=z;G++){const Y=G*N,X=_(Y),ie=G%4===0;B.push(r.jsx("div",{className:`nice-dmx-timeline__beat ${ie?"nice-dmx-timeline__beat--measure":""}`,style:{left:X},children:ie&&r.jsx("span",{className:"nice-dmx-timeline__beat-label",children:G/4+1})},G))}return B},P=(N,z)=>{const B=_(N.startTime),G=_(N.duration),Y=n.find(X=>X.id===N.sceneId);return r.jsxs("div",{className:`nice-dmx-timeline__cue ${S===N.id?"nice-dmx-timeline__cue--selected":""}`,style:{left:B,width:G,backgroundColor:(Y==null?void 0:Y.color)||z.color||"var(--nice-accent, #8b5cf6)"},onClick:X=>{X.stopPropagation(),R(N.id)},draggable:!z.locked,onDragEnd:X=>{var le;const ie=(le=X.target.parentElement)==null?void 0:le.getBoundingClientRect();ie&&F(N.id,z.id,X.clientX-ie.left-B)},children:[r.jsx("span",{className:"nice-dmx-timeline__cue-name",children:N.name||(Y==null?void 0:Y.name)}),N.fadeIn&&N.fadeIn>0&&r.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--in",style:{width:_(N.fadeIn)}}),N.fadeOut&&N.fadeOut>0&&r.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--out",style:{width:_(N.fadeOut)}})]},N.id)};return r.jsxs("div",{className:`nice-dmx-timeline ${g}`,children:[r.jsxs("div",{className:"nice-dmx-timeline__toolbar",children:[r.jsxs("div",{className:"nice-dmx-timeline__transport",children:[r.jsx("button",{type:"button",onClick:()=>o==null?void 0:o(0),title:"Go to start","aria-label":"Go to start",children:r.jsx(se.NtdSkipBack,{size:14})}),r.jsx("button",{type:"button",onClick:()=>M(!w),title:w?"Pause":"Play","aria-label":w?"Pause":"Play",children:w?r.jsx(se.NtdPause,{size:14}):r.jsx(se.NtdPlay,{size:14})}),r.jsx("button",{type:"button",onClick:()=>{M(!1),o==null||o(0),e.blackout(),m==null||m()},title:"Stop","aria-label":"Stop",children:r.jsx(se.NtdStop,{size:14})})]}),r.jsx("div",{className:"nice-dmx-timeline__time",children:q(s)}),r.jsxs("div",{className:"nice-dmx-timeline__tools",children:[r.jsx("button",{type:"button",className:O?"active":"",onClick:()=>$(!O),title:"Snap to grid","aria-label":"Snap to grid",children:r.jsx(se.NtdGrid,{size:14})}),r.jsx("button",{type:"button",onClick:()=>x(Math.max(.25,b-.25)),title:"Zoom out",children:"−"}),r.jsxs("span",{className:"nice-dmx-timeline__zoom",children:[Math.round(b*100),"%"]}),r.jsx("button",{type:"button",onClick:()=>x(Math.min(4,b+.25)),title:"Zoom in",children:"+"})]}),r.jsxs("div",{className:"nice-dmx-timeline__bpm",children:[r.jsx("label",{children:"BPM:"}),r.jsx("span",{children:i})]}),r.jsx("button",{type:"button",className:"nice-dmx-timeline__blackout",onClick:()=>e.blackout(),title:"Blackout","aria-label":"Blackout",children:r.jsx(se.NtdMoon,{size:14})})]}),r.jsxs("div",{className:"nice-dmx-timeline__content",children:[r.jsxs("div",{className:"nice-dmx-timeline__headers",children:[t.map(N=>r.jsxs("div",{className:`nice-dmx-timeline__header ${T===N.id?"nice-dmx-timeline__header--selected":""}`,onClick:()=>j(N.id),children:[r.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:N.color||"var(--nice-accent, #8b5cf6)"}}),r.jsx("span",{className:"nice-dmx-timeline__track-name",children:N.name}),r.jsxs("div",{className:"nice-dmx-timeline__track-controls",children:[r.jsx("button",{type:"button",className:N.muted?"active":"",onClick:z=>{z.stopPropagation(),p==null||p({...N,muted:!N.muted})},title:"Mute",children:"M"}),r.jsx("button",{type:"button",className:N.locked?"active":"",onClick:z=>{z.stopPropagation(),p==null||p({...N,locked:!N.locked})},title:"Lock","aria-label":"Lock",children:r.jsx(se.NtdLock,{size:14})})]})]},N.id)),r.jsx("button",{type:"button",className:"nice-dmx-timeline__add-track",onClick:()=>{h==null||h({id:`track-${Date.now()}`,name:`Track ${t.length+1}`,fixtureIds:[],cues:[]})},children:"+ Add Track"})]}),r.jsxs("div",{className:"nice-dmx-timeline__tracks",ref:L,onClick:C,onScroll:N=>v(N.currentTarget.scrollLeft),children:[r.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:_(a)},children:I()}),t.map(N=>r.jsx("div",{className:`nice-dmx-timeline__track ${N.muted?"nice-dmx-timeline__track--muted":""}`,style:{width:_(a)},children:N.cues.map(z=>P(z,N))},N.id)),r.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:_(s)}})]})]})]})};function J0(){const[e]=d.useState(()=>new Ic);return d.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function eg(e,t,n=120){const[a,s]=d.useState(0),i=d.useRef(0);return d.useEffect(()=>{if(!t)return;const o=60/n,l=()=>{const c=t.currentTime,u=Math.floor(c/o);u!==i.current&&(i.current=u,s(u))};return t.addEventListener("timeupdate",l),()=>t.removeEventListener("timeupdate",l)},[t,n]),{currentBeat:a}}const tg=[{name:"Flat",bands:[{frequency:60,gain:0},{frequency:250,gain:0},{frequency:1e3,gain:0},{frequency:4e3,gain:0},{frequency:16e3,gain:0}]},{name:"Bass Boost",bands:[{frequency:60,gain:8},{frequency:250,gain:4},{frequency:1e3,gain:0},{frequency:4e3,gain:-2},{frequency:16e3,gain:-4}]},{name:"Treble Boost",bands:[{frequency:60,gain:-4},{frequency:250,gain:-2},{frequency:1e3,gain:0},{frequency:4e3,gain:4},{frequency:16e3,gain:8}]},{name:"Voice",bands:[{frequency:60,gain:-6},{frequency:250,gain:2},{frequency:1e3,gain:6},{frequency:4e3,gain:4},{frequency:16e3,gain:-2}]},{name:"Rock",bands:[{frequency:60,gain:4},{frequency:250,gain:2},{frequency:1e3,gain:-2},{frequency:4e3,gain:4},{frequency:16e3,gain:6}]}];function Lc(){const[e,t]=d.useState(!1),[n,a]=d.useState(.8),[s,i]=d.useState(!1),[o,l]=d.useState(null),[c,u]=d.useState(null),[h,p]=d.useState(null),f=d.useRef(null),y=d.useRef(null),m=d.useRef(null),g=d.useRef(null),b=d.useRef([]),x=d.useRef(null),k=d.useRef(null),v=d.useCallback(()=>{if(y.current)return;const L=new AudioContext;y.current=L;const W=L.createGain();W.gain.value=n,g.current=W;const Z=L.createAnalyser();Z.fftSize=256,x.current=Z,W.connect(Z).connect(L.destination)},[]),w=d.useCallback(()=>{const L=f.current,W=y.current,Z=g.current;if(!L||!W||!Z||m.current)return;const A=W.createMediaElementSource(L);m.current=A,b.current.length>0?(A.connect(b.current[0]),b.current[b.current.length-1].connect(Z)):A.connect(Z)},[]),M=d.useCallback(()=>{var W;const L=f.current;!L||!k.current||(Bt(),v(),w(),((W=y.current)==null?void 0:W.state)==="suspended"&&y.current.resume(),L.play().catch(Z=>u(String(Z))))},[v,w]),S=d.useCallback(()=>{var L;(L=f.current)==null||L.pause()},[]),R=d.useCallback(()=>{e?S():M()},[e,M,S]),T=d.useCallback(L=>{const W=Math.max(0,Math.min(1,L));a(W),g.current&&(g.current.gain.value=W),f.current&&(f.current.volume=W)},[]),j=d.useCallback(L=>{k.current=L,u(null),l(null),i(!0),m.current&&(m.current.disconnect(),m.current=null),f.current||(f.current=new Audio,f.current.crossOrigin="anonymous",f.current.addEventListener("playing",()=>{t(!0),i(!1)}),f.current.addEventListener("pause",()=>t(!1)),f.current.addEventListener("waiting",()=>i(!0)),f.current.addEventListener("canplay",()=>i(!1)),f.current.addEventListener("error",()=>u("Failed to load stream"))),f.current.src=L.streamUrl,f.current.load(),l({genre:L.genre,bitrate:L.bitrate})},[]),O=d.useCallback(L=>{y.current||v();const Z=y.current;b.current.forEach(_=>_.disconnect());const A=L.bands.map(_=>{const U=Z.createBiquadFilter();return U.type="peaking",U.frequency.value=_.frequency,U.gain.value=_.gain,U.Q.value=_.Q??1.4,U});for(let _=0;_<A.length-1;_++)A[_].connect(A[_+1]);b.current=A,m.current&&g.current&&(m.current.disconnect(),m.current.connect(A[0]),A[A.length-1].connect(g.current)),p(L.name)},[v]),$=d.useCallback(()=>{b.current.forEach(L=>L.disconnect()),b.current=[],m.current&&g.current&&(m.current.disconnect(),m.current.connect(g.current)),p(null)},[]);return d.useEffect(()=>()=>{var L,W,Z;(L=f.current)==null||L.pause(),f.current=null,b.current.forEach(A=>A.disconnect()),(W=m.current)==null||W.disconnect(),(Z=y.current)==null||Z.close()},[]),[{isPlaying:e,volume:n,isBuffering:s,metadata:o,error:c,activePreset:h},{play:M,pause:S,toggle:R,setVolume:T,setStation:j,applyEQPreset:O,clearEQ:$}]}function Dc({stations:e,activeStationId:t,onSelect:n,onToggleFavorite:a,className:s}){const{t:i}=Te(),[o,l]=d.useState(""),[c,u]=d.useState(null),[h,p]=d.useState(!1),f=d.useMemo(()=>[...new Set(e.map(m=>m.genre).filter(Boolean))],[e]),y=d.useMemo(()=>e.filter(m=>{var g,b;if(h&&!m.isFavorite||c&&m.genre!==c)return!1;if(o){const x=o.toLowerCase();return m.name.toLowerCase().includes(x)||(((g=m.genre)==null?void 0:g.toLowerCase().includes(x))??!1)||(((b=m.country)==null?void 0:b.toLowerCase().includes(x))??!1)}return!0}),[e,o,c,h]);return r.jsxs("div",{className:`nice-station-browser${s?` ${s}`:""}`,children:[r.jsxs("div",{className:"nice-station-browser__toolbar",children:[r.jsx("input",{type:"text",className:"nice-station-browser__search",placeholder:(i==null?void 0:i("search_stations"))??"Search stations...",value:o,onChange:m=>l(m.target.value)}),r.jsxs("select",{className:"nice-station-browser__genre-filter",value:c??"",onChange:m=>u(m.target.value||null),children:[r.jsx("option",{value:"",children:(i==null?void 0:i("all_genres"))??"All Genres"}),f.map(m=>r.jsx("option",{value:m,children:m},m))]}),r.jsx("button",{className:`nice-station-browser__fav-toggle${h?" nice-station-browser__fav-toggle--active":""}`,onClick:()=>p(!h),title:(i==null?void 0:i("favorites"))??"Favorites","aria-label":(i==null?void 0:i("favorites"))??"Favorites",children:r.jsx(se.NtdStar,{size:14,style:{color:"var(--nice-warning, #facc15)"}})})]}),r.jsxs("div",{className:"nice-station-browser__list",children:[y.map(m=>r.jsxs("div",{className:`nice-station-browser__item${m.id===t?" nice-station-browser__item--active":""}`,onClick:()=>n(m),role:"button",tabIndex:0,onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&n(m)},children:[m.logoUrl&&r.jsx("img",{className:"nice-station-browser__logo",src:m.logoUrl,alt:m.name,loading:"lazy"}),r.jsxs("div",{className:"nice-station-browser__info",children:[r.jsx("span",{className:"nice-station-browser__name",children:m.name}),m.genre&&r.jsx("span",{className:"nice-station-browser__genre",children:m.genre}),m.country&&r.jsx("span",{className:"nice-station-browser__country",children:m.country})]}),m.bitrate&&r.jsxs("span",{className:"nice-station-browser__bitrate",children:[m.bitrate,"kbps"]}),a&&r.jsx("button",{className:`nice-station-browser__fav${m.isFavorite?" nice-station-browser__fav--active":""}`,onClick:g=>{g.stopPropagation(),a(m.id)},"aria-label":(i==null?void 0:i("favorites"))??"Favorites",children:r.jsx(se.NtdStar,{size:14,style:{color:m.isFavorite?"var(--nice-warning, #facc15)":"var(--text-muted)"}})})]},m.id)),y.length===0&&r.jsx("div",{className:"nice-station-browser__empty",children:(i==null?void 0:i("no_stations_found"))??"No stations found"})]})]})}function ng({stations:e,initialStationId:t,autoPlay:n=!1,eqPresets:a=tg,onStationChange:s,onPlayingChange:i,onMetadata:o,onToggleFavorite:l,onRecordingStart:c,onRecordingStop:u,showBrowser:h=!0,showEqualizer:p=!1,showVisualizer:f=!1,showMetadataHistory:y=!1,showRecording:m=!1,showSleepTimer:g=!1,className:b,style:x}){var P,N;const{t:k}=Te(),[v,w]=Lc(),[M,S]=d.useState(()=>t?e.find(z=>z.id===t)??null:null),[R,T]=d.useState(p),j=d.useRef(null),O=d.useRef(0),[$,E]=d.useState([]),[D,L]=d.useState(!1),W=d.useRef(null),Z=d.useRef([]),[A,_]=d.useState(0),U=d.useRef(null),[ne,V]=d.useState(0),[q,C]=d.useState(null),F=d.useRef(null);d.useEffect(()=>{i==null||i(v.isPlaying)},[v.isPlaying,i]),d.useEffect(()=>{v.metadata&&(o==null||o(v.metadata),(v.metadata.title||v.metadata.artist)&&E(z=>[{time:new Date,meta:v.metadata},...z.slice(0,49)]))},[v.metadata,o]);const I=d.useCallback(z=>{S(z),w.setStation(z),s==null||s(z),n&&setTimeout(()=>w.play(),100)},[w,s,n]);return d.useEffect(()=>{if(t&&!M){const z=e.find(B=>B.id===t);z&&I(z)}},[t,e]),d.useEffect(()=>{if(!f||!j.current)return;const z=j.current,B=z.getContext("2d");if(!B)return;const G=()=>{O.current=requestAnimationFrame(G),B.clearRect(0,0,z.width,z.height);const Y=B.createLinearGradient(0,z.height,0,0);if(Y.addColorStop(0,"var(--nice-accent-tint-80, rgba(99, 102, 241, 0.8))"),Y.addColorStop(.5,"rgba(168,85,247,0.6)"),Y.addColorStop(1,"rgba(236,72,153,0.4)"),!v.isPlaying){const te=z.width/32;for(let H=0;H<32;H++){const K=4+Math.sin(Date.now()/1e3+H*.3)*3;B.fillStyle=Y,B.fillRect(H*te+1,z.height-K,te-2,K)}return}const X=32,ie=z.width/X;for(let le=0;le<X;le++){const te=le/X,K=(Math.sin(Date.now()/200+le*.5)*.3+.5)*z.height*(1-te*.5)*(.5+Math.random()*.5);B.fillStyle=Y,B.fillRect(le*ie+1,z.height-K,ie-2,K)}};return G(),()=>cancelAnimationFrame(O.current)},[f,v.isPlaying]),d.useCallback(()=>{if(v.isPlaying)try{const B=new AudioContext().createMediaStreamDestination();Z.current=[];const G=new MediaRecorder(B.stream,{mimeType:"audio/webm"});G.ondataavailable=Y=>{Y.data.size>0&&Z.current.push(Y.data)},G.onstop=()=>{const Y=new Blob(Z.current,{type:"audio/webm"});u==null||u(Y),_(0),U.current&&window.clearInterval(U.current)},G.start(1e3),W.current=G,L(!0),_(0),U.current=window.setInterval(()=>{_(Y=>Y+1)},1e3),c==null||c()}catch{}},[v.isPlaying,c,u]),d.useCallback(()=>{W.current&&D&&(W.current.stop(),L(!1),U.current&&window.clearInterval(U.current))},[D]),d.useCallback(z=>{F.current&&window.clearInterval(F.current),V(z),C(z*60),F.current=window.setInterval(()=>{C(B=>!B||B<=1?(F.current&&window.clearInterval(F.current),F.current=null,w.pause(),null):B-1)},1e3)},[w]),d.useCallback(()=>{F.current&&window.clearInterval(F.current),F.current=null,C(null),V(0)},[]),d.useEffect(()=>()=>{U.current&&window.clearInterval(U.current),F.current&&window.clearInterval(F.current),cancelAnimationFrame(O.current)},[]),r.jsxs("div",{className:`nice-radio-player${b?` ${b}`:""}`,style:x,children:[r.jsx("div",{className:"nice-radio-player__now-playing",children:M?r.jsxs(r.Fragment,{children:[M.logoUrl&&r.jsx("img",{className:"nice-radio-player__cover",src:M.logoUrl,alt:M.name}),r.jsxs("div",{className:"nice-radio-player__info",children:[r.jsx("span",{className:"nice-radio-player__station-name",children:M.name}),((P=v.metadata)==null?void 0:P.title)&&r.jsx("span",{className:"nice-radio-player__track",children:v.metadata.artist?`${v.metadata.artist} — ${v.metadata.title}`:v.metadata.title}),((N=v.metadata)==null?void 0:N.genre)&&r.jsx("span",{className:"nice-radio-player__genre",children:v.metadata.genre}),v.isBuffering&&r.jsx("span",{className:"nice-radio-player__buffering",children:(k==null?void 0:k("buffering"))??"Buffering..."})]})]}):r.jsx("div",{className:"nice-radio-player__placeholder",children:(k==null?void 0:k("select_station"))??"Select a station"})}),r.jsxs("div",{className:"nice-radio-player__controls",children:[r.jsx("button",{className:"nice-radio-player__play-btn",onClick:w.toggle,disabled:!M,"aria-label":v.isPlaying?"Pause":"Play",children:v.isPlaying?r.jsx(se.NtdPause,{size:16}):r.jsx(se.NtdPlay,{size:16})}),r.jsxs("div",{className:"nice-radio-player__volume",children:[r.jsx("span",{className:"nice-radio-player__volume-icon","aria-hidden":"true",children:r.jsx(se.NtdVolume,{size:16})}),r.jsx("input",{type:"range",min:0,max:1,step:.01,value:v.volume,onChange:z=>w.setVolume(parseFloat(z.target.value)),className:"nice-radio-player__volume-slider","aria-label":"Volume"})]}),r.jsx("button",{className:`nice-radio-player__eq-btn${R?" nice-radio-player__eq-btn--active":""}`,onClick:()=>T(!R),title:"Equalizer",children:"EQ"})]}),v.error&&r.jsx("div",{className:"nice-radio-player__error",children:v.error}),R&&r.jsx("div",{className:"nice-radio-player__equalizer",children:r.jsxs("div",{className:"nice-radio-player__eq-presets",children:[a.map(z=>r.jsx("button",{className:`nice-radio-player__eq-preset${v.activePreset===z.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>w.applyEQPreset(z),children:z.name},z.name)),v.activePreset&&r.jsx("button",{className:"nice-radio-player__eq-preset",onClick:w.clearEQ,children:(k==null?void 0:k("clear"))??"Clear"})]})}),h&&r.jsx(Dc,{stations:e,activeStationId:M==null?void 0:M.id,onSelect:I})]})}const rg=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],ag={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class _c{constructor(t,n={}){this.localStream=null,this.peers=new Map,this.onRemoteStream=null,this.onPeerStateChange=null,this.onSignalingMessage=null,this.localUserId=t,this.config={iceServers:n.iceServers??rg,audioConstraints:{...ag,echoCancellation:n.echoCancellation??!0,noiseSuppression:n.noiseSuppression??!0,autoGainControl:n.autoGainControl??!0}}}async initialize(){return this.localStream?this.localStream:(this.localStream=await navigator.mediaDevices.getUserMedia({audio:this.config.audioConstraints,video:!1}),this.localStream)}getLocalStream(){return this.localStream}getPeerIds(){return Array.from(this.peers.keys())}getPeerState(t){var n;return((n=this.peers.get(t))==null?void 0:n.state)??null}async createOffer(t){if(!this.localStream)throw new Error("WebRTCAudioManager not initialized. Call initialize() first.");const n=this.createPeerConnection(t),a=await n.createOffer();await n.setLocalDescription(a),this.sendSignalingMessage({type:"offer",from:this.localUserId,to:t,payload:a})}async handleSignalingMessage(t){if(t.to===this.localUserId)switch(t.type){case"offer":await this.handleOffer(t.from,t.payload);break;case"answer":await this.handleAnswer(t.from,t.payload);break;case"ice-candidate":await this.handleIceCandidate(t.from,t.payload);break;case"leave":this.removePeer(t.from);break}}removePeer(t){const n=this.peers.get(t);n&&(n.pc.close(),this.peers.delete(t))}disconnect(){for(const t of this.peers.keys())this.sendSignalingMessage({type:"leave",from:this.localUserId,to:t,payload:null});for(const t of this.peers.values())t.pc.close();this.peers.clear(),this.localStream&&(this.localStream.getTracks().forEach(t=>t.stop()),this.localStream=null)}setMuted(t){this.localStream&&this.localStream.getAudioTracks().forEach(n=>{n.enabled=!t})}isMuted(){if(!this.localStream)return!0;const t=this.localStream.getAudioTracks()[0];return t?!t.enabled:!0}createPeerConnection(t){const n=new RTCPeerConnection({iceServers:this.config.iceServers}),a={id:t,pc:n,remoteStream:null,state:n.connectionState};return this.peers.set(t,a),this.localStream&&this.localStream.getTracks().forEach(s=>{n.addTrack(s,this.localStream)}),n.onicecandidate=s=>{s.candidate&&this.sendSignalingMessage({type:"ice-candidate",from:this.localUserId,to:t,payload:s.candidate.toJSON()})},n.ontrack=s=>{var o;const[i]=s.streams;i&&(a.remoteStream=i,(o=this.onRemoteStream)==null||o.call(this,t,i))},n.onconnectionstatechange=()=>{var s;a.state=n.connectionState,(s=this.onPeerStateChange)==null||s.call(this,t,n.connectionState),(n.connectionState==="failed"||n.connectionState==="disconnected")&&this.removePeer(t)},n}async handleOffer(t,n){this.localStream||await this.initialize();const a=this.createPeerConnection(t);await a.setRemoteDescription(new RTCSessionDescription(n));const s=await a.createAnswer();await a.setLocalDescription(s),this.sendSignalingMessage({type:"answer",from:this.localUserId,to:t,payload:s})}async handleAnswer(t,n){const a=this.peers.get(t);a&&await a.pc.setRemoteDescription(new RTCSessionDescription(n))}async handleIceCandidate(t,n){const a=this.peers.get(t);a&&n&&await a.pc.addIceCandidate(new RTCIceCandidate(n))}sendSignalingMessage(t){var n;(n=this.onSignalingMessage)==null||n.call(this,t)}}function sg(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function ig(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function og(){return new AudioContext({sampleRate:48e3,latencyHint:"interactive"})}const bs=d.forwardRef(function(t,n){const{mode:a="bars",width:s=300,height:i=100,barCount:o=32,barColor:l="var(--nice-primary, #3b82f6)",backgroundColor:c="transparent",fftSize:u=256,smoothing:h=.8,minDecibels:p=-90,maxDecibels:f=-10,deviceId:y,autoStart:m=!1,onStart:g,onStop:b,onAudioLevel:x,onError:k,className:v,style:w,barBorderRadius:M=2,barGap:S=2,lineWidth:R=2}=t,T=d.useRef(null),j=d.useRef(null),O=d.useRef(null),$=d.useRef(null),E=d.useRef(0),D=d.useRef(null),L=d.useRef(0),[W,Z]=d.useState(!1),A=d.useCallback((I,P,N=!0)=>{const z=N?I.createLinearGradient(0,i,0,0):I.createLinearGradient(0,0,s,0);return P.forEach((B,G)=>{z.addColorStop(G/(P.length-1),B)}),z},[s,i]),_=d.useCallback((I,P)=>{const z=(s-(o-1)*S)/o,B=Math.floor(P.length/o),G=Array.isArray(l)?l:[l],Y=G.length>1?A(I,G):G[0];I.fillStyle=Y;for(let X=0;X<o;X++){const le=P[X*B]/255*i,te=X*(z+S),H=i-le;M>0?(I.beginPath(),I.roundRect(te,H,z,le,M),I.fill()):I.fillRect(te,H,z,le)}},[o,l,S,M,s,i,A]),U=d.useCallback((I,P)=>{const N=i/2,B=(s-(o-1)*S)/o,G=Math.floor(P.length/o),Y=Array.isArray(l)?l:[l],X=Y.length>1?A(I,Y):Y[0];I.fillStyle=X;for(let ie=0;ie<o;ie++){const te=P[ie*G]/255*N,H=ie*(B+S);M>0?(I.beginPath(),I.roundRect(H,N-te,B,te,M),I.fill(),I.beginPath(),I.roundRect(H,N,B,te,M),I.fill()):(I.fillRect(H,N-te,B,te),I.fillRect(H,N,B,te))}},[o,l,S,M,s,i,A]),ne=d.useCallback((I,P)=>{const N=Array.isArray(l)?l:[l];I.strokeStyle=N.length>1?A(I,N,!1):N[0],I.lineWidth=R,I.lineCap="round",I.lineJoin="round",I.beginPath();const z=s/P.length;let B=0;for(let G=0;G<P.length;G++){const X=P[G]/128*i/2;G===0?I.moveTo(B,X):I.lineTo(B,X),B+=z}I.stroke()},[l,R,s,i,A]),V=d.useCallback((I,P)=>{const N=s/2,z=i/2,B=Math.min(s,i)/3,G=Array.isArray(l)?l:[l];I.strokeStyle=G.length>1?A(I,G):G[0],I.lineWidth=R;const Y=Math.floor(P.length/64),X=Math.PI*2/64;I.beginPath();for(let ie=0;ie<64;ie++){const le=P[ie*Y]/255,te=B+le*B*.5,H=ie*X-Math.PI/2,K=N+Math.cos(H)*te,oe=z+Math.sin(H)*te;ie===0?I.moveTo(K,oe):I.lineTo(K,oe)}I.closePath(),I.stroke()},[l,R,s,i,A]),q=d.useCallback(()=>{const I=T.current,P=O.current,N=D.current;if(!I||!P||!N)return;const z=I.getContext("2d");if(!z)return;a==="waveform"?P.getByteTimeDomainData(N):P.getByteFrequencyData(N);let B=0;for(let G=0;G<N.length;G++)B+=N[G];switch(L.current=B/(N.length*255),x==null||x(L.current),z.clearRect(0,0,s,i),c!=="transparent"&&(z.fillStyle=c,z.fillRect(0,0,s,i)),a){case"bars":_(z,N);break;case"mirror-bars":U(z,N);break;case"waveform":ne(z,N);break;case"circle":V(z,N);break}E.current=requestAnimationFrame(q)},[a,s,i,c,_,U,ne,V,x]),C=d.useCallback(async()=>{try{if(W)return;const I=await navigator.mediaDevices.getUserMedia({audio:y?{deviceId:{exact:y}}:!0,video:!1});$.current=I;const P=new AudioContext;j.current=P;const N=P.createMediaStreamSource(I),z=P.createAnalyser();z.fftSize=u,z.smoothingTimeConstant=h,z.minDecibels=p,z.maxDecibels=f,N.connect(z),O.current=z,D.current=new Uint8Array(z.frequencyBinCount),Z(!0),g==null||g(),q()}catch(I){k==null||k(I instanceof Error?I:new Error(String(I)))}},[W,y,u,h,p,f,g,k,q]),F=d.useCallback(()=>{cancelAnimationFrame(E.current),$.current&&($.current.getTracks().forEach(P=>P.stop()),$.current=null),j.current&&(j.current.close(),j.current=null),O.current=null,D.current=null,L.current=0,Z(!1),b==null||b();const I=T.current;if(I){const P=I.getContext("2d");P&&(P.clearRect(0,0,s,i),c!=="transparent"&&(P.fillStyle=c,P.fillRect(0,0,s,i)))}},[s,i,c,b]);return d.useImperativeHandle(n,()=>({start:C,stop:F,isCapturing:()=>W,getAudioLevel:()=>L.current}),[C,F,W]),d.useEffect(()=>(m&&C(),()=>{F()}),[m]),r.jsx("canvas",{ref:T,width:s,height:i,className:v,style:{display:"block",...w},"aria-label":"Audio visualizer"})}),Ci=e=>{switch(e){case"top-left":return{top:16,left:16};case"top-right":return{top:16,right:16};case"bottom-left":return{bottom:16,left:16};case"bottom-right":default:return{bottom:16,right:16}}},lg={position:"fixed",display:"flex",flexDirection:"column",gap:8,padding:12,borderRadius:12,boxShadow:"0 4px 20px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:14,minWidth:200,maxWidth:280,transition:"all 0.2s ease"},cg={background:"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",text:"var(--nice-bg, #1a1a1a)",textSecondary:"var(--nice-text-secondary, #666)",border:"var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-bg, #fee2e2)",mutedIcon:"var(--nice-danger, #ef4444)",activeBg:"var(--nice-success-bg, #dcfce7)",activeIcon:"var(--nice-success, #22c55e)",hoverBg:"var(--nice-overlay-5, rgba(0, 0, 0, 0.05))"},dg={background:"var(--nice-overlay-90, rgba(30, 30, 30, 0.95))",text:"var(--nice-bg, #fff)",textSecondary:"var(--nice-text-muted, #a0a0a0)",border:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-dark, #7f1d1d)",mutedIcon:"var(--nice-danger-bg, #fca5a5)",activeBg:"var(--nice-success, #14532d)",activeIcon:"var(--nice-success-light, #86efac)",hoverBg:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))"},Fc=d.forwardRef(function(t,n){const{userId:a,userName:s,userAvatarUrl:i,participants:o=[],rtcConfig:l,position:c="bottom-right",expanded:u=!0,onSignalingMessage:h,onMuteToggle:p,onLeave:f,onSpeakingChange:y,speakingThreshold:m=.1,theme:g="auto",className:b,style:x,zIndex:k=1e3}=t,v=d.useRef(null),w=d.useRef(null),M=d.useRef(new Map);d.useRef(new Map);const[S,R]=d.useState(!1),[T,j]=d.useState(!1),[O,$]=d.useState(!1),[E,D]=d.useState(u),W=d.useMemo(()=>g==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":g,[g])==="dark"?dg:cg;d.useEffect(()=>{const q=new _c(a,l);return q.onRemoteStream=(C,F)=>{let I=M.current.get(C);I||(I=new Audio,I.autoplay=!0,M.current.set(C,I)),I.srcObject=F},q.onSignalingMessage=C=>{h==null||h(C)},q.onPeerStateChange=(C,F)=>{F==="connected"&&j(!0)},v.current=q,q.initialize().then(()=>{var C;(C=w.current)==null||C.start()}),()=>{q.disconnect();const C=M.current;C.forEach(F=>{F.srcObject=null}),C.clear()}},[a,l,h]);const Z=d.useCallback(()=>{var C;const q=!S;R(q),(C=v.current)==null||C.setMuted(q),p==null||p(q)},[S,p]),A=d.useCallback(()=>{var q,C;(q=v.current)==null||q.disconnect(),(C=w.current)==null||C.stop(),j(!1),f==null||f()},[f]),_=d.useCallback(q=>{const C=q>m;C!==O&&($(C),y==null||y(a,C))},[m,O,a,y]),U=d.useCallback(async q=>{var C;await((C=v.current)==null?void 0:C.createOffer(q))},[]),ne=d.useCallback(async q=>{var C;await((C=v.current)==null?void 0:C.handleSignalingMessage(q))},[]);d.useImperativeHandle(n,()=>({connectToPeer:U,handleSignalingMessage:ne,toggleMute:Z,isMuted:()=>S,leave:A,getManager:()=>v.current}),[U,ne,Z,S,A]);const V=({participant:q,isLocal:C,isSpeaking:F})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 0"},children:[r.jsx("div",{style:{width:32,height:32,borderRadius:"50%",backgroundColor:W.hoverBg,border:`2px solid ${F?W.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:W.text,transition:"border-color 0.15s ease"},children:q.avatarUrl?r.jsx("img",{src:q.avatarUrl,alt:q.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):q.name.charAt(0).toUpperCase()}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsxs("div",{style:{color:W.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[q.name,C&&r.jsx("span",{style:{color:W.textSecondary,fontWeight:400},children:" (You)"})]})}),q.isMuted&&r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:W.mutedIcon,strokeWidth:"2",children:[r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),r.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),r.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),r.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),r.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})]});return E?r.jsxs("div",{className:b,style:{...lg,...Ci(c),backgroundColor:W.background,border:`1px solid ${W.border}`,zIndex:k,...x},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${W.border}`},children:[r.jsx("span",{style:{color:W.text,fontWeight:600},children:"Voice Chat"}),r.jsx("button",{onClick:()=>D(!1),style:{background:"none",border:"none",cursor:"pointer",padding:4,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:4},"aria-label":"Collapse",children:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:W.textSecondary,strokeWidth:"2",children:[r.jsx("polyline",{points:"4 14 10 14 10 20"}),r.jsx("polyline",{points:"20 10 14 10 14 4"}),r.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),r.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[r.jsx(V,{participant:{id:a,name:s,avatarUrl:i,isMuted:S},isLocal:!0,isSpeaking:O&&!S}),o.map(q=>r.jsx(V,{participant:q,isSpeaking:q.isSpeaking},q.id))]}),r.jsx(bs,{ref:w,mode:"bars",width:256,height:32,barCount:24,barColor:S?"var(--nice-text-muted, #9ca3af)":["var(--nice-primary, #3b82f6)","var(--nice-accent, #8b5cf6)"],barGap:3,barBorderRadius:2,autoStart:!1,onAudioLevel:_,style:{borderRadius:4,opacity:S?.5:1}}),r.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[r.jsx("button",{onClick:Z,style:{flex:1,padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:S?W.mutedBg:W.activeBg,color:S?W.mutedIcon:W.activeIcon,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":S?"Unmute":"Mute",children:S?r.jsxs(r.Fragment,{children:[r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),r.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),r.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),r.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),r.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Muted"]}):r.jsxs(r.Fragment,{children:[r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[r.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),r.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),r.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),r.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Mic On"]})}),r.jsx("button",{onClick:A,style:{padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:"var(--nice-danger-bg, #fef2f2)",color:"var(--nice-danger-dark, #dc2626)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":"Leave voice chat",children:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[r.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),r.jsx("polyline",{points:"16 17 21 12 16 7"}),r.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]})]}):r.jsx("div",{className:b,style:{position:"fixed",...Ci(c),zIndex:k,...x},children:r.jsxs("button",{onClick:()=>D(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:W.background,boxShadow:"0 4px 12px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":"Expand voice chat",children:[r.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:W.text,strokeWidth:"2",children:[r.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),r.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),r.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),r.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),o.length>0&&r.jsx("span",{style:{position:"absolute",top:-4,right:-4,width:20,height:20,borderRadius:"50%",backgroundColor:W.speakingRing,color:"var(--nice-bg, #fff)",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:o.length+1})]})})});function ug(e,t){const n={...t,id:`op_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now()},a=e.operations.slice(0,e.undoIndex+1);return a.push(n),{...e,operations:a,undoIndex:a.length-1}}function hg(e){return e.undoIndex<0?e:{...e,undoIndex:e.undoIndex-1}}function pg(e){return e.undoIndex>=e.operations.length-1?e:{...e,undoIndex:e.undoIndex+1}}function fg(e,t,n){const s=({"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":.6666666666666666,"1/8T":.3333333333333333,"1/16T":.16666666666666666,"1/4D":1.5,"1/8D":.75}[t.grid]??1)*n,i=t.strength/100;return e.map(o=>{const l=Math.round(o.startTick/s)*s,c=o.startTick+(l-o.startTick)*i,u=(Math.random()-.5)*2*t.humanize;return{...o,startTick:Math.max(0,Math.round(c+u))}})}function mg(e){if(e.length<2)return null;const t=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],n=[...new Set(e.map(s=>s%12))].sort((s,i)=>s-i),a=[{intervals:[0,4,7],quality:"maj"},{intervals:[0,3,7],quality:"min"},{intervals:[0,4,7,11],quality:"maj7"},{intervals:[0,3,7,10],quality:"min7"},{intervals:[0,4,7,10],quality:"7"},{intervals:[0,3,6],quality:"dim"},{intervals:[0,4,8],quality:"aug"},{intervals:[0,3,6,9],quality:"dim7"},{intervals:[0,2,7],quality:"sus2"},{intervals:[0,5,7],quality:"sus4"},{intervals:[0,4,7,9],quality:"6"},{intervals:[0,3,7,9],quality:"min6"}];for(const s of n){const i=n.map(o=>(o-s+12)%12).sort((o,l)=>o-l);for(const o of a)if(o.intervals.length===i.length&&o.intervals.every((l,c)=>l===i[c])){const l=t[s],c=t[e[0]%12];return{root:l,quality:o.quality,bass:c!==l?c:void 0,symbol:`${l}${o.quality==="maj"?"":o.quality}${c!==l?`/${c}`:""}`,intervals:o.intervals}}}return null}const zc={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],aeolian:[0,2,3,5,7,8,10],locrian:[0,1,3,5,6,8,10],"harmonic-minor":[0,2,3,5,7,8,11],"melodic-minor":[0,2,3,5,7,9,11],"pentatonic-major":[0,2,4,7,9],"pentatonic-minor":[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11],"whole-tone":[0,2,4,6,8,10]};function gg(e,t,n){const a=zc[n],s=(e-t+120)%12;let i=a[0],o=999;for(const c of a){const u=Math.min(Math.abs(s-c),12-Math.abs(s-c));u<o&&(o=u,i=c)}const l=Math.floor((e-t)/12);return t+l*12+i}function yg(e,t){switch(t.type){case"transpose":return e.map(n=>({...n,pitch:Math.max(0,Math.min(127,n.pitch+(t.params.semitones??0)))}));case"invert":{const n=t.params.axis??60;return e.map(a=>({...a,pitch:Math.max(0,Math.min(127,Math.round(2*n-a.pitch)))}))}case"retrograde":{if(e.length===0)return e;const n=Math.max(...e.map(a=>a.startTick+a.durationTicks));return e.map(a=>({...a,startTick:n-a.startTick-a.durationTicks}))}case"randomize-velocity":return e.map(n=>({...n,velocity:Math.max(1,Math.min(127,n.velocity+Math.round((Math.random()-.5)*2*(t.params.range??20))))}));default:return e}}function bg(e){return e>=95?"S":e>=85?"A":e>=70?"B":e>=55?"C":e>=40?"D":"F"}const xg={"guitar-standard":{instrument:"guitar-6",stringPitches:[40,45,50,55,59,64]},"guitar-drop-d":{instrument:"guitar-6",stringPitches:[38,45,50,55,59,64]},"bass-standard":{instrument:"bass-4",stringPitches:[28,33,38,43]},"ukulele-standard":{instrument:"ukulele",stringPitches:[67,60,64,69]}},vg={"Bass Drum":{staffLine:4,noteHead:"normal",stem:"down"},Snare:{staffLine:2,noteHead:"normal",stem:"up"},"Hi-Hat Closed":{staffLine:0,noteHead:"x",stem:"up"},"Hi-Hat Open":{staffLine:0,noteHead:"diamond",stem:"up"},Ride:{staffLine:-1,noteHead:"x",stem:"up"},Crash:{staffLine:-2,noteHead:"x",stem:"up"},"High Tom":{staffLine:1,noteHead:"normal",stem:"up"},"Mid Tom":{staffLine:2,noteHead:"normal",stem:"down"},"Low Tom":{staffLine:3,noteHead:"normal",stem:"down"}};exports.ALL_CAP_STYLES=Bn;exports.ALL_EFFECTS=Al;exports.ALL_TEXTURES=po;exports.ARTNET_PORT=q0;exports.ASYMMETRIC_CAPS=ao;exports.ArpeggiatorPanel=Ui;exports.AudioEffectType=Tc;exports.AudioPitchAnalyzer=mo;exports.AudioPlaybackEngine=xm;exports.AudioRecorder=Ea;exports.AudioTimeline=Ta;exports.AutoSavePanel=Pi;exports.BarFillEditor=fo;exports.CCAutomationLaneEditor=zi;exports.CCLane=Ri;exports.CONTROLLER_PROFILES=Ul;exports.ChaseRunner=X0;exports.CollaboratorPermission=$c;exports.DEFAULT_ARP_CONFIG=ia;exports.DEFAULT_AUDIO_INPUT_SETTINGS=Il;exports.DEFAULT_BAR_FILL=Vt;exports.DEFAULT_CAP_STYLE=io;exports.DEFAULT_EMPTY_BAR_FILL=Lr;exports.DEFAULT_FONT_SETTINGS=Fr;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=Dr;exports.DEFAULT_GOLD_FILLED_BAR_FILL=_r;exports.DEFAULT_KARAOKE_SETTINGS=oo;exports.DEFAULT_PLAYER_BAR_STYLE=un;exports.DEFAULT_SEED_CONFIG=Dl;exports.DMXEngine=Ic;exports.DRUM_PATTERN_NAMES=Em;exports.DefaultScoringPresets=_a;exports.DmxChannelControl=ys;exports.DmxChannelType=Ft;exports.DmxEditor=Ac;exports.DmxOptionsControl=gs;exports.DmxSliderControl=Gn;exports.DynamicRuleEditor=hl;exports.DynamicRuleField=ot;exports.DynamicRuleOperator=lt;exports.EditorTrackProvider=Ia;exports.EditorUndoManager=gu;exports.FIXTURE_PROFILES=Ec;exports.GENERIC_PROFILE=cs;exports.GM_DRUM_MAP=vg;exports.GRADIENT_PRESETS=Yo;exports.GROOVE_TEMPLATES=ps;exports.GenericPlayer=Ya;exports.GenericPlayerControls=el;exports.GenericPlayerStage=tl;exports.GenericPlayerStageVisualizer=nl;exports.GenericPlaylist=sl;exports.GenericPlaylistItem=ns;exports.KARAOKE_FONT_OPTIONS=Jh;exports.KEY_MAPS=No;exports.KaraokeEditorManager=Qo;exports.KaraokeFormat=Xa;exports.KaraokeLyrics=Da;exports.KaraokePhaserRenderer=Jo;exports.KaraokeSummaryOverlay=Ka;exports.KaraokeTimeline=Va;exports.LANE_COLORS=An;exports.LAUNCH_CONTROL_PROFILE=Wl;exports.LAYER_COLORS=z0;exports.LFOPanel=qi;exports.MINILAB_PROFILE=Gl;exports.MPK_MINI_PROFILE=Bl;exports.MasterFXPanel=Ei;exports.MidiCCMapper=Lm;exports.ModeSwitcher=es;exports.NOTE_NAMES=Rm;exports.NiceArpeggiatorPanel=Ui;exports.NiceAudioEffectsRack=fm;exports.NiceAudioErrorBoundary=Zc;exports.NiceAudioInputPicker=bm;exports.NiceAudioPitchAnalyzer=mo;exports.NiceAudioStudio=Vd;exports.NiceAudioTimeline=Ta;exports.NiceAutoSavePanel=Pi;exports.NiceBarFillEditor=fo;exports.NiceCCAutomationLaneEditor=zi;exports.NiceCCLane=Ri;exports.NiceDMXTimeline=Q0;exports.NiceDmxChannelControl=ys;exports.NiceDmxEditor=Ac;exports.NiceDmxOptionsControl=gs;exports.NiceDmxSliderControl=Gn;exports.NiceDynamicRuleEditor=hl;exports.NiceEditorTrackProvider=Ia;exports.NiceGenericPlayer=Ya;exports.NiceGenericPlayerControls=el;exports.NiceGenericPlayerStage=tl;exports.NiceGenericPlayerStageVisualizer=nl;exports.NiceGenericPlaylist=sl;exports.NiceGenericPlaylistItem=ns;exports.NiceI18nProvider=Yc;exports.NiceKaraokeEditorManager=Qo;exports.NiceKaraokeLyrics=Da;exports.NiceKaraokeManager=_h;exports.NiceKaraokePhaserRenderer=Jo;exports.NiceKaraokeSelectionMode=Ko;exports.NiceKaraokeSessionJoin=Xh;exports.NiceKaraokeSetupPanel=Ho;exports.NiceKaraokeSongBrowser=Wh;exports.NiceKaraokeSummaryOverlay=Ka;exports.NiceKaraokeTimeline=Va;exports.NiceKaraokeUploader=Mo;exports.NiceLFOPanel=qi;exports.NiceLatencyCalibrator=qh;exports.NiceMasterFXPanel=Ei;exports.NiceModeSwitcher=es;exports.NiceMusicLibraryExplorer=Vp;exports.NiceNoteParticles=Tl;exports.NiceNoteRiver=Nl;exports.NicePadKaraokeOverlay=Ro;exports.NicePianoRoll=Na;exports.NicePlaylistBrowser=gl;exports.NicePlaylistDualPane=pl;exports.NicePlaylistGridView=xl;exports.NicePlaylistImportWizard=wl;exports.NicePlaylistList=is;exports.NicePlaylistOverview=vl;exports.NicePlaylistSearchBar=Sl;exports.NicePlaylistSidebar=bl;exports.NicePlaylistTagEditor=il;exports.NicePlaylistTrackList=as;exports.NiceRadioPlayer=ng;exports.NiceRecordingOptionsPanel=Ii;exports.NiceStageVisualizer=ts;exports.NiceStationBrowser=Dc;exports.NiceStepSequencerPanel=Vi;exports.NiceStreamingVisualizer=bs;exports.NiceUndoRedoPanel=Ai;exports.NiceVocalEffectsRack=gm;exports.NiceVocalPerformanceReport=Oh;exports.NiceVoiceChatOverlay=Fc;exports.NiceWaveform=Ra;exports.NiceYouTubePlayer=rl;exports.NiceZoomSnapControls=$a;exports.NoteParticles=Tl;exports.NoteRiver=Nl;exports.OVERLAY_PATTERNS=Nr;exports.OXYGEN25_PROFILE=Ol;exports.PLAYER_COLORS=Je;exports.PLAYER_COLOR_VARS=cr;exports.PROGRESSION_NAMES=Am;exports.PadNotePlayer=Ao;exports.PaneSide=ll;exports.PianoRoll=Na;exports.PlaylistBrowser=gl;exports.PlaylistDualPane=pl;exports.PlaylistGridView=xl;exports.PlaylistImportWizard=wl;exports.PlaylistList=is;exports.PlaylistOverview=vl;exports.PlaylistSearchBar=Sl;exports.PlaylistSidebar=bl;exports.PlaylistTagEditor=il;exports.PlaylistTrackList=as;exports.PlaylistType=rs;exports.RecordingOptionsPanel=Ii;exports.SACN_PORT=K0;exports.SCALE_INTERVALS=zc;exports.SCALE_NAMES=Pm;exports.SKEW_CAPS=so;exports.STANDARD_TUNINGS=xg;exports.SYMMETRIC_CAPS=Wa;exports.ShortcutManager=Rc;exports.SimpleSynth=Ll;exports.SortDirection=sn;exports.SortField=cl;exports.StageVisualizer=ts;exports.StepSequencerPanel=Vi;exports.StreamingVisualizer=bs;exports.TEXTURE_CATEGORIES=Ha;exports.TrackSource=kt;exports.UndoRedoPanel=Ai;exports.ViewMode=ol;exports.VocalEffectsEngine=El;exports.VoiceChatOverlay=Fc;exports.Waveform=Ra;exports.WebRTCAudioManager=_c;exports.YouTubePlayer=rl;exports.ZoomSnapControls=$a;exports.addEffectToLayer=Xm;exports.addMidiNote=t0;exports.analyzeAudioFileWithAlgorithm=d0;exports.applyGroove=y0;exports.applyGrooveTemplate=Cc;exports.applyHumanize=jc;exports.applyKaraokeDisplayVars=Ja;exports.applyMidiTransform=yg;exports.applySwing=wc;exports.arrow_L=zt;exports.arrow_R=Tt;exports.autoCorrelate=xo;exports.bracket_L=za;exports.bracket_R=no;exports.buildArpSequence=Bi;exports.buildLanes=To;exports.buildNoteDescriptors=Za;exports.buildPadNoteEvents=Po;exports.buildSegmentScores=vo;exports.canRedo=Zl;exports.canUndo=Yl;exports.chamfer_L=jr;exports.chamfer_R=dn;exports.clearMidiNotes=r0;exports.clearPattern=fc;exports.computeGrade=bg;exports.computeTheoreticalMax=Fo;exports.computeVocalPerformanceReport=Wo;exports.convertBrowserSongToKaraokeSongFile=Mh;exports.copyCCEvents=wa;exports.createAnalyserNode=xc;exports.createArpPattern=Gm;exports.createArtNetPacket=H0;exports.createBasslinePattern=Wm;exports.createCCHistory=ql;exports.createCompressorNode=Sc;exports.createDefaultLFO=Er;exports.createDefaultShortcuts=T0;exports.createDropZoneHandlers=_0;exports.createEmptyPattern=Ht;exports.createEmptyStep=ds;exports.createGainNode=vc;exports.createHiHatPattern=Bm;exports.createKickPattern=zm;exports.createLoopRegion=w0;exports.createSACNPacket=Y0;exports.createSnarePattern=Om;exports.createVocoderNode=kc;exports.createVoiceChatAudioContext=og;exports.cutCCEvents=Ql;exports.deleteCCEventsInRange=Jl;exports.deserializeLFO=nu;exports.deserializePattern=qm;exports.detectChord=mg;exports.downsampleAndQuantizePitchPoints=So;exports.drawGlossyBarOnCanvas=Rn;exports.drawTimeline=ua;exports.estimateLatencyMs=ko;exports.estimateLatencyMsFromRecording=Vo;exports.evaluateLFO=Pa;exports.evaluateLFOAsCC=Aa;exports.exportCCLane=nc;exports.extractBpmFromNotes=Xi;exports.findTextureByUrl=ih;exports.formatShortcut=$0;exports.generateArpEvents=su;exports.generatePlaceholderWaveform=m0;exports.generateSeed=zl;exports.generateUltrastarText=u0;exports.getActiveGradient=Xo;exports.getActiveLyrics=ku;exports.getActiveWords=wu;exports.getAlgorithmColor=jh;exports.getAlgorithmCssVar=Ch;exports.getAlgorithmLabel=wh;exports.getArpModes=Gi;exports.getArpRates=Wi;exports.getAudioContext=mn;exports.getAudioInputDevices=ig;exports.getAudioWorkletProcessorCode=yc;exports.getBackgroundUrl=kh;exports.getCachedImage=rh;exports.getCapStyleByName=Cn;exports.getComboMultiplier=Do;exports.getCoverUrl=Sh;exports.getGrooveTemplate=b0;exports.getGrooveTemplateNames=x0;exports.getLaneForPitch=$o;exports.getNextPlayerColor=pd;exports.getNextPlayerColorCss=fd;exports.getOverlayCanvasPattern=Pn;exports.getPatternByName=Mn;exports.getSACNMulticastAddress=Z0;exports.getScoringPreset=Ir;exports.getTexturePattern=Tn;exports.getVerseRatingLabel=Lo;exports.handleAddCCEvent=s0;exports.handleRedo=mu;exports.handleRemoveCCEvent=o0;exports.handleSelectCCLane=a0;exports.handleUndo=fu;exports.handleUpdateCCEvent=i0;exports.hexToHsl=Tr;exports.humanizeMidiNotes=k0;exports.hydrateKaraokeDisplayFromBackend=ep;exports.hydratePlayerKaraokeSettingsFromBackend=Lu;exports.hzToUltrastarPitch=Qi;exports.importCCLane=rc;exports.initKaraokeDisplaySettings=np;exports.instrumentPresets=vm;exports.isAudioContextRunning=Ni;exports.isInLoopRegion=M0;exports.isWebRTCSupported=sg;exports.loadAllKaraokeSettings=Du;exports.loadAudioWorkletModule=bc;exports.loadKaraokeDisplaySettings=Zo;exports.loadKaraokeSettings=Ua;exports.loadPlayerBarStyle=lo;exports.loadPlayerBarStyles=Fu;exports.loadRemoteScoringPresets=Pu;exports.makeClickReference=qo;exports.makeClipSelectionId=h0;exports.mergeWaveforms=f0;exports.midiSeedGenerator=Im;exports.midiToHz=ha;exports.normalizeHex=$r;exports.openAudioFilePicker=F0;exports.ornate_L=Ba;exports.ornate_R=Rr;exports.parseLyrics=vu;exports.parseNotes=qn;exports.parseUltraStarText=Co;exports.parseVersesWithSyllables=Zi;exports.parseVersesWithWords=Su;exports.parseVideoMetadata=bo;exports.pasteCCEvents=Xl;exports.pill_L=Ut;exports.pill_R=_t;exports.preloadTexture=qa;exports.preloadTextures=ah;exports.probeAudioFile=Nc;exports.pushCCState=Vl;exports.pushOperation=ug;exports.quantizeMidiNotes=v0;exports.quantizeNotes=fg;exports.quantizeStepInBeats=Mc;exports.quantizeStepInSeconds=fs;exports.randomizeVelocity=pc;exports.recordCCEvent=ec;exports.redoCC=Kl;exports.redoOperation=pg;exports.removeEffectFromLayer=Qm;exports.removeMidiNote=n0;exports.renderGlossyBarSvg=co;exports.resumeAudioContext=Bt;exports.reversePattern=uc;exports.sampleLFOForDisplay=Fi;exports.sampleLFOToCCEvents=_i;exports.saveKaraokeDisplaySettings=tp;exports.saveKaraokeSettings=Iu;exports.savePlayerBarStyle=_u;exports.scaleResult=Oo;exports.scaleTo10k=zo;exports.scoreNotesWithPitchPoints=_o;exports.selectCCEventsInRange=Dm;exports.serializeLFO=tu;exports.serializePattern=Um;exports.setLoopFromSelection=j0;exports.setProjectWithUndo=Ki;exports.setStepGate=oc;exports.setStepNote=sc;exports.setStepProbability=lc;exports.setStepVelocity=ic;exports.sharp_L=ln;exports.sharp_R=cn;exports.shield_L=Cr;exports.shield_R=to;exports.shiftPattern=hc;exports.shouldTrigger=gc;exports.skewTL_L=dr;exports.skewTL_R=da;exports.skewTR_L=ca;exports.skewTR_R=ur;exports.snapLoopToGrid=C0;exports.snapTimeToQuantize=ja;exports.snapToGrid=p0;exports.snapToScale=gg;exports.soft_L=Fa;exports.soft_R=eo;exports.stepDuration=us;exports.stepTimeOffset=mc;exports.syncDivisionToHz=Li;exports.tab_L=Oa;exports.tab_R=ro;exports.thinCCEvents=tc;exports.toTrack=jo;exports.toggleEffectBypass=Jm;exports.toggleStep=ac;exports.toggleStepSlide=cc;exports.transposePattern=dc;exports.undoCC=Hl;exports.undoOperation=hg;exports.updateEffectParams=e0;exports.useAudioWorklet=Zm;exports.useAutoSave=du;exports.useCCAutomation=Fm;exports.useCanPickSong=Zh;exports.useDMXAudioSync=eg;exports.useDMXEngine=J0;exports.useEditorTrack=xu;exports.useKaraokePitch=Io;exports.useKaraokeScoring=Bo;exports.useLocalPlaylists=ss;exports.useMPE=jm;exports.useMidiLearn=km;exports.useNiceTranslation=Te;exports.useOxygen25=Mm;exports.usePitchWorker=Hm;exports.usePlaybackEngine=uu;exports.useProjectCRUD=bu;exports.useRadioStream=Lc;exports.useRecording=hu;exports.useScoringWorker=Km;exports.useStepSequencer=Vm;exports.useWebMidi=Br;exports.useWorker=hs;exports.validateAudioFiles=ms;exports.wave_L=Mr;exports.wave_R=Ga;exports.waveformValue=Di;exports.wrapTimeInLoop=R0;