@nice2dev/ui-audio 1.0.10 → 1.0.12

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 (48) hide show
  1. package/dist/constants/audioColors.d.ts.map +1 -1
  2. package/dist/constants/ui.d.ts.map +1 -1
  3. package/dist/dmx/DmxChannelControls.d.ts.map +1 -1
  4. package/dist/dmx/DmxEditor.d.ts.map +1 -1
  5. package/dist/editor/AudioMiniMap.d.ts.map +1 -1
  6. package/dist/editor/Waveform.d.ts.map +1 -1
  7. package/dist/editor/panels/ArpeggiatorPanel.d.ts.map +1 -1
  8. package/dist/editor/panels/CCAutomationLaneEditor.d.ts.map +1 -1
  9. package/dist/editor/panels/DisplayModeSelector.d.ts.map +1 -1
  10. package/dist/editor/panels/EditorPanels.d.ts.map +1 -1
  11. package/dist/editor/panels/LFOPanel.d.ts.map +1 -1
  12. package/dist/editor/panels/LayerTrack.d.ts.map +1 -1
  13. package/dist/editor/panels/StepSequencerPanel.d.ts.map +1 -1
  14. package/dist/editor/useEditorTrack.d.ts.map +1 -1
  15. package/dist/effects/noteThemeColors.d.ts.map +1 -1
  16. package/dist/index.cjs +18 -18
  17. package/dist/index.mjs +607 -491
  18. package/dist/karaoke/AudioPitchAnalyzer.d.ts.map +1 -1
  19. package/dist/karaoke/BarFillEditor.d.ts +1 -1
  20. package/dist/karaoke/BarFillEditor.d.ts.map +1 -1
  21. package/dist/karaoke/rendering/glossyBarRenderer.d.ts +1 -1
  22. package/dist/karaoke/rendering/glossyBarRenderer.d.ts.map +1 -1
  23. package/dist/karaoke/rendering/karaokeDisplaySettings.d.ts.map +1 -1
  24. package/dist/karaoke/rendering/karaokeSettings.d.ts +2 -2
  25. package/dist/karaoke/rendering/karaokeSettings.d.ts.map +1 -1
  26. package/dist/karaokeEditor/KaraokeEditorManager.d.ts.map +1 -1
  27. package/dist/karaokeEditor/KaraokePhaserRenderer.d.ts.map +1 -1
  28. package/dist/player/GenericPlayer.d.ts.map +1 -1
  29. package/dist/player/GenericPlayerTrackList.d.ts.map +1 -1
  30. package/dist/player/visualizer/modes/CoverMode.d.ts.map +1 -1
  31. package/dist/player/visualizer/modes/LavaLampMode.d.ts.map +1 -1
  32. package/dist/player/visualizer/modes/PlasmaBallMode.d.ts.map +1 -1
  33. package/dist/player/visualizer/modes/RadialMode.d.ts.map +1 -1
  34. package/dist/player/visualizer/modes/RiftMode.d.ts.map +1 -1
  35. package/dist/player/visualizer/modes/WaveformMode.d.ts.map +1 -1
  36. package/dist/playlist/GenericPlaylist.d.ts.map +1 -1
  37. package/dist/playlist/PlaylistBrowser.d.ts +4 -4
  38. package/dist/playlist/PlaylistBrowser.d.ts.map +1 -1
  39. package/dist/playlist/PlaylistList.d.ts.map +1 -1
  40. package/dist/playlist/PlaylistOverview.d.ts.map +1 -1
  41. package/dist/radio/NiceRadioPlayer.d.ts +1 -1
  42. package/dist/radio/NiceRadioPlayer.d.ts.map +1 -1
  43. package/dist/streaming/NiceStreamingVisualizer.d.ts +2 -2
  44. package/dist/streaming/NiceStreamingVisualizer.d.ts.map +1 -1
  45. package/dist/streaming/NiceVoiceChatOverlay.d.ts.map +1 -1
  46. package/dist/ui-audio.css +1 -1
  47. package/dist/workers/useWorker.d.ts.map +1 -1
  48. package/package.json +2 -2
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";var Tl=Object.create;var Na=Object.defineProperty;var Pl=Object.getOwnPropertyDescriptor;var El=Object.getOwnPropertyNames;var Al=Object.getPrototypeOf,Nl=Object.prototype.hasOwnProperty;var Il=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of El(t))!Nl.call(e,a)&&a!==n&&Na(e,a,{get:()=>t[a],enumerable:!(r=Pl(t,a))||r.enumerable});return e};var br=(e,t,n)=>(n=e!=null?Tl(Al(e)):{},Il(t||!e||!e.__esModule?Na(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),u=require("react"),Ve=require("react-bootstrap"),Pr=require("pitchy"),Ll=require("react-window"),Yr=require("react-youtube");var st=typeof document<"u"?document.currentScript:null;const Fl=(e,t)=>t??e,$s=u.createContext(Fl),Dl=({t:e,children:t})=>s.jsx($s.Provider,{value:e,children:t});function xe(){return{t:u.useContext($s)}}class Ol 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 vr={},Er={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function _l(){const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:st&&st.tagName.toUpperCase()==="SCRIPT"&&st.src||new URL("index.cjs",document.baseURI).href}<"u"?vr==null?void 0:vr.VITE_LOG_LEVEL:void 0;return e&&e in Er?e:"WARN"}const zl=_l();function $n(e){return Er[e]>=Er[zl]}function Tn(e){return`[${e}]`}const et={debug(e,t,...n){$n("DEBUG")&&console.debug(Tn(e),t,...n)},info(e,t,...n){$n("INFO")&&console.info(Tn(e),t,...n)},warn(e,t,...n){$n("WARN")&&console.warn(Tn(e),t,...n)},error(e,t,...n){$n("ERROR")&&console.error(Tn(e),t,...n)},scoped(e){return{debug:(t,...n)=>et.debug(e,t,...n),info:(t,...n)=>et.info(e,t,...n),warn:(t,...n)=>et.warn(e,t,...n),error:(t,...n)=>et.error(e,t,...n)}}},Ia=et.scoped("Waveform"),Bl=["audio/","video/"],Ts=({audioBlob:e,currentTime:t,duration:n,width:r=600,height:a=200,zoom:o=1,onSeek:i,onRegionSelect:l,markers:c=[],regions:d=[],displayMode:h="waveform",multiChannel:f=!1,waveColor:m="#007bff",progressColor:g="rgba(255,0,0,0.8)",backgroundColor:p="transparent",showRuler:v=!1,showChannelLabels:x=!0,showPeakMeter:b=!1,className:w})=>{const y=u.useRef(null),k=u.useRef(null),M=u.useRef(null),[N,R]=u.useState(0),[_,E]=u.useState(!1),[U,W]=u.useState(null),[j,L]=u.useState(null),[I,q]=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&&!Bl.some(z=>e.type.startsWith(z))&&Ia.warn("Unexpected blob MIME type:",e.type);let B=!1;return(async()=>{let z=null;try{const S=await e.arrayBuffer();if(S.byteLength===0||B)return;z=new AudioContext;const P=await z.decodeAudioData(S);B||(M.current=P)}catch(S){Ia.error("Failed to decode audio:",S)}finally{z==null||z.close().catch(()=>{})}})(),()=>{B=!0}},[e]),u.useEffect(()=>{if(o>1&&n>0){const B=t/n*Y;(B<N||B>N+r)&&R(Math.max(0,B-r/2))}},[t,n,o,r,Y,N]),u.useEffect(()=>{const B=y.current,z=M.current;if(!B||!n||n===1/0)return;const S=B.getContext("2d");if(!S)return;const P=Y,$=a;if(B.width=P,B.height=$+O,S.clearRect(0,0,P,$+O),p!=="transparent"&&(S.fillStyle=p,S.fillRect(0,0,P,$+O)),v){S.fillStyle="rgba(128,128,128,0.15)",S.fillRect(0,0,P,O),S.fillStyle="#888",S.font="10px monospace",S.textAlign="center";const T=Math.max(1,Math.floor(n/(Y/80)));for(let C=0;C<=n;C+=T){const A=C/n*P;S.fillText(Vl(C),A,O-4),S.fillStyle="rgba(128,128,128,0.3)",S.fillRect(A,O,1,$),S.fillStyle="#888"}}for(const T of d){const C=T.start/n*P,A=T.end/n*P;S.fillStyle=T.color??"rgba(99,102,241,0.15)",S.fillRect(C,O,A-C,$),T.label&&(S.fillStyle=T.color??"#6366f1",S.font="10px sans-serif",S.textAlign="left",S.fillText(T.label,C+2,O+12))}if(U!==null&&j!==null){const T=Math.min(U,j),C=Math.max(U,j);S.fillStyle="rgba(255,200,0,0.2)",S.fillRect(T,O,C-T,$)}if(z){const T=f?z.numberOfChannels:1,C=$/T;let A=0;for(let D=0;D<T;D++){const V=z.getChannelData(D),Q=O+D*C;if(h==="waveform"?Gl(S,V,P,C,Q,m):h==="bars"?Wl(S,V,P,C,Q,m):h==="spectrogram"&&Ul(S,V,P,C,Q,z.sampleRate),b&&n>0){const J=Math.floor(t/n*V.length),ae=Math.floor(z.sampleRate*.05);let re=0;for(let F=Math.max(0,J-ae);F<Math.min(V.length,J+ae);F++)re+=V[F]*V[F];const ee=Math.sqrt(re/(ae*2));A=Math.max(A,ee)}f&&x&&T>1&&(S.fillStyle="rgba(255,255,255,0.6)",S.font="bold 11px sans-serif",S.textAlign="left",S.fillText(D===0?"L":D===1?"R":`Ch${D+1}`,4,Q+14))}q(A)}if(n>0){const T=Math.max(0,Math.min(t/n*P,P));S.beginPath(),S.strokeStyle=g,S.lineWidth=2,S.moveTo(T,O),S.lineTo(T,$+O),S.stroke()}for(const T of c){const C=T.time/n*P;S.beginPath(),S.strokeStyle=T.color??"#f59e0b",S.lineWidth=2,S.setLineDash([4,4]),S.moveTo(C,O),S.lineTo(C,$+O),S.stroke(),S.setLineDash([]),T.label&&(S.fillStyle=T.color??"#f59e0b",S.font="bold 10px sans-serif",S.textAlign="center",S.fillText(T.label,C,O+$-4))}},[e,M.current,t,n,Y,a,o,h,f,m,g,p,v,c,d,U,j,b,x,O]);const Z=u.useCallback(B=>{var P;if(!n)return;const z=(P=y.current)==null?void 0:P.getBoundingClientRect();if(!z)return;const S=B.clientX-z.left+N;E(!0),W(S),L(S)},[n,N]),H=u.useCallback(B=>{if(!_||!y.current)return;const z=y.current.getBoundingClientRect(),S=B.clientX-z.left+N;L(S)},[_,N]),te=u.useCallback(()=>{if(!_||U===null||j===null||!n){E(!1),W(null),L(null);return}const B=Math.min(U,j),z=Math.max(U,j),S=(z-B)/Y*n;if(E(!1),W(null),L(null),S<.2){const P=B/Y*n;i==null||i(P)}else{const P=B/Y*n,$=z/Y*n;l==null||l({start:P,end:$})}},[_,U,j,n,Y,i,l]);return s.jsxs("div",{ref:k,className:`nice-waveform${w?` ${w}`:""}`,style:{position:"relative",width:r,overflow:o>1?"auto":"hidden",cursor:i?"crosshair":"default"},onScroll:B=>R(B.target.scrollLeft),children:[s.jsx("canvas",{ref:y,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:"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,I*300)}%`,background:I>.8?"#ef4444":I>.5?"#f59e0b":"#22c55e",borderRadius:4,transition:"height 50ms"}})})]})};function Gl(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,h=t.subarray(d,d+i);let f=0,m=0;for(let v=0;v<h.length;v++)h[v]<f&&(f=h[v]),h[v]>m&&(m=h[v]);const g=l-m*(r/2),p=l-f*(r/2);e.moveTo(c,g),e.lineTo(c,p)}e.stroke()}function Wl(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 h=d*c,f=t.subarray(h,h+c);let m=0;for(let x=0;x<f.length;x++)m+=Math.abs(f[x]);const p=m/f.length*r*.9,v=d*i;e.fillStyle=o,e.fillRect(v+1,a+r-p,i-2,p)}}function Ul(e,t,n,r,a,o){const l=Math.min(n,512),c=Math.floor(t.length/l),d=n/l;for(let h=0;h<l;h++){const f=h*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&&f+b<t.length;b++){const w=2*Math.PI*p*b/256;v+=t[f+b]*Math.cos(w),x-=t[f+b]*Math.sin(w)}m[p]=Math.sqrt(v*v+x*x)/256}const g=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),w=Math.floor((1-v)*200);e.fillStyle=`rgb(${x},${b},${w})`,e.fillRect(h*d,a+r-(p+1)*g,d+1,g+1)}}}function Vl(e){const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const La=88,Ft=16,Pn=16,ql=320;function Hl(e){return e-21}function Kl(e){return e+21}const Ps=({notes:e,onAddNote:t,onRemoveNote:n,selectedNoteId:r,setSelectedNoteId:a,duration:o=4,zoom:i=1})=>{const l=u.useRef(null),c=ql*i,d=La*Ft,h=u.useRef(null);u.useEffect(()=>{},[e,i,o]);const f=g=>{const p=g.target.getBoundingClientRect(),v=g.clientX-p.left,x=g.clientY-p.top,b=Math.floor(x/Ft),w=Kl(b),y=v/c*o;h.current={drawing:!0,startX:v,key:b},t(w,y,o/Pn)},m=(g,p)=>{p.stopPropagation(),a==null||a(g)};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:f,children:[[...Array(La)].map((g,p)=>s.jsx("rect",{x:0,y:p*Ft,width:c,height:Ft,fill:p%2===0?"var(--key-even, #f5f5f5)":"var(--key-odd, #e0e0e0)"},p)),[...Array(Pn+1)].map((g,p)=>s.jsx("line",{x1:p*c/Pn,y1:0,x2:p*c/Pn,y2:d,stroke:"var(--border-muted, #ccc)",strokeWidth:p%4===0?2:1},p)),e.map(g=>{const p=Hl(g.pitch),v=g.start/o*c,x=g.duration/o*c;return s.jsx("rect",{x:v,y:p*Ft,width:Math.max(6,x),height:Ft-2,fill:g.id===r?"var(--accent, #1976d2)":"var(--accent-light, #90caf9)",stroke:"var(--accent, #1976d2)",strokeWidth:g.id===r?2:1,rx:3,onClick:b=>m(g.id,b),onDoubleClick:()=>n(g.id),style:{cursor:"pointer"}},g.id)})]})},Es=({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:h}=xe(),[f,m]=u.useState(null),[g,p]=u.useState(null),[v,x]=u.useState(null),b=[...e].sort((L,I)=>L.time-I.time),w=L=>[L.time/o*i,(127-L.value)/127*l],y=(L,I,q)=>Math.max(I,Math.min(q,L)),k=L=>{var H;if(L.target instanceof SVGCircleElement)return;const I=(H=d.current)==null?void 0:H.getBoundingClientRect();if(!I)return;const q=L.clientX-I.left,Y=L.clientY-I.top,O=y(q/i*o,0,o),Z=y(127-Math.round(Y/l*127),0,127);t(a,Z,O)},M=(L,I)=>{var Z;I.stopPropagation(),m(L.id),x(L.id);const[q,Y]=w(L),O=(Z=d.current)==null?void 0:Z.getBoundingClientRect();O&&p({dx:I.clientX-O.left-q,dy:I.clientY-O.top-Y})},N=L=>{var H;if(f==null||!g)return;const I=(H=d.current)==null?void 0:H.getBoundingClientRect();if(!I)return;const q=y(L.clientX-I.left-g.dx,0,i),Y=y(L.clientY-I.top-g.dy,0,l),O=y(q/i*o,0,o),Z=y(127-Math.round(Y/l*127),0,127);n(f,Z,O)},R=()=>{m(null),p(null)};u.useEffect(()=>{const L=I=>{(I.key==="Delete"||I.key==="Backspace")&&v!=null&&(r(v),x(null))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[v,r]),u.useEffect(()=>{if(f!=null)return window.addEventListener("mousemove",N),window.addEventListener("mouseup",R),()=>{window.removeEventListener("mousemove",N),window.removeEventListener("mouseup",R)}});const[_,E]=u.useState(null),U=(L,I)=>{const[q,Y]=w(L);E({x:q+10,y:Y-10,text:`Val: ${L.value}, Time: ${L.time.toFixed(2)}s`})},W=()=>E(null),j=L=>{var H;const I=(H=d.current)==null?void 0:H.getBoundingClientRect();if(!I)return;const q=L.clientX-I.left,Y=L.clientY-I.top,O=y(q/i*o,0,o),Z=y(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:f?"grabbing":"crosshair",display:"block"},onClick:k,onDoubleClick:j,tabIndex:0,children:[[...Array(9)].map((L,I)=>s.jsx("line",{x1:0,y1:I*l/8,x2:i,y2:I*l/8,stroke:"var(--border-muted, #ddd)",strokeWidth:I===0||I===8?2:1},I)),b.length>1&&s.jsx("polyline",{fill:"none",stroke:"var(--accent, #1976d2)",strokeWidth:2,points:b.map(L=>w(L).join(",")).join(" ")}),b.map(L=>{const[I,q]=w(L);return s.jsxs("g",{children:[s.jsx("circle",{cx:I,cy:q,r:v===L.id?8:6,fill:v===L.id?"var(--accent, #1976d2)":"var(--accent-light, #90caf9)",stroke:"var(--accent, #1976d2)",strokeWidth:v===L.id?3:2,style:{cursor:"pointer"},onMouseDown:Y=>M(L,Y),onContextMenu:Y=>{Y.preventDefault(),r(L.id)},onClick:Y=>{Y.stopPropagation(),x(L.id)},onMouseOver:Y=>U(L),onMouseOut:W}),v===L.id&&s.jsx("foreignObject",{x:I+10,y:q-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:[h("ccLane.curve","Curve"),":"]}),s.jsxs("select",{value:L.handleType||c||"linear",onChange:Y=>{n(L.id,L.value,L.time,Y.target.value)},children:[s.jsx("option",{value:"linear",children:h("ccLane.linear","Linear")}),s.jsx("option",{value:"step",children:h("ccLane.step","Step")}),s.jsx("option",{value:"exp",children:h("ccLane.exponential","Exponential")})]})]})})]},L.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]})]})},Yl=et.scoped("audioContext");let wn=null;function tn(){if(!wn)try{wn=new(window.AudioContext||window.webkitAudioContext)}catch(e){Yl.error("Error initializing AudioContext:",e)}return wn}async function Et(){const e=tn();e&&e.state==="suspended"&&await e.resume()}function As(){return!!wn&&wn.state==="running"}function Ns(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 Zl(e,t){if(!t.snapEnabled)return e;const n=Ns(t);return Math.round(e/n)*n}function Xl(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 Ql(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 Is(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,h=c%1===0;if(r.strokeStyle=h?"var(--border-secondary, #ccc)":"var(--border-muted, #eee)",r.lineWidth=h?1.5:.5,r.beginPath(),r.moveTo(d,0),r.lineTo(d,o),r.stroke(),h&&i>40){r.fillStyle="var(--muted, #666)",r.font="10px monospace",r.textAlign="center";const f=n?Ql(c,t.bpm):Xl(c);r.fillText(f,d,12)}}if(t.snapEnabled){const c=Ns(t);r.strokeStyle="var(--accent-primary, #ffeb3b)",r.lineWidth=.5;for(let d=0;d<=t.duration;d+=c){const h=d/t.duration*a;r.beginPath(),r.moveTo(h,o-5),r.lineTo(h,o),r.stroke()}}}function Jl(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;Is(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 ec(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,h)=>{const f=h/(n.length-1)*o,m=l-d*c;h===0?a.moveTo(f,m):a.lineTo(f,m)}),a.stroke(),a.restore()}const Ls=({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:h,onZoomChange:f})=>{const m=u.useRef(null),g=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(()=>{Et(),w()},[e,t,a,r,o,i,l,c]),u.useEffect(()=>{n?(p.current=performance.now(),y()):g.current&&cancelAnimationFrame(g.current)},[n]);const w=()=>{m.current&&(Is(m.current,b),c!=null&&c.length&&ec(m.current,b,c,d),Jl(m.current,b,a,r))},y=()=>{if(!n)return;const E=U=>{if(p.current!==null){const W=(U-p.current)/1e3;p.current=U;const j=Math.min(a+W,t);h(j)}a<t&&(g.current=requestAnimationFrame(E))};g.current=requestAnimationFrame(E)},k=E=>{x(!0),R(E)},M=E=>{v&&R(E)},N=()=>{x(!1)},R=E=>{if(!m.current)return;const U=m.current.getBoundingClientRect();let j=(E.clientX-U.left)/U.width*t;j=Zl(j,b),h(Math.min(Math.max(j,0),t))},_=E=>{if(!f)return;E.preventDefault();const U=E.deltaY>0?-.1:.1,W=Math.max(.5,Math.min(5,e+U));f(W)};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 tc=Date.now();function en(){return tc++}function nc(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:en(),cc:t,value:nn(o.value),time:o.time}),a=o.time);return r}function Fa(e,t,n,r=32){const a=[];for(let o=0;o<=r;o++){const i=o/r;a.push({id:en(),cc:n,value:nn(Xn(e.value,t.value,i)),time:Xn(e.time,t.time,i)})}return a}function rc(e,t,n,r,a=48){const o=[];for(let i=0;i<=a;i++){const l=i/a,c=Da(e.time,t.time,n.time,l),d=Da(e.value,t.value,n.value,l);o.push({id:en(),cc:r,value:nn(d),time:c})}return o}function ac(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=nn(e.value+l*i);a.push({id:en(),cc:n,value:d,time:c}),a.push({id:en(),cc:n,value:d,time:c+o-.001})}return a}function sc(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:en(),cc:n,value:nn(Xn(e.value,t.value,c)),time:Xn(e.time,t.time,l)})}return o}function oc(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,h)=>d+h.value,0)/l.length;return{...r,value:nn(Math.round(c))}})}function ic(e,t){let n;switch(e.mode){case"pencil":n=nc(t,e.cc,e.resolution);break;case"line":n=t.length>=2?Fa(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?n=rc(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?n=Fa(t[0],t[t.length-1],e.cc):n=[];break;case"step":n=t.length>=2?ac(t[0],t[t.length-1],e.cc):[];break;case"ramp":n=t.length>=2?sc(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=oc(n,r)}return n}function nn(e){return Math.max(0,Math.min(127,Math.round(e)))}function Xn(e,t,n){return e+(t-e)*n}function Da(e,t,n,r){const a=1-r;return a*a*e+2*a*r*t+r*r*n}function ir(){return{waveform:"sine",rate:1,depth:.5,phase:0,center:.5,syncToBpm:!1,syncDivision:"1/4",enabled:!0}}const lc={"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 Fs(e,t){return e/60*lc[t]/4}function Ds(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 Zr(e,t,n){if(!e.enabled)return e.center;const r=e.syncToBpm&&n?Fs(n,e.syncDivision):e.rate,a=t*r+e.phase/(2*Math.PI),o=Ds(e.waveform,a),i=e.center+o*e.depth*.5;return Math.max(0,Math.min(1,i))}function Xr(e,t,n){return Math.round(Zr(e,t,n)*127)}function Os(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 h=t+d/l*i,f=Xr(e,h,o);c.push({time:h,value:f,cc:r})}return c}function _s(e,t,n,r=2,a,o=200){const i=[];for(let l=0;l<=o;l++){const c=l/o*r,d=Zr(e,c,a);i.push({x:l/o*t,y:(1-d)*n})}return i}function cc(e){return JSON.stringify(e,null,2)}function dc(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const xr=140,rn=24,uc=[{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"}],zs=({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:h}=xe(),f=u.useRef(null),[m,g]=u.useState("pencil"),[p,v]=u.useState(!1),x=u.useRef([]),[b,w]=u.useState(null),[y,k]=u.useState(!1),[M,N]=u.useState(ir()),R=u.useRef(null),_=d.getEvents(e),E=_.filter(S=>S.cc===t),U=Math.max(400,n*30*r),W=u.useCallback(S=>S/U*n,[U,n]),j=u.useCallback(S=>Math.round(Math.max(0,Math.min(127,127-(S-rn)/xr*127))),[]),L=u.useCallback(S=>S/n*U,[U,n]),I=u.useCallback(S=>rn+(127-S)/127*xr,[]),q=u.useCallback(()=>{const S=f.current;if(!S)return;const P=S.getContext("2d");if(!P)return;const $=S.width,T=S.height;P.clearRect(0,0,$,T),P.fillStyle="#1a1a2e",P.fillRect(0,0,$,T),P.strokeStyle="rgba(255,255,255,0.06)",P.lineWidth=1;for(let D=0;D<=127;D+=16){const V=I(D);P.beginPath(),P.moveTo(0,V),P.lineTo($,V),P.stroke()}P.fillStyle="rgba(255,255,255,0.3)",P.font="10px monospace",P.textBaseline="middle";for(const D of[0,32,64,96,127])P.fillText(String(D),2,I(D));P.strokeStyle="rgba(255,255,255,0.04)";for(let D=0;D<=n;D++){const V=L(D);P.beginPath(),P.moveTo(V,0),P.lineTo(V,T),P.stroke()}const C=[...E].sort((D,V)=>D.time-V.time);if(C.length>0){P.beginPath(),P.moveTo(L(C[0].time),T-rn);for(const D of C)P.lineTo(L(D.time),I(D.value));P.lineTo(L(C[C.length-1].time),T-rn),P.closePath(),P.fillStyle="rgba(59, 130, 246, 0.15)",P.fill(),P.beginPath(),P.strokeStyle="#3b82f6",P.lineWidth=2;for(let D=0;D<C.length;D++){const V=L(C[D].time),Q=I(C[D].value);D===0?P.moveTo(V,Q):((C[D].handleType??"linear")==="step"&&P.lineTo(V,I(C[D-1].value)),P.lineTo(V,Q))}P.stroke();for(const D of C){const V=L(D.time),Q=I(D.value),J=b===D.id;P.beginPath(),P.arc(V,Q,J?6:4,0,Math.PI*2),P.fillStyle=J?"#60a5fa":"#3b82f6",P.fill(),P.strokeStyle="#fff",P.lineWidth=1.5,P.stroke()}}P.strokeStyle="rgba(255,255,255,0.15)",P.lineWidth=1,P.setLineDash([4,4]);const A=I(0);P.beginPath(),P.moveTo(0,A),P.lineTo($,A),P.stroke(),P.setLineDash([])},[E,n,U,L,I,b]);u.useEffect(()=>{q()},[q]);const Y=S=>{var C;const P=(C=f.current)==null?void 0:C.getBoundingClientRect();if(!P)return;const $=S.clientX-P.left,T=S.clientY-P.top;m==="pencil"?(v(!0),x.current=[{time:W($),value:j(T)}]):(v(!0),x.current=[{time:W($),value:j(T)}])},O=S=>{var D;const P=(D=f.current)==null?void 0:D.getBoundingClientRect();if(!P)return;const $=S.clientX-P.left,T=S.clientY-P.top;p&&x.current.push({time:W($),value:j(T)});const C=[...E].sort((V,Q)=>V.time-Q.time);let A=null;for(const V of C){const Q=L(V.time),J=I(V.value);if(Math.abs($-Q)<8&&Math.abs(T-J)<8){A=V.id;break}}w(A)},Z=()=>{if(!p)return;v(!1);const S=x.current;if(S.length===0)return;const P=ic({mode:m,cc:t,resolution:.02,smoothing:m==="pencil"?.3:0},S);P.length>0&&d.setEvents(e,[..._,...P]),x.current=[]},H=S=>{var C;const P=(C=f.current)==null?void 0:C.getBoundingClientRect();if(!P)return;const $=S.clientX-P.left,T=S.clientY-P.top;for(const A of E){const D=L(A.time),V=I(A.value);if(Math.abs($-D)<8&&Math.abs(T-V)<8){d.removeEvent(e,A.id);return}}d.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:j(T),time:W($)})},te=()=>{const P=Os(M,0,n,t,Math.ceil(n*20),120).map(($,T)=>({...$,id:Date.now()+T}));d.setEvents(e,[..._,...P]),k(!1)},B=()=>{const S=d.exportLane(e),P=new Blob([S],{type:"application/json"}),$=URL.createObjectURL(P),T=document.createElement("a");T.href=$,T.download=`cc-lane-${t}-layer-${e}.json`,document.body.appendChild(T),T.click(),T.remove(),URL.revokeObjectURL($)},z=S=>{var $;const P=($=S.target.files)==null?void 0:$[0];P&&(P.text().then(T=>{d.importLane(e,T)}),R.current&&(R.current.value=""))};return s.jsxs("div",{className:"card p-3 mb-3",style:{background:"#0d1117",color:"#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:"#58a6ff"},children:h("ccLane.title","CC Automation Lane")}),s.jsx("select",{className:"form-select form-select-sm",style:{width:160,background:"#161b22",color:"#e6edf3",border:"1px solid #30363d"},value:t,onChange:S=>o(Number(S.target.value)),children:uc.map(S=>s.jsxs("option",{value:S.cc,children:[S.label," (CC",S.cc,")"]},S.cc))}),s.jsx("div",{className:"btn-group btn-group-sm",children:["pencil","line","curve","step","ramp"].map(S=>s.jsx("button",{className:`btn ${m===S?"btn-primary":"btn-outline-secondary"}`,onClick:()=>g(S),style:{fontSize:11,textTransform:"capitalize"},children:S},S))}),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(!y),title:"Apply LFO modulation",children:"LFO"}),s.jsx("button",{className:"btn btn-sm btn-outline-warning",onClick:B,title:"Export CC lane as JSON",children:"Export"}),s.jsx("button",{className:"btn btn-sm btn-outline-success",onClick:()=>{var S;return(S=R.current)==null?void 0:S.click()},title:"Import CC lane from JSON",children:"Import"}),s.jsx("input",{ref:R,type:"file",accept:".json",style:{display:"none"},onChange:z}),s.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:()=>d.setEvents(e,_.filter(S=>S.cc!==t)),title:"Clear all CC events for this lane",children:"Clear"}),s.jsxs("span",{style:{fontSize:11,color:"#8b949e",marginLeft:"auto"},children:[E.length," ",h("ccLane.events","events")]})]}),y&&s.jsx("div",{className:"mb-2 p-2",style:{background:"#161b22",borderRadius:6,border:"1px solid #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:"#0d1117",color:"#e6edf3",border:"1px solid #30363d"},value:M.waveform,onChange:S=>N(P=>({...P,waveform:S.target.value})),children:["sine","triangle","sawtooth","square","random","sample-hold"].map(S=>s.jsx("option",{value:S,children:S},S))})]}),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:"#0d1117",color:"#e6edf3",border:"1px solid #30363d"},min:.01,max:20,step:.1,value:M.rate,onChange:S=>N(P=>({...P,rate:Number(S.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:S=>N(P=>({...P,depth:Number(S.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:S=>N(P=>({...P,center:Number(S.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:f,width:U,height:xr+rn*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:"#8b949e",marginTop:4},children:h("ccLane.hint","Click to draw. Double-click to add/remove points. Drag to draw curves.")})]})},Bs={"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},Ar={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function hc(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 Gs(e,t){if(e.length===0)return[];const n=hc(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 fc(e,t,n,r=0,a=1){const o=Gs(e,t);if(o.length===0)return[];const i=60/n,l=Bs[t.rate]*i,c=l*t.gate,d=[],h=t.mode==="chord",f=h?a:o.length*a;for(let m=0;m<f;m++){const g=m%2===1?l*t.swing*.5:0,p=r+m*l+g;if(h)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 Ws(){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 Us(){return Object.keys(Bs)}const Vs=({config:e=Ar,onChange:t=()=>{},active:n=!1,onToggleActive:r=()=>{}})=>{const{t:a}=xe(),o=Ws(),i=Us(),l=c=>t({...e,...c});return s.jsxs("div",{className:"card p-3 mb-3",style:{background:"#0d1117",color:"#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:"#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(Ar),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:"#161b22",color:"#e6edf3",border:"1px solid #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)})})]})]})]})},pc=["sine","triangle","sawtooth","square","random","sample-hold"],mc=["1/1","1/2","1/4","1/8","1/16","1/32"],an=200,Dt=48,qs=({config:e,onChange:t,index:n,onRemove:r})=>{const{t:a}=xe(),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,an,Dt),d.fillStyle="#161b22",d.fillRect(0,0,an,Dt),d.strokeStyle="rgba(255,255,255,0.1)",d.lineWidth=1,d.setLineDash([3,3]),d.beginPath(),d.moveTo(0,Dt/2),d.lineTo(an,Dt/2),d.stroke(),d.setLineDash([]);const h=_s(e,an,Dt);if(h.length>0){d.beginPath(),d.strokeStyle=e.enabled?"#3b82f6":"#484f58",d.lineWidth=1.5;for(let f=0;f<h.length;f++){const m=h[f].x,g=h[f].y;f===0?d.moveTo(m,g):d.lineTo(m,g)}d.stroke()}},[e]);return u.useEffect(()=>{l()},[l]),s.jsxs("div",{className:"card p-2 mb-2",style:{background:"#0d1117",color:"#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:"#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(ir()),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:an,height:Dt,style:{borderRadius:4,border:"1px solid #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:pc.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:"#161b22",color:"#e6edf3",border:"1px solid #30363d",fontSize:11},value:e.syncDivision??"1/4",onChange:c=>i({syncDivision:c.target.value}),children:mc.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:"#161b22",color:"#e6edf3",border:"1px solid #30363d",fontSize:11},min:0,max:127,value:e.targetCC??1,onChange:c=>i({targetCC:Number(c.target.value)})})]})]})]})]})]})},gc=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function yc(e){const t=Math.floor(e/12)-1;return`${gc[e%12]}${t}`}const Hs=({seq:e,steps:t,tracks:n,bpm:r,pattern:a,onChange:o})=>{const{t:i}=xe();if(!e)return s.jsxs("div",{className:"card p-3 mb-3",style:{background:"#0d1117",color:"#e6edf3",borderRadius:8},children:[s.jsx("h6",{className:"mb-0",style:{color:"#58a6ff"},children:i("stepSeq.title","Step Sequencer")}),s.jsx("small",{style:{color:"#8b949e"},children:"Provide a `seq` prop (useStepSequencer) for live editing."})]});const{pattern:l,currentStep:c,playing:d}=e,h=u.useMemo(()=>l.steps.slice(0,l.length),[l]);return s.jsxs("div",{className:"card p-3 mb-3",style:{background:"#0d1117",color:"#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:"#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:"#161b22",color:"#e6edf3",border:"1px solid #30363d"},min:20,max:300,value:l.bpm,onChange:f=>e.setBpm(Number(f.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:f=>e.setSwing(Number(f.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(f=>s.jsx("button",{className:`btn ${l.length===f?"btn-primary":"btn-outline-secondary"}`,onClick:()=>e.setLength(f),style:{fontSize:11},children:f},f))})]}),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:h.map((f,m)=>{const g=f.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?"#8b949e":"#30363d"},children:m+1}),s.jsx("button",{onClick:()=>e.toggle(m),style:{width:32,height:32,borderRadius:4,border:p?"2px solid #f0c040":"1px solid #30363d",background:g?`hsl(${210+f.velocity/127*40}, 80%, ${35+f.velocity/127*20}%)`:v?"#21262d":"#161b22",cursor:"pointer",padding:0,color:g?"#fff":"#484f58",fontSize:8,fontWeight:600,transition:"background 0.1s"},children:g?yc(f.note):""}),s.jsx("div",{style:{width:32,height:20,background:"#161b22",borderRadius:2,position:"relative",overflow:"hidden"},children:s.jsx("div",{style:{position:"absolute",bottom:0,left:0,width:"100%",height:`${f.velocity/127*100}%`,background:g?"rgba(59, 130, 246, 0.6)":"rgba(59, 130, 246, 0.15)",borderRadius:2,cursor:"ns-resize"},title:`Vel: ${f.velocity}`,onMouseDown:x=>{x.preventDefault();const b=x.target.parentElement.getBoundingClientRect(),w=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)},y=()=>{document.removeEventListener("mousemove",w),document.removeEventListener("mouseup",y)};document.addEventListener("mousemove",w),document.addEventListener("mouseup",y)}})}),g&&f.probability<1&&s.jsxs("span",{style:{fontSize:8,color:"#f0c040"},children:[Math.round(f.probability*100),"%"]})]},m)})})}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:6},children:i("stepSeq.hint","Click steps to toggle. Drag velocity bars vertically.")})]})},bc="_panelNarrow_se2i3_3",vc="_panelWide_se2i3_9",xc="_smallLabel_se2i3_19",Sc="_noteText_se2i3_29",wc="_buttonRow_se2i3_41",Cc="_noteTextMargin_se2i3_49",kc="_rangeW100_se2i3_63",Mc="_zoomValue_se2i3_69",jc="_selectW100_se2i3_77",Rc="_inputW70_se2i3_83",$c="_masterVolGroup_se2i3_93",Tc="_rangeW140_se2i3_99",Pc="_volumeValue_se2i3_105",Ec="_selectW140_se2i3_115",Ac="_freqGroup_se2i3_121",Nc="_freqValue_se2i3_127",Ic="_narrowGroup_se2i3_137",Lc="_rangeW120_se2i3_143",Fc="_smallValue_se2i3_149",Dc="_presetDivider_se2i3_159",Oc="_presetLabel_se2i3_165",_c="_presetBtn_se2i3_175",zc="_deletePresetSelect_se2i3_183",Bc="_presetNameInput_se2i3_191",Gc="_savePresetBtn_se2i3_199",Wc="_countInAlert_se2i3_211",Uc="_inputW80_se2i3_219",Vc="_levelLabel_se2i3_225",qc="_levelMeter_se2i3_233",Hc="_levelBar_se2i3_249",pe={panelNarrow:bc,panelWide:vc,smallLabel:xc,noteText:Sc,buttonRow:wc,noteTextMargin:Cc,rangeW100:kc,zoomValue:Mc,selectW100:jc,inputW70:Rc,masterVolGroup:$c,rangeW140:Tc,volumeValue:Pc,selectW140:Ec,freqGroup:Ac,freqValue:Nc,narrowGroup:Ic,rangeW120:Lc,smallValue:Fc,presetDivider:Dc,presetLabel:Oc,presetBtn:_c,deletePresetSelect:zc,presetNameInput:Bc,savePresetBtn:Gc,countInAlert:Wc,inputW80:Uc,levelLabel:Vc,levelMeter:qc,levelBar:Hc},Ks=({autoSaveMode:e,setAutoSaveMode:t,autoSaveInterval:n,setAutoSaveInterval:r})=>{const{t:a}=xe();return s.jsxs("div",{className:`card p-3 mb-3 ${pe.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:pe.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.")]})]})},Ys=({undoCount:e,redoCount:t,onUndo:n,onRedo:r})=>{const{t:a}=xe();return s.jsxs("div",{className:`card p-3 mb-3 ${pe.panelNarrow}`,children:[s.jsx("h6",{className:"mb-2",children:a("editorPanels.changeHistory","Project change history")}),s.jsxs("div",{className:pe.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:pe.noteTextMargin,children:a("editorPanels.undoRedoNote","Undo/Redo works on the entire project (all editor changes). After each change Redo is cleared.")})]})},Zs=({zoom:e,setZoom:t,uiZoom:n,setUiZoom:r,snapEnabled:a,onToggleSnap:o,snapMode:i,onSnapModeChange:l,bpm:c,setBpm:d})=>{const{t:h}=xe();return s.jsx("div",{className:`card p-2 mb-3 ${pe.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 ${pe.smallLabel}`,children:"Zoom:"}),s.jsx("input",{type:"range",min:"0.5",max:"5",step:"0.1",value:e,onChange:f=>t(Number(f.target.value)),className:pe.rangeW100}),s.jsxs("span",{className:pe.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 ${pe.smallLabel}`,children:"Zoom UI:"}),s.jsx("input",{type:"range",min:"1",max:"4",step:"0.1",value:n,onChange:f=>r(Number(f.target.value)),className:pe.rangeW100}),s.jsxs("span",{className:pe.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 ${pe.smallLabel}`,children:"Snap"})]}),a&&s.jsxs("select",{className:`form-select form-select-sm ${pe.selectW100}`,value:i,onChange:f=>l(f.target.value),children:[s.jsx("option",{value:"bar",children:h("editorPanels.snapBar","Bar")}),s.jsx("option",{value:"beat",children:h("editorPanels.snapBeat","Beat")}),s.jsx("option",{value:"sub-beat",children:h("editorPanels.snap16","1/16")}),s.jsx("option",{value:"second",children:h("editorPanels.snapSecond","Second")})]}),s.jsxs("div",{className:"d-flex align-items-center gap-2",children:[s.jsx("label",{className:`form-label mb-0 ${pe.smallLabel}`,children:"BPM:"}),s.jsx("input",{type:"number",className:`form-control form-control-sm ${pe.inputW70}`,value:c,onChange:f=>d(Number(f.target.value)),min:"20",max:"300"})]})]})})},Xs=({masterVolume:e,onMasterVolumeChange:t,filterType:n,filterFreq:r,filterQ:a,filterGain:o,onFilterChange:i,masterEQPresets:l,customPresets:c,onLoadPreset:d,onSavePreset:h,onDeletePreset:f})=>{const{t:m}=xe();return s.jsxs("div",{className:`card p-2 mb-3 ${pe.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 ${pe.masterVolGroup}`,children:[s.jsx("label",{className:`form-label mb-0 ${pe.smallLabel}`,children:"Master Vol"}),s.jsx("input",{type:"range",min:"0",max:"1",step:"0.01",value:e,onChange:g=>t(Number(g.target.value)),className:pe.rangeW140}),s.jsxs("span",{className:pe.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 ${pe.smallLabel}`,children:"Filter"}),s.jsx("select",{className:`form-select form-select-sm ${pe.selectW140}`,value:n,onChange:g=>i({type:g.target.value}),children:["peaking","lowpass","highpass","lowshelf","highshelf","notch","bandpass"].map(g=>s.jsx("option",{value:g,children:g},g))})]}),s.jsxs("div",{className:`d-flex align-items-center gap-2 ${pe.freqGroup}`,children:[s.jsx("span",{className:pe.smallLabel,children:"Freq"}),s.jsx("input",{type:"range",min:"40",max:"12000",step:"10",value:r,onChange:g=>i({frequency:Number(g.target.value)}),className:pe.rangeW140}),s.jsxs("span",{className:pe.freqValue,children:[Math.round(r)," Hz"]})]}),s.jsxs("div",{className:`d-flex align-items-center gap-2 ${pe.narrowGroup}`,children:[s.jsx("span",{className:pe.smallLabel,children:"Q"}),s.jsx("input",{type:"range",min:"0.1",max:"12",step:"0.1",value:a,onChange:g=>i({q:Number(g.target.value)}),className:pe.rangeW120}),s.jsx("span",{className:pe.smallValue,children:a.toFixed(1)})]}),(n==="peaking"||n==="lowshelf"||n==="highshelf")&&s.jsxs("div",{className:`d-flex align-items-center gap-2 ${pe.narrowGroup}`,children:[s.jsx("span",{className:pe.smallLabel,children:"Gain"}),s.jsx("input",{type:"range",min:"-18",max:"18",step:"0.5",value:o,onChange:g=>i({gain:Number(g.target.value)}),className:pe.rangeW120}),s.jsxs("span",{className:pe.smallValue,children:[o.toFixed(1)," dB"]})]})]}),s.jsxs("div",{className:`mt-2 pt-2 ${pe.presetDivider}`,children:[s.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[s.jsxs("span",{className:pe.presetLabel,children:[m("editorPanels.eqPresets","EQ Presets"),":"]}),[...l,...c].map(g=>s.jsx("button",{className:`btn btn-sm btn-outline-secondary ${pe.presetBtn}`,onClick:()=>d(g),children:g.name},g.name)),c.length>0&&s.jsxs("select",{className:`form-select form-select-sm ${pe.deletePresetSelect}`,onChange:g=>{g.target.value&&(f(g.target.value),g.target.value="")},defaultValue:"",children:[s.jsx("option",{value:"",children:m("editorPanels.deletePreset","Delete preset...")}),c.map(g=>s.jsx("option",{value:g.name,children:g.name},g.name))]})]}),s.jsxs("div",{className:"d-flex align-items-center gap-2",children:[s.jsx("input",{type:"text",className:`form-control form-control-sm ${pe.presetNameInput}`,placeholder:m("editorPanels.presetName","Preset name..."),id:"presetNameInput"}),s.jsx("button",{className:`btn btn-sm btn-success ${pe.savePresetBtn}`,onClick:()=>{const g=document.getElementById("presetNameInput");g!=null&&g.value.trim()&&(h(g.value.trim()),g.value="")},children:m("editorPanels.saveCurrent","Save Current")})]})]})]})},Qs=({countInBars:e,setCountInBars:t,isCountIn:n,countInRemaining:r,overdubEnabled:a,setOverdubEnabled:o,punchIn:i,setPunchIn:l,punchOut:c,setPunchOut:d,monitorLevel:h})=>{const{t:f}=xe();return s.jsx("div",{className:`card p-2 mb-3 ${pe.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 ${pe.smallLabel}`,children:[f("editorPanels.countIn","Count-in (bars)"),":"]}),s.jsx("input",{type:"number",min:"0",max:"8",step:"1",className:`form-control form-control-sm ${pe.inputW70}`,value:e,onChange:m=>t(Number(m.target.value))}),n&&s.jsxs("span",{className:pe.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 ${pe.smallLabel}`,children:f("editorPanels.overdub","Overdub (play background)")})]}),s.jsxs("div",{className:"d-flex align-items-center gap-1",children:[s.jsx("span",{className:pe.smallLabel,children:"Punch In"}),s.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${pe.inputW80}`,value:i??"",onChange:m=>l(m.target.value===""?null:Number(m.target.value))}),s.jsx("span",{className:pe.smallLabel,children:"s"})]}),s.jsxs("div",{className:"d-flex align-items-center gap-1",children:[s.jsx("span",{className:pe.smallLabel,children:"Punch Out"}),s.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${pe.inputW80}`,value:c??"",onChange:m=>d(m.target.value===""?null:Number(m.target.value))}),s.jsx("span",{className:pe.smallLabel,children:"s"})]}),s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>{l(null),d(null)},children:f("editorPanels.clearPunch","Clear punch")}),s.jsx("div",{className:pe.levelLabel,children:"Level"}),s.jsx("div",{className:pe.levelMeter,children:s.jsx("div",{className:pe.levelBar,style:{width:`${Math.min(1,h*2)*100}%`,background:h>.7?"#f44336":"#4caf50"}})})]})})};function Kc(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 Yc(e,t,n){const r=u.useRef(null),[a,o]=u.useState(!1),[i,l]=u.useState(0),[c,d]=u.useState(10),[h,f]=u.useState(!1),[m,g]=u.useState(120),p=u.useCallback((R,_)=>`L${R}-C${_}`,[]),v=u.useCallback((R,_)=>{if(!r.current||!_.audioBuffer)return;const E=p(R,_.id),U=e[R];r.current.addClip({id:E,buffer:_.audioBuffer,startTime:_.start,offset:0,duration:_.duration,layerId:R,volume:(U==null?void 0:U.volume)??1,pan:(U==null?void 0:U.pan)??0,stretchFactor:_.stretchFactor||1,effectChain:(U==null?void 0:U.effectChain)||[]})},[e,p]),x=u.useCallback((R,_)=>{var E;(E=r.current)==null||E.removeClip(p(R,_))},[p]);u.useEffect(()=>{Object.entries(t).forEach(([R,_])=>{const E=Number(R);_==null||_.forEach(U=>v(E,U))})},[t,e,v]),u.useEffect(()=>{r.current&&Object.entries(n).forEach(([R,_])=>{const E=Number(R);r.current.setMidiCCEvents(E,_)})},[n]);const b=u.useCallback(()=>{r.current&&(a?r.current.pause():r.current.play())},[a]),w=u.useCallback(()=>{var R;(R=r.current)==null||R.stop()},[]),y=u.useCallback(R=>{var _;(_=r.current)==null||_.seek(R)},[]),k=u.useCallback(()=>{if(!r.current)return;const R=!h;f(R),r.current.setLoopRegion(0,c,R)},[h,c]),M=u.useCallback(R=>{var E;const _=Math.max(1,c+R);d(_),(E=r.current)==null||E.setLoopRegion(0,_,h)},[c,h]),N=u.useCallback(async(R,_=1024)=>{const E=await R.arrayBuffer(),U=new(window.AudioContext||window.webkitAudioContext),W=await U.decodeAudioData(E.slice(0)),j=W.getChannelData(0),L=j.length,I=Math.max(1,Math.floor(L/_)),q=[];for(let Y=0;Y<_;Y++){const O=Y*I;if(O>=L)break;q.push(j[O])}return U.close(),{waveform:q.map(Y=>Math.max(-1,Math.min(1,Y))),duration:W.duration,buffer:W}},[]);return{engineRef:r,isPlaying:a,setIsPlaying:o,currentTime:i,setCurrentTime:l,duration:c,setDuration:d,isLooping:h,setIsLooping:f,bpm:m,setBpm:g,handlePlayPause:b,handleStop:w,handleSeek:y,handleToggleLoop:k,handleAdjustDuration:M,upsertEngineClip:v,removeEngineClip:x,makeEngineClipId:p,blobToWaveform:N}}class Js{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 h=(i[d]-128)/128;l+=h*h}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 Zc(e){const[t,n]=u.useState(!1),[r,a]=u.useState(!1),[o,i]=u.useState(0),[l,c]=u.useState(0),[d,h]=u.useState(null),f=u.useRef(null),m=u.useRef(null),g=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||(f.current||(f.current=new Js),g.current=m.current??e.currentTime,n(!0),i(0),await f.current.startRecording({onLevel:i}))},[e,t]),w=u.useCallback(async()=>{var j;if(x(),a(!1),c(0),m.current=null,!f.current){n(!1),i(0);return}const M=await f.current.stopRecording();if(n(!1),i(0),!M||!e.activeLayer)return;const{waveform:N,duration:R,buffer:_}=await e.blobToWaveform(M),E=e.activeLayer.id;e.setWaveforms(L=>({...L,[E]:N}));const U=Math.max(0,g.current||0),W={id:Date.now(),label:"Recording",start:U,duration:R,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:(j=e.layerSettings[E])==null?void 0:j.color,blob:M,blobUrl:URL.createObjectURL(M),audioBuffer:_};e.setLayerClips(L=>({...L,[E]:[...L[E]||[],W]})),e.upsertEngineClip(E,W),e.setSelectedClip({layerId:E,clipId:W.id})},[e,x]),y=u.useCallback(M=>{if(M<=0){b();return}a(!0),c(M);const N=performance.now();p.current=window.setInterval(()=>{const R=(performance.now()-N)/1e3;c(Math.max(0,M-R))},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 w();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&&y(M):y(M)},[t,r,e,w,y]);return{isRecording:t,isCountIn:r,monitorLevel:o,countInRemaining:l,punchOut:d,setPunchOut:h,armedPunchInRef:m,recorderRef:f,clearCountInTimers:x,startRecordingNow:b,stopRecordingFlow:w,handleRecord:k}}var eo=(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))(eo||{});const Xc={};class En{constructor(t,n,r,a={}){this.type=t,this.name=n,this.component=Xc[t]??(()=>null),this.audioType=r,this.parameters=a}}new En("Recorder","Recorder","vocal",{deviceId:"",gain:1,sensitivity:"high"}),new En("Audio Clip","Audio Clip","instrumental",{clipId:null,octave:"4"}),new En("Speech Synth","Speech Synth","vocal",{text:"",voice:"default"}),new En("Keyboard/Pads","Keyboard","instrumental",{instrument:"piano",preset:"default",velocity:100});function to(e,t,n,r,a){n(o=>t?[...o,t]:o),r([]),a(e)}function Qc(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 Jc(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 ed{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 td=et.scoped("useProjectCRUD");function nd(e){const{project:t,activeSection:n,setProject:r,setActiveSection:a,setLayers:o,setActiveLayer:i,setUndoStack:l,setRedoStack:c}=e,d=u.useCallback(x=>to(x,t,l,c,r),[t,l,c,r]),h=u.useCallback(async()=>{var y;if(!t)return;const x=(((y=t.sections)==null?void 0:y.length)??0)+1,w={id:await e.addSection(t.id,"Section",x),projectId:t.id,name:"Section",orderNumber:x,layers:[]};d({...t,sections:[...t.sections||[],w]}),a(w)},[t,d,a]),f=u.useCallback(async x=>{var y,k,M;if(!t||!await e.confirm("Delete this section?"))return;await e.deleteSection(x);const w=(t.sections??[]).filter(N=>N.id!==x);d({...t,sections:w}),a(w[0]??null),o(((y=w[0])==null?void 0:y.layers)??[]),i(((M=(k=w[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:eo.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};o(w=>[...w,x]),i(x);try{const w=await e.addLayer(n.id,x.name,x.audioSource,x.audioSourceParameters);o(y=>y.map(k=>k.id===x.id?{...x,id:w}:k)),t&&d({...t,sections:((b=t.sections)==null?void 0:b.map(y=>y.id===n.id?{...y,layers:[...(y.layers??[]).filter(k=>k.id!==w),{...x,id:w}]}:y))??[]})}catch(w){o(y=>y.filter(k=>k.id!==x.id)),td.error("Failed to add layer:",w)}},[n,t,d,o,i]),g=u.useCallback(async x=>{var w,y;if((w=e.layerSettings[x])!=null&&w.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:((y=t.sections)==null?void 0:y.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 w;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:((w=t.sections)==null?void 0:w.map(y=>y.id===n.id?{...y,name:x,orderNumber:b}:y))??[]}),e.setStatusType("success"),e.setStatusMessage("Section saved")},[n,t,e,d,a]);return{handleAddSection:h,handleDeleteSection:f,handleAddLayer:m,handleDeleteLayer:g,handleSaveProject:p,handleSaveSection:v}}const no=u.createContext(null);function rd(){const e=u.useContext(no);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const Qr=({value:e,children:t})=>s.jsx(no.Provider,{value:e,children:t});Qr.displayName="EditorTrackProvider";const Ht=(e,t)=>t&&t>0?e*15/t:e/10,Jr=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},ad=(e,t)=>{const n=t??Jr(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 h=d.indexOf(" "),f=d.indexOf(" ",h+1),m=d.indexOf(" ",f+1),g=d.indexOf(" ",m+1);if(g===-1)return;const p=Ht(parseFloat(d.substring(h+1,f)),n);a===""&&(o=p);const v=d.substring(g+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},sd=(e,t)=>{const n=t??Jr(e),r=[];let a=[],o="",i=0,l=!0,c=null,d="";function h(){c&&d.trim()!==""&&(c.text=d.trim(),a.push({...c}),o.length>0&&(o+=" "),o+=c.text),c=null,d=""}return e.forEach(f=>{if(!(f.startsWith("#")||f.startsWith("E"))){if(f.startsWith("-"))h(),o.trim().length>0&&(r.push({text:o.trim(),timestamp:i,words:a}),o="",a=[]),l=!0;else if(f.startsWith(":")||f.startsWith("*")){const m=f.startsWith("*"),g=f.indexOf(" "),p=f.indexOf(" ",g+1),v=f.indexOf(" ",p+1),x=f.indexOf(" ",v+1);if(x===-1)return;const b=Ht(parseFloat(f.substring(g+1,p)),n),w=Ht(parseFloat(f.substring(p+1,v)),n),y=b+w;o===""&&(i=b);const k=f.substring(x+1);if(k.trim()==="~"){c&&(c.endTime=y);return}let M=k;M.startsWith("~")&&(M=M.substring(1)),l?(h(),d=M.trimEnd(),c={text:"",startTime:b,endTime:y,isGolden:m}):c?(d+=M.trimEnd(),c.endTime=y,m&&(c.isGolden=!0)):(d=M.trimEnd(),c={text:"",startTime:b,endTime:y,isGolden:m}),l=k.endsWith(" ")}}}),h(),o.trim().length>0&&r.push({text:o.trim(),timestamp:i,words:a}),r},ro=(e,t)=>{const n=t??Jr(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=Ht(d,n))}}else if(l.startsWith(":")||l.startsWith("*")){const c=l.startsWith("*"),d=l.indexOf(" "),h=l.indexOf(" ",d+1),f=l.indexOf(" ",h+1),m=l.indexOf(" ",f+1);if(m===-1)return;const g=parseFloat(l.substring(d+1,h)),p=parseFloat(l.substring(h+1,f)),v=Ht(g,n),x=v+Ht(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 w=b;w.startsWith("~")&&(w=w.substring(1));const y=b.endsWith(" "),k=y?w.slice(0,-1):w;a.push({text:k,startTime:v,endTime:x,isGolden:c,hasTrailingSpace:y})}}}),i(),r},od=(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},id=(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},Oa="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",_a="var(--karaoke-gold-glow-first, 0 0 12px #FFD700)",ld="var(--karaoke-active-glow, 0 0 10px rgba(0,229,255,0.6), 0 0 4px rgba(255,230,0,0.4))",cd="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",dd=({song:e,currentTime:t})=>{const n=u.useMemo(()=>!e||!e.notes.length?[]:ro(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:ld,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 h=Math.round(d*100),f=l.text+(l.hasTrailingSpace?" ":""),m=d>0&&d<1,g=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:f},c):d>=1?s.jsx("span",{style:{background:g?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Oa,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:g?`drop-shadow(${_a})`:"none",transition:"filter 0.2s ease"},children:f},c):s.jsxs("span",{style:{position:"relative",display:"inline",filter:m?g?`drop-shadow(${_a})`:`drop-shadow(${cd})`:"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:f}),s.jsx("span",{style:{position:"absolute",left:0,top:0,background:g?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Oa,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",clipPath:`inset(0 ${100-h}% 0 0)`,pointerEvents:"none"},children:f})]},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..."})})},ao=u.memo(dd),Sr={},ud=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:st&&st.tagName.toUpperCase()==="SCRIPT"&&st.src||new URL("index.cjs",document.baseURI).href}<"u"&&(Sr==null?void 0:Sr.VITE_DEBUG_KARAOKE)==="true";function Nr(e,t,...n){(ud||typeof window<"u"&&window.DEBUG_KARAOKE)&&console.log(`%c[KARAOKE-DEBUG]%c [${e}] ${t}`,"background:#6c3483;color:#fff;padding:1px 4px;border-radius:3px;font-weight:bold","color:#6c3483;font-weight:bold",...n)}const so=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},za=(e,t)=>t&&t>0?e*15/t:e/10,ea=(e,t)=>{const n=t??so(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:za(parseFloat(i[1]),n),duration:za(parseFloat(i[2]),n),pitch:parseInt(i[3],10),isGold:c})}}),a.length>0&&r.push(a),r},oo=(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},hd=et.scoped("karaokeScoringConfig"),ta={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}},fd="karaoke.scoringPresets";function pd(){try{const e=localStorage.getItem(fd);return e?JSON.parse(e):null}catch(e){return hd.warn("Failed to parse scoring presets overrides",e),null}}function io(e){const t={...ta},n=pd();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=io();const md=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=io(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},lo=(e="normal")=>exports.ScoringPresets[e]||ta.normal;function Ir(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 gd(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 yd=3,G=yd;function $t(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} ${G}V${e-G}A${t-G} ${t-G} 0 0 1 ${G} ${t}A${t-G} ${t-G} 0 0 1 ${t} ${G}Z`}}function Kt(e){return{w:G+1,out:`M0 0H${G+1}V${e}H0Z`,inn:`M${G} ${G}H${G+1}V${e-G}H${G}Z`}}function na(e){const t=Math.min(14,e*.22)|0,n=t+2,r=Math.max(t-G,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${G+r} ${G}H${n}V${e-G}H${G+r}Q${G} ${e-G} ${G} ${e-G-r}V${G+r}Q${G} ${G} ${G+r} ${G}Z`}}function Qn(e){const t=e*.3|0,n=t+2,r=Math.max(t-G,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e-t}V${t}Z`,inn:`M${G+r} ${G}H${n}V${e-G}H${G+r}L${G} ${e-G-r}V${G+r}Z`}}function Mt(e){const t=e*.42|0,n=t+2,r=Math.max(t-(G*1.4|0),2);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e/2}Z`,inn:`M${G+r} ${G}H${n}V${e-G}H${G+r}L${G} ${e/2}Z`}}function Jn(e){const t=e*.3|0,n=t+4,r=Math.max(t-G,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${G+r} ${G}H${n}V${e-G}H${G+(r*.6|0)}L${G} ${e-G-r}V${G+r}Q${G} ${G} ${G+r} ${G}Z`}}function ra(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${G+(t*1.2|0)} ${G}H${n}V${e-G}H${G+(t*1.2|0)}C${G+(t*2.2|0)} ${e*.37|0} ${G+(t*2.2|0)} ${e*.63|0} ${G+(t*1.2|0)} ${e-G}Z`}}function aa(e){const t=e*.32|0,n=t+3,r=Math.max(t-G,1);return{w:n,out:`M0 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}Z`,inn:`M${G} ${G}H${n}V${e-G}H${G+r}Q${G} ${e-G} ${G} ${e-G-r}Z`}}function er(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${G+(t*1.8|0)} ${G}H${n}V${e-G}H${G+(t*1.8|0)}C${G+(t*.4|0)} ${e*.78|0} ${G+(t*2.8|0)} ${e*.55|0} ${G+(t*.4|0)} ${e*.37|0}S${G+(t*.9|0)} ${G} ${G+(t*1.8|0)} ${G}Z`}}function sa(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${G+(t*2.5|0)} ${G}H${n}V${e-G}H${G+(t*2.5|0)}L${G+(t*.7|0)} ${e-G-(t*1.6|0)}L${G+(t*1.7|0)} ${e*.64|0}L${G} ${e/2|0}L${G+(t*1.7|0)} ${e*.36|0}L${G+(t*.7|0)} ${G+(t*1.6|0)}Z`}}function Un(e){const t=e*.42|0,n=t+2;return{w:n,out:`M${t} 0H${n}V${e}H0Z`,inn:`M${G+t-(G*1.3|0)} ${G}H${n}V${e-G}H${G+1}Z`}}function Lr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}V${e}H${t}Z`,inn:`M${G} ${G}H${n}V${e-G}H${G+t-(G*1.3|0)+1}Z`}}function Ct(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 ${G}A${t-G} ${t-G} 0 0 1 ${t-G} ${t}A${t-G} ${t-G} 0 0 1 0 ${e-G}Z`}}function Yt(e){return{w:G+1,out:`M0 0H${G+1}V${e}H0Z`,inn:`M0 ${G}H1V${e-G}H0Z`}}function co(e){const t=Math.min(14,e*.22)|0,n=t+2,r=Math.max(t-G,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 ${G}H${n-G-r}Q${n-G} ${G} ${n-G} ${G+r}V${e-G-r}Q${n-G} ${e-G} ${n-G-r} ${e-G}H0Z`}}function Zt(e){const t=e*.3|0,n=t+2,r=Math.max(t-G,1);return{w:n,out:`M0 0H${n-t}L${n} ${t}V${e-t}L${n-t} ${e}H0Z`,inn:`M0 ${G}H${n-G-r}L${n-G} ${G+r}V${e-G-r}L${n-G-r} ${e-G}H0Z`}}function gt(e){const t=e*.42|0,n=t+2,r=Math.max(t-(G*1.4|0),2);return{w:n,out:`M0 0H${n-t}L${n} ${e/2}L${n-t} ${e}H0Z`,inn:`M0 ${G}H${n-G-r}L${n-G} ${e/2}L${n-G-r} ${e-G}H0Z`}}function uo(e){const t=e*.3|0,n=t+4,r=Math.max(t-G,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 ${G}H${n-G-r}Q${n-G} ${G} ${n-G} ${G+r}V${e-G-r}L${n-G-(r*.6|0)} ${e-G}H0Z`}}function ho(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 ${G}H${n-G-(t*1.2|0)}C${n-G-(t*2.2|0)} ${e*.37|0} ${n-G-(t*2.2|0)} ${e*.63|0} ${n-G-(t*1.2|0)} ${e-G}H0Z`}}function fo(e){const t=e*.32|0,n=t+3,r=Math.max(t-G,1);return{w:n,out:`M0 0H${n}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${G}H${n-G}V${e-G-r}Q${n-G} ${e-G} ${n-G-r} ${e-G}H0Z`}}function oa(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 ${G}H${n-G-(t*1.8|0)}C${n-G-(t*.9|0)} ${G} ${n-G+(t*.1|0)} ${e*.22|0} ${n-G-(t*.4|0)} ${e*.37|0}S${n-G-(t*.4|0)} ${e*.78|0} ${n-G-(t*1.8|0)} ${e-G}H0Z`}}function tr(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 ${G}H${n-G-(t*2.5|0)}L${n-G-(t*.7|0)} ${G+(t*1.6|0)}L${n-G-(t*1.7|0)} ${e*.36|0}L${n-G} ${e/2|0}L${n-G-(t*1.7|0)} ${e*.64|0}L${n-G-(t*.7|0)} ${e-G-(t*1.6|0)}L${n-G-(t*2.5|0)} ${e-G}H0Z`}}function Fr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}L${n-t} ${e}H0Z`,inn:`M0 ${G}H${n-G}L${n-G-t+(G*1.3|0)} ${e-G}H0Z`}}function Vn(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n-t}L${n} ${e}H0Z`,inn:`M0 ${G}H${n-G-t+(G*1.3|0)}L${n-G} ${e-G}H0Z`}}const ia=[{name:"Pill",L:$t,R:Ct},{name:"Sharp",L:Kt,R:Yt},{name:"Soft",L:na,R:co},{name:"Chamfer",L:Qn,R:Zt},{name:"Arrow",L:Mt,R:gt},{name:"Shield",L:Jn,R:uo},{name:"Bracket",L:ra,R:ho},{name:"Tab",L:aa,R:fo},{name:"Wave",L:er,R:oa},{name:"Ornate",L:sa,R:tr}],po=[{name:"Pill→Arrow",L:$t,R:gt},{name:"Arrow→Pill",L:Mt,R:Ct},{name:"Pill→Sharp",L:$t,R:Yt},{name:"Sharp→Pill",L:Kt,R:Ct},{name:"Pill→Chamfer",L:$t,R:Zt},{name:"Chamfer→Pill",L:Qn,R:Ct},{name:"Arrow→Sharp",L:Mt,R:Yt},{name:"Sharp→Arrow",L:Kt,R:gt},{name:"Arrow→Chamfer",L:Mt,R:Zt},{name:"Chamfer→Arrow",L:Qn,R:gt},{name:"Soft→Arrow",L:na,R:gt},{name:"Shield→Chamfer",L:Jn,R:Zt},{name:"Pill→Wave",L:$t,R:oa},{name:"Wave→Arrow",L:er,R:gt},{name:"Tab→Pill",L:aa,R:Ct},{name:"Ornate→Sharp",L:sa,R:Yt},{name:"Sharp→Ornate",L:Kt,R:tr},{name:"Bracket→Arrow",L:ra,R:gt},{name:"Shield→Pill",L:Jn,R:Ct},{name:"Wave→Ornate",L:er,R:tr}],mo=[{name:"Skew ╲",L:Un,R:Fr},{name:"Skew ╱",L:Lr,R:Vn},{name:"◇ Romb",L:Mt,R:gt},{name:"╲→Pill",L:Un,R:Ct},{name:"Pill→╲",L:$t,R:Fr},{name:"╱→Sharp",L:Lr,R:Yt},{name:"Sharp→╱",L:Kt,R:Vn},{name:"╲→Arrow",L:Un,R:gt},{name:"Arrow→╱",L:Mt,R:Vn},{name:"◇→Chamfer",L:Mt,R:Zt}],Cn=[...ia,...po,...mo],go=ia[0];function dn(e){return Cn.find(t=>t.name===e)||go}const nr=[{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 un(e){return nr.find(t=>t.name===e)||null}const At={color:null,capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,glass:0,textureUrl:null,textureScale:1},lr={...At,glass:85},cr={...At,patternName:"Stars"},dr={...At,patternName:"Stars"},ur={fontFamily:null,fontSize:18,fontColor:null,outlineColor:null,outlineWidth:0,shadow:null},yo={filledBar:{...At},emptyBar:{...lr},goldFilledBar:{...dr},goldEmptyBar:{...cr},font:{...ur},disableGoldNotes:!1},Xt={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},Ba="nice2dev-player-bar-style",Ga="nice2dev-player-karaoke-settings";function Qt(e){return e!=null?`${Ga}-${e}`:Ga}function Mn(e){return e!=null?`${Ba}-${e}`:Ba}function Wa(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 Ua(e){const t=yo,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 bo(e){try{const t=localStorage.getItem(Qt(e));if(t){const r=JSON.parse(t);return Ua(r)}const n=localStorage.getItem(Mn(e));if(n){const r=JSON.parse(n),a=Wa({...Xt,...r});return localStorage.setItem(Qt(e),JSON.stringify(a)),a}if(e!=null){const r=localStorage.getItem(Qt());if(r)return Ua(JSON.parse(r));const a=localStorage.getItem(Mn());if(a)return Wa({...Xt,...JSON.parse(a)})}}catch{}return{filledBar:{...At},emptyBar:{...lr},goldFilledBar:{...dr},goldEmptyBar:{...cr},font:{...ur}}}function bd(e,t){const n=JSON.stringify(e);localStorage.setItem(Qt(t),n)}let Va=!1;async function vd(e){if(Va||(Va=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(Qt())||localStorage.setItem(Qt(),t)}catch{}}function xd(e){const t=new Map;for(const n of e)t.set(n,bo(n));return t}function vo(e){try{const t=localStorage.getItem(Mn(e));if(t)return{...Xt,...JSON.parse(t)};if(e!=null){const n=localStorage.getItem(Mn());if(n)return{...Xt,...JSON.parse(n)}}}catch{}return{...Xt}}function Sd(e,t){localStorage.setItem(Mn(t),JSON.stringify(e))}function wd(e){const t=new Map;for(const n of e)t.set(n,vo(n));return t}const Cd={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},kd=/[&<>"']/g;function Md(e){return e.replace(kd,t=>Cd[t])}function jd(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 Rd=3,Be=Rd;function rr(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 ar(e){let t=e.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),"#"+t.toLowerCase()}function Qe(e,t){return e.replace(/([MLHVCSQTAZ])/gi,`
1
+ "use strict";var Tl=Object.create;var Na=Object.defineProperty;var Pl=Object.getOwnPropertyDescriptor;var El=Object.getOwnPropertyNames;var Al=Object.getPrototypeOf,Nl=Object.prototype.hasOwnProperty;var Il=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of El(t))!Nl.call(e,a)&&a!==n&&Na(e,a,{get:()=>t[a],enumerable:!(r=Pl(t,a))||r.enumerable});return e};var br=(e,t,n)=>(n=e!=null?Tl(Al(e)):{},Il(t||!e||!e.__esModule?Na(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),u=require("react"),Ve=require("react-bootstrap"),Pr=require("pitchy"),Ll=require("react-window"),Yr=require("react-youtube");var st=typeof document<"u"?document.currentScript:null;const Fl=(e,t)=>t??e,$s=u.createContext(Fl),Dl=({t:e,children:t})=>s.jsx($s.Provider,{value:e,children:t});function xe(){return{t:u.useContext($s)}}class Ol 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 vr={},Er={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function _l(){const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:st&&st.tagName.toUpperCase()==="SCRIPT"&&st.src||new URL("index.cjs",document.baseURI).href}<"u"?vr==null?void 0:vr.VITE_LOG_LEVEL:void 0;return e&&e in Er?e:"WARN"}const zl=_l();function $n(e){return Er[e]>=Er[zl]}function Tn(e){return`[${e}]`}const et={debug(e,t,...n){$n("DEBUG")&&console.debug(Tn(e),t,...n)},info(e,t,...n){$n("INFO")&&console.info(Tn(e),t,...n)},warn(e,t,...n){$n("WARN")&&console.warn(Tn(e),t,...n)},error(e,t,...n){$n("ERROR")&&console.error(Tn(e),t,...n)},scoped(e){return{debug:(t,...n)=>et.debug(e,t,...n),info:(t,...n)=>et.info(e,t,...n),warn:(t,...n)=>et.warn(e,t,...n),error:(t,...n)=>et.error(e,t,...n)}}},Ia=et.scoped("Waveform"),Gl=["audio/","video/"],Ts=({audioBlob:e,currentTime:t,duration:n,width:r=600,height:a=200,zoom:o=1,onSeek:i,onRegionSelect:l,markers:c=[],regions:d=[],displayMode:h="waveform",multiChannel:f=!1,waveColor:m="#007bff",progressColor:g="rgba(255,0,0,0.8)",backgroundColor:p="transparent",showRuler:v=!1,showChannelLabels:x=!0,showPeakMeter:b=!1,className:w})=>{const y=u.useRef(null),k=u.useRef(null),M=u.useRef(null),[N,R]=u.useState(0),[_,E]=u.useState(!1),[U,W]=u.useState(null),[j,L]=u.useState(null),[I,q]=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&&!Gl.some(z=>e.type.startsWith(z))&&Ia.warn("Unexpected blob MIME type:",e.type);let G=!1;return(async()=>{let z=null;try{const S=await e.arrayBuffer();if(S.byteLength===0||G)return;z=new AudioContext;const P=await z.decodeAudioData(S);G||(M.current=P)}catch(S){Ia.error("Failed to decode audio:",S)}finally{z==null||z.close().catch(()=>{})}})(),()=>{G=!0}},[e]),u.useEffect(()=>{if(o>1&&n>0){const G=t/n*Y;(G<N||G>N+r)&&R(Math.max(0,G-r/2))}},[t,n,o,r,Y,N]),u.useEffect(()=>{const G=y.current,z=M.current;if(!G||!n||n===1/0)return;const S=G.getContext("2d");if(!S)return;const P=Y,$=a;if(G.width=P,G.height=$+O,S.clearRect(0,0,P,$+O),p!=="transparent"&&(S.fillStyle=p,S.fillRect(0,0,P,$+O)),v){S.fillStyle="rgba(128,128,128,0.15)",S.fillRect(0,0,P,O),S.fillStyle="var(--nice-text-secondary, #888)",S.font="10px monospace",S.textAlign="center";const T=Math.max(1,Math.floor(n/(Y/80)));for(let C=0;C<=n;C+=T){const A=C/n*P;S.fillText(Vl(C),A,O-4),S.fillStyle="rgba(128,128,128,0.3)",S.fillRect(A,O,1,$),S.fillStyle="var(--nice-text-secondary, #888)"}}for(const T of d){const C=T.start/n*P,A=T.end/n*P;S.fillStyle=T.color??"var(--nice-accent-tint-15, rgba(99, 102, 241, 0.15))",S.fillRect(C,O,A-C,$),T.label&&(S.fillStyle=T.color??"var(--nice-info, #6366f1)",S.font="10px sans-serif",S.textAlign="left",S.fillText(T.label,C+2,O+12))}if(U!==null&&j!==null){const T=Math.min(U,j),C=Math.max(U,j);S.fillStyle="rgba(255,200,0,0.2)",S.fillRect(T,O,C-T,$)}if(z){const T=f?z.numberOfChannels:1,C=$/T;let A=0;for(let D=0;D<T;D++){const V=z.getChannelData(D),Q=O+D*C;if(h==="waveform"?Bl(S,V,P,C,Q,m):h==="bars"?Wl(S,V,P,C,Q,m):h==="spectrogram"&&Ul(S,V,P,C,Q,z.sampleRate),b&&n>0){const J=Math.floor(t/n*V.length),ae=Math.floor(z.sampleRate*.05);let re=0;for(let F=Math.max(0,J-ae);F<Math.min(V.length,J+ae);F++)re+=V[F]*V[F];const ee=Math.sqrt(re/(ae*2));A=Math.max(A,ee)}f&&x&&T>1&&(S.fillStyle="var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))",S.font="bold 11px sans-serif",S.textAlign="left",S.fillText(D===0?"L":D===1?"R":`Ch${D+1}`,4,Q+14))}q(A)}if(n>0){const T=Math.max(0,Math.min(t/n*P,P));S.beginPath(),S.strokeStyle=g,S.lineWidth=2,S.moveTo(T,O),S.lineTo(T,$+O),S.stroke()}for(const T of c){const C=T.time/n*P;S.beginPath(),S.strokeStyle=T.color??"var(--nice-warning, #f59e0b)",S.lineWidth=2,S.setLineDash([4,4]),S.moveTo(C,O),S.lineTo(C,$+O),S.stroke(),S.setLineDash([]),T.label&&(S.fillStyle=T.color??"var(--nice-warning, #f59e0b)",S.font="bold 10px sans-serif",S.textAlign="center",S.fillText(T.label,C,O+$-4))}},[e,M.current,t,n,Y,a,o,h,f,m,g,p,v,c,d,U,j,b,x,O]);const Z=u.useCallback(G=>{var P;if(!n)return;const z=(P=y.current)==null?void 0:P.getBoundingClientRect();if(!z)return;const S=G.clientX-z.left+N;E(!0),W(S),L(S)},[n,N]),H=u.useCallback(G=>{if(!_||!y.current)return;const z=y.current.getBoundingClientRect(),S=G.clientX-z.left+N;L(S)},[_,N]),te=u.useCallback(()=>{if(!_||U===null||j===null||!n){E(!1),W(null),L(null);return}const G=Math.min(U,j),z=Math.max(U,j),S=(z-G)/Y*n;if(E(!1),W(null),L(null),S<.2){const P=G/Y*n;i==null||i(P)}else{const P=G/Y*n,$=z/Y*n;l==null||l({start:P,end:$})}},[_,U,j,n,Y,i,l]);return s.jsxs("div",{ref:k,className:`nice-waveform${w?` ${w}`:""}`,style:{position:"relative",width:r,overflow:o>1?"auto":"hidden",cursor:i?"crosshair":"default"},onScroll:G=>R(G.target.scrollLeft),children:[s.jsx("canvas",{ref:y,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,I*300)}%`,background:I>.8?"var(--nice-danger, #ef4444)":I>.5?"var(--nice-warning, #f59e0b)":"var(--nice-success, #22c55e)",borderRadius:4,transition:"height 50ms"}})})]})};function Bl(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,h=t.subarray(d,d+i);let f=0,m=0;for(let v=0;v<h.length;v++)h[v]<f&&(f=h[v]),h[v]>m&&(m=h[v]);const g=l-m*(r/2),p=l-f*(r/2);e.moveTo(c,g),e.lineTo(c,p)}e.stroke()}function Wl(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 h=d*c,f=t.subarray(h,h+c);let m=0;for(let x=0;x<f.length;x++)m+=Math.abs(f[x]);const p=m/f.length*r*.9,v=d*i;e.fillStyle=o,e.fillRect(v+1,a+r-p,i-2,p)}}function Ul(e,t,n,r,a,o){const l=Math.min(n,512),c=Math.floor(t.length/l),d=n/l;for(let h=0;h<l;h++){const f=h*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&&f+b<t.length;b++){const w=2*Math.PI*p*b/256;v+=t[f+b]*Math.cos(w),x-=t[f+b]*Math.sin(w)}m[p]=Math.sqrt(v*v+x*x)/256}const g=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),w=Math.floor((1-v)*200);e.fillStyle=`rgb(${x},${b},${w})`,e.fillRect(h*d,a+r-(p+1)*g,d+1,g+1)}}}function Vl(e){const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const La=88,Ft=16,Pn=16,ql=320;function Hl(e){return e-21}function Kl(e){return e+21}const Ps=({notes:e,onAddNote:t,onRemoveNote:n,selectedNoteId:r,setSelectedNoteId:a,duration:o=4,zoom:i=1})=>{const l=u.useRef(null),c=ql*i,d=La*Ft,h=u.useRef(null);u.useEffect(()=>{},[e,i,o]);const f=g=>{const p=g.target.getBoundingClientRect(),v=g.clientX-p.left,x=g.clientY-p.top,b=Math.floor(x/Ft),w=Kl(b),y=v/c*o;h.current={drawing:!0,startX:v,key:b},t(w,y,o/Pn)},m=(g,p)=>{p.stopPropagation(),a==null||a(g)};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:f,children:[[...Array(La)].map((g,p)=>s.jsx("rect",{x:0,y:p*Ft,width:c,height:Ft,fill:p%2===0?"var(--key-even, #f5f5f5)":"var(--key-odd, #e0e0e0)"},p)),[...Array(Pn+1)].map((g,p)=>s.jsx("line",{x1:p*c/Pn,y1:0,x2:p*c/Pn,y2:d,stroke:"var(--border-muted, #ccc)",strokeWidth:p%4===0?2:1},p)),e.map(g=>{const p=Hl(g.pitch),v=g.start/o*c,x=g.duration/o*c;return s.jsx("rect",{x:v,y:p*Ft,width:Math.max(6,x),height:Ft-2,fill:g.id===r?"var(--accent, #1976d2)":"var(--accent-light, #90caf9)",stroke:"var(--accent, #1976d2)",strokeWidth:g.id===r?2:1,rx:3,onClick:b=>m(g.id,b),onDoubleClick:()=>n(g.id),style:{cursor:"pointer"}},g.id)})]})},Es=({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:h}=xe(),[f,m]=u.useState(null),[g,p]=u.useState(null),[v,x]=u.useState(null),b=[...e].sort((L,I)=>L.time-I.time),w=L=>[L.time/o*i,(127-L.value)/127*l],y=(L,I,q)=>Math.max(I,Math.min(q,L)),k=L=>{var H;if(L.target instanceof SVGCircleElement)return;const I=(H=d.current)==null?void 0:H.getBoundingClientRect();if(!I)return;const q=L.clientX-I.left,Y=L.clientY-I.top,O=y(q/i*o,0,o),Z=y(127-Math.round(Y/l*127),0,127);t(a,Z,O)},M=(L,I)=>{var Z;I.stopPropagation(),m(L.id),x(L.id);const[q,Y]=w(L),O=(Z=d.current)==null?void 0:Z.getBoundingClientRect();O&&p({dx:I.clientX-O.left-q,dy:I.clientY-O.top-Y})},N=L=>{var H;if(f==null||!g)return;const I=(H=d.current)==null?void 0:H.getBoundingClientRect();if(!I)return;const q=y(L.clientX-I.left-g.dx,0,i),Y=y(L.clientY-I.top-g.dy,0,l),O=y(q/i*o,0,o),Z=y(127-Math.round(Y/l*127),0,127);n(f,Z,O)},R=()=>{m(null),p(null)};u.useEffect(()=>{const L=I=>{(I.key==="Delete"||I.key==="Backspace")&&v!=null&&(r(v),x(null))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[v,r]),u.useEffect(()=>{if(f!=null)return window.addEventListener("mousemove",N),window.addEventListener("mouseup",R),()=>{window.removeEventListener("mousemove",N),window.removeEventListener("mouseup",R)}});const[_,E]=u.useState(null),U=(L,I)=>{const[q,Y]=w(L);E({x:q+10,y:Y-10,text:`Val: ${L.value}, Time: ${L.time.toFixed(2)}s`})},W=()=>E(null),j=L=>{var H;const I=(H=d.current)==null?void 0:H.getBoundingClientRect();if(!I)return;const q=L.clientX-I.left,Y=L.clientY-I.top,O=y(q/i*o,0,o),Z=y(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:f?"grabbing":"crosshair",display:"block"},onClick:k,onDoubleClick:j,tabIndex:0,children:[[...Array(9)].map((L,I)=>s.jsx("line",{x1:0,y1:I*l/8,x2:i,y2:I*l/8,stroke:"var(--border-muted, #ddd)",strokeWidth:I===0||I===8?2:1},I)),b.length>1&&s.jsx("polyline",{fill:"none",stroke:"var(--accent, #1976d2)",strokeWidth:2,points:b.map(L=>w(L).join(",")).join(" ")}),b.map(L=>{const[I,q]=w(L);return s.jsxs("g",{children:[s.jsx("circle",{cx:I,cy:q,r:v===L.id?8:6,fill:v===L.id?"var(--accent, #1976d2)":"var(--accent-light, #90caf9)",stroke:"var(--accent, #1976d2)",strokeWidth:v===L.id?3:2,style:{cursor:"pointer"},onMouseDown:Y=>M(L,Y),onContextMenu:Y=>{Y.preventDefault(),r(L.id)},onClick:Y=>{Y.stopPropagation(),x(L.id)},onMouseOver:Y=>U(L),onMouseOut:W}),v===L.id&&s.jsx("foreignObject",{x:I+10,y:q-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:[h("ccLane.curve","Curve"),":"]}),s.jsxs("select",{value:L.handleType||c||"linear",onChange:Y=>{n(L.id,L.value,L.time,Y.target.value)},children:[s.jsx("option",{value:"linear",children:h("ccLane.linear","Linear")}),s.jsx("option",{value:"step",children:h("ccLane.step","Step")}),s.jsx("option",{value:"exp",children:h("ccLane.exponential","Exponential")})]})]})})]},L.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]})]})},Yl=et.scoped("audioContext");let wn=null;function tn(){if(!wn)try{wn=new(window.AudioContext||window.webkitAudioContext)}catch(e){Yl.error("Error initializing AudioContext:",e)}return wn}async function Et(){const e=tn();e&&e.state==="suspended"&&await e.resume()}function As(){return!!wn&&wn.state==="running"}function Ns(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 Zl(e,t){if(!t.snapEnabled)return e;const n=Ns(t);return Math.round(e/n)*n}function Xl(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 Ql(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 Is(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,h=c%1===0;if(r.strokeStyle=h?"var(--border-secondary, #ccc)":"var(--border-muted, #eee)",r.lineWidth=h?1.5:.5,r.beginPath(),r.moveTo(d,0),r.lineTo(d,o),r.stroke(),h&&i>40){r.fillStyle="var(--muted, #666)",r.font="10px monospace",r.textAlign="center";const f=n?Ql(c,t.bpm):Xl(c);r.fillText(f,d,12)}}if(t.snapEnabled){const c=Ns(t);r.strokeStyle="var(--accent-primary, #ffeb3b)",r.lineWidth=.5;for(let d=0;d<=t.duration;d+=c){const h=d/t.duration*a;r.beginPath(),r.moveTo(h,o-5),r.lineTo(h,o),r.stroke()}}}function Jl(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;Is(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 ec(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,h)=>{const f=h/(n.length-1)*o,m=l-d*c;h===0?a.moveTo(f,m):a.lineTo(f,m)}),a.stroke(),a.restore()}const Ls=({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:h,onZoomChange:f})=>{const m=u.useRef(null),g=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(()=>{Et(),w()},[e,t,a,r,o,i,l,c]),u.useEffect(()=>{n?(p.current=performance.now(),y()):g.current&&cancelAnimationFrame(g.current)},[n]);const w=()=>{m.current&&(Is(m.current,b),c!=null&&c.length&&ec(m.current,b,c,d),Jl(m.current,b,a,r))},y=()=>{if(!n)return;const E=U=>{if(p.current!==null){const W=(U-p.current)/1e3;p.current=U;const j=Math.min(a+W,t);h(j)}a<t&&(g.current=requestAnimationFrame(E))};g.current=requestAnimationFrame(E)},k=E=>{x(!0),R(E)},M=E=>{v&&R(E)},N=()=>{x(!1)},R=E=>{if(!m.current)return;const U=m.current.getBoundingClientRect();let j=(E.clientX-U.left)/U.width*t;j=Zl(j,b),h(Math.min(Math.max(j,0),t))},_=E=>{if(!f)return;E.preventDefault();const U=E.deltaY>0?-.1:.1,W=Math.max(.5,Math.min(5,e+U));f(W)};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 tc=Date.now();function en(){return tc++}function nc(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:en(),cc:t,value:nn(o.value),time:o.time}),a=o.time);return r}function Fa(e,t,n,r=32){const a=[];for(let o=0;o<=r;o++){const i=o/r;a.push({id:en(),cc:n,value:nn(Xn(e.value,t.value,i)),time:Xn(e.time,t.time,i)})}return a}function rc(e,t,n,r,a=48){const o=[];for(let i=0;i<=a;i++){const l=i/a,c=Da(e.time,t.time,n.time,l),d=Da(e.value,t.value,n.value,l);o.push({id:en(),cc:r,value:nn(d),time:c})}return o}function ac(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=nn(e.value+l*i);a.push({id:en(),cc:n,value:d,time:c}),a.push({id:en(),cc:n,value:d,time:c+o-.001})}return a}function sc(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:en(),cc:n,value:nn(Xn(e.value,t.value,c)),time:Xn(e.time,t.time,l)})}return o}function oc(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,h)=>d+h.value,0)/l.length;return{...r,value:nn(Math.round(c))}})}function ic(e,t){let n;switch(e.mode){case"pencil":n=nc(t,e.cc,e.resolution);break;case"line":n=t.length>=2?Fa(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?n=rc(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?n=Fa(t[0],t[t.length-1],e.cc):n=[];break;case"step":n=t.length>=2?ac(t[0],t[t.length-1],e.cc):[];break;case"ramp":n=t.length>=2?sc(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=oc(n,r)}return n}function nn(e){return Math.max(0,Math.min(127,Math.round(e)))}function Xn(e,t,n){return e+(t-e)*n}function Da(e,t,n,r){const a=1-r;return a*a*e+2*a*r*t+r*r*n}function ir(){return{waveform:"sine",rate:1,depth:.5,phase:0,center:.5,syncToBpm:!1,syncDivision:"1/4",enabled:!0}}const lc={"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 Fs(e,t){return e/60*lc[t]/4}function Ds(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 Zr(e,t,n){if(!e.enabled)return e.center;const r=e.syncToBpm&&n?Fs(n,e.syncDivision):e.rate,a=t*r+e.phase/(2*Math.PI),o=Ds(e.waveform,a),i=e.center+o*e.depth*.5;return Math.max(0,Math.min(1,i))}function Xr(e,t,n){return Math.round(Zr(e,t,n)*127)}function Os(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 h=t+d/l*i,f=Xr(e,h,o);c.push({time:h,value:f,cc:r})}return c}function _s(e,t,n,r=2,a,o=200){const i=[];for(let l=0;l<=o;l++){const c=l/o*r,d=Zr(e,c,a);i.push({x:l/o*t,y:(1-d)*n})}return i}function cc(e){return JSON.stringify(e,null,2)}function dc(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const xr=140,rn=24,uc=[{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"}],zs=({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:h}=xe(),f=u.useRef(null),[m,g]=u.useState("pencil"),[p,v]=u.useState(!1),x=u.useRef([]),[b,w]=u.useState(null),[y,k]=u.useState(!1),[M,N]=u.useState(ir()),R=u.useRef(null),_=d.getEvents(e),E=_.filter(S=>S.cc===t),U=Math.max(400,n*30*r),W=u.useCallback(S=>S/U*n,[U,n]),j=u.useCallback(S=>Math.round(Math.max(0,Math.min(127,127-(S-rn)/xr*127))),[]),L=u.useCallback(S=>S/n*U,[U,n]),I=u.useCallback(S=>rn+(127-S)/127*xr,[]),q=u.useCallback(()=>{const S=f.current;if(!S)return;const P=S.getContext("2d");if(!P)return;const $=S.width,T=S.height;P.clearRect(0,0,$,T),P.fillStyle="var(--nice-bg, #1a1a2e)",P.fillRect(0,0,$,T),P.strokeStyle="var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",P.lineWidth=1;for(let D=0;D<=127;D+=16){const V=I(D);P.beginPath(),P.moveTo(0,V),P.lineTo($,V),P.stroke()}P.fillStyle="var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))",P.font="10px monospace",P.textBaseline="middle";for(const D of[0,32,64,96,127])P.fillText(String(D),2,I(D));P.strokeStyle="var(--nice-overlay-light-4, rgba(255, 255, 255, 0.04))";for(let D=0;D<=n;D++){const V=L(D);P.beginPath(),P.moveTo(V,0),P.lineTo(V,T),P.stroke()}const C=[...E].sort((D,V)=>D.time-V.time);if(C.length>0){P.beginPath(),P.moveTo(L(C[0].time),T-rn);for(const D of C)P.lineTo(L(D.time),I(D.value));P.lineTo(L(C[C.length-1].time),T-rn),P.closePath(),P.fillStyle="var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",P.fill(),P.beginPath(),P.strokeStyle="var(--nice-primary, #3b82f6)",P.lineWidth=2;for(let D=0;D<C.length;D++){const V=L(C[D].time),Q=I(C[D].value);D===0?P.moveTo(V,Q):((C[D].handleType??"linear")==="step"&&P.lineTo(V,I(C[D-1].value)),P.lineTo(V,Q))}P.stroke();for(const D of C){const V=L(D.time),Q=I(D.value),J=b===D.id;P.beginPath(),P.arc(V,Q,J?6:4,0,Math.PI*2),P.fillStyle=J?"var(--nice-primary-light, #60a5fa)":"var(--nice-primary, #3b82f6)",P.fill(),P.strokeStyle="var(--nice-bg, #fff)",P.lineWidth=1.5,P.stroke()}}P.strokeStyle="var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))",P.lineWidth=1,P.setLineDash([4,4]);const A=I(0);P.beginPath(),P.moveTo(0,A),P.lineTo($,A),P.stroke(),P.setLineDash([])},[E,n,U,L,I,b]);u.useEffect(()=>{q()},[q]);const Y=S=>{var C;const P=(C=f.current)==null?void 0:C.getBoundingClientRect();if(!P)return;const $=S.clientX-P.left,T=S.clientY-P.top;m==="pencil"?(v(!0),x.current=[{time:W($),value:j(T)}]):(v(!0),x.current=[{time:W($),value:j(T)}])},O=S=>{var D;const P=(D=f.current)==null?void 0:D.getBoundingClientRect();if(!P)return;const $=S.clientX-P.left,T=S.clientY-P.top;p&&x.current.push({time:W($),value:j(T)});const C=[...E].sort((V,Q)=>V.time-Q.time);let A=null;for(const V of C){const Q=L(V.time),J=I(V.value);if(Math.abs($-Q)<8&&Math.abs(T-J)<8){A=V.id;break}}w(A)},Z=()=>{if(!p)return;v(!1);const S=x.current;if(S.length===0)return;const P=ic({mode:m,cc:t,resolution:.02,smoothing:m==="pencil"?.3:0},S);P.length>0&&d.setEvents(e,[..._,...P]),x.current=[]},H=S=>{var C;const P=(C=f.current)==null?void 0:C.getBoundingClientRect();if(!P)return;const $=S.clientX-P.left,T=S.clientY-P.top;for(const A of E){const D=L(A.time),V=I(A.value);if(Math.abs($-D)<8&&Math.abs(T-V)<8){d.removeEvent(e,A.id);return}}d.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:j(T),time:W($)})},te=()=>{const P=Os(M,0,n,t,Math.ceil(n*20),120).map(($,T)=>({...$,id:Date.now()+T}));d.setEvents(e,[..._,...P]),k(!1)},G=()=>{const S=d.exportLane(e),P=new Blob([S],{type:"application/json"}),$=URL.createObjectURL(P),T=document.createElement("a");T.href=$,T.download=`cc-lane-${t}-layer-${e}.json`,document.body.appendChild(T),T.click(),T.remove(),URL.revokeObjectURL($)},z=S=>{var $;const P=($=S.target.files)==null?void 0:$[0];P&&(P.text().then(T=>{d.importLane(e,T)}),R.current&&(R.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:h("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:S=>o(Number(S.target.value)),children:uc.map(S=>s.jsxs("option",{value:S.cc,children:[S.label," (CC",S.cc,")"]},S.cc))}),s.jsx("div",{className:"btn-group btn-group-sm",children:["pencil","line","curve","step","ramp"].map(S=>s.jsx("button",{className:`btn ${m===S?"btn-primary":"btn-outline-secondary"}`,onClick:()=>g(S),style:{fontSize:11,textTransform:"capitalize"},children:S},S))}),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(!y),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 S;return(S=R.current)==null?void 0:S.click()},title:"Import CC lane from JSON",children:"Import"}),s.jsx("input",{ref:R,type:"file",accept:".json",style:{display:"none"},onChange:z}),s.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:()=>d.setEvents(e,_.filter(S=>S.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:[E.length," ",h("ccLane.events","events")]})]}),y&&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:S=>N(P=>({...P,waveform:S.target.value})),children:["sine","triangle","sawtooth","square","random","sample-hold"].map(S=>s.jsx("option",{value:S,children:S},S))})]}),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:S=>N(P=>({...P,rate:Number(S.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:S=>N(P=>({...P,depth:Number(S.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:S=>N(P=>({...P,center:Number(S.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:f,width:U,height:xr+rn*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:h("ccLane.hint","Click to draw. Double-click to add/remove points. Drag to draw curves.")})]})},Gs={"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},Ar={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function hc(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 Bs(e,t){if(e.length===0)return[];const n=hc(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 fc(e,t,n,r=0,a=1){const o=Bs(e,t);if(o.length===0)return[];const i=60/n,l=Gs[t.rate]*i,c=l*t.gate,d=[],h=t.mode==="chord",f=h?a:o.length*a;for(let m=0;m<f;m++){const g=m%2===1?l*t.swing*.5:0,p=r+m*l+g;if(h)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 Ws(){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 Us(){return Object.keys(Gs)}const Vs=({config:e=Ar,onChange:t=()=>{},active:n=!1,onToggleActive:r=()=>{}})=>{const{t:a}=xe(),o=Ws(),i=Us(),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(Ar),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)})})]})]})]})},pc=["sine","triangle","sawtooth","square","random","sample-hold"],mc=["1/1","1/2","1/4","1/8","1/16","1/32"],an=200,Dt=48,qs=({config:e,onChange:t,index:n,onRemove:r})=>{const{t:a}=xe(),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,an,Dt),d.fillStyle="var(--nice-bg-secondary, #161b22)",d.fillRect(0,0,an,Dt),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,Dt/2),d.lineTo(an,Dt/2),d.stroke(),d.setLineDash([]);const h=_s(e,an,Dt);if(h.length>0){d.beginPath(),d.strokeStyle=e.enabled?"var(--nice-primary, #3b82f6)":"var(--nice-text-secondary, #484f58)",d.lineWidth=1.5;for(let f=0;f<h.length;f++){const m=h[f].x,g=h[f].y;f===0?d.moveTo(m,g):d.lineTo(m,g)}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(ir()),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:an,height:Dt,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:pc.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:mc.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)})})]})]})]})]})]})},gc=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function yc(e){const t=Math.floor(e/12)-1;return`${gc[e%12]}${t}`}const Hs=({seq:e,steps:t,tracks:n,bpm:r,pattern:a,onChange:o})=>{const{t:i}=xe();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,h=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:f=>e.setBpm(Number(f.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:f=>e.setSwing(Number(f.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(f=>s.jsx("button",{className:`btn ${l.length===f?"btn-primary":"btn-outline-secondary"}`,onClick:()=>e.setLength(f),style:{fontSize:11},children:f},f))})]}),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:h.map((f,m)=>{const g=f.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:g?`hsl(${210+f.velocity/127*40}, 80%, ${35+f.velocity/127*20}%)`:v?"#21262d":"var(--nice-bg-secondary, #161b22)",cursor:"pointer",padding:0,color:g?"var(--nice-bg, #fff)":"var(--nice-text-secondary, #484f58)",fontSize:8,fontWeight:600,transition:"background 0.1s"},children:g?yc(f.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:`${f.velocity/127*100}%`,background:g?"var(--nice-primary-tint-60, rgba(59, 130, 246, 0.6))":"var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",borderRadius:2,cursor:"ns-resize"},title:`Vel: ${f.velocity}`,onMouseDown:x=>{x.preventDefault();const b=x.target.parentElement.getBoundingClientRect(),w=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)},y=()=>{document.removeEventListener("mousemove",w),document.removeEventListener("mouseup",y)};document.addEventListener("mousemove",w),document.addEventListener("mouseup",y)}})}),g&&f.probability<1&&s.jsxs("span",{style:{fontSize:8,color:"var(--nice-warning, #f0c040)"},children:[Math.round(f.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.")})]})},bc="_panelNarrow_42xt3_3",vc="_panelWide_42xt3_9",xc="_smallLabel_42xt3_19",Sc="_noteText_42xt3_29",wc="_buttonRow_42xt3_41",Cc="_noteTextMargin_42xt3_49",kc="_rangeW100_42xt3_63",Mc="_zoomValue_42xt3_69",jc="_selectW100_42xt3_77",Rc="_inputW70_42xt3_83",$c="_masterVolGroup_42xt3_93",Tc="_rangeW140_42xt3_99",Pc="_volumeValue_42xt3_105",Ec="_selectW140_42xt3_115",Ac="_freqGroup_42xt3_121",Nc="_freqValue_42xt3_127",Ic="_narrowGroup_42xt3_137",Lc="_rangeW120_42xt3_143",Fc="_smallValue_42xt3_149",Dc="_presetDivider_42xt3_159",Oc="_presetLabel_42xt3_165",_c="_presetBtn_42xt3_175",zc="_deletePresetSelect_42xt3_183",Gc="_presetNameInput_42xt3_191",Bc="_savePresetBtn_42xt3_199",Wc="_countInAlert_42xt3_211",Uc="_inputW80_42xt3_219",Vc="_levelLabel_42xt3_225",qc="_levelMeter_42xt3_233",Hc="_levelBar_42xt3_249",pe={panelNarrow:bc,panelWide:vc,smallLabel:xc,noteText:Sc,buttonRow:wc,noteTextMargin:Cc,rangeW100:kc,zoomValue:Mc,selectW100:jc,inputW70:Rc,masterVolGroup:$c,rangeW140:Tc,volumeValue:Pc,selectW140:Ec,freqGroup:Ac,freqValue:Nc,narrowGroup:Ic,rangeW120:Lc,smallValue:Fc,presetDivider:Dc,presetLabel:Oc,presetBtn:_c,deletePresetSelect:zc,presetNameInput:Gc,savePresetBtn:Bc,countInAlert:Wc,inputW80:Uc,levelLabel:Vc,levelMeter:qc,levelBar:Hc},Ks=({autoSaveMode:e,setAutoSaveMode:t,autoSaveInterval:n,setAutoSaveInterval:r})=>{const{t:a}=xe();return s.jsxs("div",{className:`card p-3 mb-3 ${pe.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:pe.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.")]})]})},Ys=({undoCount:e,redoCount:t,onUndo:n,onRedo:r})=>{const{t:a}=xe();return s.jsxs("div",{className:`card p-3 mb-3 ${pe.panelNarrow}`,children:[s.jsx("h6",{className:"mb-2",children:a("editorPanels.changeHistory","Project change history")}),s.jsxs("div",{className:pe.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:pe.noteTextMargin,children:a("editorPanels.undoRedoNote","Undo/Redo works on the entire project (all editor changes). After each change Redo is cleared.")})]})},Zs=({zoom:e,setZoom:t,uiZoom:n,setUiZoom:r,snapEnabled:a,onToggleSnap:o,snapMode:i,onSnapModeChange:l,bpm:c,setBpm:d})=>{const{t:h}=xe();return s.jsx("div",{className:`card p-2 mb-3 ${pe.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 ${pe.smallLabel}`,children:"Zoom:"}),s.jsx("input",{type:"range",min:"0.5",max:"5",step:"0.1",value:e,onChange:f=>t(Number(f.target.value)),className:pe.rangeW100}),s.jsxs("span",{className:pe.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 ${pe.smallLabel}`,children:"Zoom UI:"}),s.jsx("input",{type:"range",min:"1",max:"4",step:"0.1",value:n,onChange:f=>r(Number(f.target.value)),className:pe.rangeW100}),s.jsxs("span",{className:pe.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 ${pe.smallLabel}`,children:"Snap"})]}),a&&s.jsxs("select",{className:`form-select form-select-sm ${pe.selectW100}`,value:i,onChange:f=>l(f.target.value),children:[s.jsx("option",{value:"bar",children:h("editorPanels.snapBar","Bar")}),s.jsx("option",{value:"beat",children:h("editorPanels.snapBeat","Beat")}),s.jsx("option",{value:"sub-beat",children:h("editorPanels.snap16","1/16")}),s.jsx("option",{value:"second",children:h("editorPanels.snapSecond","Second")})]}),s.jsxs("div",{className:"d-flex align-items-center gap-2",children:[s.jsx("label",{className:`form-label mb-0 ${pe.smallLabel}`,children:"BPM:"}),s.jsx("input",{type:"number",className:`form-control form-control-sm ${pe.inputW70}`,value:c,onChange:f=>d(Number(f.target.value)),min:"20",max:"300"})]})]})})},Xs=({masterVolume:e,onMasterVolumeChange:t,filterType:n,filterFreq:r,filterQ:a,filterGain:o,onFilterChange:i,masterEQPresets:l,customPresets:c,onLoadPreset:d,onSavePreset:h,onDeletePreset:f})=>{const{t:m}=xe();return s.jsxs("div",{className:`card p-2 mb-3 ${pe.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 ${pe.masterVolGroup}`,children:[s.jsx("label",{className:`form-label mb-0 ${pe.smallLabel}`,children:"Master Vol"}),s.jsx("input",{type:"range",min:"0",max:"1",step:"0.01",value:e,onChange:g=>t(Number(g.target.value)),className:pe.rangeW140}),s.jsxs("span",{className:pe.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 ${pe.smallLabel}`,children:"Filter"}),s.jsx("select",{className:`form-select form-select-sm ${pe.selectW140}`,value:n,onChange:g=>i({type:g.target.value}),children:["peaking","lowpass","highpass","lowshelf","highshelf","notch","bandpass"].map(g=>s.jsx("option",{value:g,children:g},g))})]}),s.jsxs("div",{className:`d-flex align-items-center gap-2 ${pe.freqGroup}`,children:[s.jsx("span",{className:pe.smallLabel,children:"Freq"}),s.jsx("input",{type:"range",min:"40",max:"12000",step:"10",value:r,onChange:g=>i({frequency:Number(g.target.value)}),className:pe.rangeW140}),s.jsxs("span",{className:pe.freqValue,children:[Math.round(r)," Hz"]})]}),s.jsxs("div",{className:`d-flex align-items-center gap-2 ${pe.narrowGroup}`,children:[s.jsx("span",{className:pe.smallLabel,children:"Q"}),s.jsx("input",{type:"range",min:"0.1",max:"12",step:"0.1",value:a,onChange:g=>i({q:Number(g.target.value)}),className:pe.rangeW120}),s.jsx("span",{className:pe.smallValue,children:a.toFixed(1)})]}),(n==="peaking"||n==="lowshelf"||n==="highshelf")&&s.jsxs("div",{className:`d-flex align-items-center gap-2 ${pe.narrowGroup}`,children:[s.jsx("span",{className:pe.smallLabel,children:"Gain"}),s.jsx("input",{type:"range",min:"-18",max:"18",step:"0.5",value:o,onChange:g=>i({gain:Number(g.target.value)}),className:pe.rangeW120}),s.jsxs("span",{className:pe.smallValue,children:[o.toFixed(1)," dB"]})]})]}),s.jsxs("div",{className:`mt-2 pt-2 ${pe.presetDivider}`,children:[s.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[s.jsxs("span",{className:pe.presetLabel,children:[m("editorPanels.eqPresets","EQ Presets"),":"]}),[...l,...c].map(g=>s.jsx("button",{className:`btn btn-sm btn-outline-secondary ${pe.presetBtn}`,onClick:()=>d(g),children:g.name},g.name)),c.length>0&&s.jsxs("select",{className:`form-select form-select-sm ${pe.deletePresetSelect}`,onChange:g=>{g.target.value&&(f(g.target.value),g.target.value="")},defaultValue:"",children:[s.jsx("option",{value:"",children:m("editorPanels.deletePreset","Delete preset...")}),c.map(g=>s.jsx("option",{value:g.name,children:g.name},g.name))]})]}),s.jsxs("div",{className:"d-flex align-items-center gap-2",children:[s.jsx("input",{type:"text",className:`form-control form-control-sm ${pe.presetNameInput}`,placeholder:m("editorPanels.presetName","Preset name..."),id:"presetNameInput"}),s.jsx("button",{className:`btn btn-sm btn-success ${pe.savePresetBtn}`,onClick:()=>{const g=document.getElementById("presetNameInput");g!=null&&g.value.trim()&&(h(g.value.trim()),g.value="")},children:m("editorPanels.saveCurrent","Save Current")})]})]})]})},Qs=({countInBars:e,setCountInBars:t,isCountIn:n,countInRemaining:r,overdubEnabled:a,setOverdubEnabled:o,punchIn:i,setPunchIn:l,punchOut:c,setPunchOut:d,monitorLevel:h})=>{const{t:f}=xe();return s.jsx("div",{className:`card p-2 mb-3 ${pe.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 ${pe.smallLabel}`,children:[f("editorPanels.countIn","Count-in (bars)"),":"]}),s.jsx("input",{type:"number",min:"0",max:"8",step:"1",className:`form-control form-control-sm ${pe.inputW70}`,value:e,onChange:m=>t(Number(m.target.value))}),n&&s.jsxs("span",{className:pe.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 ${pe.smallLabel}`,children:f("editorPanels.overdub","Overdub (play background)")})]}),s.jsxs("div",{className:"d-flex align-items-center gap-1",children:[s.jsx("span",{className:pe.smallLabel,children:"Punch In"}),s.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${pe.inputW80}`,value:i??"",onChange:m=>l(m.target.value===""?null:Number(m.target.value))}),s.jsx("span",{className:pe.smallLabel,children:"s"})]}),s.jsxs("div",{className:"d-flex align-items-center gap-1",children:[s.jsx("span",{className:pe.smallLabel,children:"Punch Out"}),s.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${pe.inputW80}`,value:c??"",onChange:m=>d(m.target.value===""?null:Number(m.target.value))}),s.jsx("span",{className:pe.smallLabel,children:"s"})]}),s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>{l(null),d(null)},children:f("editorPanels.clearPunch","Clear punch")}),s.jsx("div",{className:pe.levelLabel,children:"Level"}),s.jsx("div",{className:pe.levelMeter,children:s.jsx("div",{className:pe.levelBar,style:{width:`${Math.min(1,h*2)*100}%`,background:h>.7?"var(--nice-danger, #f44336)":"var(--nice-success, #4caf50)"}})})]})})};function Kc(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 Yc(e,t,n){const r=u.useRef(null),[a,o]=u.useState(!1),[i,l]=u.useState(0),[c,d]=u.useState(10),[h,f]=u.useState(!1),[m,g]=u.useState(120),p=u.useCallback((R,_)=>`L${R}-C${_}`,[]),v=u.useCallback((R,_)=>{if(!r.current||!_.audioBuffer)return;const E=p(R,_.id),U=e[R];r.current.addClip({id:E,buffer:_.audioBuffer,startTime:_.start,offset:0,duration:_.duration,layerId:R,volume:(U==null?void 0:U.volume)??1,pan:(U==null?void 0:U.pan)??0,stretchFactor:_.stretchFactor||1,effectChain:(U==null?void 0:U.effectChain)||[]})},[e,p]),x=u.useCallback((R,_)=>{var E;(E=r.current)==null||E.removeClip(p(R,_))},[p]);u.useEffect(()=>{Object.entries(t).forEach(([R,_])=>{const E=Number(R);_==null||_.forEach(U=>v(E,U))})},[t,e,v]),u.useEffect(()=>{r.current&&Object.entries(n).forEach(([R,_])=>{const E=Number(R);r.current.setMidiCCEvents(E,_)})},[n]);const b=u.useCallback(()=>{r.current&&(a?r.current.pause():r.current.play())},[a]),w=u.useCallback(()=>{var R;(R=r.current)==null||R.stop()},[]),y=u.useCallback(R=>{var _;(_=r.current)==null||_.seek(R)},[]),k=u.useCallback(()=>{if(!r.current)return;const R=!h;f(R),r.current.setLoopRegion(0,c,R)},[h,c]),M=u.useCallback(R=>{var E;const _=Math.max(1,c+R);d(_),(E=r.current)==null||E.setLoopRegion(0,_,h)},[c,h]),N=u.useCallback(async(R,_=1024)=>{const E=await R.arrayBuffer(),U=new(window.AudioContext||window.webkitAudioContext),W=await U.decodeAudioData(E.slice(0)),j=W.getChannelData(0),L=j.length,I=Math.max(1,Math.floor(L/_)),q=[];for(let Y=0;Y<_;Y++){const O=Y*I;if(O>=L)break;q.push(j[O])}return U.close(),{waveform:q.map(Y=>Math.max(-1,Math.min(1,Y))),duration:W.duration,buffer:W}},[]);return{engineRef:r,isPlaying:a,setIsPlaying:o,currentTime:i,setCurrentTime:l,duration:c,setDuration:d,isLooping:h,setIsLooping:f,bpm:m,setBpm:g,handlePlayPause:b,handleStop:w,handleSeek:y,handleToggleLoop:k,handleAdjustDuration:M,upsertEngineClip:v,removeEngineClip:x,makeEngineClipId:p,blobToWaveform:N}}class Js{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 h=(i[d]-128)/128;l+=h*h}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 Zc(e){const[t,n]=u.useState(!1),[r,a]=u.useState(!1),[o,i]=u.useState(0),[l,c]=u.useState(0),[d,h]=u.useState(null),f=u.useRef(null),m=u.useRef(null),g=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||(f.current||(f.current=new Js),g.current=m.current??e.currentTime,n(!0),i(0),await f.current.startRecording({onLevel:i}))},[e,t]),w=u.useCallback(async()=>{var j;if(x(),a(!1),c(0),m.current=null,!f.current){n(!1),i(0);return}const M=await f.current.stopRecording();if(n(!1),i(0),!M||!e.activeLayer)return;const{waveform:N,duration:R,buffer:_}=await e.blobToWaveform(M),E=e.activeLayer.id;e.setWaveforms(L=>({...L,[E]:N}));const U=Math.max(0,g.current||0),W={id:Date.now(),label:"Recording",start:U,duration:R,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:(j=e.layerSettings[E])==null?void 0:j.color,blob:M,blobUrl:URL.createObjectURL(M),audioBuffer:_};e.setLayerClips(L=>({...L,[E]:[...L[E]||[],W]})),e.upsertEngineClip(E,W),e.setSelectedClip({layerId:E,clipId:W.id})},[e,x]),y=u.useCallback(M=>{if(M<=0){b();return}a(!0),c(M);const N=performance.now();p.current=window.setInterval(()=>{const R=(performance.now()-N)/1e3;c(Math.max(0,M-R))},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 w();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&&y(M):y(M)},[t,r,e,w,y]);return{isRecording:t,isCountIn:r,monitorLevel:o,countInRemaining:l,punchOut:d,setPunchOut:h,armedPunchInRef:m,recorderRef:f,clearCountInTimers:x,startRecordingNow:b,stopRecordingFlow:w,handleRecord:k}}var eo=(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))(eo||{});const Xc={};class En{constructor(t,n,r,a={}){this.type=t,this.name=n,this.component=Xc[t]??(()=>null),this.audioType=r,this.parameters=a}}new En("Recorder","Recorder","vocal",{deviceId:"",gain:1,sensitivity:"high"}),new En("Audio Clip","Audio Clip","instrumental",{clipId:null,octave:"4"}),new En("Speech Synth","Speech Synth","vocal",{text:"",voice:"default"}),new En("Keyboard/Pads","Keyboard","instrumental",{instrument:"piano",preset:"default",velocity:100});function to(e,t,n,r,a){n(o=>t?[...o,t]:o),r([]),a(e)}function Qc(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 Jc(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 ed{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 td=et.scoped("useProjectCRUD");function nd(e){const{project:t,activeSection:n,setProject:r,setActiveSection:a,setLayers:o,setActiveLayer:i,setUndoStack:l,setRedoStack:c}=e,d=u.useCallback(x=>to(x,t,l,c,r),[t,l,c,r]),h=u.useCallback(async()=>{var y;if(!t)return;const x=(((y=t.sections)==null?void 0:y.length)??0)+1,w={id:await e.addSection(t.id,"Section",x),projectId:t.id,name:"Section",orderNumber:x,layers:[]};d({...t,sections:[...t.sections||[],w]}),a(w)},[t,d,a]),f=u.useCallback(async x=>{var y,k,M;if(!t||!await e.confirm("Delete this section?"))return;await e.deleteSection(x);const w=(t.sections??[]).filter(N=>N.id!==x);d({...t,sections:w}),a(w[0]??null),o(((y=w[0])==null?void 0:y.layers)??[]),i(((M=(k=w[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:eo.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};o(w=>[...w,x]),i(x);try{const w=await e.addLayer(n.id,x.name,x.audioSource,x.audioSourceParameters);o(y=>y.map(k=>k.id===x.id?{...x,id:w}:k)),t&&d({...t,sections:((b=t.sections)==null?void 0:b.map(y=>y.id===n.id?{...y,layers:[...(y.layers??[]).filter(k=>k.id!==w),{...x,id:w}]}:y))??[]})}catch(w){o(y=>y.filter(k=>k.id!==x.id)),td.error("Failed to add layer:",w)}},[n,t,d,o,i]),g=u.useCallback(async x=>{var w,y;if((w=e.layerSettings[x])!=null&&w.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:((y=t.sections)==null?void 0:y.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 w;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:((w=t.sections)==null?void 0:w.map(y=>y.id===n.id?{...y,name:x,orderNumber:b}:y))??[]}),e.setStatusType("success"),e.setStatusMessage("Section saved")},[n,t,e,d,a]);return{handleAddSection:h,handleDeleteSection:f,handleAddLayer:m,handleDeleteLayer:g,handleSaveProject:p,handleSaveSection:v}}const no=u.createContext(null);function rd(){const e=u.useContext(no);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const Qr=({value:e,children:t})=>s.jsx(no.Provider,{value:e,children:t});Qr.displayName="EditorTrackProvider";const Ht=(e,t)=>t&&t>0?e*15/t:e/10,Jr=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},ad=(e,t)=>{const n=t??Jr(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 h=d.indexOf(" "),f=d.indexOf(" ",h+1),m=d.indexOf(" ",f+1),g=d.indexOf(" ",m+1);if(g===-1)return;const p=Ht(parseFloat(d.substring(h+1,f)),n);a===""&&(o=p);const v=d.substring(g+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},sd=(e,t)=>{const n=t??Jr(e),r=[];let a=[],o="",i=0,l=!0,c=null,d="";function h(){c&&d.trim()!==""&&(c.text=d.trim(),a.push({...c}),o.length>0&&(o+=" "),o+=c.text),c=null,d=""}return e.forEach(f=>{if(!(f.startsWith("#")||f.startsWith("E"))){if(f.startsWith("-"))h(),o.trim().length>0&&(r.push({text:o.trim(),timestamp:i,words:a}),o="",a=[]),l=!0;else if(f.startsWith(":")||f.startsWith("*")){const m=f.startsWith("*"),g=f.indexOf(" "),p=f.indexOf(" ",g+1),v=f.indexOf(" ",p+1),x=f.indexOf(" ",v+1);if(x===-1)return;const b=Ht(parseFloat(f.substring(g+1,p)),n),w=Ht(parseFloat(f.substring(p+1,v)),n),y=b+w;o===""&&(i=b);const k=f.substring(x+1);if(k.trim()==="~"){c&&(c.endTime=y);return}let M=k;M.startsWith("~")&&(M=M.substring(1)),l?(h(),d=M.trimEnd(),c={text:"",startTime:b,endTime:y,isGolden:m}):c?(d+=M.trimEnd(),c.endTime=y,m&&(c.isGolden=!0)):(d=M.trimEnd(),c={text:"",startTime:b,endTime:y,isGolden:m}),l=k.endsWith(" ")}}}),h(),o.trim().length>0&&r.push({text:o.trim(),timestamp:i,words:a}),r},ro=(e,t)=>{const n=t??Jr(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=Ht(d,n))}}else if(l.startsWith(":")||l.startsWith("*")){const c=l.startsWith("*"),d=l.indexOf(" "),h=l.indexOf(" ",d+1),f=l.indexOf(" ",h+1),m=l.indexOf(" ",f+1);if(m===-1)return;const g=parseFloat(l.substring(d+1,h)),p=parseFloat(l.substring(h+1,f)),v=Ht(g,n),x=v+Ht(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 w=b;w.startsWith("~")&&(w=w.substring(1));const y=b.endsWith(" "),k=y?w.slice(0,-1):w;a.push({text:k,startTime:v,endTime:x,isGolden:c,hasTrailingSpace:y})}}}),i(),r},od=(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},id=(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},Oa="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",_a="var(--karaoke-gold-glow-first, 0 0 12px #FFD700)",ld="var(--karaoke-active-glow, 0 0 10px rgba(0,229,255,0.6), 0 0 4px rgba(255,230,0,0.4))",cd="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",dd=({song:e,currentTime:t})=>{const n=u.useMemo(()=>!e||!e.notes.length?[]:ro(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:ld,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 h=Math.round(d*100),f=l.text+(l.hasTrailingSpace?" ":""),m=d>0&&d<1,g=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:f},c):d>=1?s.jsx("span",{style:{background:g?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Oa,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:g?`drop-shadow(${_a})`:"none",transition:"filter 0.2s ease"},children:f},c):s.jsxs("span",{style:{position:"relative",display:"inline",filter:m?g?`drop-shadow(${_a})`:`drop-shadow(${cd})`:"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:f}),s.jsx("span",{style:{position:"absolute",left:0,top:0,background:g?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Oa,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",clipPath:`inset(0 ${100-h}% 0 0)`,pointerEvents:"none"},children:f})]},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..."})})},ao=u.memo(dd),Sr={},ud=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:st&&st.tagName.toUpperCase()==="SCRIPT"&&st.src||new URL("index.cjs",document.baseURI).href}<"u"&&(Sr==null?void 0:Sr.VITE_DEBUG_KARAOKE)==="true";function Nr(e,t,...n){(ud||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 so=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},za=(e,t)=>t&&t>0?e*15/t:e/10,ea=(e,t)=>{const n=t??so(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:za(parseFloat(i[1]),n),duration:za(parseFloat(i[2]),n),pitch:parseInt(i[3],10),isGold:c})}}),a.length>0&&r.push(a),r},oo=(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},hd=et.scoped("karaokeScoringConfig"),ta={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}},fd="karaoke.scoringPresets";function pd(){try{const e=localStorage.getItem(fd);return e?JSON.parse(e):null}catch(e){return hd.warn("Failed to parse scoring presets overrides",e),null}}function io(e){const t={...ta},n=pd();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=io();const md=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=io(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},lo=(e="normal")=>exports.ScoringPresets[e]||ta.normal;function Ir(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 gd(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 yd=3,B=yd;function $t(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} ${B}V${e-B}A${t-B} ${t-B} 0 0 1 ${B} ${t}A${t-B} ${t-B} 0 0 1 ${t} ${B}Z`}}function Kt(e){return{w:B+1,out:`M0 0H${B+1}V${e}H0Z`,inn:`M${B} ${B}H${B+1}V${e-B}H${B}Z`}}function na(e){const t=Math.min(14,e*.22)|0,n=t+2,r=Math.max(t-B,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${B+r} ${B}H${n}V${e-B}H${B+r}Q${B} ${e-B} ${B} ${e-B-r}V${B+r}Q${B} ${B} ${B+r} ${B}Z`}}function Qn(e){const t=e*.3|0,n=t+2,r=Math.max(t-B,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e-t}V${t}Z`,inn:`M${B+r} ${B}H${n}V${e-B}H${B+r}L${B} ${e-B-r}V${B+r}Z`}}function Mt(e){const t=e*.42|0,n=t+2,r=Math.max(t-(B*1.4|0),2);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e/2}Z`,inn:`M${B+r} ${B}H${n}V${e-B}H${B+r}L${B} ${e/2}Z`}}function Jn(e){const t=e*.3|0,n=t+4,r=Math.max(t-B,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${B+r} ${B}H${n}V${e-B}H${B+(r*.6|0)}L${B} ${e-B-r}V${B+r}Q${B} ${B} ${B+r} ${B}Z`}}function ra(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${B+(t*1.2|0)} ${B}H${n}V${e-B}H${B+(t*1.2|0)}C${B+(t*2.2|0)} ${e*.37|0} ${B+(t*2.2|0)} ${e*.63|0} ${B+(t*1.2|0)} ${e-B}Z`}}function aa(e){const t=e*.32|0,n=t+3,r=Math.max(t-B,1);return{w:n,out:`M0 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}Z`,inn:`M${B} ${B}H${n}V${e-B}H${B+r}Q${B} ${e-B} ${B} ${e-B-r}Z`}}function er(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${B+(t*1.8|0)} ${B}H${n}V${e-B}H${B+(t*1.8|0)}C${B+(t*.4|0)} ${e*.78|0} ${B+(t*2.8|0)} ${e*.55|0} ${B+(t*.4|0)} ${e*.37|0}S${B+(t*.9|0)} ${B} ${B+(t*1.8|0)} ${B}Z`}}function sa(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${B+(t*2.5|0)} ${B}H${n}V${e-B}H${B+(t*2.5|0)}L${B+(t*.7|0)} ${e-B-(t*1.6|0)}L${B+(t*1.7|0)} ${e*.64|0}L${B} ${e/2|0}L${B+(t*1.7|0)} ${e*.36|0}L${B+(t*.7|0)} ${B+(t*1.6|0)}Z`}}function Un(e){const t=e*.42|0,n=t+2;return{w:n,out:`M${t} 0H${n}V${e}H0Z`,inn:`M${B+t-(B*1.3|0)} ${B}H${n}V${e-B}H${B+1}Z`}}function Lr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}V${e}H${t}Z`,inn:`M${B} ${B}H${n}V${e-B}H${B+t-(B*1.3|0)+1}Z`}}function Ct(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 ${B}A${t-B} ${t-B} 0 0 1 ${t-B} ${t}A${t-B} ${t-B} 0 0 1 0 ${e-B}Z`}}function Yt(e){return{w:B+1,out:`M0 0H${B+1}V${e}H0Z`,inn:`M0 ${B}H1V${e-B}H0Z`}}function co(e){const t=Math.min(14,e*.22)|0,n=t+2,r=Math.max(t-B,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 ${B}H${n-B-r}Q${n-B} ${B} ${n-B} ${B+r}V${e-B-r}Q${n-B} ${e-B} ${n-B-r} ${e-B}H0Z`}}function Zt(e){const t=e*.3|0,n=t+2,r=Math.max(t-B,1);return{w:n,out:`M0 0H${n-t}L${n} ${t}V${e-t}L${n-t} ${e}H0Z`,inn:`M0 ${B}H${n-B-r}L${n-B} ${B+r}V${e-B-r}L${n-B-r} ${e-B}H0Z`}}function gt(e){const t=e*.42|0,n=t+2,r=Math.max(t-(B*1.4|0),2);return{w:n,out:`M0 0H${n-t}L${n} ${e/2}L${n-t} ${e}H0Z`,inn:`M0 ${B}H${n-B-r}L${n-B} ${e/2}L${n-B-r} ${e-B}H0Z`}}function uo(e){const t=e*.3|0,n=t+4,r=Math.max(t-B,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 ${B}H${n-B-r}Q${n-B} ${B} ${n-B} ${B+r}V${e-B-r}L${n-B-(r*.6|0)} ${e-B}H0Z`}}function ho(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 ${B}H${n-B-(t*1.2|0)}C${n-B-(t*2.2|0)} ${e*.37|0} ${n-B-(t*2.2|0)} ${e*.63|0} ${n-B-(t*1.2|0)} ${e-B}H0Z`}}function fo(e){const t=e*.32|0,n=t+3,r=Math.max(t-B,1);return{w:n,out:`M0 0H${n}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${B}H${n-B}V${e-B-r}Q${n-B} ${e-B} ${n-B-r} ${e-B}H0Z`}}function oa(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 ${B}H${n-B-(t*1.8|0)}C${n-B-(t*.9|0)} ${B} ${n-B+(t*.1|0)} ${e*.22|0} ${n-B-(t*.4|0)} ${e*.37|0}S${n-B-(t*.4|0)} ${e*.78|0} ${n-B-(t*1.8|0)} ${e-B}H0Z`}}function tr(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 ${B}H${n-B-(t*2.5|0)}L${n-B-(t*.7|0)} ${B+(t*1.6|0)}L${n-B-(t*1.7|0)} ${e*.36|0}L${n-B} ${e/2|0}L${n-B-(t*1.7|0)} ${e*.64|0}L${n-B-(t*.7|0)} ${e-B-(t*1.6|0)}L${n-B-(t*2.5|0)} ${e-B}H0Z`}}function Fr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}L${n-t} ${e}H0Z`,inn:`M0 ${B}H${n-B}L${n-B-t+(B*1.3|0)} ${e-B}H0Z`}}function Vn(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n-t}L${n} ${e}H0Z`,inn:`M0 ${B}H${n-B-t+(B*1.3|0)}L${n-B} ${e-B}H0Z`}}const ia=[{name:"Pill",L:$t,R:Ct},{name:"Sharp",L:Kt,R:Yt},{name:"Soft",L:na,R:co},{name:"Chamfer",L:Qn,R:Zt},{name:"Arrow",L:Mt,R:gt},{name:"Shield",L:Jn,R:uo},{name:"Bracket",L:ra,R:ho},{name:"Tab",L:aa,R:fo},{name:"Wave",L:er,R:oa},{name:"Ornate",L:sa,R:tr}],po=[{name:"Pill→Arrow",L:$t,R:gt},{name:"Arrow→Pill",L:Mt,R:Ct},{name:"Pill→Sharp",L:$t,R:Yt},{name:"Sharp→Pill",L:Kt,R:Ct},{name:"Pill→Chamfer",L:$t,R:Zt},{name:"Chamfer→Pill",L:Qn,R:Ct},{name:"Arrow→Sharp",L:Mt,R:Yt},{name:"Sharp→Arrow",L:Kt,R:gt},{name:"Arrow→Chamfer",L:Mt,R:Zt},{name:"Chamfer→Arrow",L:Qn,R:gt},{name:"Soft→Arrow",L:na,R:gt},{name:"Shield→Chamfer",L:Jn,R:Zt},{name:"Pill→Wave",L:$t,R:oa},{name:"Wave→Arrow",L:er,R:gt},{name:"Tab→Pill",L:aa,R:Ct},{name:"Ornate→Sharp",L:sa,R:Yt},{name:"Sharp→Ornate",L:Kt,R:tr},{name:"Bracket→Arrow",L:ra,R:gt},{name:"Shield→Pill",L:Jn,R:Ct},{name:"Wave→Ornate",L:er,R:tr}],mo=[{name:"Skew ╲",L:Un,R:Fr},{name:"Skew ╱",L:Lr,R:Vn},{name:"◇ Romb",L:Mt,R:gt},{name:"╲→Pill",L:Un,R:Ct},{name:"Pill→╲",L:$t,R:Fr},{name:"╱→Sharp",L:Lr,R:Yt},{name:"Sharp→╱",L:Kt,R:Vn},{name:"╲→Arrow",L:Un,R:gt},{name:"Arrow→╱",L:Mt,R:Vn},{name:"◇→Chamfer",L:Mt,R:Zt}],Cn=[...ia,...po,...mo],go=ia[0];function dn(e){return Cn.find(t=>t.name===e)||go}const nr=[{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 un(e){return nr.find(t=>t.name===e)||null}const At={color:null,capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,glass:0,textureUrl:null,textureScale:1},lr={...At,glass:85},cr={...At,patternName:"Stars"},dr={...At,patternName:"Stars"},ur={fontFamily:null,fontSize:18,fontColor:null,outlineColor:null,outlineWidth:0,shadow:null},yo={filledBar:{...At},emptyBar:{...lr},goldFilledBar:{...dr},goldEmptyBar:{...cr},font:{...ur},disableGoldNotes:!1},Xt={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},Ga="nice2dev-player-bar-style",Ba="nice2dev-player-karaoke-settings";function Qt(e){return e!=null?`${Ba}-${e}`:Ba}function Mn(e){return e!=null?`${Ga}-${e}`:Ga}function Wa(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 Ua(e){const t=yo,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 bo(e){try{const t=localStorage.getItem(Qt(e));if(t){const r=JSON.parse(t);return Ua(r)}const n=localStorage.getItem(Mn(e));if(n){const r=JSON.parse(n),a=Wa({...Xt,...r});return localStorage.setItem(Qt(e),JSON.stringify(a)),a}if(e!=null){const r=localStorage.getItem(Qt());if(r)return Ua(JSON.parse(r));const a=localStorage.getItem(Mn());if(a)return Wa({...Xt,...JSON.parse(a)})}}catch{}return{filledBar:{...At},emptyBar:{...lr},goldFilledBar:{...dr},goldEmptyBar:{...cr},font:{...ur}}}function bd(e,t){const n=JSON.stringify(e);localStorage.setItem(Qt(t),n)}let Va=!1;async function vd(e){if(Va||(Va=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(Qt())||localStorage.setItem(Qt(),t)}catch{}}function xd(e){const t=new Map;for(const n of e)t.set(n,bo(n));return t}function vo(e){try{const t=localStorage.getItem(Mn(e));if(t)return{...Xt,...JSON.parse(t)};if(e!=null){const n=localStorage.getItem(Mn());if(n)return{...Xt,...JSON.parse(n)}}}catch{}return{...Xt}}function Sd(e,t){localStorage.setItem(Mn(t),JSON.stringify(e))}function wd(e){const t=new Map;for(const n of e)t.set(n,vo(n));return t}const Cd={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},kd=/[&<>"']/g;function Md(e){return e.replace(kd,t=>Cd[t])}function jd(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 Rd=3,Ge=Rd;function rr(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 ar(e){let t=e.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),"#"+t.toLowerCase()}function Qe(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 xo(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:h=!1,textureUrl:f=null,textureScale:m=1}=e,g=f&&jd(f)?Md(f):null,[p,v,x]=rr(ar(a)),b="c"+Math.random().toString(36).slice(2,7),w=r.L(n),y=r.R(n),k=t-w.w-y.w;if(k<4)return"";if(h&&c){const J=`hsl(${p},${v}%,${x}%)`,ae=`hsl(${p},${Math.max(v-20,0)}%,${Math.min(x+30,95)}%)`,re=d||ae,ee=w.w,F=w.w+k,K=w.inn,se=`M${ee} ${Be}H${F}V${n-Be}H${ee}Z`,ce=Qe(y.inn,F),fe=w.out,X=`M${ee} 0H${F}V${n}H${ee}Z`,ue=Qe(y.out,F),ye=c.mk(b+"pat",re,d||void 0),je=Math.round(256*m),Fe=Math.round(256*m),Re=g?`<pattern id="${b}tex" patternUnits="userSpaceOnUse" width="${je}" height="${Fe}"><image href="${g}" width="${je}" height="${Fe}" preserveAspectRatio="none"/></pattern>`:"",Se=g?`<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>
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 xo(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:h=!1,textureUrl:f=null,textureScale:m=1}=e,g=f&&jd(f)?Md(f):null,[p,v,x]=rr(ar(a)),b="c"+Math.random().toString(36).slice(2,7),w=r.L(n),y=r.R(n),k=t-w.w-y.w;if(k<4)return"";if(h&&c){const J=`hsl(${p},${v}%,${x}%)`,ae=`hsl(${p},${Math.max(v-20,0)}%,${Math.min(x+30,95)}%)`,re=d||ae,ee=w.w,F=w.w+k,K=w.inn,se=`M${ee} ${Ge}H${F}V${n-Ge}H${ee}Z`,ce=Qe(y.inn,F),fe=w.out,X=`M${ee} 0H${F}V${n}H${ee}Z`,ue=Qe(y.out,F),ye=c.mk(b+"pat",re,d||void 0),je=Math.round(256*m),Fe=Math.round(256*m),Re=g?`<pattern id="${b}tex" patternUnits="userSpaceOnUse" width="${je}" height="${Fe}"><image href="${g}" width="${je}" height="${Fe}" preserveAspectRatio="none"/></pattern>`:"",Se=g?`<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
4
  ${ye}
5
5
  ${Re}
6
6
  <clipPath id="${b}c"><path d="${K}"/><path d="${se}"/><path d="${ce}"/></clipPath>
@@ -9,48 +9,48 @@ ${Re}
9
9
  <path d="${K}" fill="${J}" opacity=".22"/><path d="${se}" fill="${J}" opacity=".22"/><path d="${ce}" fill="${J}" opacity=".22"/>
10
10
  ${Se}
11
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}%)`,R=`hsl(${p},${Math.max(v-12,0)}%,${Math.min(x+18,88)}%)`,_=`hsl(${p},${Math.min(v+20,100)}%,${Math.min(x+30,93)}%)`,E=`hsl(${p},${Math.max(v-20,0)}%,${Math.min(x+30,95)}%)`,U=d||E,W=o/100*.78,j=i/100*.65,L=1-l/100*.87,I=Be,q=n-Be,Y=I+(q-I)*.44,O=I+(q-I)*.58,Z=w.w,H=w.w+k,te=w.out,B=`M${Z} 0H${H}V${n}H${Z}Z`,z=Qe(y.out,H),S=w.inn,P=`M${Z} ${Be}H${H}V${n-Be}H${Z}Z`,$=Qe(y.inn,H),T=c?c.mk(b+"pat",U,d||void 0):"",C=c?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${b}pat)" clip-path="url(#${b}c)"/>`:"",A=Math.round(256*m),D=Math.round(256*m),V=g?`<pattern id="${b}tex" patternUnits="userSpaceOnUse" width="${A}" height="${D}"><image href="${g}" width="${A}" height="${D}" preserveAspectRatio="none"/></pattern>`:"",Q=g?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${b}tex)" opacity="${L*.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>
12
+ </svg>`}const M=`hsl(${p},${Math.min(v+10,100)}%,${Math.max(x-22,4)}%)`,N=`hsl(${p},${v}%,${x}%)`,R=`hsl(${p},${Math.max(v-12,0)}%,${Math.min(x+18,88)}%)`,_=`hsl(${p},${Math.min(v+20,100)}%,${Math.min(x+30,93)}%)`,E=`hsl(${p},${Math.max(v-20,0)}%,${Math.min(x+30,95)}%)`,U=d||E,W=o/100*.78,j=i/100*.65,L=1-l/100*.87,I=Ge,q=n-Ge,Y=I+(q-I)*.44,O=I+(q-I)*.58,Z=w.w,H=w.w+k,te=w.out,G=`M${Z} 0H${H}V${n}H${Z}Z`,z=Qe(y.out,H),S=w.inn,P=`M${Z} ${Ge}H${H}V${n-Ge}H${Z}Z`,$=Qe(y.inn,H),T=c?c.mk(b+"pat",U,d||void 0):"",C=c?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${b}pat)" clip-path="url(#${b}c)"/>`:"",A=Math.round(256*m),D=Math.round(256*m),V=g?`<pattern id="${b}tex" patternUnits="userSpaceOnUse" width="${A}" height="${D}"><image href="${g}" width="${A}" height="${D}" preserveAspectRatio="none"/></pattern>`:"",Q=g?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${b}tex)" opacity="${L*.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
13
  ${T}
14
14
  ${V}
15
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
16
  <linearGradient id="${b}f" x1="0" y1="${I}" x2="0" y2="${q}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${R}"/><stop offset=".5" stop-color="${N}"/><stop offset="1" stop-color="${M}"/></linearGradient>
17
- <linearGradient id="${b}h" x1="0" y1="${I}" x2="0" y2="${Y}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fff" stop-opacity="${W}"/><stop offset=".5" stop-color="#fff" stop-opacity="${W*.25}"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient>
17
+ <linearGradient id="${b}h" x1="0" y1="${I}" x2="0" y2="${Y}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="var(--nice-bg, #fff)" stop-opacity="${W}"/><stop offset=".5" stop-color="var(--nice-bg, #fff)" stop-opacity="${W*.25}"/><stop offset="1" stop-color="var(--nice-bg, #fff)" stop-opacity="0"/></linearGradient>
18
18
  <linearGradient id="${b}g" x1="0" y1="${O}" x2="0" y2="${q}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${_}" stop-opacity="0"/><stop offset=".6" stop-color="${_}" stop-opacity="${j*.6}"/><stop offset="1" stop-color="${_}" stop-opacity="${j}"/></linearGradient>
19
19
  <clipPath id="${b}c"><path d="${S}"/><path d="${P}"/><path d="${$}"/></clipPath>
20
20
  </defs>
21
- <path d="${te}" fill="url(#${b}b)"/><path d="${B}" fill="url(#${b}b)"/><path d="${z}" fill="url(#${b}b)"/>
21
+ <path d="${te}" fill="url(#${b}b)"/><path d="${G}" fill="url(#${b}b)"/><path d="${z}" fill="url(#${b}b)"/>
22
22
  <path d="${S}" fill="url(#${b}f)" opacity="${L}"/><path d="${P}" fill="url(#${b}f)" opacity="${L}"/><path d="${$}" fill="url(#${b}f)" opacity="${L}"/>
23
23
  ${Q}
24
24
  ${C}
25
25
  <rect x="0" y="${O}" width="${t}" height="${q-O}" fill="url(#${b}g)" clip-path="url(#${b}c)"/>
26
26
  <rect x="0" y="${I}" width="${t}" height="${Y-I}" fill="url(#${b}h)" clip-path="url(#${b}c)"/>
27
- </svg>`}function Ue(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]),h=l[3]!==0,f=l[4]!==0,m=l[5],g=l[6],p=r,v=a;if(Math.abs(p-m)<.001&&Math.abs(v-g)<.001||c<.001||d<.001){e.lineTo(m,g),r=m,a=g;break}const x=(c+d)/2,b=(p-m)/2,w=(v-g)/2,y=b*b+w*w,k=y>x*x?Math.sqrt(y):x,M=k*k,N=Math.sqrt(Math.max(0,(M-y)/y)),R=h!==f?1:-1,_=(p+m)/2+R*N*w,E=(v+g)/2-R*N*b,U=Math.atan2(v-E,p-_),W=Math.atan2(g-E,m-_);e.arc(_,E,k,U,W,!f),r=m,a=g;break}case"Z":e.closePath();break}}}function hn(e,t,n,r,a,o,i,l=70,c=55,d=0,h,f,m=!1,g,p){const[v,x,b]=rr(ar(i)),w=o.L(a),y=o.R(a),k=r-w.w-y.w;if(k<0){const[S,,P]=rr(ar(i));e.save(),e.translate(t,n),e.globalAlpha=1-d/100*.87,e.fillStyle=`hsl(${S},50%,${Math.min(P+10,80)}%)`;const $=Math.min(r/2,a/2);e.beginPath(),e.moveTo($,0),e.lineTo(r-$,0),e.quadraticCurveTo(r,0,r,$),e.lineTo(r,a-$),e.quadraticCurveTo(r,a,r-$,a),e.lineTo($,a),e.quadraticCurveTo(0,a,0,a-$),e.lineTo(0,$),e.quadraticCurveTo(0,0,$,0),e.closePath(),e.fill(),e.restore();return}const M=w.w,N=w.w+k;if(m){const S=`hsla(${v},${x}%,${b}%,0.22)`;e.save(),e.translate(t,n),e.fillStyle="rgba(255,255,255,0.18)",e.beginPath(),Ue(e,w.out),e.fill(),e.fillRect(M,0,k,a),e.beginPath(),Ue(e,Qe(y.out,N)),e.fill(),e.fillStyle=S,e.beginPath(),Ue(e,w.inn),e.fill(),e.fillRect(M,Be,k,a-2*Be),e.beginPath(),Ue(e,Qe(y.inn,N)),e.fill(),g&&(e.save(),e.beginPath(),Ue(e,w.inn),e.rect(M,Be,k,a-2*Be),Ue(e,Qe(y.inn,N)),e.clip(),e.globalAlpha=.85,e.fillStyle=g,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),p&&(e.save(),e.beginPath(),Ue(e,w.inn),e.rect(M,Be,k,a-2*Be),Ue(e,Qe(y.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 R=`hsl(${v},${Math.min(x+10,100)}%,${Math.max(b-22,4)}%)`,_=`hsl(${v},${x}%,${b}%)`,E=`hsl(${v},${Math.max(x-12,0)}%,${Math.min(b+18,88)}%)`,U=`hsl(${v},${Math.min(x+20,100)}%,${Math.min(b+30,93)}%)`,W=l/100*.78,j=c/100*.65,L=1-d/100*.87,I=Be,q=a-Be,Y=q-I,O=I+Y*.44,Z=I+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,"rgba(255,255,255,0.08)"),e.fillStyle=H,e.beginPath(),Ue(e,w.out),e.fill(),e.fillRect(M,0,k,a),e.beginPath(),Ue(e,Qe(y.out,N)),e.fill();const te=e.createLinearGradient(0,I,0,q);te.addColorStop(0,E),te.addColorStop(.5,_),te.addColorStop(1,R),e.globalAlpha=L,e.fillStyle=te,e.beginPath(),Ue(e,w.inn),e.fill(),e.fillRect(M,Be,k,a-2*Be),e.beginPath(),Ue(e,Qe(y.inn,N)),e.fill(),e.globalAlpha=1,g&&(e.save(),e.beginPath(),Ue(e,w.inn),e.rect(M,Be,k,a-2*Be),Ue(e,Qe(y.inn,N)),e.clip(),e.globalAlpha=L*.9,e.fillStyle=g,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),p&&(e.save(),e.beginPath(),Ue(e,w.inn),e.rect(M,Be,k,a-2*Be),Ue(e,Qe(y.inn,N)),e.clip(),e.globalAlpha=L*.85,e.fillStyle=p,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),e.save(),e.beginPath(),Ue(e,w.inn),e.rect(M,Be,k,a-2*Be),Ue(e,Qe(y.inn,N)),e.clip();const B=e.createLinearGradient(0,Z,0,q);B.addColorStop(0,"transparent"),B.addColorStop(.6,U.replace(")",`, ${j*.6})`).replace("hsl","hsla")),B.addColorStop(1,U.replace(")",`, ${j})`).replace("hsl","hsla")),e.fillStyle=B,e.fillRect(0,Z,r,q-Z);const z=e.createLinearGradient(0,I,0,O);z.addColorStop(0,`rgba(255,255,255,${W})`),z.addColorStop(.5,`rgba(255,255,255,${W*.25})`),z.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=z,e.fillRect(0,I,r,O-I),e.restore(),e.restore()}function $d(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,"rgba(0,0,0,0)"),i.addColorStop(1,a),t.globalAlpha=.18,t.fillStyle=i,t.fillRect(Math.max(0,n-60),0,60,r),t.globalAlpha=.9,t.strokeStyle=a,t.lineWidth=3,t.shadowColor=a,t.shadowBlur=12,t.beginPath(),t.moveTo(n,0),t.lineTo(n,r),t.stroke();const l=6+Math.sin(o*6)*2;t.fillStyle=e.ballIsGold?"#FFD700":a,t.beginPath(),t.moveTo(n,e.ballY-l),t.lineTo(n+l*.7,e.ballY),t.lineTo(n,e.ballY+l),t.lineTo(n-l*.7,e.ballY),t.closePath(),t.fill(),t.restore(),t.save(),t.globalCompositeOperation="source-atop",t.globalAlpha=.35;for(const c of e.visibleNotes)c.isSung&&(t.fillStyle=c.isGold?"#FFD700":a,t.fillRect(c.x,c.y,c.w,c.h));t.restore()}function Td(e){const{ctx:t,ballX:n,ballY:r,ballRadius:a,playerColor:o,ballIsGold:i,currentTime:l}=e,c=3,d=a*1.5,h=l*4;t.save();for(let m=0;m<c;m++){const g=(h+m*2.1)%(Math.PI*2),p=Math.sin(g)*.5+.5,v=d+p*a*3,x=(1-p)*.5;t.globalAlpha=x,t.strokeStyle=i?"#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?"#FFD700":o,t.shadowBlur=16+Math.sin(l*8)*4,t.fillStyle=i?"#FFF0A8":o;const f=a*(.8+Math.sin(l*10)*.2);t.beginPath(),t.arc(n,r,f,0,Math.PI*2),t.fill();for(const m of e.visibleNotes){if(!m.isSung)continue;const g=(l*6+m.x*.01)%(Math.PI*2),p=.15+Math.sin(g)*.1;t.globalAlpha=p,t.fillStyle=m.isGold?"#FFD700":o,t.fillRect(m.x,m.y,m.w,m.h)}t.restore()}function Pd(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),h=-Math.abs(Math.sin(d))*c,f=r+h;t.save(),t.globalAlpha=.3,t.fillStyle="rgba(0,0,0,0.5)";const m=1-Math.abs(h)/(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 g=5;for(let x=0;x<g;x++){const b=(x+1)*.04,w=(l-b)*5%(Math.PI*2),y=r+-Math.abs(Math.sin(w))*c,k=.15*(1-x/g),M=a*(.6-x*.08);t.globalAlpha=k,t.fillStyle=o,t.beginPath(),t.arc(n-x*3,y,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,f),t.scale(v,p),t.shadowColor=i?"#FFD700":o,t.shadowBlur=12,t.fillStyle=i?"#FFF0A8":o,t.beginPath(),t.arc(0,0,a,0,Math.PI*2),t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0,0,0,0.35)",t.stroke(),t.restore(),Math.abs(Math.sin(d))<.1){t.save(),t.globalAlpha=.6,t.fillStyle=i?"#FFD700":o;for(let x=0;x<4;x++){const b=x/4*Math.PI*2+l,w=n+Math.cos(b)*(a+4),y=r+Math.sin(b)*2;t.beginPath(),t.arc(w,y,2,0,Math.PI*2),t.fill()}t.restore()}}function Ed(e,t){switch(e){case"wipe":return $d(t),!0;case"pulse":return Td(t),!0;case"bounce":return Pd(t),!0;case"ball":default:return!1}}const Ad=1e3,Nd=20,Id=70,Ld=5,qa=26,Ha="rgba(255,215,70,0.98)",Ka=new Map,Fd=(e,t,n,r,a)=>{const o=`g${a}`,i=`<?xml version="1.0" encoding="UTF-8"?>
27
+ </svg>`}function Ue(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]),h=l[3]!==0,f=l[4]!==0,m=l[5],g=l[6],p=r,v=a;if(Math.abs(p-m)<.001&&Math.abs(v-g)<.001||c<.001||d<.001){e.lineTo(m,g),r=m,a=g;break}const x=(c+d)/2,b=(p-m)/2,w=(v-g)/2,y=b*b+w*w,k=y>x*x?Math.sqrt(y):x,M=k*k,N=Math.sqrt(Math.max(0,(M-y)/y)),R=h!==f?1:-1,_=(p+m)/2+R*N*w,E=(v+g)/2-R*N*b,U=Math.atan2(v-E,p-_),W=Math.atan2(g-E,m-_);e.arc(_,E,k,U,W,!f),r=m,a=g;break}case"Z":e.closePath();break}}}function hn(e,t,n,r,a,o,i,l=70,c=55,d=0,h,f,m=!1,g,p){const[v,x,b]=rr(ar(i)),w=o.L(a),y=o.R(a),k=r-w.w-y.w;if(k<0){const[S,,P]=rr(ar(i));e.save(),e.translate(t,n),e.globalAlpha=1-d/100*.87,e.fillStyle=`hsl(${S},50%,${Math.min(P+10,80)}%)`;const $=Math.min(r/2,a/2);e.beginPath(),e.moveTo($,0),e.lineTo(r-$,0),e.quadraticCurveTo(r,0,r,$),e.lineTo(r,a-$),e.quadraticCurveTo(r,a,r-$,a),e.lineTo($,a),e.quadraticCurveTo(0,a,0,a-$),e.lineTo(0,$),e.quadraticCurveTo(0,0,$,0),e.closePath(),e.fill(),e.restore();return}const M=w.w,N=w.w+k;if(m){const S=`hsla(${v},${x}%,${b}%,0.22)`;e.save(),e.translate(t,n),e.fillStyle="rgba(255,255,255,0.18)",e.beginPath(),Ue(e,w.out),e.fill(),e.fillRect(M,0,k,a),e.beginPath(),Ue(e,Qe(y.out,N)),e.fill(),e.fillStyle=S,e.beginPath(),Ue(e,w.inn),e.fill(),e.fillRect(M,Ge,k,a-2*Ge),e.beginPath(),Ue(e,Qe(y.inn,N)),e.fill(),g&&(e.save(),e.beginPath(),Ue(e,w.inn),e.rect(M,Ge,k,a-2*Ge),Ue(e,Qe(y.inn,N)),e.clip(),e.globalAlpha=.85,e.fillStyle=g,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),p&&(e.save(),e.beginPath(),Ue(e,w.inn),e.rect(M,Ge,k,a-2*Ge),Ue(e,Qe(y.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 R=`hsl(${v},${Math.min(x+10,100)}%,${Math.max(b-22,4)}%)`,_=`hsl(${v},${x}%,${b}%)`,E=`hsl(${v},${Math.max(x-12,0)}%,${Math.min(b+18,88)}%)`,U=`hsl(${v},${Math.min(x+20,100)}%,${Math.min(b+30,93)}%)`,W=l/100*.78,j=c/100*.65,L=1-d/100*.87,I=Ge,q=a-Ge,Y=q-I,O=I+Y*.44,Z=I+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(),Ue(e,w.out),e.fill(),e.fillRect(M,0,k,a),e.beginPath(),Ue(e,Qe(y.out,N)),e.fill();const te=e.createLinearGradient(0,I,0,q);te.addColorStop(0,E),te.addColorStop(.5,_),te.addColorStop(1,R),e.globalAlpha=L,e.fillStyle=te,e.beginPath(),Ue(e,w.inn),e.fill(),e.fillRect(M,Ge,k,a-2*Ge),e.beginPath(),Ue(e,Qe(y.inn,N)),e.fill(),e.globalAlpha=1,g&&(e.save(),e.beginPath(),Ue(e,w.inn),e.rect(M,Ge,k,a-2*Ge),Ue(e,Qe(y.inn,N)),e.clip(),e.globalAlpha=L*.9,e.fillStyle=g,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),p&&(e.save(),e.beginPath(),Ue(e,w.inn),e.rect(M,Ge,k,a-2*Ge),Ue(e,Qe(y.inn,N)),e.clip(),e.globalAlpha=L*.85,e.fillStyle=p,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),e.save(),e.beginPath(),Ue(e,w.inn),e.rect(M,Ge,k,a-2*Ge),Ue(e,Qe(y.inn,N)),e.clip();const G=e.createLinearGradient(0,Z,0,q);G.addColorStop(0,"transparent"),G.addColorStop(.6,U.replace(")",`, ${j*.6})`).replace("hsl","hsla")),G.addColorStop(1,U.replace(")",`, ${j})`).replace("hsl","hsla")),e.fillStyle=G,e.fillRect(0,Z,r,q-Z);const z=e.createLinearGradient(0,I,0,O);z.addColorStop(0,`rgba(255,255,255,${W})`),z.addColorStop(.5,`rgba(255,255,255,${W*.25})`),z.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=z,e.fillRect(0,I,r,O-I),e.restore(),e.restore()}function $d(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 Td(e){const{ctx:t,ballX:n,ballY:r,ballRadius:a,playerColor:o,ballIsGold:i,currentTime:l}=e,c=3,d=a*1.5,h=l*4;t.save();for(let m=0;m<c;m++){const g=(h+m*2.1)%(Math.PI*2),p=Math.sin(g)*.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 f=a*(.8+Math.sin(l*10)*.2);t.beginPath(),t.arc(n,r,f,0,Math.PI*2),t.fill();for(const m of e.visibleNotes){if(!m.isSung)continue;const g=(l*6+m.x*.01)%(Math.PI*2),p=.15+Math.sin(g)*.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 Pd(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),h=-Math.abs(Math.sin(d))*c,f=r+h;t.save(),t.globalAlpha=.3,t.fillStyle="var(--nice-overlay-50, rgba(0, 0, 0, 0.5))";const m=1-Math.abs(h)/(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 g=5;for(let x=0;x<g;x++){const b=(x+1)*.04,w=(l-b)*5%(Math.PI*2),y=r+-Math.abs(Math.sin(w))*c,k=.15*(1-x/g),M=a*(.6-x*.08);t.globalAlpha=k,t.fillStyle=o,t.beginPath(),t.arc(n-x*3,y,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,f),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,w=n+Math.cos(b)*(a+4),y=r+Math.sin(b)*2;t.beginPath(),t.arc(w,y,2,0,Math.PI*2),t.fill()}t.restore()}}function Ed(e,t){switch(e){case"wipe":return $d(t),!0;case"pulse":return Td(t),!0;case"bounce":return Pd(t),!0;case"ball":default:return!1}}const Ad=1e3,Nd=20,Id=70,Ld=5,qa=26,Ha="rgba(255,215,70,0.98)",Ka=new Map,Fd=(e,t,n,r,a)=>{const o=`g${a}`,i=`<?xml version="1.0" encoding="UTF-8"?>
28
28
  <svg xmlns='http://www.w3.org/2000/svg' width='${r}' height='${r}' viewBox='0 0 ${r} ${r}'>
29
29
  <defs>
30
30
  <radialGradient id='g${o}' 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
- <stop offset='100%' stop-color='rgba(0,0,0,0)' stop-opacity='0'/>
33
+ <stop offset='100%' stop-color='transparent' stop-opacity='0'/>
34
34
  </radialGradient>
35
35
  </defs>
36
36
  <g transform='translate(${r/2}, ${r/2})'>
37
37
  <circle cx='0' cy='0' r='${r*.45}' fill='url(#g${o})' />
38
38
  </g>
39
- </svg>`;return`data:image/svg+xml;utf8,${encodeURIComponent(i)}`},Dd=(e,t,n,r,a)=>{const o=`${e}-${t}-${n}-${Math.round(r)}-${a}`;let i=Ka.get(o);return i||(i=new Image,i.src=Fd(e,t,n,r,a),Ka.set(o,i),i)},Od=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 h=o-i;switch(c=d>.5?h/(2-o-i):h/(o+i),o){case n:l=(r-a)/h+(r<a?6:0);break;case r:l=(a-n)/h+2;break;case a:l=(n-r)/h+4;break}l/=6}return{h:Math.round(l*360),s:Math.round(c*100),l:Math.round(d*100)}},_d=(e,t,n,r=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(n)}%, ${r})`;function An(e){try{const t=Ir(e),[n,r,a]=gd(t),o=i=>i.toString(16).padStart(2,"0");return`#${o(n)}${o(r)}${o(a)}`.toLowerCase()}catch{return"#ffcc00"}}function zd(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 Vt=new Map,fn=new Set,qn=new Set;function la(e){const t=Vt.get(e);return t?Promise.resolve(t):qn.has(e)?Promise.reject(new Error(`Texture failed: ${e}`)):fn.has(e)?new Promise((n,r)=>{const a=()=>{Vt.has(e)?n(Vt.get(e)):qn.has(e)?r(new Error(`Texture failed: ${e}`)):requestAnimationFrame(a)};a()}):(fn.add(e),new Promise((n,r)=>{const a=new Image;a.crossOrigin="anonymous",a.onload=()=>{Vt.set(e,a),fn.delete(e),n(a)},a.onerror=()=>{fn.delete(e),qn.add(e),r(new Error(`Failed to load texture: ${e}`))},a.src=e}))}function Bd(e){return Vt.get(e)??null}function pn(e,t,n=1){const r=Vt.get(t);if(!r)return!fn.has(t)&&!qn.has(t)&&la(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 Gd(e){for(const t of e)t&&la(t).catch(()=>{})}const mn=new Map,Gt=new Set;function So(e,t,n){return`${e}|${t}|${n??""}`}function Wd(e,t,n){const r=So(e.name,t,n),a=mn.get(r);if(a)return Promise.resolve(a);if(Gt.has(r))return new Promise((p,v)=>{const x=()=>{mn.has(r)?p(mn.get(r)):Gt.has(r)?requestAnimationFrame(x):v(new Error(`Pattern render failed: ${r}`))};x()});Gt.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,h=c?parseInt(c[1],10):16,f=`<svg xmlns="http://www.w3.org/2000/svg" width="${d}" height="${h}"><defs>${i}</defs><rect width="${d}" height="${h}" fill="url(#${o})"/></svg>`,m=new Blob([f],{type:"image/svg+xml;charset=utf-8"}),g=URL.createObjectURL(m);return new Promise((p,v)=>{const x=new Image;x.onload=()=>{mn.set(r,x),Gt.delete(r),URL.revokeObjectURL(g),p(x)},x.onerror=()=>{Gt.delete(r),URL.revokeObjectURL(g),v(new Error(`Failed to render pattern tile: ${e.name}`))},x.src=g})}function gn(e,t,n,r){const a=So(t.name,n,r),o=mn.get(a);return o?e.createPattern(o,"repeat"):(Gt.has(a)||Wd(t,n,r).catch(()=>{}),null)}let ft=null,qe=null,nt=null,St=null,it=null,Ae=null,Ya="",Za=0,Xa="";const Dr=(e,t,n,r,a,o,i,l,c,d,h,f,m,g,p,v,x,b,w,y,k,M,N,R)=>{e.clearRect(0,0,t,n);const _=R??null,E=(_==null?void 0:_.filledBar)??At,U=(_==null?void 0:_.emptyBar)??lr,W=(_==null?void 0:_.goldFilledBar)??dr,j=(_==null?void 0:_.goldEmptyBar)??cr,L=(_==null?void 0:_.font)??ur,I=dn(E.capStyleName),q=dn(U.capStyleName),Y=dn(W.capStyleName),O=dn(j.capStyleName),Z=E.patternName?un(E.patternName):null,H=U.patternName?un(U.patternName):null,te=W.patternName?un(W.patternName):null,B=j.patternName?un(j.patternName):null,z=Z?gn(e,Z,E.patternColor??E.color??"#ffffff",E.patternColor):null,S=H?gn(e,H,U.patternColor??U.color??"#d1d5db",U.patternColor):null,P=te?gn(e,te,W.patternColor??"#FFD700",W.patternColor):null,$=B?gn(e,B,j.patternColor??"#FFD700",j.patternColor):null;Xa!==o&&(Xa=o,Nr("RENDER",`?? Renderer using settings for "${o}" � filled: cap=${E.capStyleName}, glass=${E.glass} | empty: cap=${U.capStyleName}, glass=${U.glass} | goldFilled: cap=${W.capStyleName}, pattern=${W.patternName??"none"} | goldEmpty: cap=${j.capStyleName}, pattern=${j.patternName??"none"} | hasSettings=${!!_}`,{filledBar:E,emptyBar:U,goldFilledBar:W,goldEmptyBar:j,filledOverlay:!!z,emptyOverlay:!!S,goldFilledOverlay:!!P,goldEmptyOverlay:!!$}));const T=E.textureUrl?pn(e,E.textureUrl,E.textureScale):null,C=U.textureUrl?pn(e,U.textureUrl,U.textureScale):null,A=W.textureUrl?pn(e,W.textureUrl,W.textureScale):null,D=j.textureUrl?pn(e,j.textureUrl,j.textureScale):null,V=typeof document<"u"?Ir(l||"var(--accent-primary, #ffcc00)"):l||"var(--accent-primary, #ffcc00)",Q=An(V||"#ffcc00"),J=ie=>Ir(ie),ae=L.fontFamily||"Arial",re=L.fontSize||18,ee=J(L.fontColor||"var(--btn-text, #fff)"),F=L.outlineColor?J(L.outlineColor):null,K=typeof L.outlineWidth=="number"?L.outlineWidth:0,se=L.shadow||null;typeof document<"u"&&((!ft||ft.width!==t||ft.height!==n)&&(ft=document.createElement("canvas"),ft.width=t,ft.height=n,qe=ft.getContext("2d")),qe&&qe.clearRect(0,0,t,n),(!nt||nt.width!==t||nt.height!==n)&&(nt=document.createElement("canvas"),nt.width=t,nt.height=n,St=nt.getContext("2d")),St&&St.clearRect(0,0,t,n),(!it||it.width!==t||it.height!==n)&&(it=document.createElement("canvas"),it.width=t,it.height=n,Ae=it.getContext("2d")),Ae&&Ae.clearRect(0,0,t,n));const ce=w?-w:0,fe=y||t;e.fillStyle=V,e.font=`bold ${re}px ${ae}`;const ue=e.measureText(o).width+20;if(e.fillRect(ce+10,5,ue,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),F&&K>0&&(e.lineWidth=K,e.strokeStyle=F,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,Oe=8,ve=ce+10+ue+6,me=20,ge=7,ke=he+Oe*2,$e=4;e.beginPath(),e.moveTo(ve+$e,ge),e.lineTo(ve+ke-$e,ge),e.quadraticCurveTo(ve+ke,ge,ve+ke,ge+$e),e.lineTo(ve+ke,ge+me-$e),e.quadraticCurveTo(ve+ke,ge+me,ve+ke-$e,ge+me),e.lineTo(ve+$e,ge+me),e.quadraticCurveTo(ve,ge+me,ve,ge+me-$e),e.lineTo(ve,ge+$e),e.quadraticCurveTo(ve,ge,ve+$e,ge),e.closePath(),e.fillStyle=ie,e.fill(),e.fillStyle=ee,e.fillText(x,ve+Oe,ge+14),e.font=`bold ${re}px ${ae}`}const ye=120;if(e.fillStyle=V,e.fillRect(ce+fe-ye-10,5,ye,25),e.fillStyle=ee,e.fillText(`${i} pts`,ce+fe-ye+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 ve=e.measureText(he).width+16,me=ce+fe-ye-10-ve-6;e.fillStyle=J(k.currentCombo>=20?"var(--success, #FFD700)":"var(--warning, #ff9800)"),e.globalAlpha=.9,zd(e,me,7,ve,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=J(k.currentCombo>=20?"var(--text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(he,me+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!==Ya&&(Ya=he,Za=Date.now());const Oe=Date.now()-Za;if(Oe<2500){const ve=Oe<2e3?1:1-(Oe-2e3)/500,me={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=ve,e.font=`bold ${Math.round(re*1.2)}px ${ae}`;const ge=ie.label,ke=e.measureText(ge).width,$e=ce+fe/2-ke/2;e.fillStyle=me[ge]||ee,e.shadowColor="rgba(0,0,0,0.5)",e.shadowBlur=6,e.fillText(ge,$e,58),F&&K>0&&(e.lineWidth=K,e.strokeStyle=F,e.strokeText(ge,$e,58)),e.restore()}}}const je=a-2,Fe=a+5,Re=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,Oe=-1/0;c.forEach(({t:ve,hz:me})=>{if(!me||me<=0)return;let ge=ie;for(const $e of r)for(const We of $e)ve>=We.startTime&&ve<=We.startTime+We.duration&&(ge=We.pitch);const ke=oo(me,ge);ke<he&&(he=ke),ke>Oe&&(Oe=ke)}),he!==1/0&&Oe!==-1/0&&(he<Se&&(Se=Math.floor(he-2)),Oe>ne&&(ne=Math.ceil(Oe+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-Re-10;return Re+he-(ie-Se)/(ne-Se)*he},De=lo(m||"normal"),tt=(n-Re-10)/Math.max(1,ne-Se),we=Math.max(10,Math.round(tt*(1+2*De.semitoneTolerance)*.3)),dt=Math.max(5,Math.round(we*.45));((ie,he,Oe,ve,me,ge)=>{ie.lineWidth=1;for(let ke=Math.ceil(me);ke<=Math.floor(ge);ke++){const $e=oe(ke);ie.strokeStyle=J(ke%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-Re,Re,Se,ne),St&&St.clearRect(0,0,t,n);const Xe=(a-je)/(Fe-je)*t;let Ge=n*.5,It=!1,yt=!1;const mr=(ie,he,Oe,ve,me,ge,ke=0)=>{const $e=(be,Me,Te,_e,ze,Ke)=>{const Ie=Math.min(Ke,_e/2,ze/2);be.beginPath(),be.moveTo(Me+Ie,Te),be.lineTo(Me+_e-Ie,Te),be.quadraticCurveTo(Me+_e,Te,Me+_e,Te+Ie),be.lineTo(Me+_e,Te+ze-Ie),be.quadraticCurveTo(Me+_e,Te+ze,Me+_e-Ie,Te+ze),be.lineTo(Me+Ie,Te+ze),be.quadraticCurveTo(Me,Te+ze,Me,Te+ze-Ie),be.lineTo(Me,Te+Ie),be.quadraticCurveTo(Me,Te,Me+Ie,Te),be.closePath()},We=Math.max(2,we/2);ve.forEach(be=>{if(be.startTime+be.duration<me||be.startTime>ge)return;const Me=(be.startTime-me)/(ge-me)*he,Te=be.duration/(ge-me)*he,_e=oe(be.pitch)-we/2,ze=[];if(Array.isArray(f)){const Ke=be.startTime+be.duration;f.forEach(Ie=>{if(Ie.pitch!==be.pitch||Ie.noteStart!=null&&Ie.noteEnd!=null&&(Math.abs(Ie.noteStart-be.startTime)>.01||Math.abs(Ie.noteEnd-Ke)>.01))return;const ot=Math.max(Ie.start,be.startTime),bt=Math.min(Ie.end,Ke);if(ot>=bt)return;const Rt=(ot-me)/(ge-me)*he,Lt=(bt-me)/(ge-me)*he;ze.push({x1:Rt,x2:Lt,frac:Ie.frac})})}if(be.isGold){ie.save();const Ke=p&&p.shadowColor?p.shadowColor:Ha,Ie=p&&typeof p.glowBlur=="number"?p.glowBlur:qa;ie.shadowColor=Ke,ie.shadowBlur=Math.max(4,Ie-12),ie.fillStyle=J("var(--gold-overlay, rgba(255, 215, 0, 0.15))"),$e(ie,Me-1,_e-1,Te+2,we+2,We),ie.fill(),ie.restore();const ot=An("var(--gold-base, #b4af9f)");hn(ie,Me,_e,Te,we,O,j.color??ot,j.highlight,j.glow,j.glass,B,j.patternColor,j.patternOnly,D,$),ie.save(),$e(ie,Me,_e,Te,we,We),ie.clip(),ie.globalAlpha=.18,ie.fillStyle=J("var(--success, #FFD700)"),ie.fillRect(Me,_e,Te,Math.max(1,we*.25)),ie.globalAlpha=1,ie.restore(),ze.length>0&&(ie.save(),$e(ie,Me,_e,Te,we,We),ie.clip(),ze.forEach(bt=>{const Rt=Math.max(1,bt.x2-bt.x1);hn(ie,bt.x1,_e,Rt,we,Y,W.color??"#FFD700",W.highlight,W.glow,W.glass,te,W.patternColor,W.patternOnly,A,P)}),ie.restore()),ze.length===0&&(ie.lineWidth=1,ie.strokeStyle=J("var(--gold-outline, rgba(255, 215, 0, 0.35))"),$e(ie,Me+.5,_e+.5,Te-1,Math.max(1,we-1),We),ie.stroke())}else{const Ke=An("var(--note-base, #d1d5db)");hn(ie,Me,_e,Te,we,q,U.color??Ke,U.highlight,U.glow,U.glass,H,U.patternColor,U.patternOnly,C,S),ze.length>0&&(ie.save(),$e(ie,Me,_e,Te,we,We),ie.clip(),ze.forEach(Ie=>{const ot=Math.max(1,Ie.x2-Ie.x1);hn(ie,Ie.x1,_e,ot,we,I,E.color??Q,E.highlight,E.glow,E.glass,Z,E.patternColor,E.patternOnly,T,z)}),ie.restore())}St&&(St.fillStyle="#ffffff",St.fillRect(Me,_e,Te,we))})};if(r.forEach(ie=>{mr(e,t,n-Re,ie,je,Fe,Re);for(const he of ie)if(a>=he.startTime&&a<=he.startTime+he.duration){Ge=oe(he.pitch),It=!0,yt=!!he.isGold;break}}),!It){let ie=null,he=null;for(const Oe of r)for(const ve of Oe)ve.startTime>a&&(!ie||ve.startTime<ie.startTime)&&(ie=ve),ve.startTime<=a&&(!he||ve.startTime>he.startTime)&&(he=ve);ie?(Ge=oe(ie.pitch),yt=!!ie.isGold):he?(Ge=oe(he.pitch),yt=!!he.isGold):Ge=n*.5}const ut=V||J("var(--accent-primary, #ffcc00)"),le=1+Math.sin((a||0)*8)*.06,de=dt*le,Ce=[];for(const ie of r)for(const he of ie){if(he.startTime+he.duration<je||he.startTime>Fe)continue;const Oe=(he.startTime-je)/(Fe-je)*t,ve=he.duration/(Fe-je)*t,me=oe(he.pitch)-we/2,ge=he.startTime+he.duration<=a;Ce.push({x:Oe,y:me,w:ve,h:we,isGold:he.isGold,isSung:ge})}if(!Ed(N||"ball",{ctx:e,ballX:Xe,ballY:Ge,ballRadius:de,playerColor:ut,ballIsGold:yt,currentTime:a,height:n,visibleNotes:Ce})){ft&&e.drawImage(ft,0,0),it&&e.drawImage(it,0,0),e.save(),e.globalCompositeOperation="source-over",e.globalAlpha=.28;const ie=Math.max(18,de*5),he=e.createRadialGradient(Xe,Ge,0,Xe,Ge,ie);if(he.addColorStop(0,ut),he.addColorStop(1,"rgba(0,0,0,0)"),e.fillStyle=he,e.beginPath(),e.arc(Xe,Ge,ie,0,Math.PI*2),e.fill(),e.restore(),g&&qe&&nt&&(qe.save(),qe.globalCompositeOperation="source-over",qe.globalAlpha=.95,qe.fillStyle=ut,qe.beginPath(),qe.arc(Xe,Ge,de+4,0,Math.PI*2),qe.fill(),qe.restore(),qe.save(),qe.globalCompositeOperation="destination-in",qe.drawImage(nt,0,0),qe.restore(),e.drawImage(ft,0,0)),g&&Ae&&nt)try{const me=An(ut),{h:ge,s:ke,l:$e}=Od(me),be=_d(ge,Math.max(10,Math.round(ke*(typeof h=="number"?h:.25))),$e,.85);Ae.save(),Ae.globalCompositeOperation="multiply",Ae.globalAlpha=.65,Ae.fillStyle=be,Ae.beginPath(),Ae.arc(Xe,Ge,Math.max(8,de+6),0,Math.PI*2),Ae.fill(),Ae.restore(),Ae.save(),Ae.globalCompositeOperation="destination-out",Ae.drawImage(nt,0,0),Ae.restore(),e.drawImage(it,0,0)}catch{Ae.save(),Ae.globalCompositeOperation="source-over",Ae.globalAlpha=.6,Ae.fillStyle=ut,Ae.beginPath(),Ae.arc(Xe,Ge,Math.max(8,de+6),0,Math.PI*2),Ae.fill(),Ae.restore(),Ae.save(),Ae.globalCompositeOperation="destination-out",Ae.drawImage(nt,0,0),Ae.restore(),e.drawImage(it,0,0)}const Oe=p&&p.shadowColor?p.shadowColor:Ha,ve=p&&typeof p.glowBlur=="number"?p.glowBlur:qa;e.save(),yt?(e.shadowColor=Oe,e.shadowBlur=ve,e.fillStyle=J("var(--gold-light, #FFF0A8)")):(e.shadowColor=ut,e.shadowBlur=10,e.fillStyle=ut),e.globalCompositeOperation="source-over",e.globalAlpha=1,e.beginPath(),e.arc(Xe,Ge,de,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:Ad,Oe=(me,ge,ke,$e=5)=>{const We=ke,be=ke*.45;e.beginPath();let Me=Math.PI/2*3,Te=me,_e=ge;const ze=Math.PI/$e;e.moveTo(me,ge-We);for(let Ke=0;Ke<$e;Ke++)Te=me+Math.cos(Me)*We,_e=ge+Math.sin(Me)*We,e.lineTo(Te,_e),Me+=ze,Te=me+Math.cos(Me)*be,_e=ge+Math.sin(Me)*be,e.lineTo(Te,_e),Me+=ze;e.lineTo(me,ge-We),e.closePath()},ve=me=>{let ge=me>>>0;return()=>(ge=ge*1664525+1013904223>>>0,(ge&2147483647)/2147483647)};v.forEach(me=>{const ge=ie-me.createdAt;if(ge<0||ge>he)return;const ke=ge/he,$e=(me.noteStart-(a-2))/7*t,We=oe(me.notePitch),be=ve(me.seed||Math.floor(me.createdAt%1e5)),Me=p&&typeof p.count=="number"?p.count:Nd,Te=p&&typeof p.baseSpeed=="number"?p.baseSpeed:Id,_e=p&&typeof p.baseSize=="number"?p.baseSize:Ld;for(let ze=0;ze<Me;ze++){const Ke=be(),Ie=be(),ot=ze/Me*Math.PI*2+Ke*Math.PI*.6+ke*1.5,bt=6+Te*(1-ke)*(.5+Ie*.8),Rt=$e+Math.cos(ot)*bt,Lt=We+Math.sin(ot)*bt*(.8+Ke*.6),ht=Math.max(1,_e*(1-ke)*(.5+Ie)),Ea=40+Math.round(20*be()),Aa=70+Math.round(20*be()),gr=Math.max(0,1-ke)*(.9-be()*.3),$l=Math.max(6,ht*2.6),yr=Dd(Ea,Aa,60,Math.round($l),(me.seed||0)+ze);yr&&yr.complete?(e.save(),e.translate(Rt,Lt+4),e.rotate(ot+ke*4+(be()-.5)*1.2),e.globalAlpha=gr,e.drawImage(yr,-ht/2,-ht/2,ht,ht),e.restore()):(e.save(),e.translate(Rt,Lt+4),e.rotate(ot+ke*4),e.fillStyle=`hsla(${Ea}, ${Aa}%, 60%, ${gr})`,e.fillRect(-ht/2,-ht/2,ht,ht),e.restore()),be()>.85&&(e.save(),e.globalAlpha=Math.max(.35,1-ke),e.fillStyle=`hsla(${30+Math.round(10*be())}, ${60+Math.round(30*be())}%, ${70+Math.round(10*be())}%, ${gr})`,e.strokeStyle=`rgba(0,0,0,${.12*(1-ke)})`,e.lineWidth=.8,Oe(Rt,Lt+4,ht*(1.4+be())),e.fill(),e.stroke(),e.restore())}})}}catch{}return{ballX:Xe,ballY:Ge,ballIsGold:yt}},wo=({song:e,currentTime:t,playerRef:n,config:r={},userPitch:a,segmentScores:o,goldBursts:i,combo:l,verseRatings:c})=>{const{isPlaying:d=!1,playerName:h="Ziom",score:f=1e4,playerBgColor:m="var(--karaoke-player-bg, #2196f3)",playerCount:g=2,gapDesaturation:p,goldSettings:v,difficultyLevel:x,algorithmLabel:b,algorithmColor:w,latencyMs:y=null,top:k,animationMode:M,karaokeSettings:N=null}=r,R=u.useRef(null),_=u.useRef(null),[E,U]=u.useState({width:600,height:150,top:250,visibleWidth:600}),[W,j]=u.useState(0),L=u.useRef(0),I=u.useRef(null),q=u.useRef(null),Y=u.useRef(null),O=u.useRef(t),Z=u.useRef(performance.now()),H=u.useRef(e),te=u.useRef(E),B=u.useRef(a),z=u.useRef(d),S=u.useRef(0),P=u.useRef(!1),$=u.useRef(null),T=u.useRef(null),C=()=>{const A=(e==null?void 0:e.id)??null;if(A!==T.current||!$.current){T.current=A;const D=e.notes.map(ee=>ee.noteLine);$.current=ea(D,e.bpm??void 0);const V=$.current.reduce((ee,F)=>ee+F.length,0),Q=$.current.reduce((ee,F)=>ee+F.filter(K=>K.isGold).length,0),J=$.current.flat().map(ee=>ee.pitch),ae=J.length?Math.min(...J):0,re=J.length?Math.max(...J):0;Nr("BARS",`?? Parsed notes for "${e.title}" — ${$.current.length} verses, ${V} notes (including ${Q} golden), pitch range: ${ae}–${re}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:D.length,verseCount:$.current.length,totalNotes:V,goldCount:Q,minPitch:ae,maxPitch:re})}return $.current};return u.useEffect(()=>{const A=(V,Q,J)=>V+(Q-V)*J,D=V=>{q.current===null&&(q.current=V);const Q=Math.min(.1,(V-(q.current||V))/1e3);q.current=V;const J=S.current,ae=L.current,re=1-Math.exp(-12*Q),ee=Math.abs(ae-J)<.25?ae:A(J,ae,re);Math.abs(ee-J)>1e-4&&(j(ee),S.current=ee,R.current&&(R.current.style.transform=`translateX(${ee}px)`)),I.current=requestAnimationFrame(D)};return I.current=requestAnimationFrame(D),()=>{I.current&&cancelAnimationFrame(I.current),I.current=null,q.current=null}},[]),u.useEffect(()=>{const A=()=>{if(!n.current)return;const D=n.current.getBoundingClientRect(),V=2/Math.max(1,g),Q=Math.round(D.width*V),J=Math.round(D.width),ae=Q*(150/600);U({width:Q,height:ae,top:30,visibleWidth:J})};return A(),window.addEventListener("resize",A),()=>window.removeEventListener("resize",A)},[n,g]),u.useEffect(()=>{var J;if(d||!R.current)return;const A=R.current.getContext("2d");if(!A)return;const D=C(),V=t-(e.gap??0)/1e3,Q=Dr(A,E.width,E.height,D,V,h,f,m,a,e.id,p??void 0,o,x??void 0,d,v??void 0,i,b,w,S.current,E.visibleWidth,l,c,M,N);if(Q&&R.current){const ae=E.visibleWidth||(((J=_.current)==null?void 0:J.getBoundingClientRect().width)??E.width),re=E.width;let ee=Math.round(ae/2-Q.ballX);const F=ae-re;ee=Math.max(F,Math.min(0,ee)),L.current=ee}},[t,e,E,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=E},[E]),u.useEffect(()=>{B.current=a},[a]),u.useEffect(()=>{z.current=d},[d]),u.useEffect(()=>{const A=()=>{var se;const D=R.current,V=H.current,Q=te.current;if(!D||!V||!Q)return;const J=D.getContext("2d");if(!J)return;const ae=C(),re=Math.min(.5,(performance.now()-Z.current)/1e3),F=(z.current?O.current+re:O.current)-(V.gap??0)/1e3,K=Dr(J,Q.width,Q.height,ae,F,h,f,m,B.current,V.id,p??void 0,o,x??void 0,z.current,v??void 0,i,b,w,S.current,Q.visibleWidth,l,c,M,N);if(K){const ce=Q.visibleWidth||(((se=_.current)==null?void 0:se.getBoundingClientRect().width)??Q.width),fe=Q.width;let X=Math.round(ce/2-K.ballX);const ue=ce-fe;X=Math.max(ue,Math.min(0,X)),L.current=X}};if(d){P.current||(P.current=!0,Nr("BARS",`? Drawing bars in RAF loop � canvas: ${te.current.width}�${te.current.height}px, player: ${h}`,{canvasSize:te.current}));const D=()=>{A(),Y.current=requestAnimationFrame(D)};return Y.current=requestAnimationFrame(D),()=>{Y.current&&cancelAnimationFrame(Y.current),Y.current=null}}P.current=!1},[d,h,f,m,p,o,x,v,i,M,N]),s.jsxs("div",{ref:_,style:{position:"absolute",left:"50%",top:`${k??E.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:E.visibleWidth,height:E.height,overflow:"hidden"},children:[s.jsx("style",{children:"@keyframes av-latency-pulse {0% { transform: scale(1); box-shadow: 0 4px 10px rgba(0,0,0,0.2);} 50% { transform: scale(1.08); box-shadow: 0 8px 18px rgba(0,0,0,0.32);} 100% { transform: scale(1); box-shadow: 0 4px 10px rgba(0,0,0,0.2);} } .av-latency-pulse { animation: av-latency-pulse 1s ease-in-out infinite; }"}),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 y<"u"&&y!==null?(()=>{const A=y,D=A<=120?"var(--latency-good, #10b981)":A<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",V=`${A}ms`;return s.jsxs("div",{className:A>250?"av-latency-pulse":"",style:{background:D,padding:"6px 10px",borderRadius:12,boxShadow:"0 4px 10px rgba(0,0,0,0.35)",fontWeight:700,minWidth:56,textAlign:"center",display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{style:{display:"inline-block",transform:"translateY(-1px)"},children:"??"}),s.jsx("span",{children:V})]})})():s.jsx("div",{style:{background:"var(--latency-none-bg, rgba(75,85,99,0.9))",padding:"6px 8px",borderRadius:12,boxShadow:"0 4px 10px rgba(0,0,0,0.35)",minWidth:44,textAlign:"center"},children:"�"})}),s.jsx("canvas",{ref:R,width:E.width,height:E.height,role:"img","aria-label":`Pitch timeline for ${h??"player"}. Score: ${f??0}`,style:{position:"absolute",left:0,top:0,transform:`translateX(${W}px)`,willChange:"transform"}})]})},Co="/textures/seamless/256x256";function vt(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:`${Co}/${e}/Photoreal_${e}_${o}-512x512.png`}})}}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:`${Co}/${e}/${e}_${o}-256x256.png`}})}}const ca=[vt("Fire",8,"🔥"),vt("Metal",8,"⚙️"),vt("Ice",8,"❄️"),vt("Stone",8,"🪨"),vt("Wood",8,"🪵"),vt("Tile",8,"🧱"),vt("Concrete",8,"🏗️"),vt("Trees",8,"🌲"),vt("Grass",8,"🌿"),wt("Wall",24,"🏠"),wt("Rust",24,"🟤"),wt("Woven",24,"🧵"),wt("Ground",24,"🟫"),wt("Pebbles",24,"🫧"),wt("Plant",24,"🌱"),wt("Roof",24,"🏛️"),wt("Misc",24,"🎨")],ko=ca.flatMap(e=>e.entries);function Ud(e){return ko.find(t=>t.url===e)}const Vd={color:"#2196f3",highlight:"#ffffff",glow:0,capStyle:"flat",pattern:null,texture:null},Mo=({fill:e=Vd,onChange:t=()=>{},previewColor:n="#2196f3",accentColor:r="#0d6efd",width:a,height:o})=>{const{t:i}=xe(),[l,c]=u.useState(null),d=(b,w)=>{t({...e,[b]:w})},h=u.useMemo(()=>{const b=e.color||n||"#2196f3";return(w,y,k)=>{const M=Cn.find(R=>R.name===w)||Cn[0],N=y?nr.find(R=>R.name===y)??null:null;return xo({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]),f=`2px solid ${r}`,m=r==="#d4a017"?"#fff8e1":"#e7f1ff",g=u.useRef(null),p=u.useRef(null),v=u.useCallback((b,w)=>{b.current&&b.current.scrollBy({left:w*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:"#ccc",background:"linear-gradient(90deg, 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(Ve.Form.Label,{className:"mb-0",style:{fontSize:13,color:"#ccc"},children:i("playerForm.barColor","Color")}),s.jsx(Ve.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||"#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(Ve.Form.Label,{style:{fontSize:13,color:"#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(g,-1),children:"�"}),s.jsx("button",{type:"button",style:{...x,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, rgba(30,30,30,0.9) 60%, transparent)"},onClick:()=>v(g,1),children:"�"}),s.jsx("div",{ref:g,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:Cn.map(b=>{const w=e.capStyleName===b.name;return s.jsx("div",{title:b.name,onClick:()=>d("capStyleName",b.name),style:{cursor:"pointer",flexShrink:0,border:w?f:"1px solid #555",borderRadius:6,padding:3,background:w?m:"#222"},dangerouslySetInnerHTML:{__html:h(b.name,null)}},b.name)})})]}),s.jsx(Ve.Form.Label,{style:{fontSize:13,color:"#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, 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 #555":f,borderRadius:6,padding:"3px 8px",background:e.patternName?"#222":m,fontSize:12,lineHeight:"22px",color:"#ccc"},children:"�"}),nr.map(b=>{const w=e.patternName===b.name;return s.jsx("div",{title:b.name,onClick:()=>d("patternName",b.name),style:{cursor:"pointer",flexShrink:0,border:w?f:"1px solid #555",borderRadius:6,padding:3,background:w?m:"#222"},dangerouslySetInnerHTML:{__html:h(e.capStyleName,b.name)}},b.name)})]})]}),s.jsx(Ve.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(Ve.Form.Label,{className:"mb-0",style:{fontSize:13,color:"#ccc"},children:i("playerForm.patternColor","Pattern color")}),s.jsx(Ve.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||"#ffffff"),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(Ve.Form.Label,{style:{fontSize:13,color:"#ccc"},children:[i("playerForm.highlight","Highlight"),": ",e.highlight,"%"]}),s.jsx(Ve.Form.Range,{min:0,max:100,value:e.highlight,onChange:b=>d("highlight",parseInt(b.target.value)),className:"mb-2"}),s.jsxs(Ve.Form.Label,{style:{fontSize:13,color:"#ccc"},children:[i("playerForm.glow","Glow"),": ",e.glow,"%"]}),s.jsx(Ve.Form.Range,{min:0,max:100,value:e.glow,onChange:b=>d("glow",parseInt(b.target.value)),className:"mb-2"})]}),s.jsxs(Ve.Form.Label,{style:{fontSize:13,color:"#ccc"},children:[i("playerForm.glass","Transparency (glass)"),": ",e.glass,"%"]}),s.jsx(Ve.Form.Range,{min:0,max:100,value:e.glass,onChange:b=>d("glass",parseInt(b.target.value)),className:"mb-2"}),s.jsx(Ve.Form.Label,{style:{fontSize:13,fontWeight:600,marginTop:4,color:"#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")}),ca.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(w=>(w==null?void 0:w.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 #dee2e6",borderRadius:6,background:"#f8f9fa"},children:l.entries.map(b=>{const w=e.textureUrl===b.url;return s.jsx("div",{title:b.label,onClick:()=>d("textureUrl",w?null:b.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:w?`3px solid ${r}`:"1px solid #bbb",backgroundImage:`url(${b.url})`,backgroundSize:"cover",boxShadow:w?`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 #aaa"}}),s.jsx("span",{style:{fontSize:11,color:"#666"},children:e.textureUrl.split("/").pop()})]})]}),e.textureUrl&&s.jsxs(s.Fragment,{children:[s.jsxs(Ve.Form.Label,{style:{fontSize:13,color:"#ccc"},children:[i("playerForm.textureScale","Texture scale"),": ",e.textureScale.toFixed(1),"�"]}),s.jsx(Ve.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"})]})]})},He=et.scoped("AudioPitchAnalyzer");function jo({onSegments:e,defaultCompareAll:t=!1,externalFile:n=null,postPitch:r,postLibrosaPitchTrack:a}){const{t:o}=xe(),[i,l]=u.useState("pitchy"),[c,d]=u.useState(null),[h,f]=u.useState(t),[m,g]=u.useState({}),[p,v]=u.useState({}),[x,b]=u.useState([]),[w,y]=u.useState([]),[k,M]=u.useState(!1),[N,R]=u.useState(null),[_]=u.useState(null),[E]=u.useState(null),[U,W]=u.useState(null),j=u.useRef(null);function L(B){try{if(B instanceof Error){let S=`${B.message}
40
- ${B.stack??""}`;const P=B;if(P!=null&&P.attemptedUrls)try{S+=`
39
+ </svg>`;return`data:image/svg+xml;utf8,${encodeURIComponent(i)}`},Dd=(e,t,n,r,a)=>{const o=`${e}-${t}-${n}-${Math.round(r)}-${a}`;let i=Ka.get(o);return i||(i=new Image,i.src=Fd(e,t,n,r,a),Ka.set(o,i),i)},Od=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 h=o-i;switch(c=d>.5?h/(2-o-i):h/(o+i),o){case n:l=(r-a)/h+(r<a?6:0);break;case r:l=(a-n)/h+2;break;case a:l=(n-r)/h+4;break}l/=6}return{h:Math.round(l*360),s:Math.round(c*100),l:Math.round(d*100)}},_d=(e,t,n,r=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(n)}%, ${r})`;function An(e){try{const t=Ir(e),[n,r,a]=gd(t),o=i=>i.toString(16).padStart(2,"0");return`#${o(n)}${o(r)}${o(a)}`.toLowerCase()}catch{return"var(--nice-warning, #ffcc00)"}}function zd(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 Vt=new Map,fn=new Set,qn=new Set;function la(e){const t=Vt.get(e);return t?Promise.resolve(t):qn.has(e)?Promise.reject(new Error(`Texture failed: ${e}`)):fn.has(e)?new Promise((n,r)=>{const a=()=>{Vt.has(e)?n(Vt.get(e)):qn.has(e)?r(new Error(`Texture failed: ${e}`)):requestAnimationFrame(a)};a()}):(fn.add(e),new Promise((n,r)=>{const a=new Image;a.crossOrigin="anonymous",a.onload=()=>{Vt.set(e,a),fn.delete(e),n(a)},a.onerror=()=>{fn.delete(e),qn.add(e),r(new Error(`Failed to load texture: ${e}`))},a.src=e}))}function Gd(e){return Vt.get(e)??null}function pn(e,t,n=1){const r=Vt.get(t);if(!r)return!fn.has(t)&&!qn.has(t)&&la(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 Bd(e){for(const t of e)t&&la(t).catch(()=>{})}const mn=new Map,Bt=new Set;function So(e,t,n){return`${e}|${t}|${n??""}`}function Wd(e,t,n){const r=So(e.name,t,n),a=mn.get(r);if(a)return Promise.resolve(a);if(Bt.has(r))return new Promise((p,v)=>{const x=()=>{mn.has(r)?p(mn.get(r)):Bt.has(r)?requestAnimationFrame(x):v(new Error(`Pattern render failed: ${r}`))};x()});Bt.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,h=c?parseInt(c[1],10):16,f=`<svg xmlns="http://www.w3.org/2000/svg" width="${d}" height="${h}"><defs>${i}</defs><rect width="${d}" height="${h}" fill="url(#${o})"/></svg>`,m=new Blob([f],{type:"image/svg+xml;charset=utf-8"}),g=URL.createObjectURL(m);return new Promise((p,v)=>{const x=new Image;x.onload=()=>{mn.set(r,x),Bt.delete(r),URL.revokeObjectURL(g),p(x)},x.onerror=()=>{Bt.delete(r),URL.revokeObjectURL(g),v(new Error(`Failed to render pattern tile: ${e.name}`))},x.src=g})}function gn(e,t,n,r){const a=So(t.name,n,r),o=mn.get(a);return o?e.createPattern(o,"repeat"):(Bt.has(a)||Wd(t,n,r).catch(()=>{}),null)}let ft=null,qe=null,nt=null,St=null,it=null,Ae=null,Ya="",Za=0,Xa="";const Dr=(e,t,n,r,a,o,i,l,c,d,h,f,m,g,p,v,x,b,w,y,k,M,N,R)=>{e.clearRect(0,0,t,n);const _=R??null,E=(_==null?void 0:_.filledBar)??At,U=(_==null?void 0:_.emptyBar)??lr,W=(_==null?void 0:_.goldFilledBar)??dr,j=(_==null?void 0:_.goldEmptyBar)??cr,L=(_==null?void 0:_.font)??ur,I=dn(E.capStyleName),q=dn(U.capStyleName),Y=dn(W.capStyleName),O=dn(j.capStyleName),Z=E.patternName?un(E.patternName):null,H=U.patternName?un(U.patternName):null,te=W.patternName?un(W.patternName):null,G=j.patternName?un(j.patternName):null,z=Z?gn(e,Z,E.patternColor??E.color??"var(--nice-bg, #fff)",E.patternColor):null,S=H?gn(e,H,U.patternColor??U.color??"var(--nice-border, #d1d5db)",U.patternColor):null,P=te?gn(e,te,W.patternColor??"var(--nice-warning, #FFD700)",W.patternColor):null,$=G?gn(e,G,j.patternColor??"var(--nice-warning, #FFD700)",j.patternColor):null;Xa!==o&&(Xa=o,Nr("RENDER",`?? Renderer using settings for "${o}" � filled: cap=${E.capStyleName}, glass=${E.glass} | empty: cap=${U.capStyleName}, glass=${U.glass} | goldFilled: cap=${W.capStyleName}, pattern=${W.patternName??"none"} | goldEmpty: cap=${j.capStyleName}, pattern=${j.patternName??"none"} | hasSettings=${!!_}`,{filledBar:E,emptyBar:U,goldFilledBar:W,goldEmptyBar:j,filledOverlay:!!z,emptyOverlay:!!S,goldFilledOverlay:!!P,goldEmptyOverlay:!!$}));const T=E.textureUrl?pn(e,E.textureUrl,E.textureScale):null,C=U.textureUrl?pn(e,U.textureUrl,U.textureScale):null,A=W.textureUrl?pn(e,W.textureUrl,W.textureScale):null,D=j.textureUrl?pn(e,j.textureUrl,j.textureScale):null,V=typeof document<"u"?Ir(l||"var(--accent-primary, #ffcc00)"):l||"var(--accent-primary, #ffcc00)",Q=An(V||"var(--nice-warning, #ffcc00)"),J=ie=>Ir(ie),ae=L.fontFamily||"Arial",re=L.fontSize||18,ee=J(L.fontColor||"var(--btn-text, #fff)"),F=L.outlineColor?J(L.outlineColor):null,K=typeof L.outlineWidth=="number"?L.outlineWidth:0,se=L.shadow||null;typeof document<"u"&&((!ft||ft.width!==t||ft.height!==n)&&(ft=document.createElement("canvas"),ft.width=t,ft.height=n,qe=ft.getContext("2d")),qe&&qe.clearRect(0,0,t,n),(!nt||nt.width!==t||nt.height!==n)&&(nt=document.createElement("canvas"),nt.width=t,nt.height=n,St=nt.getContext("2d")),St&&St.clearRect(0,0,t,n),(!it||it.width!==t||it.height!==n)&&(it=document.createElement("canvas"),it.width=t,it.height=n,Ae=it.getContext("2d")),Ae&&Ae.clearRect(0,0,t,n));const ce=w?-w:0,fe=y||t;e.fillStyle=V,e.font=`bold ${re}px ${ae}`;const ue=e.measureText(o).width+20;if(e.fillRect(ce+10,5,ue,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),F&&K>0&&(e.lineWidth=K,e.strokeStyle=F,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,Oe=8,ve=ce+10+ue+6,me=20,ge=7,ke=he+Oe*2,$e=4;e.beginPath(),e.moveTo(ve+$e,ge),e.lineTo(ve+ke-$e,ge),e.quadraticCurveTo(ve+ke,ge,ve+ke,ge+$e),e.lineTo(ve+ke,ge+me-$e),e.quadraticCurveTo(ve+ke,ge+me,ve+ke-$e,ge+me),e.lineTo(ve+$e,ge+me),e.quadraticCurveTo(ve,ge+me,ve,ge+me-$e),e.lineTo(ve,ge+$e),e.quadraticCurveTo(ve,ge,ve+$e,ge),e.closePath(),e.fillStyle=ie,e.fill(),e.fillStyle=ee,e.fillText(x,ve+Oe,ge+14),e.font=`bold ${re}px ${ae}`}const ye=120;if(e.fillStyle=V,e.fillRect(ce+fe-ye-10,5,ye,25),e.fillStyle=ee,e.fillText(`${i} pts`,ce+fe-ye+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 ve=e.measureText(he).width+16,me=ce+fe-ye-10-ve-6;e.fillStyle=J(k.currentCombo>=20?"var(--success, #FFD700)":"var(--warning, #ff9800)"),e.globalAlpha=.9,zd(e,me,7,ve,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=J(k.currentCombo>=20?"var(--text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(he,me+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!==Ya&&(Ya=he,Za=Date.now());const Oe=Date.now()-Za;if(Oe<2500){const ve=Oe<2e3?1:1-(Oe-2e3)/500,me={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=ve,e.font=`bold ${Math.round(re*1.2)}px ${ae}`;const ge=ie.label,ke=e.measureText(ge).width,$e=ce+fe/2-ke/2;e.fillStyle=me[ge]||ee,e.shadowColor="var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",e.shadowBlur=6,e.fillText(ge,$e,58),F&&K>0&&(e.lineWidth=K,e.strokeStyle=F,e.strokeText(ge,$e,58)),e.restore()}}}const je=a-2,Fe=a+5,Re=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,Oe=-1/0;c.forEach(({t:ve,hz:me})=>{if(!me||me<=0)return;let ge=ie;for(const $e of r)for(const We of $e)ve>=We.startTime&&ve<=We.startTime+We.duration&&(ge=We.pitch);const ke=oo(me,ge);ke<he&&(he=ke),ke>Oe&&(Oe=ke)}),he!==1/0&&Oe!==-1/0&&(he<Se&&(Se=Math.floor(he-2)),Oe>ne&&(ne=Math.ceil(Oe+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-Re-10;return Re+he-(ie-Se)/(ne-Se)*he},De=lo(m||"normal"),tt=(n-Re-10)/Math.max(1,ne-Se),we=Math.max(10,Math.round(tt*(1+2*De.semitoneTolerance)*.3)),dt=Math.max(5,Math.round(we*.45));((ie,he,Oe,ve,me,ge)=>{ie.lineWidth=1;for(let ke=Math.ceil(me);ke<=Math.floor(ge);ke++){const $e=oe(ke);ie.strokeStyle=J(ke%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-Re,Re,Se,ne),St&&St.clearRect(0,0,t,n);const Xe=(a-je)/(Fe-je)*t;let Be=n*.5,It=!1,yt=!1;const mr=(ie,he,Oe,ve,me,ge,ke=0)=>{const $e=(be,Me,Te,_e,ze,Ke)=>{const Ie=Math.min(Ke,_e/2,ze/2);be.beginPath(),be.moveTo(Me+Ie,Te),be.lineTo(Me+_e-Ie,Te),be.quadraticCurveTo(Me+_e,Te,Me+_e,Te+Ie),be.lineTo(Me+_e,Te+ze-Ie),be.quadraticCurveTo(Me+_e,Te+ze,Me+_e-Ie,Te+ze),be.lineTo(Me+Ie,Te+ze),be.quadraticCurveTo(Me,Te+ze,Me,Te+ze-Ie),be.lineTo(Me,Te+Ie),be.quadraticCurveTo(Me,Te,Me+Ie,Te),be.closePath()},We=Math.max(2,we/2);ve.forEach(be=>{if(be.startTime+be.duration<me||be.startTime>ge)return;const Me=(be.startTime-me)/(ge-me)*he,Te=be.duration/(ge-me)*he,_e=oe(be.pitch)-we/2,ze=[];if(Array.isArray(f)){const Ke=be.startTime+be.duration;f.forEach(Ie=>{if(Ie.pitch!==be.pitch||Ie.noteStart!=null&&Ie.noteEnd!=null&&(Math.abs(Ie.noteStart-be.startTime)>.01||Math.abs(Ie.noteEnd-Ke)>.01))return;const ot=Math.max(Ie.start,be.startTime),bt=Math.min(Ie.end,Ke);if(ot>=bt)return;const Rt=(ot-me)/(ge-me)*he,Lt=(bt-me)/(ge-me)*he;ze.push({x1:Rt,x2:Lt,frac:Ie.frac})})}if(be.isGold){ie.save();const Ke=p&&p.shadowColor?p.shadowColor:Ha,Ie=p&&typeof p.glowBlur=="number"?p.glowBlur:qa;ie.shadowColor=Ke,ie.shadowBlur=Math.max(4,Ie-12),ie.fillStyle=J("var(--gold-overlay, rgba(255, 215, 0, 0.15))"),$e(ie,Me-1,_e-1,Te+2,we+2,We),ie.fill(),ie.restore();const ot=An("var(--gold-base, #b4af9f)");hn(ie,Me,_e,Te,we,O,j.color??ot,j.highlight,j.glow,j.glass,G,j.patternColor,j.patternOnly,D,$),ie.save(),$e(ie,Me,_e,Te,we,We),ie.clip(),ie.globalAlpha=.18,ie.fillStyle=J("var(--success, #FFD700)"),ie.fillRect(Me,_e,Te,Math.max(1,we*.25)),ie.globalAlpha=1,ie.restore(),ze.length>0&&(ie.save(),$e(ie,Me,_e,Te,we,We),ie.clip(),ze.forEach(bt=>{const Rt=Math.max(1,bt.x2-bt.x1);hn(ie,bt.x1,_e,Rt,we,Y,W.color??"var(--nice-warning, #FFD700)",W.highlight,W.glow,W.glass,te,W.patternColor,W.patternOnly,A,P)}),ie.restore()),ze.length===0&&(ie.lineWidth=1,ie.strokeStyle=J("var(--gold-outline, rgba(255, 215, 0, 0.35))"),$e(ie,Me+.5,_e+.5,Te-1,Math.max(1,we-1),We),ie.stroke())}else{const Ke=An("var(--note-base, #d1d5db)");hn(ie,Me,_e,Te,we,q,U.color??Ke,U.highlight,U.glow,U.glass,H,U.patternColor,U.patternOnly,C,S),ze.length>0&&(ie.save(),$e(ie,Me,_e,Te,we,We),ie.clip(),ze.forEach(Ie=>{const ot=Math.max(1,Ie.x2-Ie.x1);hn(ie,Ie.x1,_e,ot,we,I,E.color??Q,E.highlight,E.glow,E.glass,Z,E.patternColor,E.patternOnly,T,z)}),ie.restore())}St&&(St.fillStyle="var(--nice-bg, #fff)",St.fillRect(Me,_e,Te,we))})};if(r.forEach(ie=>{mr(e,t,n-Re,ie,je,Fe,Re);for(const he of ie)if(a>=he.startTime&&a<=he.startTime+he.duration){Be=oe(he.pitch),It=!0,yt=!!he.isGold;break}}),!It){let ie=null,he=null;for(const Oe of r)for(const ve of Oe)ve.startTime>a&&(!ie||ve.startTime<ie.startTime)&&(ie=ve),ve.startTime<=a&&(!he||ve.startTime>he.startTime)&&(he=ve);ie?(Be=oe(ie.pitch),yt=!!ie.isGold):he?(Be=oe(he.pitch),yt=!!he.isGold):Be=n*.5}const ut=V||J("var(--accent-primary, #ffcc00)"),le=1+Math.sin((a||0)*8)*.06,de=dt*le,Ce=[];for(const ie of r)for(const he of ie){if(he.startTime+he.duration<je||he.startTime>Fe)continue;const Oe=(he.startTime-je)/(Fe-je)*t,ve=he.duration/(Fe-je)*t,me=oe(he.pitch)-we/2,ge=he.startTime+he.duration<=a;Ce.push({x:Oe,y:me,w:ve,h:we,isGold:he.isGold,isSung:ge})}if(!Ed(N||"ball",{ctx:e,ballX:Xe,ballY:Be,ballRadius:de,playerColor:ut,ballIsGold:yt,currentTime:a,height:n,visibleNotes:Ce})){ft&&e.drawImage(ft,0,0),it&&e.drawImage(it,0,0),e.save(),e.globalCompositeOperation="source-over",e.globalAlpha=.28;const ie=Math.max(18,de*5),he=e.createRadialGradient(Xe,Be,0,Xe,Be,ie);if(he.addColorStop(0,ut),he.addColorStop(1,"transparent"),e.fillStyle=he,e.beginPath(),e.arc(Xe,Be,ie,0,Math.PI*2),e.fill(),e.restore(),g&&qe&&nt&&(qe.save(),qe.globalCompositeOperation="source-over",qe.globalAlpha=.95,qe.fillStyle=ut,qe.beginPath(),qe.arc(Xe,Be,de+4,0,Math.PI*2),qe.fill(),qe.restore(),qe.save(),qe.globalCompositeOperation="destination-in",qe.drawImage(nt,0,0),qe.restore(),e.drawImage(ft,0,0)),g&&Ae&&nt)try{const me=An(ut),{h:ge,s:ke,l:$e}=Od(me),be=_d(ge,Math.max(10,Math.round(ke*(typeof h=="number"?h:.25))),$e,.85);Ae.save(),Ae.globalCompositeOperation="multiply",Ae.globalAlpha=.65,Ae.fillStyle=be,Ae.beginPath(),Ae.arc(Xe,Be,Math.max(8,de+6),0,Math.PI*2),Ae.fill(),Ae.restore(),Ae.save(),Ae.globalCompositeOperation="destination-out",Ae.drawImage(nt,0,0),Ae.restore(),e.drawImage(it,0,0)}catch{Ae.save(),Ae.globalCompositeOperation="source-over",Ae.globalAlpha=.6,Ae.fillStyle=ut,Ae.beginPath(),Ae.arc(Xe,Be,Math.max(8,de+6),0,Math.PI*2),Ae.fill(),Ae.restore(),Ae.save(),Ae.globalCompositeOperation="destination-out",Ae.drawImage(nt,0,0),Ae.restore(),e.drawImage(it,0,0)}const Oe=p&&p.shadowColor?p.shadowColor:Ha,ve=p&&typeof p.glowBlur=="number"?p.glowBlur:qa;e.save(),yt?(e.shadowColor=Oe,e.shadowBlur=ve,e.fillStyle=J("var(--gold-light, #FFF0A8)")):(e.shadowColor=ut,e.shadowBlur=10,e.fillStyle=ut),e.globalCompositeOperation="source-over",e.globalAlpha=1,e.beginPath(),e.arc(Xe,Be,de,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:Ad,Oe=(me,ge,ke,$e=5)=>{const We=ke,be=ke*.45;e.beginPath();let Me=Math.PI/2*3,Te=me,_e=ge;const ze=Math.PI/$e;e.moveTo(me,ge-We);for(let Ke=0;Ke<$e;Ke++)Te=me+Math.cos(Me)*We,_e=ge+Math.sin(Me)*We,e.lineTo(Te,_e),Me+=ze,Te=me+Math.cos(Me)*be,_e=ge+Math.sin(Me)*be,e.lineTo(Te,_e),Me+=ze;e.lineTo(me,ge-We),e.closePath()},ve=me=>{let ge=me>>>0;return()=>(ge=ge*1664525+1013904223>>>0,(ge&2147483647)/2147483647)};v.forEach(me=>{const ge=ie-me.createdAt;if(ge<0||ge>he)return;const ke=ge/he,$e=(me.noteStart-(a-2))/7*t,We=oe(me.notePitch),be=ve(me.seed||Math.floor(me.createdAt%1e5)),Me=p&&typeof p.count=="number"?p.count:Nd,Te=p&&typeof p.baseSpeed=="number"?p.baseSpeed:Id,_e=p&&typeof p.baseSize=="number"?p.baseSize:Ld;for(let ze=0;ze<Me;ze++){const Ke=be(),Ie=be(),ot=ze/Me*Math.PI*2+Ke*Math.PI*.6+ke*1.5,bt=6+Te*(1-ke)*(.5+Ie*.8),Rt=$e+Math.cos(ot)*bt,Lt=We+Math.sin(ot)*bt*(.8+Ke*.6),ht=Math.max(1,_e*(1-ke)*(.5+Ie)),Ea=40+Math.round(20*be()),Aa=70+Math.round(20*be()),gr=Math.max(0,1-ke)*(.9-be()*.3),$l=Math.max(6,ht*2.6),yr=Dd(Ea,Aa,60,Math.round($l),(me.seed||0)+ze);yr&&yr.complete?(e.save(),e.translate(Rt,Lt+4),e.rotate(ot+ke*4+(be()-.5)*1.2),e.globalAlpha=gr,e.drawImage(yr,-ht/2,-ht/2,ht,ht),e.restore()):(e.save(),e.translate(Rt,Lt+4),e.rotate(ot+ke*4),e.fillStyle=`hsla(${Ea}, ${Aa}%, 60%, ${gr})`,e.fillRect(-ht/2,-ht/2,ht,ht),e.restore()),be()>.85&&(e.save(),e.globalAlpha=Math.max(.35,1-ke),e.fillStyle=`hsla(${30+Math.round(10*be())}, ${60+Math.round(30*be())}%, ${70+Math.round(10*be())}%, ${gr})`,e.strokeStyle=`rgba(0,0,0,${.12*(1-ke)})`,e.lineWidth=.8,Oe(Rt,Lt+4,ht*(1.4+be())),e.fill(),e.stroke(),e.restore())}})}}catch{}return{ballX:Xe,ballY:Be,ballIsGold:yt}},wo=({song:e,currentTime:t,playerRef:n,config:r={},userPitch:a,segmentScores:o,goldBursts:i,combo:l,verseRatings:c})=>{const{isPlaying:d=!1,playerName:h="Ziom",score:f=1e4,playerBgColor:m="var(--karaoke-player-bg, #2196f3)",playerCount:g=2,gapDesaturation:p,goldSettings:v,difficultyLevel:x,algorithmLabel:b,algorithmColor:w,latencyMs:y=null,top:k,animationMode:M,karaokeSettings:N=null}=r,R=u.useRef(null),_=u.useRef(null),[E,U]=u.useState({width:600,height:150,top:250,visibleWidth:600}),[W,j]=u.useState(0),L=u.useRef(0),I=u.useRef(null),q=u.useRef(null),Y=u.useRef(null),O=u.useRef(t),Z=u.useRef(performance.now()),H=u.useRef(e),te=u.useRef(E),G=u.useRef(a),z=u.useRef(d),S=u.useRef(0),P=u.useRef(!1),$=u.useRef(null),T=u.useRef(null),C=()=>{const A=(e==null?void 0:e.id)??null;if(A!==T.current||!$.current){T.current=A;const D=e.notes.map(ee=>ee.noteLine);$.current=ea(D,e.bpm??void 0);const V=$.current.reduce((ee,F)=>ee+F.length,0),Q=$.current.reduce((ee,F)=>ee+F.filter(K=>K.isGold).length,0),J=$.current.flat().map(ee=>ee.pitch),ae=J.length?Math.min(...J):0,re=J.length?Math.max(...J):0;Nr("BARS",`?? Parsed notes for "${e.title}" — ${$.current.length} verses, ${V} notes (including ${Q} golden), pitch range: ${ae}–${re}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:D.length,verseCount:$.current.length,totalNotes:V,goldCount:Q,minPitch:ae,maxPitch:re})}return $.current};return u.useEffect(()=>{const A=(V,Q,J)=>V+(Q-V)*J,D=V=>{q.current===null&&(q.current=V);const Q=Math.min(.1,(V-(q.current||V))/1e3);q.current=V;const J=S.current,ae=L.current,re=1-Math.exp(-12*Q),ee=Math.abs(ae-J)<.25?ae:A(J,ae,re);Math.abs(ee-J)>1e-4&&(j(ee),S.current=ee,R.current&&(R.current.style.transform=`translateX(${ee}px)`)),I.current=requestAnimationFrame(D)};return I.current=requestAnimationFrame(D),()=>{I.current&&cancelAnimationFrame(I.current),I.current=null,q.current=null}},[]),u.useEffect(()=>{const A=()=>{if(!n.current)return;const D=n.current.getBoundingClientRect(),V=2/Math.max(1,g),Q=Math.round(D.width*V),J=Math.round(D.width),ae=Q*(150/600);U({width:Q,height:ae,top:30,visibleWidth:J})};return A(),window.addEventListener("resize",A),()=>window.removeEventListener("resize",A)},[n,g]),u.useEffect(()=>{var J;if(d||!R.current)return;const A=R.current.getContext("2d");if(!A)return;const D=C(),V=t-(e.gap??0)/1e3,Q=Dr(A,E.width,E.height,D,V,h,f,m,a,e.id,p??void 0,o,x??void 0,d,v??void 0,i,b,w,S.current,E.visibleWidth,l,c,M,N);if(Q&&R.current){const ae=E.visibleWidth||(((J=_.current)==null?void 0:J.getBoundingClientRect().width)??E.width),re=E.width;let ee=Math.round(ae/2-Q.ballX);const F=ae-re;ee=Math.max(F,Math.min(0,ee)),L.current=ee}},[t,e,E,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=E},[E]),u.useEffect(()=>{G.current=a},[a]),u.useEffect(()=>{z.current=d},[d]),u.useEffect(()=>{const A=()=>{var se;const D=R.current,V=H.current,Q=te.current;if(!D||!V||!Q)return;const J=D.getContext("2d");if(!J)return;const ae=C(),re=Math.min(.5,(performance.now()-Z.current)/1e3),F=(z.current?O.current+re:O.current)-(V.gap??0)/1e3,K=Dr(J,Q.width,Q.height,ae,F,h,f,m,G.current,V.id,p??void 0,o,x??void 0,z.current,v??void 0,i,b,w,S.current,Q.visibleWidth,l,c,M,N);if(K){const ce=Q.visibleWidth||(((se=_.current)==null?void 0:se.getBoundingClientRect().width)??Q.width),fe=Q.width;let X=Math.round(ce/2-K.ballX);const ue=ce-fe;X=Math.max(ue,Math.min(0,X)),L.current=X}};if(d){P.current||(P.current=!0,Nr("BARS",`? Drawing bars in RAF loop � canvas: ${te.current.width}�${te.current.height}px, player: ${h}`,{canvasSize:te.current}));const D=()=>{A(),Y.current=requestAnimationFrame(D)};return Y.current=requestAnimationFrame(D),()=>{Y.current&&cancelAnimationFrame(Y.current),Y.current=null}}P.current=!1},[d,h,f,m,p,o,x,v,i,M,N]),s.jsxs("div",{ref:_,style:{position:"absolute",left:"50%",top:`${k??E.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:E.visibleWidth,height:E.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 y<"u"&&y!==null?(()=>{const A=y,D=A<=120?"var(--latency-good, #10b981)":A<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",V=`${A}ms`;return s.jsxs("div",{className:A>250?"av-latency-pulse":"",style:{background:D,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:V})]})})():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:R,width:E.width,height:E.height,role:"img","aria-label":`Pitch timeline for ${h??"player"}. Score: ${f??0}`,style:{position:"absolute",left:0,top:0,transform:`translateX(${W}px)`,willChange:"transform"}})]})},Co="/textures/seamless/256x256";function vt(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:`${Co}/${e}/Photoreal_${e}_${o}-512x512.png`}})}}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:`${Co}/${e}/${e}_${o}-256x256.png`}})}}const ca=[vt("Fire",8,"🔥"),vt("Metal",8,"⚙️"),vt("Ice",8,"❄️"),vt("Stone",8,"🪨"),vt("Wood",8,"🪵"),vt("Tile",8,"🧱"),vt("Concrete",8,"🏗️"),vt("Trees",8,"🌲"),vt("Grass",8,"🌿"),wt("Wall",24,"🏠"),wt("Rust",24,"🟤"),wt("Woven",24,"🧵"),wt("Ground",24,"🟫"),wt("Pebbles",24,"🫧"),wt("Plant",24,"🌱"),wt("Roof",24,"🏛️"),wt("Misc",24,"🎨")],ko=ca.flatMap(e=>e.entries);function Ud(e){return ko.find(t=>t.url===e)}const Vd={color:"var(--nice-primary, #2196f3)",highlight:"var(--nice-bg, #fff)",glow:0,capStyle:"flat",pattern:null,texture:null},Mo=({fill:e=Vd,onChange:t=()=>{},previewColor:n="var(--nice-primary, #2196f3)",accentColor:r="var(--nice-primary, #0d6efd)",width:a,height:o})=>{const{t:i}=xe(),[l,c]=u.useState(null),d=(b,w)=>{t({...e,[b]:w})},h=u.useMemo(()=>{const b=e.color||n||"var(--nice-primary, #2196f3)";return(w,y,k)=>{const M=Cn.find(R=>R.name===w)||Cn[0],N=y?nr.find(R=>R.name===y)??null:null;return xo({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]),f=`2px solid ${r}`,m=r==="var(--nice-warning-dark, #d4a017)"?"var(--nice-warning-bg, #fff8e1)":"#e7f1ff",g=u.useRef(null),p=u.useRef(null),v=u.useCallback((b,w)=>{b.current&&b.current.scrollBy({left:w*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(Ve.Form.Label,{className:"mb-0",style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:i("playerForm.barColor","Color")}),s.jsx(Ve.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(Ve.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(g,-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(g,1),children:"�"}),s.jsx("div",{ref:g,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:Cn.map(b=>{const w=e.capStyleName===b.name;return s.jsx("div",{title:b.name,onClick:()=>d("capStyleName",b.name),style:{cursor:"pointer",flexShrink:0,border:w?f:"1px solid var(--nice-text-secondary, #555)",borderRadius:6,padding:3,background:w?m:"var(--nice-text, #222)"},dangerouslySetInnerHTML:{__html:h(b.name,null)}},b.name)})})]}),s.jsx(Ve.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)":f,borderRadius:6,padding:"3px 8px",background:e.patternName?"var(--nice-text, #222)":m,fontSize:12,lineHeight:"22px",color:"var(--nice-border, #ccc)"},children:"�"}),nr.map(b=>{const w=e.patternName===b.name;return s.jsx("div",{title:b.name,onClick:()=>d("patternName",b.name),style:{cursor:"pointer",flexShrink:0,border:w?f:"1px solid var(--nice-text-secondary, #555)",borderRadius:6,padding:3,background:w?m:"var(--nice-text, #222)"},dangerouslySetInnerHTML:{__html:h(e.capStyleName,b.name)}},b.name)})]})]}),s.jsx(Ve.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(Ve.Form.Label,{className:"mb-0",style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:i("playerForm.patternColor","Pattern color")}),s.jsx(Ve.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(Ve.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[i("playerForm.highlight","Highlight"),": ",e.highlight,"%"]}),s.jsx(Ve.Form.Range,{min:0,max:100,value:e.highlight,onChange:b=>d("highlight",parseInt(b.target.value)),className:"mb-2"}),s.jsxs(Ve.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[i("playerForm.glow","Glow"),": ",e.glow,"%"]}),s.jsx(Ve.Form.Range,{min:0,max:100,value:e.glow,onChange:b=>d("glow",parseInt(b.target.value)),className:"mb-2"})]}),s.jsxs(Ve.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[i("playerForm.glass","Transparency (glass)"),": ",e.glass,"%"]}),s.jsx(Ve.Form.Range,{min:0,max:100,value:e.glass,onChange:b=>d("glass",parseInt(b.target.value)),className:"mb-2"}),s.jsx(Ve.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")}),ca.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(w=>(w==null?void 0:w.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 w=e.textureUrl===b.url;return s.jsx("div",{title:b.label,onClick:()=>d("textureUrl",w?null:b.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:w?`3px solid ${r}`:"1px solid var(--nice-text-muted, #bbb)",backgroundImage:`url(${b.url})`,backgroundSize:"cover",boxShadow:w?`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(Ve.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[i("playerForm.textureScale","Texture scale"),": ",e.textureScale.toFixed(1),"�"]}),s.jsx(Ve.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"})]})]})},He=et.scoped("AudioPitchAnalyzer");function jo({onSegments:e,defaultCompareAll:t=!1,externalFile:n=null,postPitch:r,postLibrosaPitchTrack:a}){const{t:o}=xe(),[i,l]=u.useState("pitchy"),[c,d]=u.useState(null),[h,f]=u.useState(t),[m,g]=u.useState({}),[p,v]=u.useState({}),[x,b]=u.useState([]),[w,y]=u.useState([]),[k,M]=u.useState(!1),[N,R]=u.useState(null),[_]=u.useState(null),[E]=u.useState(null),[U,W]=u.useState(null),j=u.useRef(null);function L(G){try{if(G instanceof Error){let S=`${G.message}
40
+ ${G.stack??""}`;const P=G;if(P!=null&&P.attemptedUrls)try{S+=`
41
41
  Attempted URLs: ${Array.isArray(P.attemptedUrls)?P.attemptedUrls.join(", "):String(P.attemptedUrls)}`}catch{S+=`
42
- Attempted URLs: ${String(P.attemptedUrls)}`}return S}const z=B;return z!=null&&z.attemptedUrls?`Error: ${String(z.message??z)}
43
- Attempted URLs: ${Array.isArray(z.attemptedUrls)?z.attemptedUrls.join(", "):String(z.attemptedUrls)}`:String(B)}catch{return"Unknown error"}}function I(B){if(!B||B<=0)return null;const z=12*Math.log2(B/440)+69;return Math.round(z-12)}async function q(B){var S;const z=(S=B.target.files)==null?void 0:S[0];z&&await Y(z,h)}async function Y(B,z){R(null),y([]),M(!0);try{const S=await B.arrayBuffer(),P=window.AudioContext??window.webkitAudioContext,T=await new P().decodeAudioData(S),C=T.getChannelData(0);d(C);const A=T.sampleRate,D=Math.floor(A*.1),V=D,Q=()=>{const K=[],se=Pr.PitchDetector.forFloat32Array(D);for(let ce=0;ce<C.length-D;ce+=V){const fe=C.slice(ce,ce+D),[X,ue]=se.findPitch(fe,A),ye=I(X);ye&&X>50&&X<2e3&&ue>.7&&K.push({start:ce/A,duration:D/A,pitch:ye,freq:X})}return K},J=()=>{const K=[];for(let se=0;se<C.length-D;se+=V){const ce=C.slice(se,se+D),fe=Z(ce,A),X=I(fe);X&&fe>50&&fe<2e3&&K.push({start:se/A,duration:D/A,pitch:X,freq:fe})}return K};if(z){M(!0),R(null);const K={};try{const se={};try{K.pitchy=Q(),se.pitchy=null}catch(ce){K.pitchy=[],se.pitchy=L(ce),He.warn("pitchy failed",ce)}try{K["ultrastar-wp"]=J(),se["ultrastar-wp"]=null}catch(ce){K["ultrastar-wp"]=[],se["ultrastar-wp"]=L(ce),He.warn("ultrastar-wp failed",ce)}K.aubio=[],se.aubio="disabled";try{if(!r)throw new Error("CREPE backend not configured");const fe=(await r(B)).track??[];K.crepe=fe.map((X,ue)=>{var ye;return{start:X.t,duration:(ye=fe[ue+1])!=null&&ye.t?fe[ue+1].t-X.t:.1,pitch:I(X.hz)??0,freq:X.hz}}),se.crepe=null}catch(ce){K.crepe=[],se.crepe=L(ce),He.warn("crepe failed",ce)}try{if(!a)throw new Error("Librosa backend not configured");const fe=(await a(new File([B],B.name,{type:B.type}))).track??[];K.librosa=fe.map((X,ue)=>{var ye;return{start:X.t,duration:(ye=fe[ue+1])!=null&&ye.t?fe[ue+1].t-X.t:.1,pitch:I(X.hz)??0,freq:X.hz}}),se.librosa=null}catch(ce){K.librosa=[],se.librosa=L(ce),He.warn("librosa failed",ce)}v(se),g(K),y(K[i]??[])}catch(se){He.error("compareAll overall failed",se);const ce=se instanceof Error?se.message:String(se);R(o("audioPitch.errorComparing")+ce)}finally{M(!1)}return}const ae=[],re=[];let ee=0;if(i==="pitchy"){const K=Pr.PitchDetector.forFloat32Array(D);for(let se=0;se<C.length-D;se+=V){const ce=C.slice(se,se+D);let fe=0;for(let je=0;je<ce.length;je++)fe+=ce[je]*ce[je];fe=Math.sqrt(fe/ce.length),re.push(fe);const[X,ue]=K.findPitch(ce,A),ye=I(X);ye&&X>50&&X<2e3&&ue>.7&&(ae.push({start:se/A,duration:D/A,pitch:ye,freq:X}),ee++)}}else if(i==="crepe")try{if(!r)throw new Error("CREPE backend not configured");const K=await r(B);if(!K.track||K.track.length===0)R(o("audioPitch.crepeNoNotes")),He.warn("Crepe: No notes detected in audio file.");else{const se=K.track.map((ce,fe)=>{const X=I(ce.hz);return X&&ce.hz>50&&ce.hz<2e3?{start:ce.t,duration:fe<K.track.length-1?K.track[fe+1].t-ce.t:.1,pitch:X,freq:ce.hz}:null}).filter(ce=>ce!==null);if(y(se),e)try{e(se)}catch(ce){He.error("Error in onSegments:",ce)}b([]),d(null);return}}catch(K){R(o("audioPitch.crepeBackendError")),W(L(K)),He.error("Crepe: Error calling backend:",K)}else if(i==="librosa")try{await O(B),b([]),d(null);return}catch(K){R(o("audioPitch.librosaBackendError")),W(L(K)),He.error("Librosa: Error calling backend:",K)}else if(i==="ultrastar-wp")for(let K=0;K<C.length-D;K+=V){const se=C.slice(K,K+D);let ce=0;for(let ue=0;ue<se.length;ue++)ce+=se[ue]*se[ue];ce=Math.sqrt(ce/se.length),re.push(ce);const fe=Z(se,A),X=I(fe);X&&fe>50&&fe<2e3&&(ae.push({start:K/A,duration:D/A,pitch:X,freq:fe}),ee++)}b(re);const F=H(ae);if(y(F),e)try{e(F)}catch(K){He.error("Error in onSegments:",K)}F.length===0&&i!=="crepe"&&(R(o("audioPitch.noNotesDetected")),He.warn("No notes detected in audio file."))}catch(S){R(o("audioPitch.errorAnalyzing")+(S instanceof Error?S.message:String(S))),W(L(S)),He.error("Error analyzing audio file:",S)}finally{M(!1)}}u.useEffect(()=>{n&&Y(n,!0)},[n]);async function O(B){try{if(!a)throw new Error("Librosa backend not configured");const z=new File([B],"capture.wav",{type:"audio/wav"}),P=((await a(z)).track??[]).map($=>({t:$.t,hz:$.hz}));if(e){const $=P.map((T,C)=>{var V;const A=((V=P[C+1])==null?void 0:V.t)??T.t+.1,D=I(T.hz)??0;return{start:T.t,duration:Math.max(.05,A-T.t),pitch:D,freq:T.hz}});e($),y($)}}catch(z){He.warn("Librosa analysis failed, falling back to local detectors",z);const P=(typeof z=="object"&&z!==null?z:{}).attemptedUrls;P&&He.error("Librosa attempted URLs:",P);const $=P?Array.isArray(P)?P.join(", "):String(P):null,T=z instanceof Error?z.message:String(z);R(o("audioPitch.librosaBackendError")+": "+T+($?" (attempted: "+$+")":"")),W(L(z))}}function Z(B,z){const $=Math.floor(z/50),T=Math.max(2,Math.floor(z/2e3));let C=0;for(let Q=0;Q<B.length;Q++)C+=B[Q]*B[Q];if(C<=1e-8)return 0;let A=-1,D=0;const V=1e-10;for(let Q=T;Q<=Math.min($,B.length-2);Q++){let J=0;const ae=B.length-Q;for(let ee=0;ee<ae;ee++)J+=B[ee]*B[ee+Q];const re=J/(ae+V)/(C/B.length+V);re>D&&(D=re,A=Q)}return A>0&&D>.01?z/A:0}function H(B){if(B.length===0)return[];const z=[];let S=B[0];for(let P=1;P<B.length;P++){const $=B[P];$.pitch===S.pitch&&Math.abs($.freq-S.freq)<1?S.duration+=$.duration:(z.push(S),S=$)}return z.push(S),z}function te(){try{const B=Object.keys(m).length>0?Object.keys(m):["pitchy","ultrastar-wp","aubio","crepe","librosa"],z=(()=>{let ee=0;for(const F of B){const K=m[F]??[];for(const se of K)ee=Math.max(ee,se.start+(se.duration||0))}return ee||0})(),S=(ee,F)=>!ee||!F?1/0:1200*Math.log2(ee/F),P=(ee,F)=>{if(!ee||!F)return!1;const K=Math.round(Math.log2(F/ee)),se=ee*Math.pow(2,K),ce=Math.abs(S(se,F));return Math.abs(K)>=1&&ce<50},$=ee=>{const F={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!ee||ee.length===0)return F;F.count=ee.length,F.totalDur=ee.reduce((fe,X)=>fe+(X.duration||0),0);const K=ee.map(fe=>fe.freq).filter(Boolean);if(K.length===0)return F;const se=K.reduce((fe,X)=>fe+X,0)/K.length,ce=K.reduce((fe,X)=>fe+(X-se)*(X-se),0)/K.length;return F.meanFreq=se,F.stdFreq=Math.sqrt(ce||0),F.meanDur=F.totalDur/F.count,F.voicedFraction=z>0?F.totalDur/z:null,F},T=(ee,F)=>{let K=0,se=0;const ce=[];for(const X of ee){const ue=X.start,ye=X.start+(X.duration||.05);let je=null,Fe=0;for(const Re of F){const Se=Re.start,ne=Re.start+(Re.duration||.05),oe=Math.max(0,Math.min(ye,ne)-Math.max(ue,Se));oe>Fe&&(Fe=oe,je=Re)}if(je&&Fe>0){const Re=Math.abs(S(X.freq,je.freq));ce.push(Re),Re<50&&K++,P(X.freq,je.freq)&&se++}}const fe=ce.length?ce.reduce((X,ue)=>X+ue,0)/ce.length:null;return{matches:K,compared:ee.length,meanCents:fe,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): **${z.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 A={};for(const ee of B){const F=m[ee]??[],K=$(F);A[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 D=B.includes("crepe")?"crepe":B.includes("librosa")?"librosa":B.includes("pitchy")?"pitchy":B[0];C.push(`Reference algorithm: **${D}**`),C.push(""),C.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),C.push("|---|---:|---:|---:|---:|---:|");for(const ee of B){if(ee===D)continue;const F=T(m[D]??[],m[ee]??[]),K=F.compared?(F.matches/F.compared*100).toFixed(1)+"%":"N/A";C.push(`| ${D} -> ${ee} | ${F.matches} | ${F.compared} | ${K} | ${F.meanCents!==null?F.meanCents.toFixed(1):"N/A"} | ${F.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 B){C.push(`### ${ee}`);const F=A[ee];C.push(`- Segments: ${F.count||0}`),C.push(`- Total voiced (s): ${(F.totalDur||0).toFixed(3)}`),C.push(`- Voiced fraction: ${F.voicedFraction!==null?(F.voicedFraction*100).toFixed(1)+"%":"N/A"}`),C.push(`- Mean frequency: ${F.meanFreq?F.meanFreq.toFixed(2)+" Hz":"N/A"}`),C.push(`- Std frequency: ${F.stdFreq?F.stdFreq.toFixed(2)+" Hz":"N/A"}`),C.push("")}C.push("## Conclusions & recommendation");const V=[];for(const ee of B){if(ee===D){V.push({alg:ee,score:100});continue}const F=T(m[D]??[],m[ee]??[]),K=F.compared?F.matches/F.compared:0,se=F.compared?F.octaveErrors/F.compared:0,ce=K-se*.5;V.push({alg:ee,score:ce})}V.sort((ee,F)=>F.score-ee.score),C.push(`- Based on this recording, recommended authoritative detector: **${V[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 B){const F=m[ee]??[];C.push(`### ${ee} � ${F.length} segments`);for(const se of F)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(B){He.error("generateScientificReport error",B),He.warn(o("audioPitch.reportError")+String(B))}}return s.jsxs("div",{style:{marginTop:32,padding:16,border:"1px solid #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:B=>l(B.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:h,onChange:B=>f(B.target.checked)})," ",o("audioPitch.compareAll")]}),s.jsx("input",{type:"file",accept:"audio/*",ref:j,onChange:q,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}),U&&s.jsx("pre",{style:{background:"#111",color:"#f88",padding:8,borderRadius:4,whiteSpace:"pre-wrap",marginTop:8},children:U})]}),_&&s.jsxs("div",{style:{marginTop:12},children:[s.jsx("b",{children:"Aubio diagnostics"}),s.jsx("pre",{style:{background:"#111",color:"#f88",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:_}),E&&s.jsxs("div",{style:{marginTop:8},children:[s.jsx("b",{children:"Probe:"})," ",E]})]}),(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(([B,z])=>z).map(([B,z])=>s.jsxs("div",{style:{marginTop:6},children:[s.jsxs("b",{children:[B,":"]}),s.jsx("pre",{style:{background:"#111",color:"#f88",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:z})]},B))]})]}),w.length>0&&s.jsxs("div",{style:{marginTop:16},children:[s.jsx("b",{children:o("audioPitch.resultUltrastar")}),s.jsxs("pre",{style:{background:"#222",color:"#fff",padding:8,borderRadius:4},children:[w.map(B=>`: ${Math.round(B.start*10)} ${Math.round(B.duration*10)} ${B.pitch} [${B.freq.toFixed(1)} Hz]`).join(`
42
+ Attempted URLs: ${String(P.attemptedUrls)}`}return S}const z=G;return z!=null&&z.attemptedUrls?`Error: ${String(z.message??z)}
43
+ Attempted URLs: ${Array.isArray(z.attemptedUrls)?z.attemptedUrls.join(", "):String(z.attemptedUrls)}`:String(G)}catch{return"Unknown error"}}function I(G){if(!G||G<=0)return null;const z=12*Math.log2(G/440)+69;return Math.round(z-12)}async function q(G){var S;const z=(S=G.target.files)==null?void 0:S[0];z&&await Y(z,h)}async function Y(G,z){R(null),y([]),M(!0);try{const S=await G.arrayBuffer(),P=window.AudioContext??window.webkitAudioContext,T=await new P().decodeAudioData(S),C=T.getChannelData(0);d(C);const A=T.sampleRate,D=Math.floor(A*.1),V=D,Q=()=>{const K=[],se=Pr.PitchDetector.forFloat32Array(D);for(let ce=0;ce<C.length-D;ce+=V){const fe=C.slice(ce,ce+D),[X,ue]=se.findPitch(fe,A),ye=I(X);ye&&X>50&&X<2e3&&ue>.7&&K.push({start:ce/A,duration:D/A,pitch:ye,freq:X})}return K},J=()=>{const K=[];for(let se=0;se<C.length-D;se+=V){const ce=C.slice(se,se+D),fe=Z(ce,A),X=I(fe);X&&fe>50&&fe<2e3&&K.push({start:se/A,duration:D/A,pitch:X,freq:fe})}return K};if(z){M(!0),R(null);const K={};try{const se={};try{K.pitchy=Q(),se.pitchy=null}catch(ce){K.pitchy=[],se.pitchy=L(ce),He.warn("pitchy failed",ce)}try{K["ultrastar-wp"]=J(),se["ultrastar-wp"]=null}catch(ce){K["ultrastar-wp"]=[],se["ultrastar-wp"]=L(ce),He.warn("ultrastar-wp failed",ce)}K.aubio=[],se.aubio="disabled";try{if(!r)throw new Error("CREPE backend not configured");const fe=(await r(G)).track??[];K.crepe=fe.map((X,ue)=>{var ye;return{start:X.t,duration:(ye=fe[ue+1])!=null&&ye.t?fe[ue+1].t-X.t:.1,pitch:I(X.hz)??0,freq:X.hz}}),se.crepe=null}catch(ce){K.crepe=[],se.crepe=L(ce),He.warn("crepe failed",ce)}try{if(!a)throw new Error("Librosa backend not configured");const fe=(await a(new File([G],G.name,{type:G.type}))).track??[];K.librosa=fe.map((X,ue)=>{var ye;return{start:X.t,duration:(ye=fe[ue+1])!=null&&ye.t?fe[ue+1].t-X.t:.1,pitch:I(X.hz)??0,freq:X.hz}}),se.librosa=null}catch(ce){K.librosa=[],se.librosa=L(ce),He.warn("librosa failed",ce)}v(se),g(K),y(K[i]??[])}catch(se){He.error("compareAll overall failed",se);const ce=se instanceof Error?se.message:String(se);R(o("audioPitch.errorComparing")+ce)}finally{M(!1)}return}const ae=[],re=[];let ee=0;if(i==="pitchy"){const K=Pr.PitchDetector.forFloat32Array(D);for(let se=0;se<C.length-D;se+=V){const ce=C.slice(se,se+D);let fe=0;for(let je=0;je<ce.length;je++)fe+=ce[je]*ce[je];fe=Math.sqrt(fe/ce.length),re.push(fe);const[X,ue]=K.findPitch(ce,A),ye=I(X);ye&&X>50&&X<2e3&&ue>.7&&(ae.push({start:se/A,duration:D/A,pitch:ye,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)R(o("audioPitch.crepeNoNotes")),He.warn("Crepe: No notes detected in audio file.");else{const se=K.track.map((ce,fe)=>{const X=I(ce.hz);return X&&ce.hz>50&&ce.hz<2e3?{start:ce.t,duration:fe<K.track.length-1?K.track[fe+1].t-ce.t:.1,pitch:X,freq:ce.hz}:null}).filter(ce=>ce!==null);if(y(se),e)try{e(se)}catch(ce){He.error("Error in onSegments:",ce)}b([]),d(null);return}}catch(K){R(o("audioPitch.crepeBackendError")),W(L(K)),He.error("Crepe: Error calling backend:",K)}else if(i==="librosa")try{await O(G),b([]),d(null);return}catch(K){R(o("audioPitch.librosaBackendError")),W(L(K)),He.error("Librosa: Error calling backend:",K)}else if(i==="ultrastar-wp")for(let K=0;K<C.length-D;K+=V){const se=C.slice(K,K+D);let ce=0;for(let ue=0;ue<se.length;ue++)ce+=se[ue]*se[ue];ce=Math.sqrt(ce/se.length),re.push(ce);const fe=Z(se,A),X=I(fe);X&&fe>50&&fe<2e3&&(ae.push({start:K/A,duration:D/A,pitch:X,freq:fe}),ee++)}b(re);const F=H(ae);if(y(F),e)try{e(F)}catch(K){He.error("Error in onSegments:",K)}F.length===0&&i!=="crepe"&&(R(o("audioPitch.noNotesDetected")),He.warn("No notes detected in audio file."))}catch(S){R(o("audioPitch.errorAnalyzing")+(S instanceof Error?S.message:String(S))),W(L(S)),He.error("Error analyzing audio file:",S)}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 z=new File([G],"capture.wav",{type:"audio/wav"}),P=((await a(z)).track??[]).map($=>({t:$.t,hz:$.hz}));if(e){const $=P.map((T,C)=>{var V;const A=((V=P[C+1])==null?void 0:V.t)??T.t+.1,D=I(T.hz)??0;return{start:T.t,duration:Math.max(.05,A-T.t),pitch:D,freq:T.hz}});e($),y($)}}catch(z){He.warn("Librosa analysis failed, falling back to local detectors",z);const P=(typeof z=="object"&&z!==null?z:{}).attemptedUrls;P&&He.error("Librosa attempted URLs:",P);const $=P?Array.isArray(P)?P.join(", "):String(P):null,T=z instanceof Error?z.message:String(z);R(o("audioPitch.librosaBackendError")+": "+T+($?" (attempted: "+$+")":"")),W(L(z))}}function Z(G,z){const $=Math.floor(z/50),T=Math.max(2,Math.floor(z/2e3));let C=0;for(let Q=0;Q<G.length;Q++)C+=G[Q]*G[Q];if(C<=1e-8)return 0;let A=-1,D=0;const V=1e-10;for(let Q=T;Q<=Math.min($,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+V)/(C/G.length+V);re>D&&(D=re,A=Q)}return A>0&&D>.01?z/A:0}function H(G){if(G.length===0)return[];const z=[];let S=G[0];for(let P=1;P<G.length;P++){const $=G[P];$.pitch===S.pitch&&Math.abs($.freq-S.freq)<1?S.duration+=$.duration:(z.push(S),S=$)}return z.push(S),z}function te(){try{const G=Object.keys(m).length>0?Object.keys(m):["pitchy","ultrastar-wp","aubio","crepe","librosa"],z=(()=>{let ee=0;for(const F of G){const K=m[F]??[];for(const se of K)ee=Math.max(ee,se.start+(se.duration||0))}return ee||0})(),S=(ee,F)=>!ee||!F?1/0:1200*Math.log2(ee/F),P=(ee,F)=>{if(!ee||!F)return!1;const K=Math.round(Math.log2(F/ee)),se=ee*Math.pow(2,K),ce=Math.abs(S(se,F));return Math.abs(K)>=1&&ce<50},$=ee=>{const F={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!ee||ee.length===0)return F;F.count=ee.length,F.totalDur=ee.reduce((fe,X)=>fe+(X.duration||0),0);const K=ee.map(fe=>fe.freq).filter(Boolean);if(K.length===0)return F;const se=K.reduce((fe,X)=>fe+X,0)/K.length,ce=K.reduce((fe,X)=>fe+(X-se)*(X-se),0)/K.length;return F.meanFreq=se,F.stdFreq=Math.sqrt(ce||0),F.meanDur=F.totalDur/F.count,F.voicedFraction=z>0?F.totalDur/z:null,F},T=(ee,F)=>{let K=0,se=0;const ce=[];for(const X of ee){const ue=X.start,ye=X.start+(X.duration||.05);let je=null,Fe=0;for(const Re of F){const Se=Re.start,ne=Re.start+(Re.duration||.05),oe=Math.max(0,Math.min(ye,ne)-Math.max(ue,Se));oe>Fe&&(Fe=oe,je=Re)}if(je&&Fe>0){const Re=Math.abs(S(X.freq,je.freq));ce.push(Re),Re<50&&K++,P(X.freq,je.freq)&&se++}}const fe=ce.length?ce.reduce((X,ue)=>X+ue,0)/ce.length:null;return{matches:K,compared:ee.length,meanCents:fe,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): **${z.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 A={};for(const ee of G){const F=m[ee]??[],K=$(F);A[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 D=G.includes("crepe")?"crepe":G.includes("librosa")?"librosa":G.includes("pitchy")?"pitchy":G[0];C.push(`Reference algorithm: **${D}**`),C.push(""),C.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),C.push("|---|---:|---:|---:|---:|---:|");for(const ee of G){if(ee===D)continue;const F=T(m[D]??[],m[ee]??[]),K=F.compared?(F.matches/F.compared*100).toFixed(1)+"%":"N/A";C.push(`| ${D} -> ${ee} | ${F.matches} | ${F.compared} | ${K} | ${F.meanCents!==null?F.meanCents.toFixed(1):"N/A"} | ${F.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 F=A[ee];C.push(`- Segments: ${F.count||0}`),C.push(`- Total voiced (s): ${(F.totalDur||0).toFixed(3)}`),C.push(`- Voiced fraction: ${F.voicedFraction!==null?(F.voicedFraction*100).toFixed(1)+"%":"N/A"}`),C.push(`- Mean frequency: ${F.meanFreq?F.meanFreq.toFixed(2)+" Hz":"N/A"}`),C.push(`- Std frequency: ${F.stdFreq?F.stdFreq.toFixed(2)+" Hz":"N/A"}`),C.push("")}C.push("## Conclusions & recommendation");const V=[];for(const ee of G){if(ee===D){V.push({alg:ee,score:100});continue}const F=T(m[D]??[],m[ee]??[]),K=F.compared?F.matches/F.compared:0,se=F.compared?F.octaveErrors/F.compared:0,ce=K-se*.5;V.push({alg:ee,score:ce})}V.sort((ee,F)=>F.score-ee.score),C.push(`- Based on this recording, recommended authoritative detector: **${V[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 F=m[ee]??[];C.push(`### ${ee} � ${F.length} segments`);for(const se of F)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){He.error("generateScientificReport error",G),He.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:h,onChange:G=>f(G.target.checked)})," ",o("audioPitch.compareAll")]}),s.jsx("input",{type:"file",accept:"audio/*",ref:j,onChange:q,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}),U&&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:U})]}),_&&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:_}),E&&s.jsxs("div",{style:{marginTop:8},children:[s.jsx("b",{children:"Probe:"})," ",E]})]}),(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,z])=>z).map(([G,z])=>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:z})]},G))]})]}),w.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:[w.map(G=>`: ${Math.round(G.start*10)} ${Math.round(G.duration*10)} ${G.pitch} [${G.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:"#222",borderRadius:4,width:"100%",maxWidth:600,display:"block"},role:"img","aria-label":"Waveform and RMS visualization canvas",ref:B=>{if(!B)return;const z=B.getContext("2d");if(z){z.clearRect(0,0,600,100),z.strokeStyle="#0ff",z.beginPath();for(let S=0;S<c.length;S+=Math.ceil(c.length/600)){const P=S/c.length*600,$=50-c[S]*48;S===0?z.moveTo(P,$):z.lineTo(P,$)}if(z.stroke(),x.length>0){z.strokeStyle="#ff0",z.beginPath();for(let S=0;S<x.length;S++){const P=S/x.length*600,$=100-x[S]*90;S===0?z.moveTo(P,$):z.lineTo(P,$)}z.stroke()}}}}),s.jsxs("div",{style:{color:"#aaa",fontSize:12,marginTop:4},children:[s.jsx("span",{style:{color:"#0ff"},children:"Waveform"}),"  | "," ",s.jsx("span",{style:{color:"#ff0"},children:"RMS"})]})]}),!k&&w.length===0&&!N&&s.jsx("div",{style:{marginTop:16,color:"#aaa"},children:s.jsx("i",{children:o("audioPitch.noNotesDetected")})}),h&&Object.keys(m).length>0&&s.jsxs("div",{style:{marginTop:16},children:[s.jsx("h4",{children:o("audioPitch.algorithmComparison")}),Object.entries(m).map(([B,z])=>s.jsxs("div",{style:{marginBottom:12},children:[s.jsx("b",{children:B}),": ",o("audioPitch.detectedSegments")," ",z.length,s.jsx("pre",{style:{background:"#111",color:"#ddd",padding:8,borderRadius:4,marginTop:8},children:z.map(S=>`: ${Math.round(S.start*10)} ${Math.round(S.duration*10)} ${S.pitch} [${S.freq.toFixed(1)} Hz]`).join(`
47
- `)})]},B))]})]})}function Ee(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 qd=[Ee("Belagak","BelagakRegular-dr1zE.otf"),Ee("Big Scratch Brush","BigScratchBrush-PVY9g.ttf"),Ee("Gerhaus","Gerhaus-PK69E.ttf"),Ee("Gerhaus Italic","GerhausItalic-d96l7.ttf"),Ee("Handone Medium","HandoneMedium-nAevO.otf"),Ee("Handson Bold","HandsonBold-9MnrL.otf"),Ee("Kineks Round Bold","KineksRoundBold-7OR34.ttf"),Ee("Kineks Round Light","KineksRoundLight-m2r35.ttf"),Ee("Kineks Round Medium","KineksRoundMedium-drejZ.ttf"),Ee("Kineks Round","KineksRoundRegular-PVRl7.ttf"),Ee("Kineks Round SemiBold","KineksRoundSemiBold-LVWG3.ttf"),Ee("Lemon Jelly","LemonJellyPersonalUse-dEqR.ttf"),Ee("Lemon Milk Bold","LemonMilkBold-gx2B3.otf"),Ee("Lemon Milk Bold Italic","LemonMilkBoldItalic-PKZ3P.otf"),Ee("Lemon Milk Light","LemonMilkLight-owxMq.otf"),Ee("Lemon Milk Light Italic","LemonMilkLightItalic-7BjPE.otf"),Ee("Lemon Milk Medium","LemonMilkMedium-mLZYV.otf"),Ee("Lemon Milk Medium Italic","LemonMilkMediumItalic-d95nl.otf"),Ee("Lemon Milk","LemonMilkRegular-X3XE2.otf"),Ee("Lemon Milk Italic","LemonMilkRegularItalic-L3AEy.otf"),Ee("Pemage","PemageRegular-YqrdO.otf"),Ee("Rosmatika","RosmatikaRegular-BWA45.ttf"),Ee("Scabber","Scabber-q2Mn0.ttf"),Ee("Stylish Calligraphy","StylishCalligraphyDemo-XPZZ.ttf"),Ee("Super Adorable","SuperAdorable-MAvyp.ttf"),Ee("Super Chiby","SuperChiby-BL62V.ttf"),Ee("Super Joyful","SuperJoyful-lxwPq.ttf"),Ee("Super Kindly","SuperKindly-drE8E.ttf"),Ee("Super Meatball","SuperMeatball-Yq1Gy.ttf")],da="nice2dev-karaoke-display",Hd=[{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"},...qd.map(e=>({value:e.family,label:e.family}))],Ro=[{id:"default",name:"Cyan ? Yellow ? Amber",sungGradient:["#00e5ff","#ffe600","#ffab00"],goldGradient:["#FFD700","#FFA000","#FFD700"],glowColor:"rgba(0,229,255,0.6)"},{id:"neon-pink",name:"Neon Pink ? Violet ? Blue",sungGradient:["#ff1493","#9b59b6","#3498db"],goldGradient:["#FFD700","#FF69B4","#FFD700"],glowColor:"rgba(255,20,147,0.6)"},{id:"fire",name:"Red ? Orange ? Yellow",sungGradient:["#ff1744","#ff9100","#ffea00"],goldGradient:["#FFD700","#FF6D00","#FFD700"],glowColor:"rgba(255,23,68,0.6)"},{id:"ocean",name:"Deep Blue ? Teal ? Aqua",sungGradient:["#1a237e","#00897b","#00e5ff"],goldGradient:["#FFD700","#00BCD4","#FFD700"],glowColor:"rgba(0,137,123,0.6)"},{id:"forest",name:"Green ? Lime ? Yellow",sungGradient:["#1b5e20","#76ff03","#ffea00"],goldGradient:["#FFD700","#76ff03","#FFD700"],glowColor:"rgba(118,255,3,0.6)"},{id:"retro",name:"Orange ? Pink ? Purple",sungGradient:["#ff6d00","#e91e63","#7b1fa2"],goldGradient:["#FFD700","#E91E63","#FFD700"],glowColor:"rgba(233,30,99,0.6)"}],Jt={presetId:"default",customSungGradient:["#00e5ff","#ffe600","#ffab00"],customGoldGradient:["#FFD700","#FFA000","#FFD700"],customGlowColor:"rgba(0,229,255,0.6)",animationMode:"ball",fontFamily:"Arial",transitionEffect:"none",curtainPrimaryColor:"#8b0000",curtainSecondaryColor:"#1a0000",curtainDurationMs:900,immersiveMode:!1};let Qa=!1;function $o(){try{const e=localStorage.getItem(da);if(e){const t=JSON.parse(e);return{...Jt,...t}}}catch{}return{...Jt}}async function Kd(e){if(Qa||(Qa=!0,!e))return;const t=await e();if(t)try{const n=JSON.parse(t),r={...Jt,...n};localStorage.setItem(da,JSON.stringify(r))}catch{}}function Yd(e){const t=JSON.stringify(e);localStorage.setItem(da,t),ua(e)}function To(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=Ro.find(n=>n.id===e.presetId);return t?{sungGradient:t.sungGradient,goldGradient:t.goldGradient,glowColor:t.glowColor}:{sungGradient:Jt.customSungGradient,goldGradient:Jt.customGoldGradient,glowColor:Jt.customGlowColor}}function ua(e){const{sungGradient:t,goldGradient:n,glowColor:r}=To(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 Zd(){const e=$o();ua(e)}const yn=["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)"],Po={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 Or(e){return 440*Math.pow(2,(e-69)/12)}function Eo(e,t){const n=Po[t],r=n.keys.length,a=[];for(const d of e)for(const h of d)a.includes(h.pitch)||a.push(h.pitch);if(a.sort((d,h)=>d-h),a.length===0)return n.keys.map((d,h)=>({index:h,key:d,gamepadButton:n.buttons[h],label:n.labels[h],minPitch:-999,maxPitch:999,color:yn[h%yn.length]}));const o=a[0],l=a[a.length-1]-o+1,c=[];for(let d=0;d<r;d++){const h=o+Math.floor(l*d/r),f=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:h,maxPitch:d===r-1?999:f,color:yn[d%yn.length]})}return c}function Ao(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 No(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:Ao(i.pitch,t),lineIndex:a,noteIndex:o})}return r.sort((a,o)=>a.note.startTime-o.note.startTime),r}class Xd{constructor(t){this.lanes=[],this.events=[],this.raf=null,this.keysDown=new Set,this.gamepadButtonsDown=new Set,this.running=!1,this.getCurrentTime=()=>0,this.lastFeedbackTime=0,this.lastActiveNote=null,this.preWindow=.15,this.postWindow=.15,this.loop=()=>{var c,d,h,f,m,g,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,(f=(h=this.config).onCurrentNote)==null||f.call(h,i)),o.some(Boolean)&&i){const x=i.lane,b=o.indexOf(!0);if(o[x]){const w=Or(i.note.pitch);this.config.onPitch(w),a-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=a,(g=(m=this.config).onHitFeedback)==null||g.call(m,{type:"perfect",lane:x,time:a}))}else if(b>=0){const y=Math.abs(b-x)*3,k=Or(i.note.pitch+y);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=ea(t.noteLines,t.bpm),r=(t.gap??0)/1e3;switch(this.lanes=Eo(n,t.difficulty),this.events=No(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 Qd(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 Jd=({index:e,style:t,data:n})=>{const{lines:r,notes:a,currentIndex:o,animationConfig:i}=n,l=r[e]??"",c=a.findIndex(w=>w.lineIndex===e),d=c>=0&&c===o,h=(i==null?void 0:i.enabled)??!0,f=(i==null?void 0:i.durationMs)??300,m=(i==null?void 0:i.translateX)??8,g=(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:h?`transform ${f}ms ${p}, opacity ${f}ms ${p}`:"none",transform:d?`translateX(${m}px) scale(${g})`:"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})})})},Io=({ultrastarText:e,audioUrl:t,audioRef:n,animationConfig:r})=>{const{t:a}=xe(),o=u.useRef(null),i=n??o,[l,c]=u.useState(!1),d=u.useMemo(()=>Qd(e),[e]),h=u.useRef(null),f=u.useRef(null),m=u.useRef(null),g=u.useRef(0),p=u.useRef(0),[v,x]=u.useState(-1),b=u.useMemo(()=>(e||"").split(/\r?\n/),[e]),w=28,y=b.length*w,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 R=r??null,_=R&&typeof R.scrollSmooth=="number"?R.scrollSmooth:.18;let E=performance.now();const U=()=>{var B,z;const W=performance.now(),j=Math.max(0,Math.min(.2,(W-E)/1e3));E=W;const L=M.currentTime||0;g.current=L;let I=-1;for(let S=0;S<d.length;S++){const P=d[S];if(L>=P.start&&L<P.start+Math.max(.001,P.duration)){I=S;break}}I!==N&&(N=I,x(I));let q=0;if(N>=0){const S=((B=d[N])==null?void 0:B.lineIndex)??0,P=((z=f.current)==null?void 0:z.clientHeight)??220;q=S*w-P/2+w/2;const $=Math.max(0,y-P);(isNaN(q)||!isFinite(q))&&(q=0),q=Math.max(0,Math.min(q,$))}const Y=1-Math.pow(Math.max(0,1-_),Math.min(4,j*60)),te=(((r==null?void 0:r.scrollEasing)||"easeOutCubic")==="linear"?S=>S:S=>1-Math.pow(1-S,3))(Y);p.current=p.current+(q-p.current)*te;try{const S=f.current;S&&typeof S.scrollTop=="number"&&(S.scrollTop=Math.round(p.current))}catch{}m.current=requestAnimationFrame(U)};return m.current=requestAnimationFrame(U),()=>{m.current&&cancelAnimationFrame(m.current)}},[i,d,y,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:"#666"},children:[(g.current||0).toFixed(2),"s"]}),s.jsxs("div",{style:{marginLeft:"auto",fontSize:13,color:"#666"},children:["Notes: ",d.length]})]}),s.jsx("div",{style:{border:"1px solid #ddd",height:220,overflow:"hidden",padding:8,position:"relative"},children:e?s.jsx(Ll.FixedSizeList,{height:220,width:"100%",itemCount:b.length,itemSize:w,ref:h,outerRef:f,itemData:k,children:Jd}):s.jsx("div",{style:{color:"#888"},children:a("karaokeEditor.noText","No text")})}),!n&&s.jsx("audio",{ref:o,src:t||void 0,preload:"metadata",style:{display:"none"}})]})};function eu(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 Lo({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:h,notes:f}=eu(e);i.current=h,l.current=f;const m=c.current;m&&"rebuildTexts"in m&&typeof m.rebuildTexts=="function"&&m.rebuildTexts()},[e]),u.useEffect(()=>{let h=!0;return(async()=>{var N;if(!h||!a.current)return;const f=await import("phaser"),m="default"in f?f.default:f;if(!a.current||!h)return;const g=i,p=l,v=c,x=n,b=r,w=d;class y 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=_:w.current?(this.audioEl=document.createElement("audio"),this.audioEl.src=w.current,this.audioEl.preload="metadata",this.audioEl.style.display="none",document.body.appendChild(this.audioEl)):this.audioEl=null}}rebuildTexts(){for(const j of this.texts)j.destroy();this.texts=[];const _={font:"18px monospace",color:"#ffffff"},E=22;let U=20;const W=g.current;for(let j=0;j<W.length;j++){const L=this.add.text(10,U,W[j]||" ",_).setOrigin(0,0);this.texts.push(L),U+=E}}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 U=0;U<this.texts.length;U++)this.texts[U].setStyle({backgroundColor:void 0,color:"#ffffff"});const E=p.current;for(const U of E)if(_>=U.start&&_<U.start+Math.max(.001,U.duration)){const W=this.texts[U.lineIndex];W&&W.setStyle({backgroundColor:"rgba(0,130,200,0.16)",color:"#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:[y]};o.current=new m.Game(M)})(),()=>{h=!1,c.current=null;try{const f=o.current;f&&typeof f.destroy=="function"&&f.destroy(!0)}catch{}}},[]),s.jsx("div",{ref:a,style:{width:"100%",height:340}})}const tu=et.scoped("GenericPlayer"),nu=e=>/youtu(\.be|be\.com)/i.test(e),Fo=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),ru=e=>!!e&&/\.(mp3|aac|m4a|flac|wav|ogg)(\?.*)?$/i.test(e),au=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&&nu(i.url)))??null;if(n)return n;const r=t("hls")||e.sources.find(i=>i.url&&Fo(i.url))||null;if(r)return r;const a=t("audio")||e.sources.find(i=>i.url&&ru(i.url))||null;return a||(e.sources[0]??null)},sr=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")}`},su=[.25,.5,.75,1,1.25,1.5,1.75,2],Do=({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:h=3,progressBarPosition:f="inline",loop:m=!1,onEnded:g,enableKeyboardShortcuts:p=!0,shuffle:v=!1,repeatMode:x="none",playbackSpeed:b=1,abLoop:w=null,onRepeatModeChange:y,onShuffleChange:k,onSpeedChange:M,sleepTimer:N=0,onSleepTimerExpired:R})=>{const{t:_}=xe(),[E,U]=u.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),W=e[E],j=u.useMemo(()=>au(W),[W]),[L,I]=u.useState(!1),[q,Y]=u.useState(0),[O,Z]=u.useState(0),[H,te]=u.useState(.9),[B,z]=u.useState(null),[S,P]=u.useState(null),$=u.useRef(null),[T,C]=u.useState(v),[A,D]=u.useState(x),[V,Q]=u.useState(b),[J,ae]=u.useState(w),[re,ee]=u.useState([]),[F,K]=u.useState(N>0?N*60:null),se=u.useRef(null),[ce,fe]=u.useState(()=>As()),X=u.useRef(null),ue=u.useRef(null),ye=u.useRef(null),je=u.useRef(null);u.useEffect(()=>{if(T&&e.length>0){const le=e.map((de,Ce)=>Ce);for(let de=le.length-1;de>0;de--){const Ce=Math.floor(Math.random()*(de+1));[le[de],le[Ce]]=[le[Ce],le[de]]}ee(le)}},[T,e.length]),u.useEffect(()=>(se.current&&(window.clearInterval(se.current),se.current=null),N>0&&L&&(K(N*60),se.current=window.setInterval(()=>{K(le=>!le||le<=1?(se.current&&window.clearInterval(se.current),se.current=null,R==null||R(),null):le-1)},1e3)),()=>{se.current&&window.clearInterval(se.current)}),[N,L]);const Fe=u.useCallback(le=>{const de=Math.min(Math.max(0,le),Math.max(0,e.length-1));U(de),o==null||o(de)},[e.length,o]),Re=u.useCallback(()=>{if(T&&re.length>0){const de=re.indexOf(E)+1;return de<re.length?re[de]:A==="all"?re[0]:-1}return E<e.length-1?E+1:A==="all"?0:-1},[E,e.length,T,re,A]),Se=u.useCallback(()=>{if(T&&re.length>0){const le=re.indexOf(E);return le>0?re[le-1]:A==="all"?re[re.length-1]:-1}return E>0?E-1:A==="all"?e.length-1:-1},[E,e.length,T,re,A]),ne=u.useCallback(()=>{const le=Re();le>=0&&Fe(le)},[Re,Fe]),oe=u.useCallback(async()=>{var le,de;await Et(),fe(!0),(j==null?void 0:j.kind)==="youtube"?(le=X.current)==null||le.playVideo():(de=ue.current)==null||de.play(),I(!0),i==null||i(!0)},[j,i]),Ne=u.useCallback(()=>{var le,de;(j==null?void 0:j.kind)==="youtube"?(le=X.current)==null||le.pauseVideo():(de=ue.current)==null||de.pause(),I(!1),i==null||i(!1)},[j,i]),De=u.useCallback(()=>L?Ne():oe(),[L,oe,Ne]),Pe=u.useCallback(le=>{var ie;const de=(W==null?void 0:W.startOffset)??0,Ce=le+de;(j==null?void 0:j.kind)==="youtube"?(ie=X.current)==null||ie.seekTo(Ce,!0):ue.current&&(ue.current.currentTime=Ce);const xt=Math.max(0,le);Z(xt),l==null||l(xt)},[j,l]),tt=u.useCallback(()=>{if(O>3){Pe(0);return}const le=Se();le>=0&&Fe(le)},[Se,Fe,O,Pe]),we=u.useCallback(le=>{var de,Ce;te(le),z(null),(j==null?void 0:j.kind)==="youtube"?(Ce=(de=X.current)==null?void 0:de.setVolume)==null||Ce.call(de,Math.round(le*100)):ue.current&&(ue.current.volume=le)},[j]),dt=u.useCallback(()=>{B!==null?we(B):(z(H),we(0))},[H,B,we]),Rn=u.useCallback(le=>{var de,Ce;Q(le),ue.current&&(ue.current.playbackRate=le),(j==null?void 0:j.kind)==="youtube"&&((Ce=(de=X.current)==null?void 0:de.setPlaybackRate)==null||Ce.call(de,le)),M==null||M(le)},[j,M]),Xe=u.useCallback(()=>{const le=["none","all","one"],de=le[(le.indexOf(A)+1)%le.length];D(de),y==null||y(de)},[A,y]),Ge=u.useCallback(()=>{const le=!T;C(le),k==null||k(le)},[T,k]),It=u.useCallback(le=>{ae(le)},[]);u.useImperativeHandle(c,()=>({play:oe,pause:Ne,toggle:De,seekTo:Pe,setVolume:we,setSpeed:Rn,setRepeatMode:le=>{D(le),y==null||y(le)},toggleShuffle:Ge,setABLoop:It,getUnderlyingPlayer:()=>(j==null?void 0:j.kind)==="youtube"?X.current:(j==null?void 0:j.kind)==="hls"||(j==null?void 0:j.kind)==="audio"?ue.current:null}),[oe,Ne,De,Pe,we,Rn,Ge,It,j==null?void 0:j.kind]),u.useEffect(()=>{const le=window.setInterval(()=>{let de=0,Ce=0;(j==null?void 0:j.kind)==="youtube"&&X.current?(de=X.current.getCurrentTime()||0,Ce=X.current.getDuration()||0):ue.current&&(de=ue.current.currentTime||0,Ce=ue.current.duration||0);const xt=(W==null?void 0:W.startOffset)??0,ie=Math.max(0,de-xt);Z(ie),Y(Ce),l==null||l(ie),J&&ie>=J.b&&Pe(J.a)},250);return()=>window.clearInterval(le)},[j==null?void 0:j.kind,l,J]),u.useEffect(()=>()=>{$.current&&(window.clearInterval($.current),$.current=null)},[]),u.useEffect(()=>{if(ye.current){try{ye.current.destroy()}catch{}ye.current=null}if(ue.current&&(ue.current.volume=H,ue.current.crossOrigin=j!=null&&j.withCredentials?"use-credentials":"anonymous"),(j==null?void 0:j.kind)==="hls"&&Fo(j.url)){const le=ue.current;if(!le)return;const de=()=>{le.src=j.url,le.load();const Ce=(W==null?void 0:W.startOffset)??0;try{Ce&&!isNaN(Ce)&&(le.currentTime=Ce)}catch{}n&&le.play().catch(()=>{})};le.canPlayType("application/vnd.apple.mpegurl")?de():(async()=>{var Ce;try{const ie=(await import("hls.js")).default;if((Ce=ie==null?void 0:ie.isSupported)!=null&&Ce.call(ie)){const he=new ie({xhrSetup:Oe=>{if(j!=null&&j.withCredentials&&(Oe.withCredentials=!0),j!=null&&j.headers)for(const[ve,me]of Object.entries(j.headers))try{Oe.setRequestHeader(ve,me)}catch{}}});ye.current=he,he.loadSource(j.url),he.attachMedia(le),he.on(ie.Events.MANIFEST_PARSED,()=>{n&&le.play().catch(()=>{})})}else de()}catch(xt){tu.debug("HLS.js setup failed, falling back to native playback",xt),de()}})()}else if((j==null?void 0:j.kind)==="audio"&&j.url&&ue.current){const le=ue.current;le.src=j.url,le.load();const de=(W==null?void 0:W.startOffset)??0;try{de&&!isNaN(de)&&(le.currentTime=de)}catch{}n&&le.play().catch(()=>{})}$.current&&(window.clearInterval($.current),$.current=null),P(null),Z(0),Y(0),n&&(j==null?void 0:j.kind)==="youtube"&&r>0?(P(r),$.current=window.setInterval(()=>{P(le=>{var de;if(!le)return null;if(le<=1){$.current&&(window.clearInterval($.current),$.current=null);try{(de=X.current)==null||de.playVideo()}catch{}return I(!0),i==null||i(!0),null}return le-1})},1e3)):I(!!n)},[j==null?void 0:j.url,j==null?void 0:j.kind,j==null?void 0:j.withCredentials,JSON.stringify(j==null?void 0:j.headers),n,H]);const yt=u.useCallback(()=>{if(A==="one"){Pe(0),oe();return}const le=Re();le>=0?Fe(le):(I(!1),i==null||i(!1),Pe(0),g==null||g())},[A,Re,Fe,i,Pe,g,oe]);u.useEffect(()=>{if(!p)return;const le=de=>{const Ce=de.target;if(!(Ce.tagName==="INPUT"||Ce.tagName==="TEXTAREA"||Ce.isContentEditable))switch(de.key){case" ":de.preventDefault(),De();break;case"ArrowRight":de.preventDefault(),Pe(Math.min(O+5,q));break;case"ArrowLeft":de.preventDefault(),Pe(Math.max(0,O-5));break;case"ArrowUp":de.preventDefault(),we(Math.min(1,H+.05));break;case"ArrowDown":de.preventDefault(),we(Math.max(0,H-.05));break;case"m":case"M":dt();break;case"n":case"N":ne();break;case"p":case"P":tt();break;case"r":case"R":Xe();break;case"s":case"S":Ge();break}};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[p,De,Pe,O,q,we,H,dt,ne,tt,Xe,Ge]);const mr=(j==null?void 0:j.kind)==="youtube"||d==="full"||d==="nobuttons",ut=h>0?e.slice(E+1,E+1+h):[];return s.jsxs("div",{ref:je,className:"gp-player",style:{display:"grid",gap:12},tabIndex:-1,children:[n&&!ce&&s.jsx("div",{className:"gp-audio-activation",onClick:()=>{fe(!0),oe()},style:{position:"fixed",inset:0,zIndex:200,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.6)",cursor:"pointer"},children:s.jsx("span",{style:{color:"#fff",fontSize:24},children:"Click to activate audio"})}),mr&&s.jsxs("div",{className:"gp-stage",style:{width:"100%",height:a,background:(j==null?void 0:j.kind)==="youtube"?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(j==null?void 0:j.kind)==="youtube"&&s.jsx(Yr,{videoId:j.videoId??uu(j.url),onReady:le=>{X.current=le.target,we(H);const de=(W==null?void 0:W.startOffset)??0;try{de&&le.target.seekTo(de,!0)}catch{}if(d==="nobuttons"){try{le.target.playVideo()}catch{}I(!0)}},onEnd:yt,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%"}}),S!==null&&s.jsx("div",{style:{position:"absolute",inset:0,zIndex:120,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.7)"},children:s.jsx("span",{style:{color:"#fff",fontSize:72,fontWeight:"bold"},children:S})}),d==="nobuttons"&&s.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"auto",zIndex:100,cursor:"default"}}),((j==null?void 0:j.kind)==="audio"||(j==null?void 0:j.kind)==="hls")&&s.jsxs(s.Fragment,{children:[d==="full"&&s.jsx("div",{style:{textAlign:"center",color:"var(--text, #e2e8f0)"},children:W!=null&&W.coverUrl?s.jsx("img",{alt:"cover",src:W.coverUrl,style:{height:a-24,objectFit:"contain"}}):s.jsxs("div",{style:{opacity:.8},children:[s.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[W==null?void 0:W.artist," � ",W==null?void 0:W.title]}),s.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-dim, #94a3b8)"},children:(j==null?void 0:j.label)??`${(j==null?void 0:j.codec)??""} ${(j==null?void 0:j.quality)??""}`.trim()})]})}),s.jsx("audio",{ref:ue,onEnded:yt,onLoadedMetadata:()=>{const le=ue.current;le&&Y(le.duration||0)},crossOrigin:j!=null&&j.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:(W==null?void 0:W.title)??"�"}),s.jsx("div",{style:{color:"var(--text-dim, #64748b)",fontSize:13},children:(W==null?void 0:W.artist)??"�"})]})}),d==="full"&&s.jsxs(s.Fragment,{children:[s.jsx(Oo,{currentTime:O,duration:q}),s.jsx(ou,{isPlaying:L,index:E,count:e.length,currentTime:O,duration:q,volume:H,onPrev:tt,onNext:ne,onToggle:De,onSeek:Pe,onVolume:we}),s.jsx(du,{shuffleOn:T,repeatMode:A,speed:V,abLoop:J,currentTime:O,sleepRemaining:F,onToggleShuffle:Ge,onCycleRepeat:Xe,onSpeedChange:Rn,onSetABLoop:It,onMuteToggle:dt,isMuted:B!==null})]}),d==="progressOnly"&&s.jsx("div",{style:f==="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(iu,{currentTime:O,duration:q,onSeek:Pe})}),(d==="minimal"||d==="compact")&&s.jsx(lu,{isPlaying:L,canPrev:E>0,canNext:E<e.length-1,onPrev:tt,onNext:ne,onToggle:De}),d==="compact"&&ut.length>0&&s.jsx(cu,{items:ut,onPick:le=>Fe(E+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,de)=>s.jsxs("button",{onClick:()=>Fe(de),style:{textAlign:"left",border:"1px solid var(--border-light, #e5e7eb)",borderRadius:8,padding:"8px 10px",background:de===E?"var(--active-bg, #eef2ff)":"var(--bg, #fff)",cursor:"pointer"},title:le.sources.map(Ce=>Ce.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))})]})},at={border:"1px solid var(--border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--bg, #fff)",cursor:"pointer"},Oo=({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:[sr(e)," / ",sr(t)]})]}),ou=({isPlaying:e,index:t,count:n,currentTime:r,duration:a,volume:o,onPrev:i,onNext:l,onToggle:c,onSeek:d,onVolume:h})=>{const{t:f}=xe();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:f("player.previousTrack"),"aria-label":f("player.previousTrack"),style:at,children:"?"}),s.jsx("button",{onClick:c,title:f(e?"player.pause":"player.play"),"aria-label":f(e?"player.pause":"player.play"),style:at,children:"?"}),s.jsx("button",{onClick:l,disabled:t>=n-1,title:f("player.nextTrack"),"aria-label":f("player.nextTrack"),style:at,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=>h(parseFloat(m.target.value)),"aria-label":"Volume"})]})]})},iu=({currentTime:e,duration:t,onSeek:n})=>s.jsxs(s.Fragment,{children:[s.jsx(Oo,{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"})]}),lu=({isPlaying:e,canPrev:t,canNext:n,onPrev:r,onNext:a,onToggle:o})=>{const{t:i}=xe();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:at,children:"?"}),s.jsx("button",{onClick:o,title:i(e?"player.pause":"player.play"),"aria-label":i(e?"player.pause":"player.play"),style:at,children:"?"}),s.jsx("button",{onClick:a,disabled:!n,title:i("player.nextTrack"),"aria-label":i("player.nextTrack"),style:at,children:"?"})]})},cu=({items:e,onPick:t})=>{const{t:n}=xe();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))})]})},du=({shuffleOn:e,repeatMode:t,speed:n,abLoop:r,currentTime:a,sleepRemaining:o,onToggleShuffle:i,onCycleRepeat:l,onSpeedChange:c,onSetABLoop:d,onMuteToggle:h,isMuted:f})=>{const{t:m}=xe(),g={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:{...at,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:{...at,opacity:t==="none"?.4:1},children:g[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:{...at,minWidth:56,fontSize:12},children:su.map(v=>s.jsxs("option",{value:v,children:[v,"x"]},v))}),s.jsx("button",{onClick:h,title:m("player.mute","Mute"),"aria-label":m("player.mute","Mute"),style:{...at,opacity:f?1:.6},children:f?"🔇":"🔊"}),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: ",sr(r.a)," — B: ",sr(r.b)]}),s.jsx("button",{onClick:()=>d(null),title:m("player.clearLoop","Clear loop"),style:{...at,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:{...at,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 uu(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 hu=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),Ja=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")}`},wr={border:"1px solid #d1d5db",borderRadius:8,padding:"6px 10px",background:"#fff",cursor:"pointer"},fu=({isPlaying:e,index:t,count:n,currentTime:r,duration:a,volume:o,onPrev:i,onNext:l,onToggle:c,onSeek:d,onVolume:h})=>{const{t:f}=xe();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:"#64748b"},children:[Ja(r)," / ",Ja(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:f("playerControls.prev","Prev"),"aria-label":f("playerControls.previousTrack","Previous track"),style:wr,children:"⏮"}),s.jsx("button",{onClick:c,title:e?f("playerControls.pause","Pause"):f("playerControls.play","Play"),"aria-label":e?f("playerControls.pause","Pause"):f("playerControls.play","Play"),style:wr,children:e?"⏸":"▶"}),s.jsx("button",{onClick:l,disabled:t>=n-1,title:f("playerControls.next","Next"),"aria-label":f("playerControls.nextTrack","Next track"),style:wr,children:"⏭"})]}),s.jsx("input",{type:"range",min:0,max:Math.max(1,a),step:.1,value:r,"aria-label":f("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":f("playerControls.volume","Volume"),onChange:m=>h(parseFloat(m.target.value))})]})]})]})},_o=u.memo(fu);function pu(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,h=d*(n-6),f=c*l,m=n-h,g=c/48*240+a;e.fillStyle=`hsl(${g%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(f+1,m,l-2,h)}}function mu(e,t,n,r,a,o){if(!o.current){const f=[];for(let g=0;g<24;g++)f.push({ang:g/24*Math.PI*2,phase:Math.random()*Math.PI*2,baseR:Math.min(t,n)*.22+Math.random()*30});o.current={nodes:f}}const i=o.current,l=t/2,c=n/2,d=26+r*80,h=[];for(const f of i.nodes){f.phase+=.02+r*.06;const m=f.baseR+Math.sin(f.phase)*d,g=l+Math.cos(f.ang)*m,p=c+Math.sin(f.ang)*m;h.push([g,p])}e.fillStyle=`hsla(${a}, 70%, 55%, .22)`,e.strokeStyle=`hsla(${(a+40)%360}, 90%, 65%, .9)`,e.lineWidth=2,e.beginPath();for(let f=0;f<h.length;f++){const[m,g]=h[f],[p,v]=h[(f+1)%h.length],x=(m+p)/2,b=(g+v)/2;f===0?e.moveTo(x,b):e.quadraticCurveTo(m,g,x,b)}e.closePath(),e.fill(),e.stroke()}function gu(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 yu="#94a3b8",bu=({height:e,coverUrl:t,title:n,subtitle:r,label:a})=>s.jsx("div",{style:{textAlign:"center",color:"#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:yu},children:a??r??"—"})]})});function Ot(e,t){return e+Math.random()*(t-e)}function vu(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 f=0;f<d;f++){const m=(f+.5)/d*t,g=(r[Math.floor((f+1)/(d+1)*r.length)]||0)/255,p=n*.18+(.25+a*.6+g*.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+f*.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 h=Math.floor(1+a*6);for(let f=0;f<h;f++)l.embers.push({x:Ot(t*.25,t*.75),y:n-Ot(4,14),r:Ot(1,3),vx:Ot(-.15,.15),vy:-Ot(.6,1.8)-a*1.2,life:Ot(.8,1.6)});e.save(),e.globalCompositeOperation="lighter";for(let f=l.embers.length-1;f>=0;f--){const m=l.embers[f];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(f,1);continue}const g=e.createRadialGradient(m.x,m.y,0,m.x,m.y,m.r*3);g.addColorStop(0,`hsla(${(o+25)%360},100%,65%,.9)`),g.addColorStop(1,`hsla(${(o+25)%360},100%,65%,0)`),e.fillStyle=g,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 xu(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 h=0;h<c;h++){const f=(r[h*d]??0)/255,m=h/c*Math.PI*2,g=f*(Math.min(t,n)*.22)+6,p=o+Math.cos(m)*l,v=i+Math.sin(m)*l,x=o+Math.cos(m)*(l+g),b=i+Math.sin(m)*(l+g);e.strokeStyle=`hsl(${(a+h*3)%360}, 90%, ${40+f*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 Su(e,t,n,r,a){const l=t/14,c=n/8;for(let d=0;d<8;d++)for(let h=0;h<14;h++){const f=Math.min(r.length-1,d*14+h),m=r[f]/255,g=(a+h/14*210+d/8*90)%360,p=65+m*30,v=20+m*40,x=(1-m)*4;e.fillStyle=`hsl(${g}, ${p}%, ${v}%)`,e.fillRect(h*l+x,d*c+x,Math.max(1,l-2*x),Math.max(1,c-2*x))}}function wu(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 Cu(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 wu(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 h=Math.random()*Math.min(r,a)*.38+40;o.sprites.push({img:c(d),x:(Math.random()-.5)*h*.4,y:(Math.random()-.5)*h*.4,z:Math.random()*600+100,ang:Math.random()*Math.PI*2,spin:(Math.random()*.03+.01)*(Math.random()<.5?-1:1),vz:Math.random()*1.2+.2,size:Math.random()*.35+.65})}}}function ku(e,t,n,r,a,o,i,l){const c=o.current;if(!(c!=null&&c.ready))return;const d=t/2,h=n/2,f=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=f);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 g=[...c.sprites].sort((p,v)=>v.z-p.z);for(const p of g){const v=f/(f-p.z)*.6*p.size,x=d+p.x*v,b=h+p.y*v,w=64*v,y=64*v;e.save(),e.globalAlpha=.12+(1-p.z/f)*.2,e.fillStyle=`hsl(${(a+(1-p.z/f)*60)%360}, 90%, 60%)`,e.beginPath(),e.ellipse(x,b,w*.7,y*.7,0,0,Math.PI*2),e.fill(),e.restore(),p.img&&p.img.width?e.drawImage(p.img,x-w/2,b-y/2,w,y):(e.save(),e.fillStyle=`hsl(${(a+180)%360}, 40%, 55%)`,e.fillRect(x-w/2,b-y/2,w,y),e.restore())}}function sn(e,t){return e+Math.random()*(t-e)}function Mu(e,t,n,r,a,o){o.current||(o.current={blobs:Array.from({length:7},(d,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:(a+h*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,h=e.createRadialGradient(c.x,c.y,c.r*.2,c.x,c.y,c.r);h.addColorStop(0,`hsla(${d}, 95%, 70%, .8)`),h.addColorStop(1,`hsla(${(d+40)%360}, 90%, 30%, 0)`),e.fillStyle=h,e.shadowBlur=18,e.shadowColor=`hsl(${d}, 100%, 60%)`,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}e.restore(),e.strokeStyle="rgba(255,255,255,.06)",e.lineWidth=2,e.strokeRect(1,1,t-2,n-2)}function ju(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 h of i.tris){h.a+=.002+r*.02*(h.dr>0?1:-1),h.r+=Math.sin(h.a*2)*(.3+r*1.4);const f=Math.max(40,Math.min(h.r,Math.min(t,n)*.48));e.save(),e.translate(c,d),e.rotate(h.a),e.strokeStyle=`hsla(${(a+f*.2)%360}, 90%, 60%, .9)`,e.lineWidth=2.5,e.beginPath(),e.moveTo(f,0);for(let m=1;m<3;m++){const g=m*Math.PI*2/3;e.lineTo(Math.cos(g)*f,Math.sin(g)*f)}e.closePath(),e.shadowBlur=12,e.shadowColor=e.strokeStyle,e.stroke(),e.restore()}}function Ru(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 h=0;h<c;h++){const f=(h+1)/(c+1),m=f*d;e.strokeStyle=`hsla(${(a+h*30)%360}, 70%, 45%, 0.35)`,e.lineWidth=1,e.beginPath(),e.arc(i,l,m,0,Math.PI*2),e.stroke();const g=Math.floor(r.length*f|0),p=(r[g]??0)/255,v=6+h*2;for(let x=0;x<v;x++){const b=o.current*(1+h*.15)+x/v*Math.PI*2,w=m+Math.sin(b*2)*6*p,y=i+Math.cos(b)*w,k=l+Math.sin(b)*w;e.fillStyle=`hsla(${(a+h*30+x*6)%360}, 90%, ${55+p*30}%, ${.6+p*.3})`,e.beginPath(),e.arc(y,k,2+p*4,0,Math.PI*2),e.fill()}}}function $u(e,t,n,r,a){const l=t/12,c=n/6;for(let d=0;d<6;d++)for(let h=0;h<12;h++){const f=(d*12+h)%r.length,m=r[f]/255,g=(a+h/12*180+d/6*90)%360,p=70+m*25,v=25+m*35;e.fillStyle=`hsl(${g}, ${p}%, ${v}%)`,e.fillRect(h*l,d*c,Math.ceil(l),Math.ceil(c))}}function Tu(e,t,n,r,a,o){const i=t/2,l=n/2,c=2+Math.floor(r*14);for(let h=0;h<c;h++){const f=Math.random()*Math.PI*2,m=.5+Math.random()*(2.5+r*4);o.current.push({x:i,y:l,vx:Math.cos(f)*m,vy:Math.sin(f)*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 h=d.length-1;h>=0;h--){const f=d[h];f.x+=f.vx,f.y+=f.vy,f.life+=1;const m=1-f.life/f.max;e.fillStyle=`hsla(${f.hue},85%,60%,${Math.max(0,m)})`,e.beginPath(),e.arc(f.x,f.y,2+m*3,0,Math.PI*2),e.fill(),(f.life>=f.max||f.x<-20||f.y<-20||f.x>t+20||f.y>n+20)&&d.splice(h,1)}d.length>1200&&d.splice(0,d.length-1200)}function Pu(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,"rgba(0,0,0,0)"),e.fillStyle=d,e.beginPath(),e.arc(i,l,c,0,Math.PI*2),e.fill();const h=18+Math.floor(a*50);for(let f=0;f<h;f++){const m=f/h*Math.PI*2+r*(.6+a*1.4),g=(Math.sin(r*2+f*1.7)+Math.cos(r*1.3+f*2.1))*.15,p=c*(.4+.55*Math.abs(Math.sin(r*1.2+f))),v=6;e.save(),e.translate(i,l),e.rotate(m+g),e.beginPath(),e.moveTo(0,0);for(let b=1;b<=v;b++){const w=p/v*b,y=(Math.sin(r*3+f*.8+b)*.6+Math.cos(r*2+f+b*.7))*(8+24*a),k=w,M=y;e.lineTo(M,k)}e.globalCompositeOperation="lighter";const x=(o+f*(240/h))%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 Eu(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,h=Math.min(t,n)*.48;for(let f=0;f<96;f++){const m=r[f*i]/255,g=f/96*Math.PI*2,p=d,v=d+m*(h-d),x=l+Math.cos(g)*p,b=c+Math.sin(g)*p,w=l+Math.cos(g)*v,y=c+Math.sin(g)*v;e.strokeStyle=`hsl(${f/96*360+a},85%,60%)`,e.lineWidth=3,e.beginPath(),e.moveTo(x,b),e.lineTo(w,y),e.stroke()}e.fillStyle="rgba(255,255,255,0.08)",e.beginPath(),e.arc(l,c,d*.85,0,Math.PI*2),e.fill()}function Au(e,t,n,r,a,o){const i=t/2,l=n/2,c=Math.min(t,n)*.5,d=es(r,0,Math.floor(r.length*.1))/255,h=es(r,Math.floor(r.length*.6),r.length)/255;o.current+=.01+h*.03;const f=24;for(let m=0;m<f;m++){const g=o.current+m/f*Math.PI*2,p=(.35+d*.55)*c,v=i+Math.cos(g)*p,x=l+Math.sin(g)*p,b=e.createRadialGradient(i,l,0,i,l,p),w=m/f*360+a;b.addColorStop(0,`hsla(${w},85%,65%,0.0)`),b.addColorStop(1,`hsla(${w},85%,65%,0.9)`),e.strokeStyle=b,e.lineWidth=6+h*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 es(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 Nu(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,h=t/(d-1);e.beginPath();for(let g=0;g<d;g++){const p=(r[g]-128)/128,v=Math.sin(o*1.5+g*.03)*.12,x=g*h,b=i-l-(p+v)*c;g===0?e.moveTo(x,b):e.lineTo(x,b)}const f=e.createLinearGradient(0,0,0,i-l);f.addColorStop(0,"hsla(260,90%,75%,0.9)"),f.addColorStop(1,"hsla(220,85%,60%,0.4)"),e.strokeStyle=f,e.lineWidth=2,e.stroke(),e.beginPath();for(let g=0;g<d;g++){const p=(r[g]-128)/128,v=Math.cos(o*1.3+g*.035)*.12,x=g*h,b=i+l+(p+v)*c;g===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="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 Iu(e,t,n,r,a,o){const i=t/2,l=n/2,c=5,d=Math.min(t,n)*.12;for(let h=0;h<c;h++){const f=Math.floor(h/c*r.length),m=r[f]/255,g=d+h*d*.55+m*d*.5,p=(o+h*40)%360;e.lineWidth=3+m*6,e.strokeStyle=`hsla(${p},80%,60%,${.5+.5*a})`,e.beginPath(),e.arc(i,l,g,0,Math.PI*2),e.stroke()}}function Lu(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,h=d*(n-6),f=c*l,m=n-h,g=c/o*240+a;e.fillStyle=`hsl(${g%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(f+1,m,l-2,h)}}function Fu(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 Du(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 h of i.stars){h.z-=d,h.z<20&&(h.x=(Math.random()-.5)*t,h.y=(Math.random()-.5)*n,h.z=900,h.pz=h.z);const f=h.x/h.z*600,m=h.y/h.z*600,g=h.x/h.pz*600,p=h.y/h.pz*600;h.pz=h.z,e.strokeStyle=`hsla(${(a+200)%360}, 90%, 70%, 0.7)`,e.lineWidth=Math.max(1,(1-h.z/900)*2),e.beginPath(),e.moveTo(g,p),e.lineTo(f,m),e.stroke()}e.restore()}function Ou(e,t,n,r){e.lineWidth=2,e.strokeStyle="#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 _u=({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?"#6366f1":"#334155"}`,background:e?"rgba(99,102,241,.12)":"rgba(15,23,42,.6)",color:e?"#e2e8f0":"#cbd5e1",cursor:"pointer",whiteSpace:"nowrap",lineHeight:1.2},children:r}),ha=({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:"rgba(2,6,23,.5)",padding:6,borderRadius:10,border:"1px solid #334155",backdropFilter:"blur(2px)",justifyItems:"end",alignItems:"start"},children:e.map(o=>s.jsx(_u,{active:t===o,onClick:()=>n(o),title:`Tryb: ${o}`,children:o},o))})})};function zu(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 Bu=({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:"rgba(2,6,23,.5)",padding:"6px 8px",borderRadius:8,border:"1px solid #334155",backdropFilter:"blur(2px)",pointerEvents:"none",zIndex:9998},children:Array.from({length:n}).map((a,o)=>{const i=120*(o/n);return s.jsx("div",{style:{width:6,height:18,borderRadius:2,background:o<r?`hsl(${i}, 80%, 50%)`:"#1f2937"}},o)})})},Gu="var(--player-bg, #0f172a)",fa=({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:h,imageUrls:f,imageCount:m=14})=>{const g=u.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette","radial","rays","particles","rings","grid","imageTornado","colorRipples","starfield","orbitals","eqcircle","triangles","blob","plasma","lavaLamp","cozyFire","rift"],[e,h]),p=u.useMemo(()=>{const te=g.includes(c)?c:g[0];try{const B=localStorage.getItem(d);if(!B)return te;const z=JSON.parse(B);return g.includes(z)?z:te}catch{return te}},[g,c,d]),[v,x]=zu(d,p),b=u.useRef(null),w=u.useRef(null),y=u.useRef(null),k=u.useRef(null),M=u.useRef(null),N=u.useRef(null),R=u.useRef(0),_=u.useRef(0),E=u.useRef([]),[U,W]=u.useState(0),j=u.useRef(null),L=u.useRef(null),I=u.useRef(null),q=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"||(w.current&&(cancelAnimationFrame(w.current),w.current=null),!H))return;Et();const te=tn(),B=t.current;if(!B)return;if(!y.current)try{y.current=te.createMediaElementSource(B)}catch{}if(!k.current){const C=te.createAnalyser();C.fftSize=2048,C.smoothingTimeConstant=.85,k.current=C;try{(T=y.current)==null||T.connect(C)}catch{}try{C.connect(te.destination)}catch{}}const z=k.current;M.current=new Uint8Array(z.frequencyBinCount),N.current=new Uint8Array(z.fftSize);const S=()=>{const C=b.current,A=Math.max(1,Math.floor(window.devicePixelRatio||1));C.width=Math.floor(C.clientWidth*A),C.height=Math.floor(C.clientHeight*A);const D=C.getContext("2d");D==null||D.setTransform(1,0,0,1,0,0),D==null||D.scale(A,A)};S();const P=()=>S();window.addEventListener("resize",P),Fu(I,220,b.current.width,b.current.height);const $=async()=>{const C=b.current;if(!C)return;const A=C.getContext("2d");if(!A)return;const D=Math.max(1,Math.floor(window.devicePixelRatio||1)),V=C.width/D,Q=C.height/D,J=performance.now()*.001,ae=v==="waveform"||v==="rift";ae?z.getByteTimeDomainData(N.current):z.getByteFrequencyData(M.current);let re=0;const ee=ae?N.current:M.current;for(let F=0;F<ee.length;F++){const K=ae?(ee[F]-128)/128:ee[F]/255;re+=K*K}if(re=Math.sqrt(re/ee.length),W(Math.min(1,re)),A.clearRect(0,0,V,Q),v==="spectrum")Lu(A,V,Q,M.current,R.current);else if(v==="bars")pu(A,V,Q,M.current,R.current);else if(v==="waveform")Ou(A,V,Q,N.current);else if(v==="palette"){const F=(R.current+re*120)%360;$u(A,V,Q,M.current,F)}else if(v==="radial")Eu(A,V,Q,M.current,R.current);else if(v==="rays")Au(A,V,Q,M.current,R.current,_);else if(v==="particles")Tu(A,V,Q,re,R.current,E);else if(v==="rings")Iu(A,V,Q,M.current,re,R.current);else if(v==="grid"){const F=(R.current+re*160)%360;Su(A,V,Q,M.current,F)}else if(v==="imageTornado"){const F=f!=null&&f.length?f:a?[a]:[];await Cu(j,F,m,V,Q);const K=(R.current+re*100)%360;ku(A,V,Q,re,K,j)}else if(v==="colorRipples"){const F=(R.current+re*120)%360;gu(A,V,Q,re,F,L)}else if(v==="starfield"){const F=(R.current+60)%360;Du(A,V,Q,re,F,I)}else if(v==="orbitals"){const F=(R.current+re*180)%360;Ru(A,V,Q,M.current,F,_)}else if(v==="eqcircle"){const F=(R.current+120)%360;xu(A,V,Q,M.current,F)}else if(v==="triangles"){const F=(R.current+40)%360;ju(A,V,Q,re,F,q)}else if(v==="blob"){const F=(R.current+90)%360;mu(A,V,Q,re,F,Y)}else if(v==="plasma"){const F=(R.current+re*200)%360;Pu(A,V,Q,J,re,F)}else if(v==="rift")Nu(A,V,Q,N.current,re,J);else if(v==="lavaLamp"){const F=(R.current+re*80)%360;Mu(A,V,Q,re,F,O)}else if(v==="cozyFire"){const F=(R.current+re*140)%360;vu(A,V,Q,M.current,re,F,Z)}R.current=(R.current+.4)%360,w.current=requestAnimationFrame($)};return w.current=requestAnimationFrame($),()=>{window.removeEventListener("resize",P),w.current&&cancelAnimationFrame(w.current)}},[H,e,t,v,f,m,a]),s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none",background:v==="cover"?"transparent":Gu},children:v==="cover"?s.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:s.jsx(bu,{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(ha,{modes:g,active:v,setActive:x,rows:2}),s.jsx(Bu,{vu:U,hide:e==="youtube"})]})]})},zo=({height:e,autoPlay:t,track:n,source:r,ytRef:a,audioRef:o,hlsRef:i,setVol:l,onEnd:c,volume:d,extractVideoId:h})=>{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"&&hu(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 w=new b({xhrSetup:y=>{if(r!=null&&r.withCredentials&&(y.withCredentials=!0),r!=null&&r.headers)for(const[k,M]of Object.entries(r.headers))y.setRequestHeader(k,String(M))}});i.current=w,w.loadSource(r.url),w.attachMedia(p),w.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 f=(r==null?void 0:r.kind)==="youtube",m=f?"video":"cover",g=`gp-stage:mode:${(r==null?void 0:r.kind)??"none"}`;return s.jsxs("div",{className:"gp-stage",style:{width:"100%",height:e,background:f?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(r==null?void 0:r.kind)==="youtube"&&s.jsx(Yr,{videoId:r.videoId??h(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(fa,{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:g},`vis-${g}`)]})};function Wu(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 Uu="var(--text-dim, #94a3b8)",Vu=({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}),Bo=({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:h,overlayOnly:f=!1})=>{const m=u.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette"],[e,h]),g=u.useMemo(()=>{const j=m.includes(c)?c:m[0];try{const L=localStorage.getItem(d);if(!L)return j;const I=JSON.parse(L);return m.includes(I)?I:j}catch{return j}},[m,c,d]),[p,v]=Wu(d,g),x=u.useRef(null),[b,w]=u.useState(0),y=u.useRef(null),k=u.useRef(null),M=u.useRef(null),N=u.useRef(null),R=u.useRef(null),_=u.useRef(0),E=p==="spectrum"||p==="bars"||p==="waveform"||p==="palette";u.useEffect(()=>{var O;if(e==="youtube")return;if(!E){y.current&&cancelAnimationFrame(y.current);return}Et();const j=tn(),L=t.current;if(!L)return;if(!k.current)try{k.current=j.createMediaElementSource(L)}catch{}if(!M.current){const Z=j.createAnalyser();Z.fftSize=2048,Z.smoothingTimeConstant=.85,M.current=Z;try{(O=k.current)==null||O.connect(Z)}catch{}try{Z.connect(j.destination)}catch{}}const I=M.current;N.current=new Uint8Array(I.frequencyBinCount),R.current=new Uint8Array(I.fftSize);const q=()=>{if(!x.current)return;const Z=x.current,H=Z.getContext("2d");if(!H)return;const te=Z.width,B=Z.height;H.clearRect(0,0,te,B),p==="waveform"?I.getByteTimeDomainData(R.current):I.getByteFrequencyData(N.current);let z=0;const S=p==="waveform"?R.current:N.current;for(let P=0;P<S.length;P++){const $=p==="waveform"?(S[P]-128)/128:S[P]/255;z+=$*$}if(z=Math.sqrt(z/S.length),w(Math.min(1,z)),p==="spectrum"||p==="bars"){const P=N.current,$=p==="bars"?48:Math.min(P.length,256),T=Math.floor(P.length/$),C=te/$;for(let A=0;A<$;A++){const D=P[A*T]/255,V=D*(B-6),Q=A*C,J=B-V,ae=A/$*240+_.current;H.fillStyle=`hsl(${ae%360}, 80%, ${Math.max(30,40+D*30)}%)`,H.fillRect(Q+1,J,C-2,V)}}else if(p==="waveform"){const P=R.current;H.lineWidth=2,H.strokeStyle="#c7d2fe",H.beginPath();const $=te/P.length;for(let T=0;T<P.length;T++){const C=(P[T]-128)/128,A=T*$,D=B/2+C*(B*.45);T===0?H.moveTo(A,D):H.lineTo(A,D)}H.stroke()}else if(p==="palette"){const T=te/12,C=B/6,A=(_.current+z*120)%360;for(let D=0;D<6;D++)for(let V=0;V<12;V++){const Q=(D*12+V)%N.current.length,J=N.current[Q]/255,ae=(A+V/12*180+D/6*90)%360,re=70+J*25,ee=25+J*35;H.fillStyle=`hsl(${ae}, ${re}%, ${ee}%)`,H.fillRect(V*T,D*C,Math.ceil(T),Math.ceil(C))}}H.strokeStyle=getComputedStyle(document.documentElement).getPropertyValue("--waveform-stroke")||"#c7d2fe",y.current=requestAnimationFrame(q)},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),y.current=requestAnimationFrame(q),()=>{window.removeEventListener("resize",Y),y.current&&cancelAnimationFrame(y.current)}},[E,e,t,p]);const U=()=>{if(e==="youtube")return null;const j=12,L=Math.round(b*j);return s.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"rgba(2,6,23,.5)",padding:"6px 8px",borderRadius:8,border:"1px solid #334155",backdropFilter:"blur(2px)"},children:Array.from({length:j}).map((I,q)=>{const Y=120*(q/j);return s.jsx("div",{style:{width:6,height:18,borderRadius:2,background:q<L?`hsl(${Y}, 80%, 50%)`:"#1f2937"}},q)})})},W=()=>s.jsx("div",{style:{textAlign:"center",color:"#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:Uu},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:W()}):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:"rgba(2,6,23,.5)",padding:"6px",borderRadius:10,border:"1px solid #334155",backdropFilter:"blur(2px)",pointerEvents:"auto",zIndex:9999},children:m.map(j=>s.jsx(Vu,{active:p===j,onClick:()=>v(j),title:`Tryb: ${j}`,children:j},j))}),s.jsx("div",{style:{position:"absolute",right:10,bottom:10,pointerEvents:"none",zIndex:9998},children:s.jsx(U,{})})]})]})},Go=({artist:e,title:t,hideControls:n=!0,isPlaying:r,onTimeUpdate:a,searchYouTubeByArtistTitle:o})=>{const{t:i}=xe(),[l,c]=u.useState(e||""),[d,h]=u.useState(t||""),[f,m]=u.useState(null),[g,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(()=>{g&&(r?g.playVideo():g.pauseVideo())},[r,g]),u.useEffect(()=>{if(g&&a){const y=setInterval(()=>{const k=g.getCurrentTime();a(k)},100);return()=>clearInterval(y)}},[g,a]),u.useEffect(()=>{const y=()=>{if(v.current){const k=v.current.clientWidth,M=Math.round(k*(9/16));b({width:k,height:M})}};return y(),window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[]);const w=async()=>{if(!o)return;const y=await o(l,d);m(y)};return s.jsxs("div",{ref:v,style:{width:"100%",maxWidth:"900px",margin:"0 auto"},children:[(!e||!t||!f)&&s.jsxs("div",{children:[s.jsx("input",{value:l,onChange:y=>c(y.target.value),placeholder:i("youtubePlayer.artist","Artist"),"aria-label":i("youtubePlayer.artist","Artist")}),s.jsx("input",{value:d,onChange:y=>h(y.target.value),placeholder:i("youtubePlayer.title","Title"),"aria-label":i("youtubePlayer.title","Title")}),s.jsx("button",{onClick:w,children:i("youtubePlayer.search","Search")})]}),f&&s.jsxs("div",{children:[s.jsx(Yr,{videoId:f,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:y=>p(y.target)}),!n&&s.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px"},children:[s.jsx("button",{onClick:()=>g==null?void 0:g.playVideo(),children:"? Play"}),s.jsx("button",{onClick:()=>g==null?void 0:g.pauseVideo(),children:"? Pause"})]})]})]})},qu=({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"})})}},pa=({data:e,display:t,callbacks:n,state:r})=>{const{id:a,index:o,artist:i,title:l,version:c,lp:d,sourcesAvailable:h=[]}=e,{allowVersion:f=!0,dragHandleProps:m}=t,{onChange:g,onRemove:p,onMoveUp:v,onMoveDown:x,onChangeLp:b,onSelectSource:w}=n,{readOnly:y=!1,canMoveUp:k=!0,canMoveDown:M=!0,activeSource:N}=r,{t:R}=xe(),_=u.useRef(null);u.useEffect(()=>{!i&&_.current&&_.current.focus()},[i]);const E=L=>{if(!y&&L.key==="Enter"){const I=L.target.closest("div.gpi-row"),q=I==null?void 0:I.querySelectorAll("input[data-role='field']");if(!q||q.length===0)return;const Y=Array.from(q).indexOf(L.target),O=q[Y+1]??q[0];O==null||O.focus()}},U=L=>{const I=h.includes(L),q=N===L,Y={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid #e5e7eb",background:q?"var(--active-bg, #eef2ff)":"var(--bg, #fff)",opacity:I?1:.35,cursor:I&&w&&!y?"pointer":"default",transition:"transform .05s ease"},O=L==="youtube"?"#FF0000":L==="spotify"?"#1DB954":L==="tidal"?"#111827":L==="hls"?"#7C3AED":"#374151",Z=L==="youtube"?"YouTube":L==="spotify"?"Spotify":L==="tidal"?"TIDAL":L==="hls"?"HLS":"Audio",H=R("playlistItem.sourceLabel")+": "+Z+(q?` ${R("playlistItem.sourceSelected")}`:""),te=()=>{!I||!w||y||w(L)};return s.jsx("button",{type:"button",title:Z,onClick:te,disabled:!I||y,style:Y,"aria-pressed":q,"aria-label":H,children:s.jsx(qu,{kind:L,color:O})},L)},W=["youtube","tidal","spotify","hls","audio"],j=typeof d=="number"?d:o+1;return s.jsxs("div",{className:"gpi-row",role:"group","aria-label":R("playlistItem.trackNumber")+" "+(o+1),style:{display:"grid",gridTemplateColumns:f?"56px 1fr 1fr 1fr auto auto":"56px 1fr 1fr auto auto",gap:8,alignItems:"center"},children:[s.jsx("input",{type:"number",min:1,value:j,onChange:L=>b==null?void 0:b(Number(L.target.value)),disabled:y||!b,"aria-label":"Lp",title:R("playlistItem.positionOnList"),style:Hu}),s.jsx("input",{ref:_,"data-role":"field",type:"text",value:i,onChange:L=>g({artist:L.target.value}),placeholder:"Artist",onKeyDown:E,disabled:y,"aria-label":"Artist",className:"gpi-input",style:Cr}),s.jsx("input",{"data-role":"field",type:"text",value:l,onChange:L=>g({title:L.target.value}),placeholder:"Title",onKeyDown:E,disabled:y,"aria-label":"Title",className:"gpi-input",style:Cr}),f&&s.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:L=>g({version:L.target.value||void 0}),placeholder:R("playlistItem.versionOptional"),onKeyDown:E,disabled:y,"aria-label":"Version",className:"gpi-input",style:Cr}),s.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":R("playlistItem.availableSources"),children:W.map(U)}),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":R("playlistItem.dragReorder"),title:R("playlistItem.dragReorder"),style:Nn,children:"≡"}),s.jsx("button",{type:"button",onClick:v,disabled:!k||y,"aria-label":R("playlistItem.moveUp"),title:R("playlistItem.moveUp"),style:Nn,children:"↑"}),s.jsx("button",{type:"button",onClick:x,disabled:!M||y,"aria-label":R("playlistItem.moveDown"),title:R("playlistItem.moveDown"),style:Nn,children:"↓"}),s.jsx("button",{type:"button",onClick:p,disabled:y,"aria-label":R("common.delete"),title:R("common.delete"),style:{...Nn,color:"var(--danger, #b91c1c)"},children:"✕"})]})]})},Hu={width:48,border:"1px solid #e5e7eb",borderRadius:6,padding:"8px 6px",fontSize:14,textAlign:"center"},Cr={width:"100%",border:"1px solid #e5e7eb",borderRadius:6,padding:"8px 10px",fontSize:14},Nn={border:"1px solid #d1d5db",background:"var(--bg, #fff)",padding:"6px 8px",borderRadius:6,cursor:"pointer"},_r=()=>Math.random().toString(36).slice(2,10),In=e=>(e??[]).map(t=>({id:_r(),...t})),Ku=e=>e.map(({id:t,...n})=>n),Yu=null,Zu=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}},Wo=({value:e,defaultValue:t,onChange:n,allowVersion:r=!0,maxItems:a,addButtonLabel:o,emptyState:i=Yu,readOnly:l=!1,autoFocusNewItem:c=!0,enableBulkPaste:d=!0})=>{const{t:h}=xe(),f=e!==void 0,[m,g]=u.useState(()=>In(e||t)),[p,v]=u.useState(""),x=u.useRef(null),[b,w]=u.useState(null);u.useEffect(()=>{f&&g(In(e))},[f,JSON.stringify(e)]);const y=u.useCallback(H=>{n==null||n(Ku(H))},[n]),k=u.useCallback(H=>{if(f){const te=H(In(e));y(te)}else g(te=>{const B=H(te);return y(B),B})},[y,f,e]),M=a?m.length<a:!0,N=u.useCallback(()=>{!M||l||k(H=>[...H,{id:_r(),artist:"",title:"",version:void 0}])},[M,l,k]),R=u.useCallback((H,te)=>{k(B=>B.map(z=>z.id===H?{...z,...te}:z))},[k]),_=u.useCallback(H=>{l||k(te=>te.filter(B=>B.id!==H))},[l,k]),E=u.useCallback((H,te)=>{k(B=>{const z=B.findIndex(T=>T.id===H);if(z<0)return B;const S=z+te;if(S<0||S>=B.length)return B;const P=[...B],[$]=P.splice(z,1);return P.splice(S,0,$),P})},[k]),U=u.useCallback((H,te)=>{k(B=>{const z=B.findIndex(T=>T.id===H);if(z<0)return B;const S=Math.max(0,Math.min(B.length-1,te-1));if(z===S)return B;const P=[...B],[$]=P.splice(z,1);return P.splice(S,0,$),P})},[k]),W=H=>te=>{l||(x.current=H,te.dataTransfer.effectAllowed="move",te.dataTransfer.setData("text/plain",H))},j=H=>te=>{l||(te.preventDefault(),te.dataTransfer.dropEffect="move",w(H))},L=H=>()=>w(te=>te===H?null:te),I=H=>te=>{if(l)return;te.preventDefault();const B=x.current??te.dataTransfer.getData("text/plain");w(null),x.current=null,!(!B||B===H)&&k(z=>{const S=z.findIndex(C=>C.id===B),P=z.findIndex(C=>C.id===H);if(S<0||P<0||S===P)return z;const $=[...z],[T]=$.splice(S,1);return $.splice(P,0,T),$})},q=()=>{x.current=null,w(null)},Y=u.useCallback(()=>{if(!d||l)return;const te=p.split(/\r?\n/).map(B=>B.trim()).filter(Boolean).map(Zu).filter(B=>!!B);te.length!==0&&(k(B=>{const z=(a??1/0)-B.length,S=te.slice(0,Math.max(0,z)).map(P=>({id:_r(),...P}));return[...B,...S]}),v(""))},[d,l,p,a,k]);u.useEffect(()=>{},[m.length,c]);const O=i??s.jsx("div",{style:{padding:"0.75rem",color:"#777",fontStyle:"italic"},children:h("genericPlaylist.emptyState","No songs. Add the first one below.")}),Z=o??h("genericPlaylist.addSong","Add song");return s.jsxs("div",{className:"gp-container",style:{border:"1px solid #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:h("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 #d1d5db",background:"#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 B=b===H.id;return s.jsx("li",{draggable:!l,onDragStart:W(H.id),onDragOver:j(H.id),onDragLeave:L(H.id),onDrop:I(H.id),onDragEnd:q,style:{border:B?"2px dashed #6366f1":"2px solid transparent",borderRadius:8,padding:B?4:0},children:s.jsx(pa,{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:W(H.id)}},callbacks:{onChange:z=>R(H.id,z),onRemove:()=>_(H.id),onMoveUp:()=>E(H.id,-1),onMoveDown:()=>E(H.id,1),onChangeLp:z=>U(H.id,z)},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:"#374151"},children:h("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:h("genericPlaylist.bulkPastePlaceholder",`Paste lines in format:
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 z=G.getContext("2d");if(z){z.clearRect(0,0,600,100),z.strokeStyle="var(--nice-info, #0ff)",z.beginPath();for(let S=0;S<c.length;S+=Math.ceil(c.length/600)){const P=S/c.length*600,$=50-c[S]*48;S===0?z.moveTo(P,$):z.lineTo(P,$)}if(z.stroke(),x.length>0){z.strokeStyle="var(--nice-warning, #ff0)",z.beginPath();for(let S=0;S<x.length;S++){const P=S/x.length*600,$=100-x[S]*90;S===0?z.moveTo(P,$):z.lineTo(P,$)}z.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&&w.length===0&&!N&&s.jsx("div",{style:{marginTop:16,color:"var(--nice-text-muted, #aaa)"},children:s.jsx("i",{children:o("audioPitch.noNotesDetected")})}),h&&Object.keys(m).length>0&&s.jsxs("div",{style:{marginTop:16},children:[s.jsx("h4",{children:o("audioPitch.algorithmComparison")}),Object.entries(m).map(([G,z])=>s.jsxs("div",{style:{marginBottom:12},children:[s.jsx("b",{children:G}),": ",o("audioPitch.detectedSegments")," ",z.length,s.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-border, #ddd)",padding:8,borderRadius:4,marginTop:8},children:z.map(S=>`: ${Math.round(S.start*10)} ${Math.round(S.duration*10)} ${S.pitch} [${S.freq.toFixed(1)} Hz]`).join(`
47
+ `)})]},G))]})]})}function Ee(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 qd=[Ee("Belagak","BelagakRegular-dr1zE.otf"),Ee("Big Scratch Brush","BigScratchBrush-PVY9g.ttf"),Ee("Gerhaus","Gerhaus-PK69E.ttf"),Ee("Gerhaus Italic","GerhausItalic-d96l7.ttf"),Ee("Handone Medium","HandoneMedium-nAevO.otf"),Ee("Handson Bold","HandsonBold-9MnrL.otf"),Ee("Kineks Round Bold","KineksRoundBold-7OR34.ttf"),Ee("Kineks Round Light","KineksRoundLight-m2r35.ttf"),Ee("Kineks Round Medium","KineksRoundMedium-drejZ.ttf"),Ee("Kineks Round","KineksRoundRegular-PVRl7.ttf"),Ee("Kineks Round SemiBold","KineksRoundSemiBold-LVWG3.ttf"),Ee("Lemon Jelly","LemonJellyPersonalUse-dEqR.ttf"),Ee("Lemon Milk Bold","LemonMilkBold-gx2B3.otf"),Ee("Lemon Milk Bold Italic","LemonMilkBoldItalic-PKZ3P.otf"),Ee("Lemon Milk Light","LemonMilkLight-owxMq.otf"),Ee("Lemon Milk Light Italic","LemonMilkLightItalic-7BjPE.otf"),Ee("Lemon Milk Medium","LemonMilkMedium-mLZYV.otf"),Ee("Lemon Milk Medium Italic","LemonMilkMediumItalic-d95nl.otf"),Ee("Lemon Milk","LemonMilkRegular-X3XE2.otf"),Ee("Lemon Milk Italic","LemonMilkRegularItalic-L3AEy.otf"),Ee("Pemage","PemageRegular-YqrdO.otf"),Ee("Rosmatika","RosmatikaRegular-BWA45.ttf"),Ee("Scabber","Scabber-q2Mn0.ttf"),Ee("Stylish Calligraphy","StylishCalligraphyDemo-XPZZ.ttf"),Ee("Super Adorable","SuperAdorable-MAvyp.ttf"),Ee("Super Chiby","SuperChiby-BL62V.ttf"),Ee("Super Joyful","SuperJoyful-lxwPq.ttf"),Ee("Super Kindly","SuperKindly-drE8E.ttf"),Ee("Super Meatball","SuperMeatball-Yq1Gy.ttf")],da="nice2dev-karaoke-display",Hd=[{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"},...qd.map(e=>({value:e.family,label:e.family}))],Ro=[{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)"}],Jt={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 Qa=!1;function $o(){try{const e=localStorage.getItem(da);if(e){const t=JSON.parse(e);return{...Jt,...t}}}catch{}return{...Jt}}async function Kd(e){if(Qa||(Qa=!0,!e))return;const t=await e();if(t)try{const n=JSON.parse(t),r={...Jt,...n};localStorage.setItem(da,JSON.stringify(r))}catch{}}function Yd(e){const t=JSON.stringify(e);localStorage.setItem(da,t),ua(e)}function To(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=Ro.find(n=>n.id===e.presetId);return t?{sungGradient:t.sungGradient,goldGradient:t.goldGradient,glowColor:t.glowColor}:{sungGradient:Jt.customSungGradient,goldGradient:Jt.customGoldGradient,glowColor:Jt.customGlowColor}}function ua(e){const{sungGradient:t,goldGradient:n,glowColor:r}=To(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 Zd(){const e=$o();ua(e)}const yn=["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)"],Po={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 Or(e){return 440*Math.pow(2,(e-69)/12)}function Eo(e,t){const n=Po[t],r=n.keys.length,a=[];for(const d of e)for(const h of d)a.includes(h.pitch)||a.push(h.pitch);if(a.sort((d,h)=>d-h),a.length===0)return n.keys.map((d,h)=>({index:h,key:d,gamepadButton:n.buttons[h],label:n.labels[h],minPitch:-999,maxPitch:999,color:yn[h%yn.length]}));const o=a[0],l=a[a.length-1]-o+1,c=[];for(let d=0;d<r;d++){const h=o+Math.floor(l*d/r),f=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:h,maxPitch:d===r-1?999:f,color:yn[d%yn.length]})}return c}function Ao(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 No(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:Ao(i.pitch,t),lineIndex:a,noteIndex:o})}return r.sort((a,o)=>a.note.startTime-o.note.startTime),r}class Xd{constructor(t){this.lanes=[],this.events=[],this.raf=null,this.keysDown=new Set,this.gamepadButtonsDown=new Set,this.running=!1,this.getCurrentTime=()=>0,this.lastFeedbackTime=0,this.lastActiveNote=null,this.preWindow=.15,this.postWindow=.15,this.loop=()=>{var c,d,h,f,m,g,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,(f=(h=this.config).onCurrentNote)==null||f.call(h,i)),o.some(Boolean)&&i){const x=i.lane,b=o.indexOf(!0);if(o[x]){const w=Or(i.note.pitch);this.config.onPitch(w),a-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=a,(g=(m=this.config).onHitFeedback)==null||g.call(m,{type:"perfect",lane:x,time:a}))}else if(b>=0){const y=Math.abs(b-x)*3,k=Or(i.note.pitch+y);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=ea(t.noteLines,t.bpm),r=(t.gap??0)/1e3;switch(this.lanes=Eo(n,t.difficulty),this.events=No(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 Qd(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 Jd=({index:e,style:t,data:n})=>{const{lines:r,notes:a,currentIndex:o,animationConfig:i}=n,l=r[e]??"",c=a.findIndex(w=>w.lineIndex===e),d=c>=0&&c===o,h=(i==null?void 0:i.enabled)??!0,f=(i==null?void 0:i.durationMs)??300,m=(i==null?void 0:i.translateX)??8,g=(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:h?`transform ${f}ms ${p}, opacity ${f}ms ${p}`:"none",transform:d?`translateX(${m}px) scale(${g})`:"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})})})},Io=({ultrastarText:e,audioUrl:t,audioRef:n,animationConfig:r})=>{const{t:a}=xe(),o=u.useRef(null),i=n??o,[l,c]=u.useState(!1),d=u.useMemo(()=>Qd(e),[e]),h=u.useRef(null),f=u.useRef(null),m=u.useRef(null),g=u.useRef(0),p=u.useRef(0),[v,x]=u.useState(-1),b=u.useMemo(()=>(e||"").split(/\r?\n/),[e]),w=28,y=b.length*w,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 R=r??null,_=R&&typeof R.scrollSmooth=="number"?R.scrollSmooth:.18;let E=performance.now();const U=()=>{var G,z;const W=performance.now(),j=Math.max(0,Math.min(.2,(W-E)/1e3));E=W;const L=M.currentTime||0;g.current=L;let I=-1;for(let S=0;S<d.length;S++){const P=d[S];if(L>=P.start&&L<P.start+Math.max(.001,P.duration)){I=S;break}}I!==N&&(N=I,x(I));let q=0;if(N>=0){const S=((G=d[N])==null?void 0:G.lineIndex)??0,P=((z=f.current)==null?void 0:z.clientHeight)??220;q=S*w-P/2+w/2;const $=Math.max(0,y-P);(isNaN(q)||!isFinite(q))&&(q=0),q=Math.max(0,Math.min(q,$))}const Y=1-Math.pow(Math.max(0,1-_),Math.min(4,j*60)),te=(((r==null?void 0:r.scrollEasing)||"easeOutCubic")==="linear"?S=>S:S=>1-Math.pow(1-S,3))(Y);p.current=p.current+(q-p.current)*te;try{const S=f.current;S&&typeof S.scrollTop=="number"&&(S.scrollTop=Math.round(p.current))}catch{}m.current=requestAnimationFrame(U)};return m.current=requestAnimationFrame(U),()=>{m.current&&cancelAnimationFrame(m.current)}},[i,d,y,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:[(g.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(Ll.FixedSizeList,{height:220,width:"100%",itemCount:b.length,itemSize:w,ref:h,outerRef:f,itemData:k,children:Jd}):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 eu(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 Lo({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:h,notes:f}=eu(e);i.current=h,l.current=f;const m=c.current;m&&"rebuildTexts"in m&&typeof m.rebuildTexts=="function"&&m.rebuildTexts()},[e]),u.useEffect(()=>{let h=!0;return(async()=>{var N;if(!h||!a.current)return;const f=await import("phaser"),m="default"in f?f.default:f;if(!a.current||!h)return;const g=i,p=l,v=c,x=n,b=r,w=d;class y 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=_:w.current?(this.audioEl=document.createElement("audio"),this.audioEl.src=w.current,this.audioEl.preload="metadata",this.audioEl.style.display="none",document.body.appendChild(this.audioEl)):this.audioEl=null}}rebuildTexts(){for(const j of this.texts)j.destroy();this.texts=[];const _={font:"18px monospace",color:"var(--nice-bg, #fff)"},E=22;let U=20;const W=g.current;for(let j=0;j<W.length;j++){const L=this.add.text(10,U,W[j]||" ",_).setOrigin(0,0);this.texts.push(L),U+=E}}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 U=0;U<this.texts.length;U++)this.texts[U].setStyle({backgroundColor:void 0,color:"var(--nice-bg, #fff)"});const E=p.current;for(const U of E)if(_>=U.start&&_<U.start+Math.max(.001,U.duration)){const W=this.texts[U.lineIndex];W&&W.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:[y]};o.current=new m.Game(M)})(),()=>{h=!1,c.current=null;try{const f=o.current;f&&typeof f.destroy=="function"&&f.destroy(!0)}catch{}}},[]),s.jsx("div",{ref:a,style:{width:"100%",height:340}})}const tu=et.scoped("GenericPlayer"),nu=e=>/youtu(\.be|be\.com)/i.test(e),Fo=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),ru=e=>!!e&&/\.(mp3|aac|m4a|flac|wav|ogg)(\?.*)?$/i.test(e),au=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&&nu(i.url)))??null;if(n)return n;const r=t("hls")||e.sources.find(i=>i.url&&Fo(i.url))||null;if(r)return r;const a=t("audio")||e.sources.find(i=>i.url&&ru(i.url))||null;return a||(e.sources[0]??null)},sr=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")}`},su=[.25,.5,.75,1,1.25,1.5,1.75,2],Do=({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:h=3,progressBarPosition:f="inline",loop:m=!1,onEnded:g,enableKeyboardShortcuts:p=!0,shuffle:v=!1,repeatMode:x="none",playbackSpeed:b=1,abLoop:w=null,onRepeatModeChange:y,onShuffleChange:k,onSpeedChange:M,sleepTimer:N=0,onSleepTimerExpired:R})=>{const{t:_}=xe(),[E,U]=u.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),W=e[E],j=u.useMemo(()=>au(W),[W]),[L,I]=u.useState(!1),[q,Y]=u.useState(0),[O,Z]=u.useState(0),[H,te]=u.useState(.9),[G,z]=u.useState(null),[S,P]=u.useState(null),$=u.useRef(null),[T,C]=u.useState(v),[A,D]=u.useState(x),[V,Q]=u.useState(b),[J,ae]=u.useState(w),[re,ee]=u.useState([]),[F,K]=u.useState(N>0?N*60:null),se=u.useRef(null),[ce,fe]=u.useState(()=>As()),X=u.useRef(null),ue=u.useRef(null),ye=u.useRef(null),je=u.useRef(null);u.useEffect(()=>{if(T&&e.length>0){const le=e.map((de,Ce)=>Ce);for(let de=le.length-1;de>0;de--){const Ce=Math.floor(Math.random()*(de+1));[le[de],le[Ce]]=[le[Ce],le[de]]}ee(le)}},[T,e.length]),u.useEffect(()=>(se.current&&(window.clearInterval(se.current),se.current=null),N>0&&L&&(K(N*60),se.current=window.setInterval(()=>{K(le=>!le||le<=1?(se.current&&window.clearInterval(se.current),se.current=null,R==null||R(),null):le-1)},1e3)),()=>{se.current&&window.clearInterval(se.current)}),[N,L]);const Fe=u.useCallback(le=>{const de=Math.min(Math.max(0,le),Math.max(0,e.length-1));U(de),o==null||o(de)},[e.length,o]),Re=u.useCallback(()=>{if(T&&re.length>0){const de=re.indexOf(E)+1;return de<re.length?re[de]:A==="all"?re[0]:-1}return E<e.length-1?E+1:A==="all"?0:-1},[E,e.length,T,re,A]),Se=u.useCallback(()=>{if(T&&re.length>0){const le=re.indexOf(E);return le>0?re[le-1]:A==="all"?re[re.length-1]:-1}return E>0?E-1:A==="all"?e.length-1:-1},[E,e.length,T,re,A]),ne=u.useCallback(()=>{const le=Re();le>=0&&Fe(le)},[Re,Fe]),oe=u.useCallback(async()=>{var le,de;await Et(),fe(!0),(j==null?void 0:j.kind)==="youtube"?(le=X.current)==null||le.playVideo():(de=ue.current)==null||de.play(),I(!0),i==null||i(!0)},[j,i]),Ne=u.useCallback(()=>{var le,de;(j==null?void 0:j.kind)==="youtube"?(le=X.current)==null||le.pauseVideo():(de=ue.current)==null||de.pause(),I(!1),i==null||i(!1)},[j,i]),De=u.useCallback(()=>L?Ne():oe(),[L,oe,Ne]),Pe=u.useCallback(le=>{var ie;const de=(W==null?void 0:W.startOffset)??0,Ce=le+de;(j==null?void 0:j.kind)==="youtube"?(ie=X.current)==null||ie.seekTo(Ce,!0):ue.current&&(ue.current.currentTime=Ce);const xt=Math.max(0,le);Z(xt),l==null||l(xt)},[j,l]),tt=u.useCallback(()=>{if(O>3){Pe(0);return}const le=Se();le>=0&&Fe(le)},[Se,Fe,O,Pe]),we=u.useCallback(le=>{var de,Ce;te(le),z(null),(j==null?void 0:j.kind)==="youtube"?(Ce=(de=X.current)==null?void 0:de.setVolume)==null||Ce.call(de,Math.round(le*100)):ue.current&&(ue.current.volume=le)},[j]),dt=u.useCallback(()=>{G!==null?we(G):(z(H),we(0))},[H,G,we]),Rn=u.useCallback(le=>{var de,Ce;Q(le),ue.current&&(ue.current.playbackRate=le),(j==null?void 0:j.kind)==="youtube"&&((Ce=(de=X.current)==null?void 0:de.setPlaybackRate)==null||Ce.call(de,le)),M==null||M(le)},[j,M]),Xe=u.useCallback(()=>{const le=["none","all","one"],de=le[(le.indexOf(A)+1)%le.length];D(de),y==null||y(de)},[A,y]),Be=u.useCallback(()=>{const le=!T;C(le),k==null||k(le)},[T,k]),It=u.useCallback(le=>{ae(le)},[]);u.useImperativeHandle(c,()=>({play:oe,pause:Ne,toggle:De,seekTo:Pe,setVolume:we,setSpeed:Rn,setRepeatMode:le=>{D(le),y==null||y(le)},toggleShuffle:Be,setABLoop:It,getUnderlyingPlayer:()=>(j==null?void 0:j.kind)==="youtube"?X.current:(j==null?void 0:j.kind)==="hls"||(j==null?void 0:j.kind)==="audio"?ue.current:null}),[oe,Ne,De,Pe,we,Rn,Be,It,j==null?void 0:j.kind]),u.useEffect(()=>{const le=window.setInterval(()=>{let de=0,Ce=0;(j==null?void 0:j.kind)==="youtube"&&X.current?(de=X.current.getCurrentTime()||0,Ce=X.current.getDuration()||0):ue.current&&(de=ue.current.currentTime||0,Ce=ue.current.duration||0);const xt=(W==null?void 0:W.startOffset)??0,ie=Math.max(0,de-xt);Z(ie),Y(Ce),l==null||l(ie),J&&ie>=J.b&&Pe(J.a)},250);return()=>window.clearInterval(le)},[j==null?void 0:j.kind,l,J]),u.useEffect(()=>()=>{$.current&&(window.clearInterval($.current),$.current=null)},[]),u.useEffect(()=>{if(ye.current){try{ye.current.destroy()}catch{}ye.current=null}if(ue.current&&(ue.current.volume=H,ue.current.crossOrigin=j!=null&&j.withCredentials?"use-credentials":"anonymous"),(j==null?void 0:j.kind)==="hls"&&Fo(j.url)){const le=ue.current;if(!le)return;const de=()=>{le.src=j.url,le.load();const Ce=(W==null?void 0:W.startOffset)??0;try{Ce&&!isNaN(Ce)&&(le.currentTime=Ce)}catch{}n&&le.play().catch(()=>{})};le.canPlayType("application/vnd.apple.mpegurl")?de():(async()=>{var Ce;try{const ie=(await import("hls.js")).default;if((Ce=ie==null?void 0:ie.isSupported)!=null&&Ce.call(ie)){const he=new ie({xhrSetup:Oe=>{if(j!=null&&j.withCredentials&&(Oe.withCredentials=!0),j!=null&&j.headers)for(const[ve,me]of Object.entries(j.headers))try{Oe.setRequestHeader(ve,me)}catch{}}});ye.current=he,he.loadSource(j.url),he.attachMedia(le),he.on(ie.Events.MANIFEST_PARSED,()=>{n&&le.play().catch(()=>{})})}else de()}catch(xt){tu.debug("HLS.js setup failed, falling back to native playback",xt),de()}})()}else if((j==null?void 0:j.kind)==="audio"&&j.url&&ue.current){const le=ue.current;le.src=j.url,le.load();const de=(W==null?void 0:W.startOffset)??0;try{de&&!isNaN(de)&&(le.currentTime=de)}catch{}n&&le.play().catch(()=>{})}$.current&&(window.clearInterval($.current),$.current=null),P(null),Z(0),Y(0),n&&(j==null?void 0:j.kind)==="youtube"&&r>0?(P(r),$.current=window.setInterval(()=>{P(le=>{var de;if(!le)return null;if(le<=1){$.current&&(window.clearInterval($.current),$.current=null);try{(de=X.current)==null||de.playVideo()}catch{}return I(!0),i==null||i(!0),null}return le-1})},1e3)):I(!!n)},[j==null?void 0:j.url,j==null?void 0:j.kind,j==null?void 0:j.withCredentials,JSON.stringify(j==null?void 0:j.headers),n,H]);const yt=u.useCallback(()=>{if(A==="one"){Pe(0),oe();return}const le=Re();le>=0?Fe(le):(I(!1),i==null||i(!1),Pe(0),g==null||g())},[A,Re,Fe,i,Pe,g,oe]);u.useEffect(()=>{if(!p)return;const le=de=>{const Ce=de.target;if(!(Ce.tagName==="INPUT"||Ce.tagName==="TEXTAREA"||Ce.isContentEditable))switch(de.key){case" ":de.preventDefault(),De();break;case"ArrowRight":de.preventDefault(),Pe(Math.min(O+5,q));break;case"ArrowLeft":de.preventDefault(),Pe(Math.max(0,O-5));break;case"ArrowUp":de.preventDefault(),we(Math.min(1,H+.05));break;case"ArrowDown":de.preventDefault(),we(Math.max(0,H-.05));break;case"m":case"M":dt();break;case"n":case"N":ne();break;case"p":case"P":tt();break;case"r":case"R":Xe();break;case"s":case"S":Be();break}};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[p,De,Pe,O,q,we,H,dt,ne,tt,Xe,Be]);const mr=(j==null?void 0:j.kind)==="youtube"||d==="full"||d==="nobuttons",ut=h>0?e.slice(E+1,E+1+h):[];return s.jsxs("div",{ref:je,className:"gp-player",style:{display:"grid",gap:12},tabIndex:-1,children:[n&&!ce&&s.jsx("div",{className:"gp-audio-activation",onClick:()=>{fe(!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"})}),mr&&s.jsxs("div",{className:"gp-stage",style:{width:"100%",height:a,background:(j==null?void 0:j.kind)==="youtube"?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(j==null?void 0:j.kind)==="youtube"&&s.jsx(Yr,{videoId:j.videoId??uu(j.url),onReady:le=>{X.current=le.target,we(H);const de=(W==null?void 0:W.startOffset)??0;try{de&&le.target.seekTo(de,!0)}catch{}if(d==="nobuttons"){try{le.target.playVideo()}catch{}I(!0)}},onEnd:yt,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%"}}),S!==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:S})}),d==="nobuttons"&&s.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"auto",zIndex:100,cursor:"default"}}),((j==null?void 0:j.kind)==="audio"||(j==null?void 0:j.kind)==="hls")&&s.jsxs(s.Fragment,{children:[d==="full"&&s.jsx("div",{style:{textAlign:"center",color:"var(--text, #e2e8f0)"},children:W!=null&&W.coverUrl?s.jsx("img",{alt:"cover",src:W.coverUrl,style:{height:a-24,objectFit:"contain"}}):s.jsxs("div",{style:{opacity:.8},children:[s.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[W==null?void 0:W.artist," � ",W==null?void 0:W.title]}),s.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-dim, #94a3b8)"},children:(j==null?void 0:j.label)??`${(j==null?void 0:j.codec)??""} ${(j==null?void 0:j.quality)??""}`.trim()})]})}),s.jsx("audio",{ref:ue,onEnded:yt,onLoadedMetadata:()=>{const le=ue.current;le&&Y(le.duration||0)},crossOrigin:j!=null&&j.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:(W==null?void 0:W.title)??"�"}),s.jsx("div",{style:{color:"var(--text-dim, #64748b)",fontSize:13},children:(W==null?void 0:W.artist)??"�"})]})}),d==="full"&&s.jsxs(s.Fragment,{children:[s.jsx(Oo,{currentTime:O,duration:q}),s.jsx(ou,{isPlaying:L,index:E,count:e.length,currentTime:O,duration:q,volume:H,onPrev:tt,onNext:ne,onToggle:De,onSeek:Pe,onVolume:we}),s.jsx(du,{shuffleOn:T,repeatMode:A,speed:V,abLoop:J,currentTime:O,sleepRemaining:F,onToggleShuffle:Be,onCycleRepeat:Xe,onSpeedChange:Rn,onSetABLoop:It,onMuteToggle:dt,isMuted:G!==null})]}),d==="progressOnly"&&s.jsx("div",{style:f==="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(iu,{currentTime:O,duration:q,onSeek:Pe})}),(d==="minimal"||d==="compact")&&s.jsx(lu,{isPlaying:L,canPrev:E>0,canNext:E<e.length-1,onPrev:tt,onNext:ne,onToggle:De}),d==="compact"&&ut.length>0&&s.jsx(cu,{items:ut,onSelect:le=>Fe(E+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,de)=>s.jsxs("button",{onClick:()=>Fe(de),style:{textAlign:"left",border:"1px solid var(--border-light, #e5e7eb)",borderRadius:8,padding:"8px 10px",background:de===E?"var(--active-bg, #eef2ff)":"var(--bg, #fff)",cursor:"pointer"},title:le.sources.map(Ce=>Ce.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))})]})},at={border:"1px solid var(--border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--bg, #fff)",cursor:"pointer"},Oo=({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:[sr(e)," / ",sr(t)]})]}),ou=({isPlaying:e,index:t,count:n,currentTime:r,duration:a,volume:o,onPrev:i,onNext:l,onToggle:c,onSeek:d,onVolume:h})=>{const{t:f}=xe();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:f("player.previousTrack"),"aria-label":f("player.previousTrack"),style:at,children:"?"}),s.jsx("button",{onClick:c,title:f(e?"player.pause":"player.play"),"aria-label":f(e?"player.pause":"player.play"),style:at,children:"?"}),s.jsx("button",{onClick:l,disabled:t>=n-1,title:f("player.nextTrack"),"aria-label":f("player.nextTrack"),style:at,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=>h(parseFloat(m.target.value)),"aria-label":"Volume"})]})]})},iu=({currentTime:e,duration:t,onSeek:n})=>s.jsxs(s.Fragment,{children:[s.jsx(Oo,{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"})]}),lu=({isPlaying:e,canPrev:t,canNext:n,onPrev:r,onNext:a,onToggle:o})=>{const{t:i}=xe();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:at,children:"?"}),s.jsx("button",{onClick:o,title:i(e?"player.pause":"player.play"),"aria-label":i(e?"player.pause":"player.play"),style:at,children:"?"}),s.jsx("button",{onClick:a,disabled:!n,title:i("player.nextTrack"),"aria-label":i("player.nextTrack"),style:at,children:"?"})]})},cu=({items:e,onSelect:t})=>{const{t:n}=xe();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))})]})},du=({shuffleOn:e,repeatMode:t,speed:n,abLoop:r,currentTime:a,sleepRemaining:o,onToggleShuffle:i,onCycleRepeat:l,onSpeedChange:c,onSetABLoop:d,onMuteToggle:h,isMuted:f})=>{const{t:m}=xe(),g={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:{...at,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:{...at,opacity:t==="none"?.4:1},children:g[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:{...at,minWidth:56,fontSize:12},children:su.map(v=>s.jsxs("option",{value:v,children:[v,"x"]},v))}),s.jsx("button",{onClick:h,title:m("player.mute","Mute"),"aria-label":m("player.mute","Mute"),style:{...at,opacity:f?1:.6},children:f?"🔇":"🔊"}),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: ",sr(r.a)," — B: ",sr(r.b)]}),s.jsx("button",{onClick:()=>d(null),title:m("player.clearLoop","Clear loop"),style:{...at,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:{...at,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 uu(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 hu=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),Ja=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")}`},wr={border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg, #fff)",cursor:"pointer"},fu=({isPlaying:e,index:t,count:n,currentTime:r,duration:a,volume:o,onPrev:i,onNext:l,onToggle:c,onSeek:d,onVolume:h})=>{const{t:f}=xe();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:[Ja(r)," / ",Ja(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:f("playerControls.prev","Prev"),"aria-label":f("playerControls.previousTrack","Previous track"),style:wr,children:"⏮"}),s.jsx("button",{onClick:c,title:e?f("playerControls.pause","Pause"):f("playerControls.play","Play"),"aria-label":e?f("playerControls.pause","Pause"):f("playerControls.play","Play"),style:wr,children:e?"⏸":"▶"}),s.jsx("button",{onClick:l,disabled:t>=n-1,title:f("playerControls.next","Next"),"aria-label":f("playerControls.nextTrack","Next track"),style:wr,children:"⏭"})]}),s.jsx("input",{type:"range",min:0,max:Math.max(1,a),step:.1,value:r,"aria-label":f("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":f("playerControls.volume","Volume"),onChange:m=>h(parseFloat(m.target.value))})]})]})]})},_o=u.memo(fu);function pu(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,h=d*(n-6),f=c*l,m=n-h,g=c/48*240+a;e.fillStyle=`hsl(${g%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(f+1,m,l-2,h)}}function mu(e,t,n,r,a,o){if(!o.current){const f=[];for(let g=0;g<24;g++)f.push({ang:g/24*Math.PI*2,phase:Math.random()*Math.PI*2,baseR:Math.min(t,n)*.22+Math.random()*30});o.current={nodes:f}}const i=o.current,l=t/2,c=n/2,d=26+r*80,h=[];for(const f of i.nodes){f.phase+=.02+r*.06;const m=f.baseR+Math.sin(f.phase)*d,g=l+Math.cos(f.ang)*m,p=c+Math.sin(f.ang)*m;h.push([g,p])}e.fillStyle=`hsla(${a}, 70%, 55%, .22)`,e.strokeStyle=`hsla(${(a+40)%360}, 90%, 65%, .9)`,e.lineWidth=2,e.beginPath();for(let f=0;f<h.length;f++){const[m,g]=h[f],[p,v]=h[(f+1)%h.length],x=(m+p)/2,b=(g+v)/2;f===0?e.moveTo(x,b):e.quadraticCurveTo(m,g,x,b)}e.closePath(),e.fill(),e.stroke()}function gu(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 yu="var(--nice-text-muted, #94a3b8)",bu=({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:yu},children:a??r??"—"})]})});function Ot(e,t){return e+Math.random()*(t-e)}function vu(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 f=0;f<d;f++){const m=(f+.5)/d*t,g=(r[Math.floor((f+1)/(d+1)*r.length)]||0)/255,p=n*.18+(.25+a*.6+g*.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+f*.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 h=Math.floor(1+a*6);for(let f=0;f<h;f++)l.embers.push({x:Ot(t*.25,t*.75),y:n-Ot(4,14),r:Ot(1,3),vx:Ot(-.15,.15),vy:-Ot(.6,1.8)-a*1.2,life:Ot(.8,1.6)});e.save(),e.globalCompositeOperation="lighter";for(let f=l.embers.length-1;f>=0;f--){const m=l.embers[f];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(f,1);continue}const g=e.createRadialGradient(m.x,m.y,0,m.x,m.y,m.r*3);g.addColorStop(0,`hsla(${(o+25)%360},100%,65%,.9)`),g.addColorStop(1,`hsla(${(o+25)%360},100%,65%,0)`),e.fillStyle=g,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 xu(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 h=0;h<c;h++){const f=(r[h*d]??0)/255,m=h/c*Math.PI*2,g=f*(Math.min(t,n)*.22)+6,p=o+Math.cos(m)*l,v=i+Math.sin(m)*l,x=o+Math.cos(m)*(l+g),b=i+Math.sin(m)*(l+g);e.strokeStyle=`hsl(${(a+h*3)%360}, 90%, ${40+f*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 Su(e,t,n,r,a){const l=t/14,c=n/8;for(let d=0;d<8;d++)for(let h=0;h<14;h++){const f=Math.min(r.length-1,d*14+h),m=r[f]/255,g=(a+h/14*210+d/8*90)%360,p=65+m*30,v=20+m*40,x=(1-m)*4;e.fillStyle=`hsl(${g}, ${p}%, ${v}%)`,e.fillRect(h*l+x,d*c+x,Math.max(1,l-2*x),Math.max(1,c-2*x))}}function wu(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 Cu(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 wu(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 h=Math.random()*Math.min(r,a)*.38+40;o.sprites.push({img:c(d),x:(Math.random()-.5)*h*.4,y:(Math.random()-.5)*h*.4,z:Math.random()*600+100,ang:Math.random()*Math.PI*2,spin:(Math.random()*.03+.01)*(Math.random()<.5?-1:1),vz:Math.random()*1.2+.2,size:Math.random()*.35+.65})}}}function ku(e,t,n,r,a,o,i,l){const c=o.current;if(!(c!=null&&c.ready))return;const d=t/2,h=n/2,f=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=f);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 g=[...c.sprites].sort((p,v)=>v.z-p.z);for(const p of g){const v=f/(f-p.z)*.6*p.size,x=d+p.x*v,b=h+p.y*v,w=64*v,y=64*v;e.save(),e.globalAlpha=.12+(1-p.z/f)*.2,e.fillStyle=`hsl(${(a+(1-p.z/f)*60)%360}, 90%, 60%)`,e.beginPath(),e.ellipse(x,b,w*.7,y*.7,0,0,Math.PI*2),e.fill(),e.restore(),p.img&&p.img.width?e.drawImage(p.img,x-w/2,b-y/2,w,y):(e.save(),e.fillStyle=`hsl(${(a+180)%360}, 40%, 55%)`,e.fillRect(x-w/2,b-y/2,w,y),e.restore())}}function sn(e,t){return e+Math.random()*(t-e)}function Mu(e,t,n,r,a,o){o.current||(o.current={blobs:Array.from({length:7},(d,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:(a+h*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,h=e.createRadialGradient(c.x,c.y,c.r*.2,c.x,c.y,c.r);h.addColorStop(0,`hsla(${d}, 95%, 70%, .8)`),h.addColorStop(1,`hsla(${(d+40)%360}, 90%, 30%, 0)`),e.fillStyle=h,e.shadowBlur=18,e.shadowColor=`hsl(${d}, 100%, 60%)`,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}e.restore(),e.strokeStyle="var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",e.lineWidth=2,e.strokeRect(1,1,t-2,n-2)}function ju(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 h of i.tris){h.a+=.002+r*.02*(h.dr>0?1:-1),h.r+=Math.sin(h.a*2)*(.3+r*1.4);const f=Math.max(40,Math.min(h.r,Math.min(t,n)*.48));e.save(),e.translate(c,d),e.rotate(h.a),e.strokeStyle=`hsla(${(a+f*.2)%360}, 90%, 60%, .9)`,e.lineWidth=2.5,e.beginPath(),e.moveTo(f,0);for(let m=1;m<3;m++){const g=m*Math.PI*2/3;e.lineTo(Math.cos(g)*f,Math.sin(g)*f)}e.closePath(),e.shadowBlur=12,e.shadowColor=e.strokeStyle,e.stroke(),e.restore()}}function Ru(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 h=0;h<c;h++){const f=(h+1)/(c+1),m=f*d;e.strokeStyle=`hsla(${(a+h*30)%360}, 70%, 45%, 0.35)`,e.lineWidth=1,e.beginPath(),e.arc(i,l,m,0,Math.PI*2),e.stroke();const g=Math.floor(r.length*f|0),p=(r[g]??0)/255,v=6+h*2;for(let x=0;x<v;x++){const b=o.current*(1+h*.15)+x/v*Math.PI*2,w=m+Math.sin(b*2)*6*p,y=i+Math.cos(b)*w,k=l+Math.sin(b)*w;e.fillStyle=`hsla(${(a+h*30+x*6)%360}, 90%, ${55+p*30}%, ${.6+p*.3})`,e.beginPath(),e.arc(y,k,2+p*4,0,Math.PI*2),e.fill()}}}function $u(e,t,n,r,a){const l=t/12,c=n/6;for(let d=0;d<6;d++)for(let h=0;h<12;h++){const f=(d*12+h)%r.length,m=r[f]/255,g=(a+h/12*180+d/6*90)%360,p=70+m*25,v=25+m*35;e.fillStyle=`hsl(${g}, ${p}%, ${v}%)`,e.fillRect(h*l,d*c,Math.ceil(l),Math.ceil(c))}}function Tu(e,t,n,r,a,o){const i=t/2,l=n/2,c=2+Math.floor(r*14);for(let h=0;h<c;h++){const f=Math.random()*Math.PI*2,m=.5+Math.random()*(2.5+r*4);o.current.push({x:i,y:l,vx:Math.cos(f)*m,vy:Math.sin(f)*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 h=d.length-1;h>=0;h--){const f=d[h];f.x+=f.vx,f.y+=f.vy,f.life+=1;const m=1-f.life/f.max;e.fillStyle=`hsla(${f.hue},85%,60%,${Math.max(0,m)})`,e.beginPath(),e.arc(f.x,f.y,2+m*3,0,Math.PI*2),e.fill(),(f.life>=f.max||f.x<-20||f.y<-20||f.x>t+20||f.y>n+20)&&d.splice(h,1)}d.length>1200&&d.splice(0,d.length-1200)}function Pu(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 h=18+Math.floor(a*50);for(let f=0;f<h;f++){const m=f/h*Math.PI*2+r*(.6+a*1.4),g=(Math.sin(r*2+f*1.7)+Math.cos(r*1.3+f*2.1))*.15,p=c*(.4+.55*Math.abs(Math.sin(r*1.2+f))),v=6;e.save(),e.translate(i,l),e.rotate(m+g),e.beginPath(),e.moveTo(0,0);for(let b=1;b<=v;b++){const w=p/v*b,y=(Math.sin(r*3+f*.8+b)*.6+Math.cos(r*2+f+b*.7))*(8+24*a),k=w,M=y;e.lineTo(M,k)}e.globalCompositeOperation="lighter";const x=(o+f*(240/h))%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 Eu(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,h=Math.min(t,n)*.48;for(let f=0;f<96;f++){const m=r[f*i]/255,g=f/96*Math.PI*2,p=d,v=d+m*(h-d),x=l+Math.cos(g)*p,b=c+Math.sin(g)*p,w=l+Math.cos(g)*v,y=c+Math.sin(g)*v;e.strokeStyle=`hsl(${f/96*360+a},85%,60%)`,e.lineWidth=3,e.beginPath(),e.moveTo(x,b),e.lineTo(w,y),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 Au(e,t,n,r,a,o){const i=t/2,l=n/2,c=Math.min(t,n)*.5,d=es(r,0,Math.floor(r.length*.1))/255,h=es(r,Math.floor(r.length*.6),r.length)/255;o.current+=.01+h*.03;const f=24;for(let m=0;m<f;m++){const g=o.current+m/f*Math.PI*2,p=(.35+d*.55)*c,v=i+Math.cos(g)*p,x=l+Math.sin(g)*p,b=e.createRadialGradient(i,l,0,i,l,p),w=m/f*360+a;b.addColorStop(0,`hsla(${w},85%,65%,0.0)`),b.addColorStop(1,`hsla(${w},85%,65%,0.9)`),e.strokeStyle=b,e.lineWidth=6+h*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 es(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 Nu(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,h=t/(d-1);e.beginPath();for(let g=0;g<d;g++){const p=(r[g]-128)/128,v=Math.sin(o*1.5+g*.03)*.12,x=g*h,b=i-l-(p+v)*c;g===0?e.moveTo(x,b):e.lineTo(x,b)}const f=e.createLinearGradient(0,0,0,i-l);f.addColorStop(0,"hsla(260,90%,75%,0.9)"),f.addColorStop(1,"hsla(220,85%,60%,0.4)"),e.strokeStyle=f,e.lineWidth=2,e.stroke(),e.beginPath();for(let g=0;g<d;g++){const p=(r[g]-128)/128,v=Math.cos(o*1.3+g*.035)*.12,x=g*h,b=i+l+(p+v)*c;g===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 Iu(e,t,n,r,a,o){const i=t/2,l=n/2,c=5,d=Math.min(t,n)*.12;for(let h=0;h<c;h++){const f=Math.floor(h/c*r.length),m=r[f]/255,g=d+h*d*.55+m*d*.5,p=(o+h*40)%360;e.lineWidth=3+m*6,e.strokeStyle=`hsla(${p},80%,60%,${.5+.5*a})`,e.beginPath(),e.arc(i,l,g,0,Math.PI*2),e.stroke()}}function Lu(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,h=d*(n-6),f=c*l,m=n-h,g=c/o*240+a;e.fillStyle=`hsl(${g%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(f+1,m,l-2,h)}}function Fu(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 Du(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 h of i.stars){h.z-=d,h.z<20&&(h.x=(Math.random()-.5)*t,h.y=(Math.random()-.5)*n,h.z=900,h.pz=h.z);const f=h.x/h.z*600,m=h.y/h.z*600,g=h.x/h.pz*600,p=h.y/h.pz*600;h.pz=h.z,e.strokeStyle=`hsla(${(a+200)%360}, 90%, 70%, 0.7)`,e.lineWidth=Math.max(1,(1-h.z/900)*2),e.beginPath(),e.moveTo(g,p),e.lineTo(f,m),e.stroke()}e.restore()}function Ou(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 _u=({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}),ha=({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(_u,{active:t===o,onClick:()=>n(o),title:`Tryb: ${o}`,children:o},o))})})};function zu(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 Gu=({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)})})},Bu="var(--player-bg, #0f172a)",fa=({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:h,imageUrls:f,imageCount:m=14})=>{const g=u.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette","radial","rays","particles","rings","grid","imageTornado","colorRipples","starfield","orbitals","eqcircle","triangles","blob","plasma","lavaLamp","cozyFire","rift"],[e,h]),p=u.useMemo(()=>{const te=g.includes(c)?c:g[0];try{const G=localStorage.getItem(d);if(!G)return te;const z=JSON.parse(G);return g.includes(z)?z:te}catch{return te}},[g,c,d]),[v,x]=zu(d,p),b=u.useRef(null),w=u.useRef(null),y=u.useRef(null),k=u.useRef(null),M=u.useRef(null),N=u.useRef(null),R=u.useRef(0),_=u.useRef(0),E=u.useRef([]),[U,W]=u.useState(0),j=u.useRef(null),L=u.useRef(null),I=u.useRef(null),q=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"||(w.current&&(cancelAnimationFrame(w.current),w.current=null),!H))return;Et();const te=tn(),G=t.current;if(!G)return;if(!y.current)try{y.current=te.createMediaElementSource(G)}catch{}if(!k.current){const C=te.createAnalyser();C.fftSize=2048,C.smoothingTimeConstant=.85,k.current=C;try{(T=y.current)==null||T.connect(C)}catch{}try{C.connect(te.destination)}catch{}}const z=k.current;M.current=new Uint8Array(z.frequencyBinCount),N.current=new Uint8Array(z.fftSize);const S=()=>{const C=b.current,A=Math.max(1,Math.floor(window.devicePixelRatio||1));C.width=Math.floor(C.clientWidth*A),C.height=Math.floor(C.clientHeight*A);const D=C.getContext("2d");D==null||D.setTransform(1,0,0,1,0,0),D==null||D.scale(A,A)};S();const P=()=>S();window.addEventListener("resize",P),Fu(I,220,b.current.width,b.current.height);const $=async()=>{const C=b.current;if(!C)return;const A=C.getContext("2d");if(!A)return;const D=Math.max(1,Math.floor(window.devicePixelRatio||1)),V=C.width/D,Q=C.height/D,J=performance.now()*.001,ae=v==="waveform"||v==="rift";ae?z.getByteTimeDomainData(N.current):z.getByteFrequencyData(M.current);let re=0;const ee=ae?N.current:M.current;for(let F=0;F<ee.length;F++){const K=ae?(ee[F]-128)/128:ee[F]/255;re+=K*K}if(re=Math.sqrt(re/ee.length),W(Math.min(1,re)),A.clearRect(0,0,V,Q),v==="spectrum")Lu(A,V,Q,M.current,R.current);else if(v==="bars")pu(A,V,Q,M.current,R.current);else if(v==="waveform")Ou(A,V,Q,N.current);else if(v==="palette"){const F=(R.current+re*120)%360;$u(A,V,Q,M.current,F)}else if(v==="radial")Eu(A,V,Q,M.current,R.current);else if(v==="rays")Au(A,V,Q,M.current,R.current,_);else if(v==="particles")Tu(A,V,Q,re,R.current,E);else if(v==="rings")Iu(A,V,Q,M.current,re,R.current);else if(v==="grid"){const F=(R.current+re*160)%360;Su(A,V,Q,M.current,F)}else if(v==="imageTornado"){const F=f!=null&&f.length?f:a?[a]:[];await Cu(j,F,m,V,Q);const K=(R.current+re*100)%360;ku(A,V,Q,re,K,j)}else if(v==="colorRipples"){const F=(R.current+re*120)%360;gu(A,V,Q,re,F,L)}else if(v==="starfield"){const F=(R.current+60)%360;Du(A,V,Q,re,F,I)}else if(v==="orbitals"){const F=(R.current+re*180)%360;Ru(A,V,Q,M.current,F,_)}else if(v==="eqcircle"){const F=(R.current+120)%360;xu(A,V,Q,M.current,F)}else if(v==="triangles"){const F=(R.current+40)%360;ju(A,V,Q,re,F,q)}else if(v==="blob"){const F=(R.current+90)%360;mu(A,V,Q,re,F,Y)}else if(v==="plasma"){const F=(R.current+re*200)%360;Pu(A,V,Q,J,re,F)}else if(v==="rift")Nu(A,V,Q,N.current,re,J);else if(v==="lavaLamp"){const F=(R.current+re*80)%360;Mu(A,V,Q,re,F,O)}else if(v==="cozyFire"){const F=(R.current+re*140)%360;vu(A,V,Q,M.current,re,F,Z)}R.current=(R.current+.4)%360,w.current=requestAnimationFrame($)};return w.current=requestAnimationFrame($),()=>{window.removeEventListener("resize",P),w.current&&cancelAnimationFrame(w.current)}},[H,e,t,v,f,m,a]),s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none",background:v==="cover"?"transparent":Bu},children:v==="cover"?s.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:s.jsx(bu,{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(ha,{modes:g,active:v,setActive:x,rows:2}),s.jsx(Gu,{vu:U,hide:e==="youtube"})]})]})},zo=({height:e,autoPlay:t,track:n,source:r,ytRef:a,audioRef:o,hlsRef:i,setVol:l,onEnd:c,volume:d,extractVideoId:h})=>{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"&&hu(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 w=new b({xhrSetup:y=>{if(r!=null&&r.withCredentials&&(y.withCredentials=!0),r!=null&&r.headers)for(const[k,M]of Object.entries(r.headers))y.setRequestHeader(k,String(M))}});i.current=w,w.loadSource(r.url),w.attachMedia(p),w.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 f=(r==null?void 0:r.kind)==="youtube",m=f?"video":"cover",g=`gp-stage:mode:${(r==null?void 0:r.kind)??"none"}`;return s.jsxs("div",{className:"gp-stage",style:{width:"100%",height:e,background:f?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(r==null?void 0:r.kind)==="youtube"&&s.jsx(Yr,{videoId:r.videoId??h(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(fa,{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:g},`vis-${g}`)]})};function Wu(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 Uu="var(--text-dim, #94a3b8)",Vu=({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}),Go=({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:h,overlayOnly:f=!1})=>{const m=u.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette"],[e,h]),g=u.useMemo(()=>{const j=m.includes(c)?c:m[0];try{const L=localStorage.getItem(d);if(!L)return j;const I=JSON.parse(L);return m.includes(I)?I:j}catch{return j}},[m,c,d]),[p,v]=Wu(d,g),x=u.useRef(null),[b,w]=u.useState(0),y=u.useRef(null),k=u.useRef(null),M=u.useRef(null),N=u.useRef(null),R=u.useRef(null),_=u.useRef(0),E=p==="spectrum"||p==="bars"||p==="waveform"||p==="palette";u.useEffect(()=>{var O;if(e==="youtube")return;if(!E){y.current&&cancelAnimationFrame(y.current);return}Et();const j=tn(),L=t.current;if(!L)return;if(!k.current)try{k.current=j.createMediaElementSource(L)}catch{}if(!M.current){const Z=j.createAnalyser();Z.fftSize=2048,Z.smoothingTimeConstant=.85,M.current=Z;try{(O=k.current)==null||O.connect(Z)}catch{}try{Z.connect(j.destination)}catch{}}const I=M.current;N.current=new Uint8Array(I.frequencyBinCount),R.current=new Uint8Array(I.fftSize);const q=()=>{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"?I.getByteTimeDomainData(R.current):I.getByteFrequencyData(N.current);let z=0;const S=p==="waveform"?R.current:N.current;for(let P=0;P<S.length;P++){const $=p==="waveform"?(S[P]-128)/128:S[P]/255;z+=$*$}if(z=Math.sqrt(z/S.length),w(Math.min(1,z)),p==="spectrum"||p==="bars"){const P=N.current,$=p==="bars"?48:Math.min(P.length,256),T=Math.floor(P.length/$),C=te/$;for(let A=0;A<$;A++){const D=P[A*T]/255,V=D*(G-6),Q=A*C,J=G-V,ae=A/$*240+_.current;H.fillStyle=`hsl(${ae%360}, 80%, ${Math.max(30,40+D*30)}%)`,H.fillRect(Q+1,J,C-2,V)}}else if(p==="waveform"){const P=R.current;H.lineWidth=2,H.strokeStyle="var(--nice-primary-light, #c7d2fe)",H.beginPath();const $=te/P.length;for(let T=0;T<P.length;T++){const C=(P[T]-128)/128,A=T*$,D=G/2+C*(G*.45);T===0?H.moveTo(A,D):H.lineTo(A,D)}H.stroke()}else if(p==="palette"){const T=te/12,C=G/6,A=(_.current+z*120)%360;for(let D=0;D<6;D++)for(let V=0;V<12;V++){const Q=(D*12+V)%N.current.length,J=N.current[Q]/255,ae=(A+V/12*180+D/6*90)%360,re=70+J*25,ee=25+J*35;H.fillStyle=`hsl(${ae}, ${re}%, ${ee}%)`,H.fillRect(V*T,D*C,Math.ceil(T),Math.ceil(C))}}H.strokeStyle=getComputedStyle(document.documentElement).getPropertyValue("--waveform-stroke")||"var(--nice-primary-light, #c7d2fe)",y.current=requestAnimationFrame(q)},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),y.current=requestAnimationFrame(q),()=>{window.removeEventListener("resize",Y),y.current&&cancelAnimationFrame(y.current)}},[E,e,t,p]);const U=()=>{if(e==="youtube")return null;const j=12,L=Math.round(b*j);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:j}).map((I,q)=>{const Y=120*(q/j);return s.jsx("div",{style:{width:6,height:18,borderRadius:2,background:q<L?`hsl(${Y}, 80%, 50%)`:"var(--nice-text, #1f2937)"}},q)})})},W=()=>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:Uu},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:W()}):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(j=>s.jsx(Vu,{active:p===j,onClick:()=>v(j),title:`Tryb: ${j}`,children:j},j))}),s.jsx("div",{style:{position:"absolute",right:10,bottom:10,pointerEvents:"none",zIndex:9998},children:s.jsx(U,{})})]})]})},Bo=({artist:e,title:t,hideControls:n=!0,isPlaying:r,onTimeUpdate:a,searchYouTubeByArtistTitle:o})=>{const{t:i}=xe(),[l,c]=u.useState(e||""),[d,h]=u.useState(t||""),[f,m]=u.useState(null),[g,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(()=>{g&&(r?g.playVideo():g.pauseVideo())},[r,g]),u.useEffect(()=>{if(g&&a){const y=setInterval(()=>{const k=g.getCurrentTime();a(k)},100);return()=>clearInterval(y)}},[g,a]),u.useEffect(()=>{const y=()=>{if(v.current){const k=v.current.clientWidth,M=Math.round(k*(9/16));b({width:k,height:M})}};return y(),window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[]);const w=async()=>{if(!o)return;const y=await o(l,d);m(y)};return s.jsxs("div",{ref:v,style:{width:"100%",maxWidth:"900px",margin:"0 auto"},children:[(!e||!t||!f)&&s.jsxs("div",{children:[s.jsx("input",{value:l,onChange:y=>c(y.target.value),placeholder:i("youtubePlayer.artist","Artist"),"aria-label":i("youtubePlayer.artist","Artist")}),s.jsx("input",{value:d,onChange:y=>h(y.target.value),placeholder:i("youtubePlayer.title","Title"),"aria-label":i("youtubePlayer.title","Title")}),s.jsx("button",{onClick:w,children:i("youtubePlayer.search","Search")})]}),f&&s.jsxs("div",{children:[s.jsx(Yr,{videoId:f,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:y=>p(y.target)}),!n&&s.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px"},children:[s.jsx("button",{onClick:()=>g==null?void 0:g.playVideo(),children:"? Play"}),s.jsx("button",{onClick:()=>g==null?void 0:g.pauseVideo(),children:"? Pause"})]})]})]})},qu=({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"})})}},pa=({data:e,display:t,callbacks:n,state:r})=>{const{id:a,index:o,artist:i,title:l,version:c,lp:d,sourcesAvailable:h=[]}=e,{allowVersion:f=!0,dragHandleProps:m}=t,{onChange:g,onRemove:p,onMoveUp:v,onMoveDown:x,onChangeLp:b,onSelectSource:w}=n,{readOnly:y=!1,canMoveUp:k=!0,canMoveDown:M=!0,activeSource:N}=r,{t:R}=xe(),_=u.useRef(null);u.useEffect(()=>{!i&&_.current&&_.current.focus()},[i]);const E=L=>{if(!y&&L.key==="Enter"){const I=L.target.closest("div.gpi-row"),q=I==null?void 0:I.querySelectorAll("input[data-role='field']");if(!q||q.length===0)return;const Y=Array.from(q).indexOf(L.target),O=q[Y+1]??q[0];O==null||O.focus()}},U=L=>{const I=h.includes(L),q=N===L,Y={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid var(--nice-border, #e5e7eb)",background:q?"var(--active-bg, #eef2ff)":"var(--bg, #fff)",opacity:I?1:.35,cursor:I&&w&&!y?"pointer":"default",transition:"transform .05s ease"},O=L==="youtube"?"var(--nice-danger, #ff0000)":L==="spotify"?"var(--nice-success, #1db954)":L==="tidal"?"var(--nice-text, #111827)":L==="hls"?"var(--nice-accent, #7c3aed)":"var(--nice-text, #374151)",Z=L==="youtube"?"YouTube":L==="spotify"?"Spotify":L==="tidal"?"TIDAL":L==="hls"?"HLS":"Audio",H=R("playlistItem.sourceLabel")+": "+Z+(q?` ${R("playlistItem.sourceSelected")}`:""),te=()=>{!I||!w||y||w(L)};return s.jsx("button",{type:"button",title:Z,onClick:te,disabled:!I||y,style:Y,"aria-pressed":q,"aria-label":H,children:s.jsx(qu,{kind:L,color:O})},L)},W=["youtube","tidal","spotify","hls","audio"],j=typeof d=="number"?d:o+1;return s.jsxs("div",{className:"gpi-row",role:"group","aria-label":R("playlistItem.trackNumber")+" "+(o+1),style:{display:"grid",gridTemplateColumns:f?"56px 1fr 1fr 1fr auto auto":"56px 1fr 1fr auto auto",gap:8,alignItems:"center"},children:[s.jsx("input",{type:"number",min:1,value:j,onChange:L=>b==null?void 0:b(Number(L.target.value)),disabled:y||!b,"aria-label":"Lp",title:R("playlistItem.positionOnList"),style:Hu}),s.jsx("input",{ref:_,"data-role":"field",type:"text",value:i,onChange:L=>g({artist:L.target.value}),placeholder:"Artist",onKeyDown:E,disabled:y,"aria-label":"Artist",className:"gpi-input",style:Cr}),s.jsx("input",{"data-role":"field",type:"text",value:l,onChange:L=>g({title:L.target.value}),placeholder:"Title",onKeyDown:E,disabled:y,"aria-label":"Title",className:"gpi-input",style:Cr}),f&&s.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:L=>g({version:L.target.value||void 0}),placeholder:R("playlistItem.versionOptional"),onKeyDown:E,disabled:y,"aria-label":"Version",className:"gpi-input",style:Cr}),s.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":R("playlistItem.availableSources"),children:W.map(U)}),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":R("playlistItem.dragReorder"),title:R("playlistItem.dragReorder"),style:Nn,children:"≡"}),s.jsx("button",{type:"button",onClick:v,disabled:!k||y,"aria-label":R("playlistItem.moveUp"),title:R("playlistItem.moveUp"),style:Nn,children:"↑"}),s.jsx("button",{type:"button",onClick:x,disabled:!M||y,"aria-label":R("playlistItem.moveDown"),title:R("playlistItem.moveDown"),style:Nn,children:"↓"}),s.jsx("button",{type:"button",onClick:p,disabled:y,"aria-label":R("common.delete"),title:R("common.delete"),style:{...Nn,color:"var(--danger, #b91c1c)"},children:"✕"})]})]})},Hu={width:48,border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 6px",fontSize:14,textAlign:"center"},Cr={width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 10px",fontSize:14},Nn={border:"1px solid var(--nice-border, #d1d5db)",background:"var(--bg, #fff)",padding:"6px 8px",borderRadius:6,cursor:"pointer"},_r=()=>Math.random().toString(36).slice(2,10),In=e=>(e??[]).map(t=>({id:_r(),...t})),Ku=e=>e.map(({id:t,...n})=>n),Yu=null,Zu=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}},Wo=({value:e,defaultValue:t,onChange:n,allowVersion:r=!0,maxItems:a,addButtonLabel:o,emptyState:i=Yu,readOnly:l=!1,autoFocusNewItem:c=!0,enableBulkPaste:d=!0})=>{const{t:h}=xe(),f=e!==void 0,[m,g]=u.useState(()=>In(e||t)),[p,v]=u.useState(""),x=u.useRef(null),[b,w]=u.useState(null);u.useEffect(()=>{f&&g(In(e))},[f,JSON.stringify(e)]);const y=u.useCallback(H=>{n==null||n(Ku(H))},[n]),k=u.useCallback(H=>{if(f){const te=H(In(e));y(te)}else g(te=>{const G=H(te);return y(G),G})},[y,f,e]),M=a?m.length<a:!0,N=u.useCallback(()=>{!M||l||k(H=>[...H,{id:_r(),artist:"",title:"",version:void 0}])},[M,l,k]),R=u.useCallback((H,te)=>{k(G=>G.map(z=>z.id===H?{...z,...te}:z))},[k]),_=u.useCallback(H=>{l||k(te=>te.filter(G=>G.id!==H))},[l,k]),E=u.useCallback((H,te)=>{k(G=>{const z=G.findIndex(T=>T.id===H);if(z<0)return G;const S=z+te;if(S<0||S>=G.length)return G;const P=[...G],[$]=P.splice(z,1);return P.splice(S,0,$),P})},[k]),U=u.useCallback((H,te)=>{k(G=>{const z=G.findIndex(T=>T.id===H);if(z<0)return G;const S=Math.max(0,Math.min(G.length-1,te-1));if(z===S)return G;const P=[...G],[$]=P.splice(z,1);return P.splice(S,0,$),P})},[k]),W=H=>te=>{l||(x.current=H,te.dataTransfer.effectAllowed="move",te.dataTransfer.setData("text/plain",H))},j=H=>te=>{l||(te.preventDefault(),te.dataTransfer.dropEffect="move",w(H))},L=H=>()=>w(te=>te===H?null:te),I=H=>te=>{if(l)return;te.preventDefault();const G=x.current??te.dataTransfer.getData("text/plain");w(null),x.current=null,!(!G||G===H)&&k(z=>{const S=z.findIndex(C=>C.id===G),P=z.findIndex(C=>C.id===H);if(S<0||P<0||S===P)return z;const $=[...z],[T]=$.splice(S,1);return $.splice(P,0,T),$})},q=()=>{x.current=null,w(null)},Y=u.useCallback(()=>{if(!d||l)return;const te=p.split(/\r?\n/).map(G=>G.trim()).filter(Boolean).map(Zu).filter(G=>!!G);te.length!==0&&(k(G=>{const z=(a??1/0)-G.length,S=te.slice(0,Math.max(0,z)).map(P=>({id:_r(),...P}));return[...G,...S]}),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:h("genericPlaylist.emptyState","No songs. Add the first one below.")}),Z=o??h("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:h("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:W(H.id),onDragOver:j(H.id),onDragLeave:L(H.id),onDrop:I(H.id),onDragEnd:q,style:{border:G?"2px dashed var(--nice-info, #6366f1)":"2px solid transparent",borderRadius:8,padding:G?4:0},children:s.jsx(pa,{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:W(H.id)}},callbacks:{onChange:z=>R(H.id,z),onRemove:()=>_(H.id),onMoveUp:()=>E(H.id,-1),onMoveDown:()=>E(H.id,1),onChangeLp:z=>U(H.id,z)},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:h("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:h("genericPlaylist.bulkPastePlaceholder",`Paste lines in format:
48
48
  Artist - Title (Version)
49
49
  Artist � Title [Remastered 2011]
50
- OR: Artist;Title;Version`),rows:3,style:{width:"100%",border:"1px solid #e5e7eb",borderRadius:6,padding:8,fontFamily:"inherit"}}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:6},children:[s.jsx("div",{style:{color:"#6b7280",fontSize:12},children:h("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 #d1d5db",background:"#f9fafb"},children:h("genericPlaylist.addFromList","Add from list")})]})]})]})})]})},ts=["#ef4444","#f97316","#f59e0b","#eab308","#84cc16","#22c55e","#14b8a6","#06b6d4","#3b82f6","#6366f1","#8b5cf6","#a855f7","#d946ef","#ec4899","#f43f5e","#78716c","#64748b","#000000"],Ln=["??","??","??","??","??","??","??","??","??","?","??","??","??","??","??","??"],Uo=({tags:e,onCreateTag:t,onUpdateTag:n,onDeleteTag:r,selectedTracks:a,onAssignTag:o,onUnassignTag:i})=>{const{t:l}=xe(),[c,d]=u.useState(null),[h,f]=u.useState(""),[m,g]=u.useState(ts[8]),[p,v]=u.useState(Ln[0]),[x,b]=u.useState(!1),[w,y]=u.useState(null),[k,M]=u.useState(""),[N,R]=u.useState(""),[_,E]=u.useState(""),U=u.useCallback(O=>{d(O.id),M(O.name),R(O.color),E(O.icon||Ln[0])},[]),W=u.useCallback(()=>{c&&k.trim()&&(n(c,k.trim(),N,_),d(null))},[c,k,N,_,n]),j=u.useCallback(()=>{h.trim()&&(t(h.trim(),m,p),f(""),b(!1))},[h,m,p,t]),L=u.useCallback(O=>{w===O?(r(O),y(null)):(y(O),setTimeout(()=>y(null),3e3))},[w,r]),I=a&&a.length>0,q=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))&&!q(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:h,onChange:O=>f(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"&&j()}),s.jsx("button",{onClick:j,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:"?"})]}),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:ts.map(O=>s.jsx("div",{onClick:()=>g(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:Ln.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))})]})]}),I&&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=>E(Z.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:Ln.map(Z=>s.jsx("option",{value:Z,children:Z},Z))}),s.jsx("input",{type:"color",value:N,onChange:Z=>R(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"&&W()}),s.jsx("button",{onClick:W,style:Fn("var(--accent, #3b82f6)"),children:"?"}),s.jsx("button",{onClick:()=>d(null),style:Fn("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]}),I&&o&&i&&s.jsx("input",{type:"checkbox",checked:q(O.id),ref:Z=>{Z&&(Z.indeterminate=Y(O.id))},onChange:()=>{const Z=a.map(H=>H.id);q(O.id)?i(Z,O.id):o(Z,O.id)},style:{cursor:"pointer"}}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:()=>U(O),style:Fn("var(--text-secondary, #9ca3af)"),title:l("playlistManager.editTag"),children:"?"}),s.jsx("button",{onClick:()=>L(O.id),style:Fn(w===O.id?"var(--error, #ef4444)":"var(--text-secondary, #9ca3af)"),title:w===O.id?l("playlistManager.confirmDelete"):l("playlistManager.deleteTag"),children:w===O.id?"?":"??"})]})},O.id))})]})]})},Fn=e=>({background:"none",border:"none",cursor:"pointer",fontSize:"0.82rem",color:e,padding:"2px 4px"});var ma=(e=>(e.Static="static",e.Dynamic="dynamic",e))(ma||{}),Vo=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(Vo||{}),qo=(e=>(e.Left="left",e.Right="right",e))(qo||{}),Ye=(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))(Ye||{}),Ze=(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))(Ze||{}),Ho=(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))(Ho||{}),qt=(e=>(e.Asc="asc",e.Desc="desc",e))(qt||{}),lt=(e=>(e.Library="library",e.Spotify="spotify",e.Tidal="tidal",e.YouTube="youtube",e.MusicBrainz="musicbrainz",e.Import="import",e.Manual="manual",e))(lt||{});const Xu=[{value:Ye.Artist,label:"Artist"},{value:Ye.Title,label:"Title"},{value:Ye.Album,label:"Album"},{value:Ye.Genre,label:"Genre"},{value:Ye.Year,label:"Year"},{value:Ye.Duration,label:"Duration (s)"},{value:Ye.Rating,label:"Rating"},{value:Ye.PlayCount,label:"Play Count"},{value:Ye.Tag,label:"Tag"},{value:Ye.Source,label:"Source"},{value:Ye.AddedDate,label:"Added Date"}],Qu=[{value:Ze.Equals,label:"="},{value:Ze.NotEquals,label:"≠"},{value:Ze.Contains,label:"contains"},{value:Ze.NotContains,label:"not contains"},{value:Ze.StartsWith,label:"starts with"},{value:Ze.GreaterThan,label:">"},{value:Ze.LessThan,label:"<"},{value:Ze.Between,label:"between"},{value:Ze.In,label:"in"},{value:Ze.NotIn,label:"not in"}];function Ju(e){return"logic"in e&&"rules"in e}function zr(){return{id:crypto.randomUUID(),field:Ye.Artist,operator:Ze.Contains,value:""}}function Ko(){return{id:crypto.randomUUID(),logic:"and",rules:[zr()]}}const eh=({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:Xu.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:Qu.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===Ze.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:"✕"})]}),Yo=({group:e,onChange:t,onRemove:n,depth:r=0})=>{const{t:a}=xe(),o=u.useCallback((f,m)=>{const g=[...e.rules];g[f]=m,t({...e,rules:g})},[e,t]),i=u.useCallback(f=>{const m=e.rules.filter((g,p)=>p!==f);t({...e,rules:m.length>0?m:[zr()]})},[e,t]),l=u.useCallback(()=>{t({...e,rules:[...e.rules,zr()]})},[e,t]),c=u.useCallback(()=>{t({...e,rules:[...e.rules,Ko()]})},[e,t]),d=u.useCallback(()=>{t({...e,logic:e.logic==="and"?"or":"and"})},[e,t]),h=e.logic==="and"?"var(--bs-primary)":"var(--bs-warning)";return s.jsxs("div",{className:"p-2 mb-2 rounded",style:{borderLeft:`3px solid ${h}`,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((f,m)=>Ju(f)?s.jsx(Yo,{group:f,onChange:g=>o(m,g),onRemove:()=>i(m),depth:r+1},f.id):s.jsx(eh,{rule:f,onChange:g=>o(m,g),onRemove:()=>i(m)},f.id))]})},Zo=({rules:e,onChange:t,limit:n,onLimitChange:r})=>{const{t:a}=xe(),o=e??Ko();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(Yo,{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)")})]})]})},ns=e=>{if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`},th={library:"??",spotify:"??",tidal:"?",youtube:"??",musicbrainz:"??",import:"??",manual:"?"},ga=({tracks:e,tags:t,selectedTrackIds:n,onSelectionChange:r,onPlay:a,onRemove:o,onReorder:i,onTagTracks:l,onRateTracks:c,sortField:d,sortDir:h,onSortChange:f,filterText:m,onFilterChange:g,compact:p=!1,draggable:v=!1,onDragStart:x,dropTarget:b=!1,onDrop:w})=>{const{t:y}=xe(),[k,M]=u.useState(null),[N,R]=u.useState(null),_=u.useRef(null),E=u.useMemo(()=>{let S=e??[];if(m.trim()){const P=m.toLowerCase();S=S.filter($=>{var T,C;return $.title.toLowerCase().includes(P)||$.artist.toLowerCase().includes(P)||((T=$.album)==null?void 0:T.toLowerCase().includes(P))||((C=$.genre)==null?void 0:C.toLowerCase().includes(P))})}return[...S].sort((P,$)=>{const T=h==="asc"?1:-1;switch(d){case"title":return T*P.title.localeCompare($.title);case"artist":return T*P.artist.localeCompare($.artist);case"album":return T*(P.album??"").localeCompare($.album??"");case"duration":return T*((P.duration??0)-($.duration??0));case"year":return T*((P.year??0)-($.year??0));case"rating":return T*((P.rating??0)-($.rating??0));case"addedDate":return T*(P.addedAt??"").localeCompare($.addedAt??"");case"custom":return T*((P.customOrder??0)-($.customOrder??0));default:return 0}})},[e,m,d,h]),U=u.useCallback((S,P)=>{const $=E[S];if($){if(P.ctrlKey||P.metaKey){const T=new Set(n);T.has($.id)?T.delete($.id):T.add($.id),r(T)}else if(P.shiftKey&&_.current!==null){const T=Math.min(_.current,S),C=Math.max(_.current,S),A=new Set(n);for(let D=T;D<=C;D++)A.add(E[D].id);r(A)}else r(new Set([$.id]));_.current=S}},[E,n,r]),W=u.useCallback(()=>{n.size===E.length?r(new Set):r(new Set(E.map(S=>S.id)))},[E,n,r]),j=({field:S,label:P,width:$})=>{const T=d===S;return s.jsxs("div",{style:{width:$,flex:$?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?f(S,h===qt.Asc?qt.Desc:qt.Asc):f(S,qt.Asc)},children:[P,T&&s.jsx("span",{children:"?"})]})},L=u.useCallback((S,P)=>{const $=n.has(S.id)?Array.from(n):[S.id];P.dataTransfer.setData("trackIds",JSON.stringify($)),P.dataTransfer.effectAllowed="move",x==null||x($,P)},[n,x]),I=u.useCallback((S,P)=>{P.preventDefault(),P.dataTransfer.dropEffect="move",M(S)},[]),q=u.useCallback((S,P)=>{P.preventDefault(),M(null);try{const $=P.dataTransfer.getData("trackIds");if($&&i){const T=JSON.parse($),C=E.filter(V=>!T.includes(V.id)),A=E.filter(V=>T.includes(V.id)),D=Math.min(S,C.length);C.splice(D,0,...A),i(C.map(V=>V.id))}}catch{}},[E,i]),Y=u.useCallback(S=>{S.preventDefault(),M(null),w==null||w(S)},[w]),O=u.useMemo(()=>new Map(t.map(S=>[S.id,S])),[t]),Z=S=>S.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)"},B=(S,P)=>({display:"flex",alignItems:"center",gap:8,padding:p?"4px 12px":"6px 12px",height:H,cursor:"pointer",background:P?"var(--accent-light, #dbeafe)":S?"var(--selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--border-subtle, #f3f4f6)",transition:"background 0.1s"}),z=E.length>0&&n.size===E.length;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:b?S=>{S.preventDefault(),S.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:S=>g(S.target.value),placeholder:"?? "+y("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:[E.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:z,onChange:W,style:{cursor:"pointer"}})}),s.jsx("div",{style:{width:20},children:"#"}),!p&&s.jsx("div",{style:{width:44}}),s.jsx(j,{field:"title",label:y("playlistManager.colTitle")}),s.jsx(j,{field:"artist",label:y("playlistManager.colArtist")}),!p&&s.jsx(j,{field:"album",label:y("playlistManager.colAlbum")}),s.jsx(j,{field:"duration",label:y("playlistManager.colDuration"),width:60}),!p&&s.jsx(j,{field:"year",label:y("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:[E.length===0&&s.jsx("div",{style:{padding:24,textAlign:"center",opacity:.4,fontSize:"0.85rem"},children:e.length===0?y("playlistManager.emptyPlaylist"):y("playlistManager.noMatchingTracks")}),E.map((S,P)=>{const $=n.has(S.id),T=k===P;return s.jsxs("div",{style:B($,T),onClick:C=>U(P,C),onDoubleClick:()=>a==null?void 0:a(S),draggable:v,onDragStart:C=>L(S,C),onDragOver:C=>I(P,C),onDrop:C=>q(P,C),onDragLeave:()=>M(null),children:[s.jsx("div",{style:{width:28},children:s.jsx("input",{type:"checkbox",checked:$,onChange:()=>{const C=new Set(n);$?C.delete(S.id):C.add(S.id),r(C)},onClick:C=>C.stopPropagation(),style:{cursor:"pointer"}})}),s.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:P+1}),!p&&s.jsx("div",{style:{width:44,height:36,flexShrink:0},children:S.coverUrl?s.jsx("img",{src:S.coverUrl,alt:S.title||y("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:S.title}),s.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",opacity:.7},children:S.artist}),!p&&s.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",opacity:.5},children:S.album}),s.jsx("div",{style:{width:60,fontSize:"0.78rem",opacity:.5,textAlign:"right"},children:ns(S.duration)}),!p&&s.jsx("div",{style:{width:50,fontSize:"0.72rem",opacity:.4,textAlign:"center"},children:S.year||""}),s.jsx("div",{style:{width:30,textAlign:"center",fontSize:"0.75rem"},title:S.source,children:th[S.source]??"?"}),!p&&s.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[S.tags.slice(0,2).map(C=>{const A=O.get(C);if(!A)return null;const D=`--tag-${Z(C)}`;return s.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${D}-bg, ${A.color}22)`,color:`var(${D}, ${A.color})`,whiteSpace:"nowrap"},children:A.name},C)}),S.tags.length>2&&s.jsxs("span",{style:{fontSize:"0.6rem",opacity:.4},children:["+",S.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(),R(N===S.id?null:S.id)},title:y("playlistManager.morActions"),children:"?"}),N===S.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 rgba(0,0,0,0.1)",minWidth:140},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:y("playlistManager.assignTag")}),t.map(C=>{const A=S.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:A?`var(--tag-${Z(C.id)}-bg, ${C.color}22)`:"transparent"},onClick:D=>{D.stopPropagation();const V=n.size>0?Array.from(n):[S.id];A||l==null||l(V,[C.id]),R(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}),A&&s.jsx("span",{style:{marginLeft:"auto"},children:"?"})]},C.id)})]})]})]},S.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:[E.length," ",y("playlistManager.tracks")]}),s.jsx("span",{children:ns(E.reduce((S,P)=>S+(P.duration??0),0))}),n.size>0&&s.jsxs("span",{children:[n.size," ",y("playlistManager.selected")]})]})]})},rs=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),Xo=({playlists:e=[],tags:t=[],onCopyTracks:n=()=>{},onMoveTracks:r=()=>{},onRemoveTracks:a=()=>{},onReorderTracks:o=()=>{},onPlay:i=()=>{},onTagTracks:l=()=>{},initialLeftId:c,initialRightId:d,library:h,queue:f,onAddToQueue:m,onRemoveFromQueue:g})=>{const{t:p}=xe(),[v,x]=u.useState(()=>rs(c??null)),[b,w]=u.useState(()=>rs(d??null)),[y,k]=u.useState("left"),[M,N]=u.useState(null),[R,_]=u.useState(50),[E,U]=u.useState(!1),W=u.useMemo(()=>e.find(T=>T.id===v.playlistId),[e,v.playlistId]),j=u.useMemo(()=>e.find(T=>T.id===b.playlistId),[e,b.playlistId]),L=u.useCallback((T,C)=>{T==="left"?x(A=>({...A,...C})):w(A=>({...A,...C}))},[]),I=u.useCallback(T=>T==="left"?v:b,[v,b]),q=T=>T==="left"?"right":"left",Y=u.useCallback(T=>{const C=I(T),A=I(q(T));!C.playlistId||!A.playlistId||C.selectedTrackIds.size===0||(n(C.playlistId,A.playlistId,Array.from(C.selectedTrackIds)),L(T,{selectedTrackIds:new Set}))},[I,n,L]),O=u.useCallback(T=>{const C=I(T),A=I(q(T));!C.playlistId||!A.playlistId||C.selectedTrackIds.size===0||(r(C.playlistId,A.playlistId,Array.from(C.selectedTrackIds)),L(T,{selectedTrackIds:new Set}))},[I,r,L]),Z=u.useCallback(T=>{const C=I(T);!C.playlistId||C.selectedTrackIds.size===0||N({operation:"copy",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[I]),H=u.useCallback(T=>{const C=I(T);!C.playlistId||C.selectedTrackIds.size===0||N({operation:"cut",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[I]),te=u.useCallback(T=>{const C=I(T);!M||!C.playlistId||(M.operation==="copy"?n(M.sourcePlaylistId,C.playlistId,M.trackIds):r(M.sourcePlaylistId,C.playlistId,M.trackIds),N(null))},[M,I,n,r]),B=u.useCallback(T=>{T.key==="Tab"&&!T.shiftKey&&(T.preventDefault(),k(C=>q(C))),(T.ctrlKey||T.metaKey)&&T.key==="c"&&Z(y),(T.ctrlKey||T.metaKey)&&T.key==="x"&&H(y),(T.ctrlKey||T.metaKey)&&T.key==="v"&&te(y)},[y,Z,H,te]),z=u.useCallback(()=>U(!0),[]),S=u.useCallback(T=>{if(!E)return;const C=T.currentTarget.getBoundingClientRect(),A=(T.clientX-C.left)/C.width*100;_(Math.max(20,Math.min(80,A)))},[E]),P=u.useCallback(()=>U(!1),[]),$=T=>{const C=I(T),A=T==="left"?W:j,D=y===T,Q=!!I(q(T)).playlistId;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",border:D?"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:D?"var(--accent, #3b82f6)":"var(--surface-bg, #f3f4f6)",color:D?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:s.jsxs("select",{value:C.playlistId??"",onChange:J=>L(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:D?"var(--accent-overlay, #ffffff30)":"var(--input-bg, #fff)",color:D?"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:kr(!1),onClick:()=>Y(T),disabled:!C.playlistId||!Q||C.selectedTrackIds.size===0,title:p("playlistManager.copyToOther"),children:["???"," ",p("playlistManager.copy")]}),s.jsxs("button",{style:kr(!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:kr(!0),onClick:()=>te(T),disabled:!C.playlistId,children:["?? ",p("playlistManager.paste")," (",M.trackIds.length,")"]})]}),A?s.jsx(ga,{tracks:A.tracks,tags:t,selectedTrackIds:C.selectedTrackIds,onSelectionChange:J=>L(T,{selectedTrackIds:J}),onPlay:i,onRemove:J=>a(A.id,J),onReorder:J=>o(A.id,J),onTagTracks:l,sortField:C.sortField,sortDir:C.sortDir,onSortChange:(J,ae)=>L(T,{sortField:J,sortDir:ae}),filterText:C.filterText,onFilterChange:J=>L(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:E?"none":"auto"},onKeyDown:B,onMouseMove:S,onMouseUp:P,tabIndex:0,children:[s.jsx("div",{style:{width:`${R}%`,minWidth:200},children:$("left")}),s.jsx("div",{style:{width:6,cursor:"col-resize",background:E?"var(--accent, #3b82f6)":"var(--border-color, #e5e7eb)",transition:E?"none":"background 0.15s",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseDown:z,children:s.jsx("div",{style:{width:2,height:40,borderRadius:1,background:E?"var(--btn-text, #fff)":"var(--text-secondary, #9ca3af)"}})}),s.jsx("div",{style:{flex:1,minWidth:200},children:$("right")})]})},kr=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"}),Qo="av:local-playlists";function nh(){try{const e=localStorage.getItem(Qo);return e?JSON.parse(e):[]}catch{return[]}}function rh(e){const t=JSON.stringify(e);try{localStorage.setItem(Qo,t)}catch{}}function ya(){const[e,t]=u.useState(()=>nh()),n=u.useRef(!1);return u.useEffect(()=>{n.current=!0},[]),u.useEffect(()=>{rh(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 ah=et.scoped("PlaylistList"),sh={border:"1px solid #e5e7eb",borderRadius:8,background:"#fff"},oh={...sh,padding:"8px 10px",cursor:"pointer"},Jo={border:"1px solid var(--border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--bg, #fff)",cursor:"pointer"},ih={...Jo,background:"var(--primary, #4f46e5)",borderColor:"var(--primary, #4f46e5)",color:"var(--bg, #fff)"},ba=({selectedId:e,onSelect:t,onCreateRemote:n})=>{const{t:r}=xe(),a=ya(),[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 #d1d5db",borderRadius:8,padding:"6px 10px"},"aria-label":"Playlist name"}),s.jsxs("button",{type:"button",disabled:!o.trim(),style:o.trim()?ih:{...Jo,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){ah.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:{...oh,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 ↑")})]})]})},lh=et.scoped("PlaylistBrowser"),as={display:"grid",gap:12},ss=e=>({artist:(e.artists??[]).join(", "),title:e.title}),ei=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:n,tracks:r,view:a,onSelect:o,onPlay:i})=>{var x;const{t:l}=xe(),c=ya(),[d,h]=u.useState(null),[f,m]=u.useState(""),[,g]=u.useState([]),p=d==null?void 0:d.id,v=(b,w)=>{if("addItems"in c){c.addItems(b.id,w);const k=c.list().find(M=>M.id===b.id)||b;h(k);return}const y=c;if("update"in c&&typeof y.update=="function"){const k=Array.from([...b.items||[],...w]);y.update({...b,items:k});const M=c.list().find(N=>N.id===b.id)||{...b,items:k};h(M);return}lh.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:as,children:[s.jsx("h3",{style:{margin:0},children:l("playlistBrowser.playlists")}),s.jsx(ba,{selectedId:p,onSelect:h}),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:as,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..."),onPick:b=>{d&&v(d,[ss(b)])}}),s.jsx("input",{placeholder:l("playlistBrowser.fullSearch","Full search (Enter does not add, full list below)"),value:f,onChange:b=>m(b.target.value),style:{width:"100%",border:"1px solid #d1d5db",borderRadius:8,padding:"6px 10px",marginTop:10}})]}),t==null?void 0:t({query:f,onPick:b=>{d&&v(d,[ss(b)])}}),n==null?void 0:n({onPlayNow:b=>g(b),onAddToQueue:b=>g(w=>[...w,...b]),onAddDescriptors:b=>d&&v(d,b)})]})]})};var Tt=(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))(Tt||{});const ti=(e,t=null)=>e.filter(n=>n.parentId===t).sort((n,r)=>n.sortOrder-r.sortOrder).map(n=>({...n,children:ti(e,n.id)})),ch={[Tt.Spotify]:{icon:"??",label:"Spotify",color:"var(--source-spotify, #1DB954)",bg:"var(--source-spotify-bg, #1DB95418)"},[Tt.Tidal]:{icon:"?",label:"Tidal",color:"var(--source-tidal, #000000)",bg:"var(--source-tidal-bg, #00000010)"},[Tt.YouTube]:{icon:"??",label:"YouTube",color:"var(--source-youtube, #FF0000)",bg:"var(--source-youtube-bg, #FF000010)"}},ni=({folders:e,playlists:t,tags:n,services:r,activeFolderId:a,activePlaylistId:o,onSelectFolder:i,onSelectPlaylist:l,onCreateFolder:c,onRenameFolder:d,onDeleteFolder:h,onCreatePlaylist:f,onConnectService:m,onDisconnectService:g,onDragPlaylistToFolder:p,collapsed:v=!1,onToggleCollapse:x})=>{const{t:b}=xe(),[w,y]=u.useState(new Set),[k,M]=u.useState(!1),[N,R]=u.useState(""),[_,E]=u.useState(null),[U,W]=u.useState(!1),[j,L]=u.useState(""),[I,q]=u.useState("static"),[Y,O]=u.useState(null),[Z,H]=u.useState(""),[te,B]=u.useState(null),[z,S]=u.useState(!1),P=u.useMemo(()=>ti(e),[e]),$=u.useCallback(X=>{y(ue=>{const ye=new Set(ue);return ye.has(X)?ye.delete(X):ye.add(X),ye})},[]),T=u.useCallback(()=>{N.trim()&&(c(N.trim(),_),R(""),M(!1))},[N,_,c]),C=u.useCallback(()=>{j.trim()&&(f(j.trim(),I,a),L(""),W(!1))},[j,I,a,f]),A=u.useCallback(X=>{Z.trim()&&(d(X,Z.trim()),O(null),H(""))},[Z,d]),D=u.useCallback((X,ue)=>{X.preventDefault(),X.dataTransfer.dropEffect="move",B(ue)},[]),V=u.useCallback((X,ue)=>{X.preventDefault();const ye=X.dataTransfer.getData("playlistId");ye&&p&&p(ye,ue),B(null)},[p]),Q=u.useCallback(()=>B(null),[]),J=u.useCallback(X=>t.filter(ue=>(ue.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,ue=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:ue?"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"}),F={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,ue)=>{var Se,ne;const ye=w.has(X.id),je=a===X.id,Fe=te===X.id,Re=J(X.id);return s.jsxs("div",{children:[s.jsxs("div",{style:{...ee(je,Fe),paddingLeft:12+ue*16},onClick:()=>{i(X.id),X.children&&X.children.length>0&&$(X.id)},onDragOver:oe=>D(oe,X.id),onDrop:oe=>V(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||Re.length>0?"?":"�"}),Y===X.id?s.jsx("input",{value:Z,onChange:oe=>H(oe.target.value),onKeyDown:oe=>{oe.key==="Enter"&&A(X.id),oe.key==="Escape"&&O(null)},onBlur:()=>A(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:Re.length}),s.jsx("button",{style:F,onClick:oe=>{oe.stopPropagation(),O(X.id),H(X.name)},title:b("common.rename"),children:"?"}),s.jsx("button",{style:{...F,color:"var(--error, #ef4444)"},onClick:oe=>{oe.stopPropagation(),h(X.id)},title:b("common.delete"),children:"?"})]})]}),ye&&s.jsxs(s.Fragment,{children:[Re.map(oe=>ce(oe,ue+1)),(ne=X.children)==null?void 0:ne.map(oe=>se(oe,ue+1))]})]},X.id)},ce=(X,ue)=>{const ye=o===X.id;return s.jsxs("div",{style:{...ee(ye),paddingLeft:12+ue*16+22},onClick:()=>l(X.id),draggable:!0,onDragStart:je=>{je.dataTransfer.setData("playlistId",X.id),je.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:{...F,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:x,title:b("playlistManager.expandSidebar"),children:"?"})});const fe=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:F,onClick:x,title:b("playlistManager.collapseSidebar"),children:"?"})]}),s.jsxs("div",{style:{...re,display:"flex",gap:4,flexWrap:"wrap"},children:[s.jsxs("button",{style:{...F,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:6,padding:"4px 10px"},onClick:()=>W(!0),children:["+ ",b("playlistManager.newPlaylist")]}),s.jsxs("button",{style:{...F,border:"1px solid var(--border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{M(!0),E(a)},children:["?? ",b("playlistManager.newFolder")]})]}),U&&s.jsxs("div",{style:{...re,display:"flex",flexDirection:"column",gap:6},children:[s.jsx("input",{value:j,onChange:X=>L(X.target.value),placeholder:b("playlistManager.playlistName"),style:K,autoFocus:!0,onKeyDown:X=>{X.key==="Enter"&&C(),X.key==="Escape"&&W(!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:I==="static",onChange:()=>q("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:I==="dynamic",onChange:()=>q("dynamic")}),"? ",b("playlistManager.dynamic")]}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{style:{...F,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:F,onClick:()=>W(!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=>R(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:{...F,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:F,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=>D(X,null),onDrop:X=>V(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})]}),fe.map(X=>ce(X,0)),P.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:()=>S(!z),children:[s.jsxs("span",{children:["?? ",b("playlistManager.services")]}),s.jsx("span",{children:"?"})]}),z&&s.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[Tt.Spotify,Tt.Tidal,Tt.YouTube].map(X=>{const ue=ch[X],ye=r.find(je=>je.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:ue.icon}),s.jsx("span",{style:{flex:1},children:ue.label}),ye!=null&&ye.connected?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:"0.65rem",opacity:.6},children:ye.username??b("playlistManager.connected")}),s.jsx("button",{style:{...F,color:"#ef4444"},onClick:()=>g(X),children:"?"})]}):s.jsx("button",{style:{...F,background:ue.color,color:"#fff",borderRadius:4,padding:"2px 8px"},onClick:()=>m(X),children:b("playlistManager.connect")})]},X)})})]})]})},dh=({playlist:e,tags:t,onPlay:n,selectedTrackIds:r,onSelectionChange:a})=>{const{t:o}=xe(),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)})})},ri=u.memo(dh),os=e=>e.replace(/[^a-z0-9_-]/gi,"-"),is={background:"none",border:"none",cursor:"pointer",fontSize:"0.78rem",padding:"2px 4px",opacity:.4},uh=({playlists:e,folders:t,tags:n,activeFolderId:r,onSelectPlaylist:a,onDeletePlaylist:o,onDuplicatePlaylist:i})=>{const{t:l}=xe(),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 f;const h=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 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===ma.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"),h&&` � ?? ${h.name}`]}),((f=d.tags)==null?void 0:f.length)>0&&s.jsx("div",{style:{display:"flex",gap:4,marginTop:6,flexWrap:"wrap"},children:d.tags.slice(0,3).map(m=>{const g=n.find(p=>p.id===m);return g?s.jsx("span",{style:{padding:"1px 8px",borderRadius:12,background:`var(--tag-${os(m)}-bg, ${g.color}18)`,color:`var(--tag-${os(m)}, ${g.color})`,fontSize:"0.65rem",fontWeight:500},children:g.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:is,title:l("playlistManager.duplicate"),children:"??"}),s.jsx("button",{onClick:m=>{m.stopPropagation(),o(d.id)},style:is,title:l("playlistManager.delete"),children:"??"})]})]},d.id)})})},ai=u.memo(uh),ls=[{value:lt.Library,label:"Library",icon:"??",hex:"#6366f1",css:"var(--source-library, #6366f1)",cssBg:"var(--source-library-bg, #6366f118)"},{value:lt.Spotify,label:"Spotify",icon:"??",hex:"#1db954",css:"var(--source-spotify, #1db954)",cssBg:"var(--source-spotify-bg, #1db95418)"},{value:lt.Tidal,label:"Tidal",icon:"?",hex:"#000000",css:"var(--source-tidal, #000000)",cssBg:"var(--source-tidal-bg, #00000018)"},{value:lt.YouTube,label:"YouTube",icon:"??",hex:"#ff0000",css:"var(--source-youtube, #ff0000)",cssBg:"var(--source-youtube-bg, #ff000018)"},{value:lt.MusicBrainz,label:"MusicBrainz",icon:"??",hex:"#ba478f",css:"var(--source-musicbrainz, #ba478f)",cssBg:"var(--source-musicbrainz-bg, #ba478f18)"}],si=({onSearch:e,results:t,isSearching:n,onAddToPlaylist:r,onPlayPreview:a})=>{const{t:o}=xe(),[i,l]=u.useState(""),[c,d]=u.useState(new Set([lt.Library,lt.Spotify,lt.Tidal,lt.YouTube])),[h,f]=u.useState(new Set),[m,g]=u.useState(!1),p=u.useRef(null),v=u.useCallback(R=>{d(_=>{const E=new Set(_);return E.has(R)?E.delete(R):E.add(R),E})},[]),x=u.useCallback(R=>{l(R),p.current&&clearTimeout(p.current),R.trim().length>=2&&(p.current=setTimeout(()=>{e(R.trim(),Array.from(c))},350))},[c,e]),b=u.useCallback(R=>{R.preventDefault(),i.trim().length>=2&&e(i.trim(),Array.from(c))},[i,c,e]),w=u.useCallback(R=>{f(_=>{const E=new Set(_);return E.has(R)?E.delete(R):E.add(R),E})},[]),y=u.useCallback(()=>{h.size===t.length?f(new Set):f(new Set(t.map(R=>R.id)))},[h,t]),k=u.useCallback(()=>{const R=t.filter(_=>h.has(_.id));R.length>0&&(r(R),f(new Set))},[t,h,r]),M=R=>{if(!R)return"--:--";const _=Math.floor(R/60),E=R%60;return`${_}:${E.toString().padStart(2,"0")}`},N=R=>{const _=ls.find(E=>E.value===R);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:()=>g(!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:ls.map(R=>{const _=c.has(R.value);return s.jsxs("button",{onClick:()=>v(R.value),style:{padding:"4px 10px",borderRadius:20,border:_?`2px solid ${R.css}`:"1px solid var(--border-color, #d1d5db)",background:_?R.cssBg:"transparent",color:_?R.css:"var(--text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:_?600:400,transition:"all 0.15s"},children:[R.icon," ",R.label]},R.value)})}),s.jsxs("form",{onSubmit:b,style:{display:"flex",gap:6,marginBottom:8},children:[s.jsx("input",{type:"text",value:i,onChange:R=>x(R.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:h.size===t.length&&t.length>0,onChange:y}),o("playlistManager.selectAll")]}),s.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[t.length," ",o("playlistManager.results")]}),s.jsx("div",{style:{flex:1}}),h.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")," (",h.size,")"]})]}),s.jsx("div",{style:{maxHeight:300,overflowY:"auto",borderRadius:6,border:"1px solid var(--border-color, #e5e7eb)"},children:t.map(R=>s.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:()=>w(R.id),children:[s.jsx("input",{type:"checkbox",checked:h.has(R.id),readOnly:!0}),s.jsx("span",{children:N(R.source)}),R.imageUrl&&s.jsx("img",{src:R.imageUrl,alt:R.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:R.title}),s.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[R.artist,R.album?` � ${R.album}`:""]})]}),s.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:M(R.duration)}),a&&s.jsx("button",{onClick:_=>{_.stopPropagation(),a(R)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem"},title:o("playlistManager.preview"),children:"?"})]},R.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")})]})]})},hh=[{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)"}],fh={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},ph={display:"flex",justifyContent:"space-between",alignItems:"center"},mh={display:"flex",gap:4,marginBottom:8},bn={padding:"8px 20px",borderRadius:6,border:"none",background:"var(--accent, #6366f1)",color:"#fff",cursor:"pointer",fontWeight:600},Dn={...bn,background:"transparent",color:"var(--text, #334155)",border:"1px solid var(--border, #e2e8f0)"},cs={padding:12,borderRadius:8,border:"1px solid var(--border, #e2e8f0)",cursor:"pointer",transition:"border-color 0.15s"},oi=["connect","browse","tracks","options","importing","done"];function gh(e){return oi.indexOf(e)}function yh(e){if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const ii=({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}=xe(),[h,f]=u.useState("connect"),[m,g]=u.useState(null),[p,v]=u.useState([]),[x,b]=u.useState(null),[w,y]=u.useState([]),[k,M]=u.useState(new Set),[N,R]=u.useState(!1),[_,E]=u.useState(null),[U,W]=u.useState(null),[j,L]=u.useState(null),[I,q]=u.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[Y,O]=u.useState(""),Z=u.useMemo(()=>new Set(e.filter(F=>F.connected).map(F=>F.platform)),[e]),H=u.useCallback(F=>e.find(K=>K.platform===F),[e]),te=u.useCallback(F=>{if(g(F),F===99){f("tracks"),O(""),y([]),R(!1);return}Z.has(F)?(f("browse"),R(!0),L(null),r(F).then(K=>{v(K),R(!1)}).catch(K=>{L(String(K)),R(!1)})):t(F)},[Z,t,r]),B=u.useCallback(F=>{b(F),f("tracks"),R(!0),L(null),a(F).then(K=>{y(K),M(new Set(K.map(se=>se.externalId))),R(!1)}).catch(K=>{L(String(K)),R(!1)})},[a]),z=u.useCallback(F=>{M(K=>{const se=new Set(K);return se.has(F)?se.delete(F):se.add(F),se})},[]),S=u.useCallback(()=>{M(F=>F.size===w.length?new Set:new Set(w.map(K=>K.externalId)))},[w]),P=u.useCallback(async()=>{if(!x)return;const F=w.filter(K=>k.has(K.externalId));if(F.length!==0){f("importing"),E({total:F.length,imported:0,skipped:0,failed:0}),L(null);try{const K=await o(x,F,I),se=K&&typeof K=="object"&&"imported"in K?K:{playlistName:x.name,imported:F.length,skipped:0,failed:0,failedTracks:[]};W(se),f("done")}catch(K){L(String(K)),f("options")}}},[x,w,k,I,o]),$=h!=="connect"&&h!=="importing"&&h!=="done",T=u.useCallback(()=>{switch(h){case"browse":f("connect");break;case"tracks":f("browse");break;case"options":f("tracks");break}},[h]),C=()=>s.jsx("div",{style:mh,children:oi.map((F,K)=>s.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:K<=gh(h)?"var(--accent, #6366f1)":"var(--border, #e2e8f0)",transition:"background 0.2s"}},F))}),A=()=>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")}),hh.map(F=>{const K=H(F.value),se=Z.has(F.value);return s.jsxs("div",{style:{...cs,display:"flex",alignItems:"center",gap:12,borderColor:se?F.color:void 0},onClick:()=>te(F.value),role:"button",tabIndex:0,onKeyDown:ce=>ce.key==="Enter"&&te(F.value),children:[s.jsx("span",{style:{fontSize:24},children:F.icon}),s.jsxs("div",{style:{flex:1},children:[s.jsx("strong",{children:F.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:F.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")})]},F.value)})]}),D=()=>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(F=>s.jsxs("div",{style:{...cs,display:"flex",alignItems:"center",gap:12},onClick:()=>B(F),role:"button",tabIndex:0,onKeyDown:K=>K.key==="Enter"&&B(F),children:[F.coverUrl&&s.jsx("img",{src:F.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:F.name}),F.description&&s.jsx("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:F.description})]}),s.jsxs("span",{style:{fontSize:12,color:"var(--text-dim, #64748b)",whiteSpace:"nowrap"},children:[F.trackCount," ",d("importWizard.tracks","tracks")]})]},F.id)),p.length===0&&s.jsx("div",{style:{textAlign:"center",padding:24,color:"var(--text-dim, #64748b)"},children:d("importWizard.noPlaylists","No playlists found")})]})]}),V=u.useCallback(F=>{const se=F.split(`
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:h("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:h("genericPlaylist.addFromList","Add from list")})]})]})]})})]})},ts=["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)"],Ln=["??","??","??","??","??","??","??","??","??","?","??","??","??","??","??","??"],Uo=({tags:e,onCreateTag:t,onUpdateTag:n,onDeleteTag:r,selectedTracks:a,onAssignTag:o,onUnassignTag:i})=>{const{t:l}=xe(),[c,d]=u.useState(null),[h,f]=u.useState(""),[m,g]=u.useState(ts[8]),[p,v]=u.useState(Ln[0]),[x,b]=u.useState(!1),[w,y]=u.useState(null),[k,M]=u.useState(""),[N,R]=u.useState(""),[_,E]=u.useState(""),U=u.useCallback(O=>{d(O.id),M(O.name),R(O.color),E(O.icon||Ln[0])},[]),W=u.useCallback(()=>{c&&k.trim()&&(n(c,k.trim(),N,_),d(null))},[c,k,N,_,n]),j=u.useCallback(()=>{h.trim()&&(t(h.trim(),m,p),f(""),b(!1))},[h,m,p,t]),L=u.useCallback(O=>{w===O?(r(O),y(null)):(y(O),setTimeout(()=>y(null),3e3))},[w,r]),I=a&&a.length>0,q=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))&&!q(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:h,onChange:O=>f(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"&&j()}),s.jsx("button",{onClick:j,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:"?"})]}),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:ts.map(O=>s.jsx("div",{onClick:()=>g(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:Ln.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))})]})]}),I&&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=>E(Z.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:Ln.map(Z=>s.jsx("option",{value:Z,children:Z},Z))}),s.jsx("input",{type:"color",value:N,onChange:Z=>R(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"&&W()}),s.jsx("button",{onClick:W,style:Fn("var(--accent, #3b82f6)"),children:"?"}),s.jsx("button",{onClick:()=>d(null),style:Fn("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]}),I&&o&&i&&s.jsx("input",{type:"checkbox",checked:q(O.id),ref:Z=>{Z&&(Z.indeterminate=Y(O.id))},onChange:()=>{const Z=a.map(H=>H.id);q(O.id)?i(Z,O.id):o(Z,O.id)},style:{cursor:"pointer"}}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:()=>U(O),style:Fn("var(--text-secondary, #9ca3af)"),title:l("playlistManager.editTag"),children:"?"}),s.jsx("button",{onClick:()=>L(O.id),style:Fn(w===O.id?"var(--error, #ef4444)":"var(--text-secondary, #9ca3af)"),title:w===O.id?l("playlistManager.confirmDelete"):l("playlistManager.deleteTag"),children:w===O.id?"?":"??"})]})},O.id))})]})]})},Fn=e=>({background:"none",border:"none",cursor:"pointer",fontSize:"0.82rem",color:e,padding:"2px 4px"});var ma=(e=>(e.Static="static",e.Dynamic="dynamic",e))(ma||{}),Vo=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(Vo||{}),qo=(e=>(e.Left="left",e.Right="right",e))(qo||{}),Ye=(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))(Ye||{}),Ze=(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))(Ze||{}),Ho=(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))(Ho||{}),qt=(e=>(e.Asc="asc",e.Desc="desc",e))(qt||{}),lt=(e=>(e.Library="library",e.Spotify="spotify",e.Tidal="tidal",e.YouTube="youtube",e.MusicBrainz="musicbrainz",e.Import="import",e.Manual="manual",e))(lt||{});const Xu=[{value:Ye.Artist,label:"Artist"},{value:Ye.Title,label:"Title"},{value:Ye.Album,label:"Album"},{value:Ye.Genre,label:"Genre"},{value:Ye.Year,label:"Year"},{value:Ye.Duration,label:"Duration (s)"},{value:Ye.Rating,label:"Rating"},{value:Ye.PlayCount,label:"Play Count"},{value:Ye.Tag,label:"Tag"},{value:Ye.Source,label:"Source"},{value:Ye.AddedDate,label:"Added Date"}],Qu=[{value:Ze.Equals,label:"="},{value:Ze.NotEquals,label:"≠"},{value:Ze.Contains,label:"contains"},{value:Ze.NotContains,label:"not contains"},{value:Ze.StartsWith,label:"starts with"},{value:Ze.GreaterThan,label:">"},{value:Ze.LessThan,label:"<"},{value:Ze.Between,label:"between"},{value:Ze.In,label:"in"},{value:Ze.NotIn,label:"not in"}];function Ju(e){return"logic"in e&&"rules"in e}function zr(){return{id:crypto.randomUUID(),field:Ye.Artist,operator:Ze.Contains,value:""}}function Ko(){return{id:crypto.randomUUID(),logic:"and",rules:[zr()]}}const eh=({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:Xu.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:Qu.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===Ze.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:"✕"})]}),Yo=({group:e,onChange:t,onRemove:n,depth:r=0})=>{const{t:a}=xe(),o=u.useCallback((f,m)=>{const g=[...e.rules];g[f]=m,t({...e,rules:g})},[e,t]),i=u.useCallback(f=>{const m=e.rules.filter((g,p)=>p!==f);t({...e,rules:m.length>0?m:[zr()]})},[e,t]),l=u.useCallback(()=>{t({...e,rules:[...e.rules,zr()]})},[e,t]),c=u.useCallback(()=>{t({...e,rules:[...e.rules,Ko()]})},[e,t]),d=u.useCallback(()=>{t({...e,logic:e.logic==="and"?"or":"and"})},[e,t]),h=e.logic==="and"?"var(--bs-primary)":"var(--bs-warning)";return s.jsxs("div",{className:"p-2 mb-2 rounded",style:{borderLeft:`3px solid ${h}`,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((f,m)=>Ju(f)?s.jsx(Yo,{group:f,onChange:g=>o(m,g),onRemove:()=>i(m),depth:r+1},f.id):s.jsx(eh,{rule:f,onChange:g=>o(m,g),onRemove:()=>i(m)},f.id))]})},Zo=({rules:e,onChange:t,limit:n,onLimitChange:r})=>{const{t:a}=xe(),o=e??Ko();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(Yo,{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)")})]})]})},ns=e=>{if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`},th={library:"??",spotify:"??",tidal:"?",youtube:"??",musicbrainz:"??",import:"??",manual:"?"},ga=({tracks:e,tags:t,selectedTrackIds:n,onSelectionChange:r,onPlay:a,onRemove:o,onReorder:i,onTagTracks:l,onRateTracks:c,sortField:d,sortDir:h,onSortChange:f,filterText:m,onFilterChange:g,compact:p=!1,draggable:v=!1,onDragStart:x,dropTarget:b=!1,onDrop:w})=>{const{t:y}=xe(),[k,M]=u.useState(null),[N,R]=u.useState(null),_=u.useRef(null),E=u.useMemo(()=>{let S=e??[];if(m.trim()){const P=m.toLowerCase();S=S.filter($=>{var T,C;return $.title.toLowerCase().includes(P)||$.artist.toLowerCase().includes(P)||((T=$.album)==null?void 0:T.toLowerCase().includes(P))||((C=$.genre)==null?void 0:C.toLowerCase().includes(P))})}return[...S].sort((P,$)=>{const T=h==="asc"?1:-1;switch(d){case"title":return T*P.title.localeCompare($.title);case"artist":return T*P.artist.localeCompare($.artist);case"album":return T*(P.album??"").localeCompare($.album??"");case"duration":return T*((P.duration??0)-($.duration??0));case"year":return T*((P.year??0)-($.year??0));case"rating":return T*((P.rating??0)-($.rating??0));case"addedDate":return T*(P.addedAt??"").localeCompare($.addedAt??"");case"custom":return T*((P.customOrder??0)-($.customOrder??0));default:return 0}})},[e,m,d,h]),U=u.useCallback((S,P)=>{const $=E[S];if($){if(P.ctrlKey||P.metaKey){const T=new Set(n);T.has($.id)?T.delete($.id):T.add($.id),r(T)}else if(P.shiftKey&&_.current!==null){const T=Math.min(_.current,S),C=Math.max(_.current,S),A=new Set(n);for(let D=T;D<=C;D++)A.add(E[D].id);r(A)}else r(new Set([$.id]));_.current=S}},[E,n,r]),W=u.useCallback(()=>{n.size===E.length?r(new Set):r(new Set(E.map(S=>S.id)))},[E,n,r]),j=({field:S,label:P,width:$})=>{const T=d===S;return s.jsxs("div",{style:{width:$,flex:$?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?f(S,h===qt.Asc?qt.Desc:qt.Asc):f(S,qt.Asc)},children:[P,T&&s.jsx("span",{children:"?"})]})},L=u.useCallback((S,P)=>{const $=n.has(S.id)?Array.from(n):[S.id];P.dataTransfer.setData("trackIds",JSON.stringify($)),P.dataTransfer.effectAllowed="move",x==null||x($,P)},[n,x]),I=u.useCallback((S,P)=>{P.preventDefault(),P.dataTransfer.dropEffect="move",M(S)},[]),q=u.useCallback((S,P)=>{P.preventDefault(),M(null);try{const $=P.dataTransfer.getData("trackIds");if($&&i){const T=JSON.parse($),C=E.filter(V=>!T.includes(V.id)),A=E.filter(V=>T.includes(V.id)),D=Math.min(S,C.length);C.splice(D,0,...A),i(C.map(V=>V.id))}}catch{}},[E,i]),Y=u.useCallback(S=>{S.preventDefault(),M(null),w==null||w(S)},[w]),O=u.useMemo(()=>new Map(t.map(S=>[S.id,S])),[t]),Z=S=>S.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=(S,P)=>({display:"flex",alignItems:"center",gap:8,padding:p?"4px 12px":"6px 12px",height:H,cursor:"pointer",background:P?"var(--accent-light, #dbeafe)":S?"var(--selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--border-subtle, #f3f4f6)",transition:"background 0.1s"}),z=E.length>0&&n.size===E.length;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:b?S=>{S.preventDefault(),S.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:S=>g(S.target.value),placeholder:"?? "+y("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:[E.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:z,onChange:W,style:{cursor:"pointer"}})}),s.jsx("div",{style:{width:20},children:"#"}),!p&&s.jsx("div",{style:{width:44}}),s.jsx(j,{field:"title",label:y("playlistManager.colTitle")}),s.jsx(j,{field:"artist",label:y("playlistManager.colArtist")}),!p&&s.jsx(j,{field:"album",label:y("playlistManager.colAlbum")}),s.jsx(j,{field:"duration",label:y("playlistManager.colDuration"),width:60}),!p&&s.jsx(j,{field:"year",label:y("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:[E.length===0&&s.jsx("div",{style:{padding:24,textAlign:"center",opacity:.4,fontSize:"0.85rem"},children:e.length===0?y("playlistManager.emptyPlaylist"):y("playlistManager.noMatchingTracks")}),E.map((S,P)=>{const $=n.has(S.id),T=k===P;return s.jsxs("div",{style:G($,T),onClick:C=>U(P,C),onDoubleClick:()=>a==null?void 0:a(S),draggable:v,onDragStart:C=>L(S,C),onDragOver:C=>I(P,C),onDrop:C=>q(P,C),onDragLeave:()=>M(null),children:[s.jsx("div",{style:{width:28},children:s.jsx("input",{type:"checkbox",checked:$,onChange:()=>{const C=new Set(n);$?C.delete(S.id):C.add(S.id),r(C)},onClick:C=>C.stopPropagation(),style:{cursor:"pointer"}})}),s.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:P+1}),!p&&s.jsx("div",{style:{width:44,height:36,flexShrink:0},children:S.coverUrl?s.jsx("img",{src:S.coverUrl,alt:S.title||y("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:S.title}),s.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",opacity:.7},children:S.artist}),!p&&s.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",opacity:.5},children:S.album}),s.jsx("div",{style:{width:60,fontSize:"0.78rem",opacity:.5,textAlign:"right"},children:ns(S.duration)}),!p&&s.jsx("div",{style:{width:50,fontSize:"0.72rem",opacity:.4,textAlign:"center"},children:S.year||""}),s.jsx("div",{style:{width:30,textAlign:"center",fontSize:"0.75rem"},title:S.source,children:th[S.source]??"?"}),!p&&s.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[S.tags.slice(0,2).map(C=>{const A=O.get(C);if(!A)return null;const D=`--tag-${Z(C)}`;return s.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${D}-bg, ${A.color}22)`,color:`var(${D}, ${A.color})`,whiteSpace:"nowrap"},children:A.name},C)}),S.tags.length>2&&s.jsxs("span",{style:{fontSize:"0.6rem",opacity:.4},children:["+",S.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(),R(N===S.id?null:S.id)},title:y("playlistManager.morActions"),children:"?"}),N===S.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:y("playlistManager.assignTag")}),t.map(C=>{const A=S.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:A?`var(--tag-${Z(C.id)}-bg, ${C.color}22)`:"transparent"},onClick:D=>{D.stopPropagation();const V=n.size>0?Array.from(n):[S.id];A||l==null||l(V,[C.id]),R(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}),A&&s.jsx("span",{style:{marginLeft:"auto"},children:"?"})]},C.id)})]})]})]},S.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:[E.length," ",y("playlistManager.tracks")]}),s.jsx("span",{children:ns(E.reduce((S,P)=>S+(P.duration??0),0))}),n.size>0&&s.jsxs("span",{children:[n.size," ",y("playlistManager.selected")]})]})]})},rs=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),Xo=({playlists:e=[],tags:t=[],onCopyTracks:n=()=>{},onMoveTracks:r=()=>{},onRemoveTracks:a=()=>{},onReorderTracks:o=()=>{},onPlay:i=()=>{},onTagTracks:l=()=>{},initialLeftId:c,initialRightId:d,library:h,queue:f,onAddToQueue:m,onRemoveFromQueue:g})=>{const{t:p}=xe(),[v,x]=u.useState(()=>rs(c??null)),[b,w]=u.useState(()=>rs(d??null)),[y,k]=u.useState("left"),[M,N]=u.useState(null),[R,_]=u.useState(50),[E,U]=u.useState(!1),W=u.useMemo(()=>e.find(T=>T.id===v.playlistId),[e,v.playlistId]),j=u.useMemo(()=>e.find(T=>T.id===b.playlistId),[e,b.playlistId]),L=u.useCallback((T,C)=>{T==="left"?x(A=>({...A,...C})):w(A=>({...A,...C}))},[]),I=u.useCallback(T=>T==="left"?v:b,[v,b]),q=T=>T==="left"?"right":"left",Y=u.useCallback(T=>{const C=I(T),A=I(q(T));!C.playlistId||!A.playlistId||C.selectedTrackIds.size===0||(n(C.playlistId,A.playlistId,Array.from(C.selectedTrackIds)),L(T,{selectedTrackIds:new Set}))},[I,n,L]),O=u.useCallback(T=>{const C=I(T),A=I(q(T));!C.playlistId||!A.playlistId||C.selectedTrackIds.size===0||(r(C.playlistId,A.playlistId,Array.from(C.selectedTrackIds)),L(T,{selectedTrackIds:new Set}))},[I,r,L]),Z=u.useCallback(T=>{const C=I(T);!C.playlistId||C.selectedTrackIds.size===0||N({operation:"copy",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[I]),H=u.useCallback(T=>{const C=I(T);!C.playlistId||C.selectedTrackIds.size===0||N({operation:"cut",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[I]),te=u.useCallback(T=>{const C=I(T);!M||!C.playlistId||(M.operation==="copy"?n(M.sourcePlaylistId,C.playlistId,M.trackIds):r(M.sourcePlaylistId,C.playlistId,M.trackIds),N(null))},[M,I,n,r]),G=u.useCallback(T=>{T.key==="Tab"&&!T.shiftKey&&(T.preventDefault(),k(C=>q(C))),(T.ctrlKey||T.metaKey)&&T.key==="c"&&Z(y),(T.ctrlKey||T.metaKey)&&T.key==="x"&&H(y),(T.ctrlKey||T.metaKey)&&T.key==="v"&&te(y)},[y,Z,H,te]),z=u.useCallback(()=>U(!0),[]),S=u.useCallback(T=>{if(!E)return;const C=T.currentTarget.getBoundingClientRect(),A=(T.clientX-C.left)/C.width*100;_(Math.max(20,Math.min(80,A)))},[E]),P=u.useCallback(()=>U(!1),[]),$=T=>{const C=I(T),A=T==="left"?W:j,D=y===T,Q=!!I(q(T)).playlistId;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",border:D?"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:D?"var(--accent, #3b82f6)":"var(--surface-bg, #f3f4f6)",color:D?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:s.jsxs("select",{value:C.playlistId??"",onChange:J=>L(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:D?"var(--accent-overlay, #ffffff30)":"var(--input-bg, #fff)",color:D?"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:kr(!1),onClick:()=>Y(T),disabled:!C.playlistId||!Q||C.selectedTrackIds.size===0,title:p("playlistManager.copyToOther"),children:["???"," ",p("playlistManager.copy")]}),s.jsxs("button",{style:kr(!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:kr(!0),onClick:()=>te(T),disabled:!C.playlistId,children:["?? ",p("playlistManager.paste")," (",M.trackIds.length,")"]})]}),A?s.jsx(ga,{tracks:A.tracks,tags:t,selectedTrackIds:C.selectedTrackIds,onSelectionChange:J=>L(T,{selectedTrackIds:J}),onPlay:i,onRemove:J=>a(A.id,J),onReorder:J=>o(A.id,J),onTagTracks:l,sortField:C.sortField,sortDir:C.sortDir,onSortChange:(J,ae)=>L(T,{sortField:J,sortDir:ae}),filterText:C.filterText,onFilterChange:J=>L(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:E?"none":"auto"},onKeyDown:G,onMouseMove:S,onMouseUp:P,tabIndex:0,children:[s.jsx("div",{style:{width:`${R}%`,minWidth:200},children:$("left")}),s.jsx("div",{style:{width:6,cursor:"col-resize",background:E?"var(--accent, #3b82f6)":"var(--border-color, #e5e7eb)",transition:E?"none":"background 0.15s",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseDown:z,children:s.jsx("div",{style:{width:2,height:40,borderRadius:1,background:E?"var(--btn-text, #fff)":"var(--text-secondary, #9ca3af)"}})}),s.jsx("div",{style:{flex:1,minWidth:200},children:$("right")})]})},kr=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"}),Qo="av:local-playlists";function nh(){try{const e=localStorage.getItem(Qo);return e?JSON.parse(e):[]}catch{return[]}}function rh(e){const t=JSON.stringify(e);try{localStorage.setItem(Qo,t)}catch{}}function ya(){const[e,t]=u.useState(()=>nh()),n=u.useRef(!1);return u.useEffect(()=>{n.current=!0},[]),u.useEffect(()=>{rh(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 ah=et.scoped("PlaylistList"),sh={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,background:"var(--nice-bg, #fff)"},oh={...sh,padding:"8px 10px",cursor:"pointer"},Jo={border:"1px solid var(--border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--bg, #fff)",cursor:"pointer"},ih={...Jo,background:"var(--primary, #4f46e5)",borderColor:"var(--primary, #4f46e5)",color:"var(--bg, #fff)"},ba=({selectedId:e,onSelect:t,onCreateRemote:n})=>{const{t:r}=xe(),a=ya(),[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()?ih:{...Jo,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){ah.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:{...oh,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 ↑")})]})]})},lh=et.scoped("PlaylistBrowser"),as={display:"grid",gap:12},ss=e=>({artist:(e.artists??[]).join(", "),title:e.title}),ei=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:n,tracks:r,view:a,onSelect:o,onPlay:i})=>{var x;const{t:l}=xe(),c=ya(),[d,h]=u.useState(null),[f,m]=u.useState(""),[,g]=u.useState([]),p=d==null?void 0:d.id,v=(b,w)=>{if("addItems"in c){c.addItems(b.id,w);const k=c.list().find(M=>M.id===b.id)||b;h(k);return}const y=c;if("update"in c&&typeof y.update=="function"){const k=Array.from([...b.items||[],...w]);y.update({...b,items:k});const M=c.list().find(N=>N.id===b.id)||{...b,items:k};h(M);return}lh.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:as,children:[s.jsx("h3",{style:{margin:0},children:l("playlistBrowser.playlists")}),s.jsx(ba,{selectedId:p,onSelect:h}),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:as,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,[ss(b)])}}),s.jsx("input",{placeholder:l("playlistBrowser.fullSearch","Full search (Enter does not add, full list below)"),value:f,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:f,onSelect:b=>{d&&v(d,[ss(b)])}}),n==null?void 0:n({onPlayNow:b=>g(b),onAddToQueue:b=>g(w=>[...w,...b]),onAddDescriptors:b=>d&&v(d,b)})]})]})};var Tt=(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))(Tt||{});const ti=(e,t=null)=>e.filter(n=>n.parentId===t).sort((n,r)=>n.sortOrder-r.sortOrder).map(n=>({...n,children:ti(e,n.id)})),ch={[Tt.Spotify]:{icon:"??",label:"Spotify",color:"var(--source-spotify, #1DB954)",bg:"var(--source-spotify-bg, #1DB95418)"},[Tt.Tidal]:{icon:"?",label:"Tidal",color:"var(--source-tidal, #000000)",bg:"var(--source-tidal-bg, #00000010)"},[Tt.YouTube]:{icon:"??",label:"YouTube",color:"var(--source-youtube, #FF0000)",bg:"var(--source-youtube-bg, #FF000010)"}},ni=({folders:e,playlists:t,tags:n,services:r,activeFolderId:a,activePlaylistId:o,onSelectFolder:i,onSelectPlaylist:l,onCreateFolder:c,onRenameFolder:d,onDeleteFolder:h,onCreatePlaylist:f,onConnectService:m,onDisconnectService:g,onDragPlaylistToFolder:p,collapsed:v=!1,onToggleCollapse:x})=>{const{t:b}=xe(),[w,y]=u.useState(new Set),[k,M]=u.useState(!1),[N,R]=u.useState(""),[_,E]=u.useState(null),[U,W]=u.useState(!1),[j,L]=u.useState(""),[I,q]=u.useState("static"),[Y,O]=u.useState(null),[Z,H]=u.useState(""),[te,G]=u.useState(null),[z,S]=u.useState(!1),P=u.useMemo(()=>ti(e),[e]),$=u.useCallback(X=>{y(ue=>{const ye=new Set(ue);return ye.has(X)?ye.delete(X):ye.add(X),ye})},[]),T=u.useCallback(()=>{N.trim()&&(c(N.trim(),_),R(""),M(!1))},[N,_,c]),C=u.useCallback(()=>{j.trim()&&(f(j.trim(),I,a),L(""),W(!1))},[j,I,a,f]),A=u.useCallback(X=>{Z.trim()&&(d(X,Z.trim()),O(null),H(""))},[Z,d]),D=u.useCallback((X,ue)=>{X.preventDefault(),X.dataTransfer.dropEffect="move",G(ue)},[]),V=u.useCallback((X,ue)=>{X.preventDefault();const ye=X.dataTransfer.getData("playlistId");ye&&p&&p(ye,ue),G(null)},[p]),Q=u.useCallback(()=>G(null),[]),J=u.useCallback(X=>t.filter(ue=>(ue.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,ue=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:ue?"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"}),F={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,ue)=>{var Se,ne;const ye=w.has(X.id),je=a===X.id,Fe=te===X.id,Re=J(X.id);return s.jsxs("div",{children:[s.jsxs("div",{style:{...ee(je,Fe),paddingLeft:12+ue*16},onClick:()=>{i(X.id),X.children&&X.children.length>0&&$(X.id)},onDragOver:oe=>D(oe,X.id),onDrop:oe=>V(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||Re.length>0?"?":"�"}),Y===X.id?s.jsx("input",{value:Z,onChange:oe=>H(oe.target.value),onKeyDown:oe=>{oe.key==="Enter"&&A(X.id),oe.key==="Escape"&&O(null)},onBlur:()=>A(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:Re.length}),s.jsx("button",{style:F,onClick:oe=>{oe.stopPropagation(),O(X.id),H(X.name)},title:b("common.rename"),children:"?"}),s.jsx("button",{style:{...F,color:"var(--error, #ef4444)"},onClick:oe=>{oe.stopPropagation(),h(X.id)},title:b("common.delete"),children:"?"})]})]}),ye&&s.jsxs(s.Fragment,{children:[Re.map(oe=>ce(oe,ue+1)),(ne=X.children)==null?void 0:ne.map(oe=>se(oe,ue+1))]})]},X.id)},ce=(X,ue)=>{const ye=o===X.id;return s.jsxs("div",{style:{...ee(ye),paddingLeft:12+ue*16+22},onClick:()=>l(X.id),draggable:!0,onDragStart:je=>{je.dataTransfer.setData("playlistId",X.id),je.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:{...F,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:x,title:b("playlistManager.expandSidebar"),children:"?"})});const fe=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:F,onClick:x,title:b("playlistManager.collapseSidebar"),children:"?"})]}),s.jsxs("div",{style:{...re,display:"flex",gap:4,flexWrap:"wrap"},children:[s.jsxs("button",{style:{...F,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:6,padding:"4px 10px"},onClick:()=>W(!0),children:["+ ",b("playlistManager.newPlaylist")]}),s.jsxs("button",{style:{...F,border:"1px solid var(--border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{M(!0),E(a)},children:["?? ",b("playlistManager.newFolder")]})]}),U&&s.jsxs("div",{style:{...re,display:"flex",flexDirection:"column",gap:6},children:[s.jsx("input",{value:j,onChange:X=>L(X.target.value),placeholder:b("playlistManager.playlistName"),style:K,autoFocus:!0,onKeyDown:X=>{X.key==="Enter"&&C(),X.key==="Escape"&&W(!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:I==="static",onChange:()=>q("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:I==="dynamic",onChange:()=>q("dynamic")}),"? ",b("playlistManager.dynamic")]}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{style:{...F,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:F,onClick:()=>W(!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=>R(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:{...F,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:F,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=>D(X,null),onDrop:X=>V(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})]}),fe.map(X=>ce(X,0)),P.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:()=>S(!z),children:[s.jsxs("span",{children:["?? ",b("playlistManager.services")]}),s.jsx("span",{children:"?"})]}),z&&s.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[Tt.Spotify,Tt.Tidal,Tt.YouTube].map(X=>{const ue=ch[X],ye=r.find(je=>je.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:ue.icon}),s.jsx("span",{style:{flex:1},children:ue.label}),ye!=null&&ye.connected?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:"0.65rem",opacity:.6},children:ye.username??b("playlistManager.connected")}),s.jsx("button",{style:{...F,color:"var(--nice-danger, #ef4444)"},onClick:()=>g(X),children:"?"})]}):s.jsx("button",{style:{...F,background:ue.color,color:"var(--nice-bg, #fff)",borderRadius:4,padding:"2px 8px"},onClick:()=>m(X),children:b("playlistManager.connect")})]},X)})})]})]})},dh=({playlist:e,tags:t,onPlay:n,selectedTrackIds:r,onSelectionChange:a})=>{const{t:o}=xe(),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)})})},ri=u.memo(dh),os=e=>e.replace(/[^a-z0-9_-]/gi,"-"),is={background:"none",border:"none",cursor:"pointer",fontSize:"0.78rem",padding:"2px 4px",opacity:.4},uh=({playlists:e,folders:t,tags:n,activeFolderId:r,onSelectPlaylist:a,onDeletePlaylist:o,onDuplicatePlaylist:i})=>{const{t:l}=xe(),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 f;const h=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===ma.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"),h&&` � ?? ${h.name}`]}),((f=d.tags)==null?void 0:f.length)>0&&s.jsx("div",{style:{display:"flex",gap:4,marginTop:6,flexWrap:"wrap"},children:d.tags.slice(0,3).map(m=>{const g=n.find(p=>p.id===m);return g?s.jsx("span",{style:{padding:"1px 8px",borderRadius:12,background:`var(--tag-${os(m)}-bg, ${g.color}18)`,color:`var(--tag-${os(m)}, ${g.color})`,fontSize:"0.65rem",fontWeight:500},children:g.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:is,title:l("playlistManager.duplicate"),children:"??"}),s.jsx("button",{onClick:m=>{m.stopPropagation(),o(d.id)},style:is,title:l("playlistManager.delete"),children:"??"})]})]},d.id)})})},ai=u.memo(uh),ls=[{value:lt.Library,label:"Library",icon:"??",hex:"var(--nice-info, #6366f1)",css:"var(--source-library, #6366f1)",cssBg:"var(--source-library-bg, #6366f118)"},{value:lt.Spotify,label:"Spotify",icon:"??",hex:"var(--nice-success, #1db954)",css:"var(--source-spotify, #1db954)",cssBg:"var(--source-spotify-bg, #1db95418)"},{value:lt.Tidal,label:"Tidal",icon:"?",hex:"var(--nice-text, #000000)",css:"var(--source-tidal, #000000)",cssBg:"var(--source-tidal-bg, #00000018)"},{value:lt.YouTube,label:"YouTube",icon:"??",hex:"var(--nice-danger, #ff0000)",css:"var(--source-youtube, #ff0000)",cssBg:"var(--source-youtube-bg, #ff000018)"},{value:lt.MusicBrainz,label:"MusicBrainz",icon:"??",hex:"#ba478f",css:"var(--source-musicbrainz, #ba478f)",cssBg:"var(--source-musicbrainz-bg, #ba478f18)"}],si=({onSearch:e,results:t,isSearching:n,onAddToPlaylist:r,onPlayPreview:a})=>{const{t:o}=xe(),[i,l]=u.useState(""),[c,d]=u.useState(new Set([lt.Library,lt.Spotify,lt.Tidal,lt.YouTube])),[h,f]=u.useState(new Set),[m,g]=u.useState(!1),p=u.useRef(null),v=u.useCallback(R=>{d(_=>{const E=new Set(_);return E.has(R)?E.delete(R):E.add(R),E})},[]),x=u.useCallback(R=>{l(R),p.current&&clearTimeout(p.current),R.trim().length>=2&&(p.current=setTimeout(()=>{e(R.trim(),Array.from(c))},350))},[c,e]),b=u.useCallback(R=>{R.preventDefault(),i.trim().length>=2&&e(i.trim(),Array.from(c))},[i,c,e]),w=u.useCallback(R=>{f(_=>{const E=new Set(_);return E.has(R)?E.delete(R):E.add(R),E})},[]),y=u.useCallback(()=>{h.size===t.length?f(new Set):f(new Set(t.map(R=>R.id)))},[h,t]),k=u.useCallback(()=>{const R=t.filter(_=>h.has(_.id));R.length>0&&(r(R),f(new Set))},[t,h,r]),M=R=>{if(!R)return"--:--";const _=Math.floor(R/60),E=R%60;return`${_}:${E.toString().padStart(2,"0")}`},N=R=>{const _=ls.find(E=>E.value===R);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:()=>g(!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:ls.map(R=>{const _=c.has(R.value);return s.jsxs("button",{onClick:()=>v(R.value),style:{padding:"4px 10px",borderRadius:20,border:_?`2px solid ${R.css}`:"1px solid var(--border-color, #d1d5db)",background:_?R.cssBg:"transparent",color:_?R.css:"var(--text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:_?600:400,transition:"all 0.15s"},children:[R.icon," ",R.label]},R.value)})}),s.jsxs("form",{onSubmit:b,style:{display:"flex",gap:6,marginBottom:8},children:[s.jsx("input",{type:"text",value:i,onChange:R=>x(R.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:h.size===t.length&&t.length>0,onChange:y}),o("playlistManager.selectAll")]}),s.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[t.length," ",o("playlistManager.results")]}),s.jsx("div",{style:{flex:1}}),h.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")," (",h.size,")"]})]}),s.jsx("div",{style:{maxHeight:300,overflowY:"auto",borderRadius:6,border:"1px solid var(--border-color, #e5e7eb)"},children:t.map(R=>s.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:()=>w(R.id),children:[s.jsx("input",{type:"checkbox",checked:h.has(R.id),readOnly:!0}),s.jsx("span",{children:N(R.source)}),R.imageUrl&&s.jsx("img",{src:R.imageUrl,alt:R.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:R.title}),s.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[R.artist,R.album?` � ${R.album}`:""]})]}),s.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:M(R.duration)}),a&&s.jsx("button",{onClick:_=>{_.stopPropagation(),a(R)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem"},title:o("playlistManager.preview"),children:"?"})]},R.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")})]})]})},hh=[{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)"}],fh={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},ph={display:"flex",justifyContent:"space-between",alignItems:"center"},mh={display:"flex",gap:4,marginBottom:8},bn={padding:"8px 20px",borderRadius:6,border:"none",background:"var(--accent, #6366f1)",color:"var(--nice-bg, #fff)",cursor:"pointer",fontWeight:600},Dn={...bn,background:"transparent",color:"var(--text, #334155)",border:"1px solid var(--border, #e2e8f0)"},cs={padding:12,borderRadius:8,border:"1px solid var(--border, #e2e8f0)",cursor:"pointer",transition:"border-color 0.15s"},oi=["connect","browse","tracks","options","importing","done"];function gh(e){return oi.indexOf(e)}function yh(e){if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const ii=({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}=xe(),[h,f]=u.useState("connect"),[m,g]=u.useState(null),[p,v]=u.useState([]),[x,b]=u.useState(null),[w,y]=u.useState([]),[k,M]=u.useState(new Set),[N,R]=u.useState(!1),[_,E]=u.useState(null),[U,W]=u.useState(null),[j,L]=u.useState(null),[I,q]=u.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[Y,O]=u.useState(""),Z=u.useMemo(()=>new Set(e.filter(F=>F.connected).map(F=>F.platform)),[e]),H=u.useCallback(F=>e.find(K=>K.platform===F),[e]),te=u.useCallback(F=>{if(g(F),F===99){f("tracks"),O(""),y([]),R(!1);return}Z.has(F)?(f("browse"),R(!0),L(null),r(F).then(K=>{v(K),R(!1)}).catch(K=>{L(String(K)),R(!1)})):t(F)},[Z,t,r]),G=u.useCallback(F=>{b(F),f("tracks"),R(!0),L(null),a(F).then(K=>{y(K),M(new Set(K.map(se=>se.externalId))),R(!1)}).catch(K=>{L(String(K)),R(!1)})},[a]),z=u.useCallback(F=>{M(K=>{const se=new Set(K);return se.has(F)?se.delete(F):se.add(F),se})},[]),S=u.useCallback(()=>{M(F=>F.size===w.length?new Set:new Set(w.map(K=>K.externalId)))},[w]),P=u.useCallback(async()=>{if(!x)return;const F=w.filter(K=>k.has(K.externalId));if(F.length!==0){f("importing"),E({total:F.length,imported:0,skipped:0,failed:0}),L(null);try{const K=await o(x,F,I),se=K&&typeof K=="object"&&"imported"in K?K:{playlistName:x.name,imported:F.length,skipped:0,failed:0,failedTracks:[]};W(se),f("done")}catch(K){L(String(K)),f("options")}}},[x,w,k,I,o]),$=h!=="connect"&&h!=="importing"&&h!=="done",T=u.useCallback(()=>{switch(h){case"browse":f("connect");break;case"tracks":f("browse");break;case"options":f("tracks");break}},[h]),C=()=>s.jsx("div",{style:mh,children:oi.map((F,K)=>s.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:K<=gh(h)?"var(--accent, #6366f1)":"var(--border, #e2e8f0)",transition:"background 0.2s"}},F))}),A=()=>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")}),hh.map(F=>{const K=H(F.value),se=Z.has(F.value);return s.jsxs("div",{style:{...cs,display:"flex",alignItems:"center",gap:12,borderColor:se?F.color:void 0},onClick:()=>te(F.value),role:"button",tabIndex:0,onKeyDown:ce=>ce.key==="Enter"&&te(F.value),children:[s.jsx("span",{style:{fontSize:24},children:F.icon}),s.jsxs("div",{style:{flex:1},children:[s.jsx("strong",{children:F.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:F.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")})]},F.value)})]}),D=()=>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(F=>s.jsxs("div",{style:{...cs,display:"flex",alignItems:"center",gap:12},onClick:()=>G(F),role:"button",tabIndex:0,onKeyDown:K=>K.key==="Enter"&&G(F),children:[F.coverUrl&&s.jsx("img",{src:F.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:F.name}),F.description&&s.jsx("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:F.description})]}),s.jsxs("span",{style:{fontSize:12,color:"var(--text-dim, #64748b)",whiteSpace:"nowrap"},children:[F.trackCount," ",d("importWizard.tracks","tracks")]})]},F.id)),p.length===0&&s.jsx("div",{style:{textAlign:"center",padding:24,color:"var(--text-dim, #64748b)"},children:d("importWizard.noPlaylists","No playlists found")})]})]}),V=u.useCallback(F=>{const se=F.split(`
51
51
  `).map(ce=>ce.trim()).filter(Boolean).map((ce,fe)=>{const X=ce.match(/^(.+?)\s*[-–—]\s*(.+)$/);return X?{externalId:`paste-${fe}`,title:X[2].trim(),artist:X[1].trim(),album:void 0,duration:0}:{externalId:`paste-${fe}`,title:ce,artist:"",album:void 0,duration:0}});y(se),M(new Set(se.map(ce=>ce.externalId)))},[]),Q=()=>s.jsxs("div",{style:{display:"grid",gap:12},children:[m===99&&w.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:F=>O(F.target.value),placeholder:`Daft Punk - Get Lucky
52
52
  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:{...bn,opacity:Y.trim().length===0?.5:1},disabled:Y.trim().length===0,onClick:()=>V(Y),type:"button",children:d("importWizard.parseTracks","Parse Tracks")})]}),(m!==99||w.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,"/",w.length," ",d("importWizard.selected","selected")]}),s.jsx("button",{style:Dn,onClick:S,type:"button",children:k.size===w.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:w.map(F=>{const K=k.has(F.externalId);return s.jsxs("tr",{style:{borderBottom:"1px solid var(--border, #e2e8f0)",opacity:K?1:.5,cursor:"pointer"},onClick:()=>z(F.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:F.title}),s.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:F.artist}),s.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:F.album??"—"}),s.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--text-dim, #64748b)"},children:yh(F.duration)})]},F.externalId)})})]})}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsxs("button",{style:{...bn,opacity:k.size===0?.5:1},disabled:k.size===0,onClick:()=>f("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:I.mergeTags,onChange:F=>q(K=>({...K,mergeTags:F.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:I.mergeFolders,onChange:F=>q(K=>({...K,mergeFolders:F.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:I.overwriteExisting,onChange:F=>q(K=>({...K,overwriteExisting:F.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:I.targetFolderId??"",onChange:F=>q(K=>({...K,targetFolderId:F.target.value||void 0})),children:[s.jsx("option",{value:"",children:d("importWizard.root","— Root —")}),l.map(F=>s.jsx("option",{value:F.id,children:F.name},F.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:Dn,onClick:T,type:"button",children:d("importWizard.back","← Back")}),s.jsx("button",{style:bn,onClick:P,type:"button",children:d("importWizard.startImport","Start Import")})]})]}),ae=()=>{const F=_?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:`${F}%`,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")}),U&&s.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[s.jsxs("div",{children:[s.jsx("strong",{children:U.imported})," ",d("importWizard.imported","imported")]}),U.skipped>0&&s.jsxs("div",{style:{color:"var(--warning, #f59e0b)"},children:[U.skipped," ",d("importWizard.skipped","skipped (duplicates)")]}),U.failed>0&&s.jsxs("div",{style:{color:"var(--error, #ef4444)"},children:[U.failed," ",d("importWizard.failed","failed")]}),U.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:U.failedTracks.map((F,K)=>s.jsx("li",{children:F},K))})]})]}),s.jsx("button",{style:bn,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:fh,children:[C(),s.jsxs("div",{style:ph,children:[s.jsxs("h2",{style:{margin:0,fontSize:18},children:[d("importWizard.title","Import Playlist")," — ",ee[h]]}),$&&s.jsxs("button",{style:Dn,onClick:T,type:"button",children:["← ",d("importWizard.back","Back")]}),h==="connect"&&s.jsx("button",{style:Dn,onClick:i,type:"button",children:"✕"})]}),j&&s.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--error-bg, #fef2f2)",color:"var(--error, #ef4444)",fontSize:13},children:j}),h==="connect"&&A(),h==="browse"&&D(),h==="tracks"&&Q(),h==="options"&&J(),h==="importing"&&ae(),h==="done"&&re()]})},bh=[{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}],vh="concert-harp",va=Object.fromEntries(bh.map(e=>[e.id,e])),xh="nice2dev-note-sound-set";function li(){try{const e=localStorage.getItem(xh);if(e&&va[e])return e}catch{}return vh}function ds(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function ci(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 Mr(e,t){const n=ci(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function Sh(e){const t=ci(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function di(){const e=ds("--text-primary")||"rgba(255,255,255,0.95)",t=ds("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",a=Sh(e)<.45;return{base:Mr(e,.92),staffLine:Mr(e,.22),outline:a?"rgba(255,255,255,0.75)":"rgba(0,0,0,0.55)",accents:[Mr(t,.95)],isDark:n,notesDark:a}}const hr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),ui=46,ct=5,Hn=4,wh=(ui-(ct-1)*Hn)/2,Ch=6,kh=18,Mh=110,jh=50,fr=hr?jh:Mh,Rh=hr?4:2,$h=hr?2:4,us=hr?1:0,Th=180,hs=2.8,fs=40,Ph=14,ps=1.2,Eh=16,jr=[64,67,71,74,77],Wt=64,vn=77;function Ah(e){const t=Math.max(0,Math.min(ct-1,e)),n=Math.floor(t),r=Math.min(n+1,ct-1),a=t-n;return Math.round(jr[n]+(jr[r]-jr[n])*a)}function Nh(e){return(Math.max(Wt-1*(vn-Wt)/(ct-1),Math.min(vn+1*(vn-Wt)/(ct-1),e))-Wt)/(vn-Wt)*(ct-1)}const ms=2.5,gs=.72,Ih=.55,xn=new Map;let Kn=null;async function Lh(e){const t=e??li(),n=va[t];if(!n||!n.dir){xn.clear(),Kn=t;return}if(Kn===t&&xn.size>0)return;xn.clear(),Kn=t;const r=tn(),a=[];for(let o=Wt;o<=vn;o++)a.push(fetch(`/assets/soundfonts/notes/${n.dir}/note-${o}.mp3`).then(i=>i.arrayBuffer()).then(i=>r.decodeAudioData(i)).then(i=>{xn.set(o,i)}).catch(()=>{}));await Promise.all(a)}function ys(e){const t=xn.get(e);if(!t)return;const n=tn(),r=n.createBufferSource();r.buffer=t;const a=n.createGain();a.gain.value=.7,r.connect(a).connect(n.destination),r.start()}const bs=["𝅘𝅥","𝅘𝅥𝅮","𝅘𝅥𝅯","𝅘𝅥𝅰","𝅘𝅥𝅱","♪","♫","♬"];function Fh(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 Dh(e){const t=Fh(42),n=[];for(let r=0;r<e;r++){const o=t()<.15?0:-1;n.push({x:t(),lineIdx:t()*(ct+1)-.5,char:bs[Math.floor(t()*bs.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:o})}return n.sort((r,a)=>r.x-a.x),n}const Je=Dh(fr),on=new Float32Array(fr),On=new Float32Array(fr),Sn=new Float32Array(fr);let Br=!1;const Oh=(ct-1)/2;function _h(){if(!Br){Br=!0;for(let e=0;e<Je.length;e++)Sn[e]=Je[e].lineIdx}}let Gr=[],vs="";function zh(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function Bh(e){const t=zh(e);t===vs&&Gr.length===Je.length||(vs=t,Gr=Je.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 hi({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),h=u.useRef(!1),f=u.useCallback((v,x,b)=>{const w=wh+v*Hn,y=x/b*Math.PI*2;return w+Math.sin(y)*Ch},[]),m=u.useCallback(v=>{const x=t.current;if(!x)return;if(l.current++,us>0&&l.current%(us+1)!==0){a.current=v,n.current=requestAnimationFrame(m);return}const b=x.getContext("2d");if(!b)return;const w=Math.min(window.devicePixelRatio||1,$h),y=x.getBoundingClientRect(),k=y.width,M=y.height;(x.width!==Math.round(k*w)||x.height!==Math.round(M*w))&&(x.width=Math.round(k*w),x.height=Math.round(M*w),b.setTransform(w,0,0,w,0,0));const N=a.current?(v-a.current)/1e3:0;a.current=v,r.current=(r.current+kh*N)%k,b.clearRect(0,0,k,M),i.current++,(!o.current||i.current%60===0)&&(o.current=di());const R=o.current;Bh(R),b.strokeStyle=R.staffLine,b.lineWidth=.7;for(let W=0;W<ct;W++){b.beginPath();for(let j=0;j<=k;j+=Rh){const L=f(W,j,k);j===0?b.moveTo(j,L):b.lineTo(j,L)}b.stroke()}const _=r.current,E=(e==null?void 0:e.current)??null;if(E!==null){_h();const W=Nh(E),j=ms*N;for(let L=0;L<Je.length;L++){const q=(Je[L].lineIdx-Oh)*Ih,O=W*gs+(W+q)*(1-gs)-Sn[L];Sn[L]+=O>0?Math.min(j,O):Math.max(-j,O)}}else if(Br){const W=ms*.4*N;for(let j=0;j<Je.length;j++){const I=Je[j].lineIdx-Sn[j];Sn[j]+=I>0?Math.min(W,I):Math.max(-W,I)}}const U=c.current;U&&(U.timer-=N,U.timer<=0&&(c.current=null));for(let W=0;W<Je.length;W++){const j=Je[W];if(On[W]>0){On[W]-=N;const q=Math.max(0,On[W]/hs);on[W]+=Th*q*N,on[W]>k&&(on[W]-=k)}const L=Gr[W];if(!L)continue;const I=j.lineIdx;for(let q=0;q<2;q++){let O=((j.x*k-_-on[W]+q*k)%k+k)%k;const Z=f(Math.max(0,Math.min(ct-1,Math.round(I))),O,k),H=(I-Math.round(I))*Hn;let te=Z+H;if(U&&U.timer>0){const B=O-U.x,z=te-U.y,S=Math.sqrt(B*B+z*z);if(S<fs&&S>.1){const P=U.timer/ps,$=Ph*(1-S/fs)*P;O+=B/S*$,te+=z/S*$}}b.drawImage(L.canvas,O-L.ox,te-L.oy)}}n.current=requestAnimationFrame(m)},[f]),g=u.useCallback(v=>{const x=t.current;if(!x)return;const b=x.getBoundingClientRect(),w=v.clientX-b.left,y=v.clientY-b.top,k=b.width,M=r.current;let N=1/0,R=-1;for(let _=0;_<Je.length;_++){const E=Je[_],W=((E.x*k-M-on[_])%k+k)%k,j=f(Math.max(0,Math.min(ct-1,Math.round(E.lineIdx))),W,k),L=(E.lineIdx-Math.round(E.lineIdx))*Hn,I=j+L,q=W-w,Y=I-y,O=q*q+Y*Y;O<N&&(N=O,R=_)}if(R>=0&&Math.sqrt(N)<Eh){On[R]=hs;const _=Je[R],E=Ah(_.lineIdx);try{Et();const U=li(),W=va[U];W!=null&&W.dir&&(Kn!==U||!h.current?(h.current=!0,Lh(U).then(()=>ys(E))):ys(E))}catch{}}c.current={x:w,y,timer:ps}},[f]),p=u.useCallback(v=>{const x=t.current;if(!x)return;const b=x.getBoundingClientRect(),w=v.clientX-b.left,y=v.clientY-b.top;d.current={x:w,y},c.current&&c.current.timer>0&&(c.current.x=w,c.current.y=y)},[]);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:g,onMouseMove:p,style:{display:"block",width:"100%",height:ui,marginBottom:5,cursor:"pointer",background:"transparent"}})}const Gh=14,Wh=.9,Uh=320,Vh=160,qh=6,xs=8,Hh=14,Ss=["♪","♫","♬","𝅘𝅥𝅮","𝅘𝅥𝅯"];function fi(){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,h)=>{for(let f=0;f<Gh;f++){const m=Math.random()*Math.PI*2,g=Vh*(.4+Math.random()*.6),p=Wh*(.6+Math.random()*.4),v=Math.random()<.15?0:-1;t.current.push({x:d,y:h,vx:Math.cos(m)*g,vy:Math.sin(m)*g-60,rot:Math.random()*Math.PI*2,vr:(Math.random()-.5)*qh*2,size:xs+Math.random()*(Hh-xs),char:Ss[Math.floor(Math.random()*Ss.length)],life:p,maxLife:p,colorIdx:v})}},[]),c=u.useCallback(d=>{const h=e.current;if(!h){n.current=requestAnimationFrame(c);return}const f=h.getContext("2d");if(!f){n.current=requestAnimationFrame(c);return}const m=window.devicePixelRatio||1,g=window.innerWidth,p=window.innerHeight;(h.width!==Math.round(g*m)||h.height!==Math.round(p*m))&&(h.width=Math.round(g*m),h.height=Math.round(p*m),h.style.width=`${g}px`,h.style.height=`${p}px`,f.setTransform(m,0,0,m,0,0));const v=r.current?Math.min((d-r.current)/1e3,.05):0;r.current=d,f.clearRect(0,0,g,p),i.current++,(!o.current||i.current%60===0)&&(o.current=di());const x=o.current;if(navigator.getGamepads){const w=navigator.getGamepads();for(let y=0;y<w.length;y++){const k=w[y];if(k)for(let M=0;M<k.buttons.length;M++){const N=y*100+M,R=k.buttons[M].pressed;R&&!a.current[N]&&l(g/2,p/2),a.current[N]=R}}}const b=[];f.textAlign="center",f.textBaseline="middle";for(const w of t.current){if(w.life-=v,w.life<=0)continue;w.vy+=Uh*v,w.x+=w.vx*v,w.y+=w.vy*v,w.rot+=w.vr*v;const y=Math.max(0,w.life/w.maxLife),k=.5+.5*y;f.save(),f.globalAlpha=y,f.translate(w.x,w.y),f.rotate(w.rot),f.font=`${w.size*k}px serif`,f.lineWidth=1.4,f.strokeStyle=x.notesDark?`rgba(255,255,255,${y*.8})`:`rgba(0,0,0,${y*.55})`,f.strokeText(w.char,0,0);const M=w.colorIdx<0?x.base:x.accents[w.colorIdx%x.accents.length];f.fillStyle=M.replace(/[\d.]+\)$/,`${y})`),f.fillText(w.char,0,0),f.restore(),b.push(w)}t.current=b,n.current=requestAnimationFrame(c)},[l]);return u.useEffect(()=>{const d=f=>{l(f.clientX,f.clientY)},h=f=>{if(f.key!=="Enter")return;const m=document.activeElement;if(m){const g=m.getBoundingClientRect();l(g.left+g.width/2,g.top+g.height/2)}else l(window.innerWidth/2,window.innerHeight/2)};return window.addEventListener("click",d,!0),window.addEventListener("keydown",h,!0),n.current=requestAnimationFrame(c),()=>{window.removeEventListener("click",d,!0),window.removeEventListener("keydown",h,!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 pi{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 h=n;return c.gain.setValueAtTime(0,h),c.gain.linearRampToValueAtTime(d,h+.01),c.gain.exponentialRampToValueAtTime(d*.7,h+.1),c.gain.setValueAtTime(d*.7,h+r-.05),c.gain.exponentialRampToValueAtTime(.001,h+r),l.start(h),l.stop(h+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 ws=et.scoped("AudioPlaybackEngine");class Kh{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){ws.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 h=d*2/a-1;o[d]=(3+r)*h*20*i/(Math.PI+r*Math.abs(h))}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 ws.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 pi(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 h of t.effectChain){const f=this.createEffectNode(h);if(f)if("input"in f&&"output"in f){const m=f;i.connect(m.input),i=m.output,"dry"in f&&a.connect(m.dry)}else i.connect(f),i=f}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,h=o.value,f=l.value,m=o.handleType||"linear",g=Math.max(2,Math.ceil((d-c)*20));for(let p=0;p<=g;++p){const v=p/g;let x=h;if(m==="linear")x=h+(f-h)*v;else if(m==="step")x=v<1?h:f;else if(m==="exp"){const k=Math.max(h/127,.001),M=Math.max(f/127,.001);x=k*Math.pow(M/k,v)*127}const b=c+(d-c)*v,w=this.audioContext.currentTime+(b-this.currentTime);w>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(l.cc,x,w)}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 Yh=[{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 pr(e={}){const{channelFilter:t,sysex:n=!1,onEvent:r,inputNameIncludes:a,onInputsChanged:o}=e,[i,l]=u.useState(null),[c,d]=u.useState(!1),[h,f]=u.useState([]),m=u.useRef(null),g=u.useCallback((p,v)=>{const x=p.data??new Uint8Array(0),b=x[0]??0,w=x[1]??0,y=x[2]??0,k=p.timeStamp,M=b&240,N=b&15,R=v.id,_=v.name??"MIDI Input",E=t===void 0||t===N;if((M===144||M===128)&&E){const U=M===144&&y>0;return{type:U?"noteon":"noteoff",note:w,velocity:U?y:0,channel:N,ts:k,deviceId:R,deviceName:_}}return M===176&&E?{type:"cc",controller:w,value:y,channel:N,ts:k,deviceId:R,deviceName:_}:M===208&&E?{type:"aftertouch",pressure:w,channel:N,ts:k,deviceId:R,deviceName:_}:M===224&&E?{type:"pitchbend",value:(w|y<<7)-8192,channel:N,ts:k,deviceId:R,deviceName:_}:M===192&&E?{type:"program",program:w,channel:N,ts:k,deviceId:R,deviceName:_}:{type:"unknown",status:b,data1:w,data2:y,channel:N,ts:k,deviceId:R,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()),w=a?b.filter(y=>(y.name||"").toUpperCase().includes(a.toUpperCase())):b;f(w),o==null||o(w),b.forEach(y=>y.onmidimessage=null),w.forEach(y=>{y.onmidimessage=k=>r==null?void 0:r(g(k,y))})};x(),v.onstatechange=()=>x()}),()=>{p=!0;const v=m.current;v&&(v.inputs.forEach(x=>x.onmidimessage=null),v.onstatechange=null)}},[a,r,o,g,n]),{supported:i,granted:c,inputs:h}}const xa="nice2dev.midiLearn";function Zh(){try{const e=localStorage.getItem(xa);return e?JSON.parse(e):{}}catch{return{}}}function Cs(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(xa,JSON.stringify(t))}function Xh(e){const{parameters:t,onParameterChange:n}=e,[r,a]=u.useState(()=>{const y=Zh();return t.map(k=>{const M=y[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 h=u.useRef(n);h.current=n;const f=u.useRef(o);f.current=o;const m=u.useCallback(y=>{var M;c(y);const k=f.current;if(k.learning&&k.targetId){if(!d.current.find(_=>_.id===k.targetId))return;let R={};switch(y.type){case"cc":R={type:"cc",number:y.controller,channel:y.channel};break;case"noteon":R={type:"note",number:y.note,channel:y.channel};break;case"pitchbend":R={type:"pitchbend",channel:y.channel};break;case"aftertouch":R={type:"aftertouch",channel:y.channel};break;default:return}a(_=>{const E=_.map(U=>U.id===k.targetId?{...U,...R}:U);return Cs(E),E}),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&&y.channel!==N.channel)continue;let R=null,_=127;if(N.type==="cc"&&y.type==="cc"&&y.controller===N.number?R=y.value:N.type==="note"&&y.type==="noteon"&&y.note===N.number?R=y.velocity:N.type==="pitchbend"&&y.type==="pitchbend"?(R=y.value+8192,_=16383):N.type==="aftertouch"&&y.type==="aftertouch"&&(R=y.pressure),R!==null){const E=R/_,U=N.min+E*(N.max-N.min);a(W=>W.map(j=>j.id===N.id?{...j,value:E}:j)),(M=h.current)==null||M.call(h,N.id,U,E)}}},[]),{supported:g,granted:p}=pr({onEvent:m}),v=u.useCallback(y=>{i({learning:!0,targetId:y})},[]),x=u.useCallback(()=>{i({learning:!1,targetId:null})},[]),b=u.useCallback(y=>{a(k=>{const M=k.map(N=>N.id===y?{...N,type:"cc",number:void 0,channel:void 0}:N);return Cs(M),M})},[]),w=u.useCallback(()=>{a(y=>{const k=y.map(M=>({...M,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(xa),k})},[]);return{bindings:r,startLearn:v,cancelLearn:x,removeBinding:b,clearAll:w,learnState:o,midiSupported:g,midiGranted:p,lastEvent:l}}const Qh={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function Jh(e={}){const{lowerZone:t=Qh,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 h=u.useRef(a);h.current=a;const f=u.useRef(new Set(t.memberChannels));u.useEffect(()=>{f.current=new Set(t.memberChannels)},[t.memberChannels]);const m=u.useCallback(v=>{var b,w,y,k,M;if(!f.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())),(w=h.current)==null||w.call(h,v.channel,v.note);break}case"pitchbend":{const N=l.current.get(x);N&&(N.pitchBend=v.value,N.lastUpdate=v.ts,(y=c.current)==null||y.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:g,granted:p}=pr({onEvent:m,sysex:!1});return{activeNotes:o,midiSupported:g,midiGranted:p}}const ef={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 tf(e={},t=ef){const[n,r]=u.useState(()=>{const g=localStorage.getItem("oxygen25.layout");return g?JSON.parse(g):t}),[a,o]=u.useState([]),i=u.useRef({mode:"idle"}),l=u.useCallback(g=>{r(p=>{const v={...p,...g};return localStorage.setItem("oxygen25.layout",JSON.stringify(v)),v})},[]),c=u.useCallback(g=>{var x,b,w,y,k,M,N,R,_;const p=g.deviceName||"MIDI";o(E=>E.includes(p)?E:[...E,p]);const v=i.current;if(v.mode!=="idle"){if(v.mode==="knob"&&g.type==="cc"){const E=v.index;l({knobs:n.knobs.map(U=>U.index===E?{...U,cc:g.controller}:U)}),i.current={mode:"idle"};return}if(v.mode==="fader"&&g.type==="cc"){l({fader:{cc:g.controller,label:"Fader"}}),i.current={mode:"idle"};return}if(v.mode==="pad"&&g.type==="noteon"){const E=n.pads.slice();E[v.padIdx]={...E[v.padIdx],note:g.note},l({pads:E}),i.current={mode:"idle"};return}if(v.mode==="transport"&&g.type==="cc"){const E={...n.transport};E[v.action]=g.controller,l({transport:E}),i.current={mode:"idle"};return}}switch(g.type){case"noteon":{n.pads.findIndex(U=>U.note===g.note)>=0?(x=e.onPad)==null||x.call(e,{note:g.note,velocity:g.velocity,ts:g.ts,device:p}):(b=e.onKey)==null||b.call(e,{note:g.note,velocity:g.velocity,ts:g.ts,device:p});break}case"cc":{if(n.fader&&g.controller===n.fader.cc){(w=e.onFader)==null||w.call(e,{cc:g.controller,value:g.value,ts:g.ts,device:p});break}const E=n.knobs.find(W=>W.cc===g.controller);if(E){(y=e.onKnob)==null||y.call(e,{index:E.index,cc:g.controller,value:g.value,ts:g.ts,device:p});break}const U=Object.keys(n.transport).find(W=>n.transport[W]===g.controller);if(U){(k=e.onTransport)==null||k.call(e,{action:U,value:g.value,ts:g.ts,device:p});break}(M=e.onUnknown)==null||M.call(e,g);break}case"pitchbend":(N=e.onPitchBend)==null||N.call(e,{value:g.value,ts:g.ts,device:p});break;case"aftertouch":(R=e.onAftertouch)==null||R.call(e,{pressure:g.pressure,ts:g.ts,device:p});break;default:(_=e.onUnknown)==null||_.call(e,g)}},[l,e,n]),{supported:d,granted:h,inputs:f}=pr({inputNameIncludes:void 0,onEvent:c,sysex:!1,channelFilter:void 0,onInputsChanged:g=>o(g.map(p=>p.name||"MIDI"))}),m=u.useMemo(()=>({knob:g=>i.current={mode:"knob",index:g},fader:()=>i.current={mode:"fader"},pad:g=>i.current={mode:"pad",padIdx:g},transport:g=>i.current={mode:"transport",action:g},cancel:()=>i.current={mode:"idle"},state:()=>i.current}),[]);return{supported:d,granted:h,inputs:f,layout:n,setLayout:l,learn:m,inputsInfo:a}}const Wr={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],mixolydian:[0,2,4,5,7,9,10],pentatonic:[0,2,4,7,9],minorPenta:[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11]},nf=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Ur={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]]},_t=36,ln=38,pt=42,zt=51,rf=49,Vr={basic:[{step:0,pitch:_t,vel:110},{step:0,pitch:pt,vel:80},{step:2,pitch:pt,vel:70},{step:4,pitch:ln,vel:100},{step:4,pitch:pt,vel:80},{step:6,pitch:pt,vel:70},{step:8,pitch:_t,vel:100},{step:10,pitch:pt,vel:70},{step:12,pitch:ln,vel:100},{step:12,pitch:pt,vel:80},{step:14,pitch:pt,vel:70}],rock:[{step:0,pitch:_t,vel:120},{step:0,pitch:rf,vel:90},{step:4,pitch:ln,vel:110},{step:4,pitch:pt,vel:80},{step:8,pitch:_t,vel:110},{step:8,pitch:pt,vel:80},{step:10,pitch:_t,vel:90},{step:12,pitch:ln,vel:110},{step:12,pitch:pt,vel:80}],swing:[{step:0,pitch:zt,vel:90},{step:3,pitch:zt,vel:70},{step:4,pitch:zt,vel:80},{step:8,pitch:zt,vel:90},{step:11,pitch:zt,vel:70},{step:12,pitch:zt,vel:80},{step:4,pitch:_t,vel:80},{step:12,pitch:ln,vel:70}]},mi={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function af(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 gi=1;const _n=()=>gi++,yi=e=>60/e,sf=e=>yi(e)/4;function Rr(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 bi(e=mi){gi=1;const t=e.seed>0?af(e.seed):Math.random,n=Wr[e.scale]??Wr.pentatonic,r=Ur[e.progression]??Ur.pop,a=Vr[e.drumPattern]??Vr.basic,o=yi(e.tempo),i=sf(e.tempo),l=Math.max(1,e.bars),c=16,d=[],h=[],f=[],m=[];let g=0;for(let p=0;p<l;p++){const v=p*4*o,x=p%r.length,b=r[x];for(const y of b)f.push({id:_n(),pitch:Rr(e.root,n,y,e.octave-1),start:v,duration:4*o-.01,velocity:70+Math.floor(t()*20)});const w=b[0];for(let y=0;y<4;y++){const k=y===2?w+(t()>.5?2:0):w;h.push({id:_n(),pitch:Rr(e.root,n,k,e.octave-2),start:v+y*o,duration:o*.9,velocity:80+Math.floor(t()*30)})}for(let y=0;y<c;y++){if(t()>e.density)continue;const k=v+y*i,M=t()>.8?t()>.5?2:-2:t()>.5?1:-1;g=Math.max(-3,Math.min(n.length+3,g+M));const N=1+Math.floor(t()*3);d.push({id:_n(),pitch:Rr(e.root,n,g,e.octave),start:k,duration:N*i*.95,velocity:85+Math.floor(t()*30)})}for(const y of a)m.push({id:_n(),pitch:y.pitch,start:v+y.step*i,duration:i*.8,velocity:y.vel+Math.floor(t()*10-5)})}return{melody:d,bass:h,chords:f,drums:m,config:e}}const of=Object.keys(Wr),lf=Object.keys(Ur),cf=Object.keys(Vr),df=bi;function Le(e,t,n){return{cc:e,paramId:n,label:`Knob ${t}`,controlType:"knob",min:0,max:127,inverted:!1}}function jn(e,t,n){return{cc:e,paramId:n,label:t,controlType:"fader",min:0,max:127,inverted:!1}}function Bt(e,t,n){return{cc:e,paramId:n,label:t,controlType:"button",min:0,max:127,inverted:!1}}const vi={id:"oxygen25",name:"M-Audio Oxygen 25 (MkIV)",deviceMatch:"OXYGEN",mappings:[Le(21,1,"mixer.volume"),Le(22,2,"mixer.pan"),Le(23,3,"fx.reverb"),Le(24,4,"fx.delay"),Le(25,5,"fx.chorus"),Le(26,6,"fx.filter"),Le(27,7,"fx.drive"),Le(28,8,"fx.eq"),jn(7,"Master Fader","mixer.master"),Bt(115,"Play","transport.play"),Bt(114,"Stop","transport.stop"),Bt(117,"Record","transport.record"),Bt(112,"Rewind","transport.rewind"),Bt(113,"Forward","transport.forward"),Bt(116,"Loop","transport.loop")]},xi={id:"mpk-mini",name:"Akai MPK Mini",deviceMatch:"MPK",mappings:[Le(1,1,"mixer.volume"),Le(2,2,"mixer.pan"),Le(3,3,"fx.reverb"),Le(4,4,"fx.delay"),Le(5,5,"fx.chorus"),Le(6,6,"fx.filter"),Le(7,7,"fx.drive"),Le(8,8,"fx.eq")]},Si={id:"minilab",name:"Arturia MiniLab",deviceMatch:"Arturia MiniLab",mappings:[Le(7,1,"mixer.volume"),Le(74,2,"mixer.pan"),Le(71,3,"fx.reverb"),Le(76,4,"fx.delay"),Le(77,5,"fx.chorus"),Le(93,6,"fx.filter"),Le(73,7,"fx.drive"),Le(75,8,"fx.eq"),jn(1,"Mod Wheel","mixer.master")]},wi={id:"launch-control-xl",name:"Novation Launch Control XL",deviceMatch:"Launch Control",mappings:[...Array.from({length:8},(e,t)=>Le(13+t,t+1,`mixer.send${t+1}`)),...Array.from({length:8},(e,t)=>jn(77+t,`Fader ${t+1}`,`mixer.track${t+1}`))]},Sa={id:"generic",name:"Generic MIDI Controller",deviceMatch:"",mappings:[Le(1,1,"mixer.modWheel"),jn(7,"Volume","mixer.volume"),Le(10,2,"mixer.pan"),jn(11,"Expression","mixer.expression")]},Ci=[vi,xi,Si,wi,Sa];class uf{constructor(t){this.ccMap=new Map,this.onChange=null,this.profile=t??Sa,this.rebuildMap()}setProfile(t){this.profile=t,this.rebuildMap()}getProfile(){return this.profile}autoDetect(t){const n=t.toUpperCase(),r=Ci.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 ki(e){return{past:[],present:e,future:[]}}function Mi(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function ji(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 Ri(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 $i(e){return e.past.length>0}function Ti(e){return e.future.length>0}function qr(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>({...n}))}function Pi(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 Ei(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 Ai(e,t){return e.filter(n=>n.time<t.start||n.time>t.end)}function hf(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>n.id)}function Ni(e,t,n,r){const a={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:r};return[...e,a]}function Ii(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 Li(e){return JSON.stringify(e,null,2)}function Fi(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 rt(e,t){var n;return((n=e.find(r=>r.layerId===t))==null?void 0:n.events)??[]}function mt(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 ff(e,t){switch(t.type){case"UNDO":return ji(e);case"REDO":return Ri(e);default:{let n=e.present;switch(t.type){case"ADD_EVENT":{const r=[...rt(n,t.layerId),t.event];n=mt(n,t.layerId,r);break}case"UPDATE_EVENT":{const r=rt(n,t.layerId).map(a=>a.id===t.id?{...a,value:t.value,time:t.time,handleType:t.handleType??a.handleType}:a);n=mt(n,t.layerId,r);break}case"REMOVE_EVENT":{const r=rt(n,t.layerId).filter(a=>a.id!==t.id);n=mt(n,t.layerId,r);break}case"SET_EVENTS":n=mt(n,t.layerId,t.events);break;case"PASTE":{const r=rt(n,t.layerId),a=Pi(r,t.clipboard,t.targetTime);n=mt(n,t.layerId,a);break}case"CUT":{const r=rt(n,t.layerId),{remaining:a}=Ei(r,t.range);n=mt(n,t.layerId,a);break}case"DELETE_RANGE":{const r=rt(n,t.layerId),a=Ai(r,t.range);n=mt(n,t.layerId,a);break}case"RECORD":{const r=rt(n,t.layerId),a=Ni(r,t.cc,t.value,t.time);n=mt(n,t.layerId,a);break}case"THIN":{const r=rt(n,t.layerId),a=Ii(r,t.keepEveryN);n=mt(n,t.layerId,a);break}case"IMPORT":{const r=Fi(t.json);r.length>0&&(n=mt(n,t.layerId,r));break}}return Mi(e,n)}}}function pf(e=[]){const[t,n]=u.useReducer(ff,ki(e)),r=u.useRef([]),a=u.useCallback(y=>rt(t.present,y),[t.present]),o=u.useCallback((y,k)=>n({type:"ADD_EVENT",layerId:y,event:k}),[]),i=u.useCallback((y,k,M,N,R)=>n({type:"UPDATE_EVENT",layerId:y,id:k,value:M,time:N,handleType:R}),[]),l=u.useCallback((y,k)=>n({type:"REMOVE_EVENT",layerId:y,id:k}),[]),c=u.useCallback((y,k)=>n({type:"SET_EVENTS",layerId:y,events:k}),[]),d=u.useCallback(()=>n({type:"UNDO"}),[]),h=u.useCallback(()=>n({type:"REDO"}),[]),f=u.useCallback((y,k)=>{r.current=qr(rt(t.present,y),k)},[t.present]),m=u.useCallback((y,k)=>{r.current=qr(rt(t.present,y),k),n({type:"CUT",layerId:y,range:k})},[t.present]),g=u.useCallback((y,k)=>{r.current.length>0&&n({type:"PASTE",layerId:y,clipboard:r.current,targetTime:k})},[]),p=u.useCallback((y,k)=>n({type:"DELETE_RANGE",layerId:y,range:k}),[]),v=u.useCallback((y,k,M,N)=>n({type:"RECORD",layerId:y,cc:k,value:M,time:N}),[]),x=u.useCallback((y,k)=>n({type:"THIN",layerId:y,keepEveryN:k}),[]),b=u.useCallback(y=>Li(rt(t.present,y)),[t.present]),w=u.useCallback((y,k)=>n({type:"IMPORT",layerId:y,json:k}),[]);return{snapshots:t.present,getEvents:a,addEvent:o,updateEvent:i,removeEvent:l,setEvents:c,undo:d,redo:h,canUndo:$i(t),canRedo:Ti(t),copy:f,cut:m,paste:g,clipboard:r.current,deleteRange:p,record:v,thin:x,exportLane:b,importLane:w}}function wa(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function Nt(e="New Pattern",t=16,n=120){return{name:e,length:t,steps:Array.from({length:t},()=>wa()),bpm:n,swing:0,rootNote:60}}function Di(e,t){const n=e.steps.map((r,a)=>a===t?{...r,active:!r.active}:r);return{...e,steps:n}}function Oi(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 _i(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 zi(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 Bi(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 Gi(e,t){const n=e.steps.map((r,a)=>a===t?{...r,slide:!r.slide}:r);return{...e,steps:n}}function Wi(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 Ui(e){return{...e,steps:[...e.steps].reverse()}}function Vi(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 qi(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 Hi(e){return{...e,steps:e.steps.map(()=>wa(e.rootNote))}}function Ca(e,t=4){return 60/e/t}function Ki(e,t,n=0,r=4){const a=Ca(t,r),o=e*a;return e%2===1&&n>0?o+a*n*.5:o}function Yi(e){return e.active&&Math.random()<e.probability}function mf(){const e=Nt("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function gf(){const e=Nt("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function yf(){const e=Nt("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 bf(e=60){const t=Nt("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 vf(e=36){const t=Nt("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 xf(e){return JSON.stringify(e,null,2)}function Sf(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function wf(e={}){const{onTrigger:t,onLFOOutput:n,initialPattern:r}=e,[a,o]=u.useState(()=>r??Nt()),[i,l]=u.useState(-1),[c,d]=u.useState(!1),[h,f]=u.useState([]),m=u.useRef(a);m.current=a;const g=u.useRef(h);g.current=h;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),w=u.useRef(0),y=u.useRef(0),k=u.useCallback(()=>{var Q,J;if(!p.current)return;const $=m.current,T=w.current%$.length,C=$.steps[T];if(Yi(C)){const ae=Ki(w.current,$.bpm,$.swing);(Q=v.current)==null||Q.call(v,C,T,ae)}const A=(Date.now()-y.current)/1e3;for(let ae=0;ae<g.current.length;ae++){const re=g.current[ae];if(re.enabled&&re.targetCC!==void 0){const ee=Xr(re,A,$.bpm);(J=x.current)==null||J.call(x,ae,re.targetCC,ee)}}l(T),w.current++;const D=Ca($.bpm)*1e3,V=T%2===0?0:D*$.swing*.5;b.current=setTimeout(k,D+V)},[]),M=u.useCallback(()=>{p.current||(w.current=0,y.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)},[]),R=u.useCallback(()=>{p.current?N():M()},[M,N]);u.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const _=u.useCallback($=>o(T=>Di(T,$)),[]),E=u.useCallback(($,T)=>o(C=>Oi(C,$,T)),[]),U=u.useCallback(($,T)=>o(C=>_i(C,$,T)),[]),W=u.useCallback(($,T)=>o(C=>zi(C,$,T)),[]),j=u.useCallback(($,T)=>o(C=>Bi(C,$,T)),[]),L=u.useCallback($=>o(T=>Gi(T,$)),[]),I=u.useCallback($=>o(T=>Wi(T,$)),[]),q=u.useCallback(()=>o($=>Ui($)),[]),Y=u.useCallback($=>o(T=>Vi(T,$)),[]),O=u.useCallback(($,T)=>o(C=>qi(C,$,T)),[]),Z=u.useCallback(()=>o($=>Hi($)),[]),H=u.useCallback($=>o(T=>({...T,bpm:Math.max(20,Math.min(300,$))})),[]),te=u.useCallback($=>o(T=>({...T,swing:Math.max(0,Math.min(1,$))})),[]),B=u.useCallback($=>{o(T=>{if(T.length===$)return T;const C=Array.from({length:$},(A,D)=>D<T.steps.length?T.steps[D]:{active:!1,note:T.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...T,length:$,steps:C}})},[]),z=u.useCallback($=>{f(T=>[...T,$??ir()])},[]),S=u.useCallback($=>{f(T=>T.filter((C,A)=>A!==$))},[]),P=u.useCallback(($,T)=>{f(C=>C.map((A,D)=>D===$?{...A,...T}:A))},[]);return{pattern:a,currentStep:i,playing:c,lfos:h,play:M,stop:N,togglePlayback:R,toggle:_,setNote:E,setVelocity:U,setGate:W,setProbability:j,toggleSlide:L,transpose:I,reverse:q,shift:Y,randomizeVel:O,clear:Z,setPattern:o,setBpm:H,setSwing:te,setLength:B,addLFO:z,removeLFO:S,updateLFO:P}}function ka(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(()=>()=>{var i;(i=t.current)==null||i.terminate(),t.current=null;for(const[,l]of n.current)l.reject(new Error("Worker terminated on unmount"));n.current.clear()},[]),u.useCallback((i,l)=>{const c=r.current++,d=a();return new Promise((h,f)=>{n.current.set(c,{resolve:h,reject:f}),d.postMessage({...i,id:c},l??[])})},[a])}function Cf(){const e=ka(u.useCallback(()=>new Worker(new URL("/assets/pitchWorker-BgAp5Z97.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:st&&st.tagName.toUpperCase()==="SCRIPT"&&st.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 kf(){const e=ka(u.useCallback(()=>new Worker(new URL("/assets/scoringWorker-B1PkYu_m.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:st&&st.tagName.toUpperCase()==="SCRIPT"&&st.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 Mf={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function Zi(){return`
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:{...bn,opacity:Y.trim().length===0?.5:1},disabled:Y.trim().length===0,onClick:()=>V(Y),type:"button",children:d("importWizard.parseTracks","Parse Tracks")})]}),(m!==99||w.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,"/",w.length," ",d("importWizard.selected","selected")]}),s.jsx("button",{style:Dn,onClick:S,type:"button",children:k.size===w.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:w.map(F=>{const K=k.has(F.externalId);return s.jsxs("tr",{style:{borderBottom:"1px solid var(--border, #e2e8f0)",opacity:K?1:.5,cursor:"pointer"},onClick:()=>z(F.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:F.title}),s.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:F.artist}),s.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:F.album??"—"}),s.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--text-dim, #64748b)"},children:yh(F.duration)})]},F.externalId)})})]})}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsxs("button",{style:{...bn,opacity:k.size===0?.5:1},disabled:k.size===0,onClick:()=>f("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:I.mergeTags,onChange:F=>q(K=>({...K,mergeTags:F.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:I.mergeFolders,onChange:F=>q(K=>({...K,mergeFolders:F.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:I.overwriteExisting,onChange:F=>q(K=>({...K,overwriteExisting:F.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:I.targetFolderId??"",onChange:F=>q(K=>({...K,targetFolderId:F.target.value||void 0})),children:[s.jsx("option",{value:"",children:d("importWizard.root","— Root —")}),l.map(F=>s.jsx("option",{value:F.id,children:F.name},F.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:Dn,onClick:T,type:"button",children:d("importWizard.back","← Back")}),s.jsx("button",{style:bn,onClick:P,type:"button",children:d("importWizard.startImport","Start Import")})]})]}),ae=()=>{const F=_?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:`${F}%`,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")}),U&&s.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[s.jsxs("div",{children:[s.jsx("strong",{children:U.imported})," ",d("importWizard.imported","imported")]}),U.skipped>0&&s.jsxs("div",{style:{color:"var(--warning, #f59e0b)"},children:[U.skipped," ",d("importWizard.skipped","skipped (duplicates)")]}),U.failed>0&&s.jsxs("div",{style:{color:"var(--error, #ef4444)"},children:[U.failed," ",d("importWizard.failed","failed")]}),U.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:U.failedTracks.map((F,K)=>s.jsx("li",{children:F},K))})]})]}),s.jsx("button",{style:bn,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:fh,children:[C(),s.jsxs("div",{style:ph,children:[s.jsxs("h2",{style:{margin:0,fontSize:18},children:[d("importWizard.title","Import Playlist")," — ",ee[h]]}),$&&s.jsxs("button",{style:Dn,onClick:T,type:"button",children:["← ",d("importWizard.back","Back")]}),h==="connect"&&s.jsx("button",{style:Dn,onClick:i,type:"button",children:"✕"})]}),j&&s.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--error-bg, #fef2f2)",color:"var(--error, #ef4444)",fontSize:13},children:j}),h==="connect"&&A(),h==="browse"&&D(),h==="tracks"&&Q(),h==="options"&&J(),h==="importing"&&ae(),h==="done"&&re()]})},bh=[{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}],vh="concert-harp",va=Object.fromEntries(bh.map(e=>[e.id,e])),xh="nice2dev-note-sound-set";function li(){try{const e=localStorage.getItem(xh);if(e&&va[e])return e}catch{}return vh}function ds(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function ci(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 Mr(e,t){const n=ci(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function Sh(e){const t=ci(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function di(){const e=ds("--text-primary")||"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",t=ds("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",a=Sh(e)<.45;return{base:Mr(e,.92),staffLine:Mr(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:[Mr(t,.95)],isDark:n,notesDark:a}}const hr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),ui=46,ct=5,Hn=4,wh=(ui-(ct-1)*Hn)/2,Ch=6,kh=18,Mh=110,jh=50,fr=hr?jh:Mh,Rh=hr?4:2,$h=hr?2:4,us=hr?1:0,Th=180,hs=2.8,fs=40,Ph=14,ps=1.2,Eh=16,jr=[64,67,71,74,77],Wt=64,vn=77;function Ah(e){const t=Math.max(0,Math.min(ct-1,e)),n=Math.floor(t),r=Math.min(n+1,ct-1),a=t-n;return Math.round(jr[n]+(jr[r]-jr[n])*a)}function Nh(e){return(Math.max(Wt-1*(vn-Wt)/(ct-1),Math.min(vn+1*(vn-Wt)/(ct-1),e))-Wt)/(vn-Wt)*(ct-1)}const ms=2.5,gs=.72,Ih=.55,xn=new Map;let Kn=null;async function Lh(e){const t=e??li(),n=va[t];if(!n||!n.dir){xn.clear(),Kn=t;return}if(Kn===t&&xn.size>0)return;xn.clear(),Kn=t;const r=tn(),a=[];for(let o=Wt;o<=vn;o++)a.push(fetch(`/assets/soundfonts/notes/${n.dir}/note-${o}.mp3`).then(i=>i.arrayBuffer()).then(i=>r.decodeAudioData(i)).then(i=>{xn.set(o,i)}).catch(()=>{}));await Promise.all(a)}function ys(e){const t=xn.get(e);if(!t)return;const n=tn(),r=n.createBufferSource();r.buffer=t;const a=n.createGain();a.gain.value=.7,r.connect(a).connect(n.destination),r.start()}const bs=["𝅘𝅥","𝅘𝅥𝅮","𝅘𝅥𝅯","𝅘𝅥𝅰","𝅘𝅥𝅱","♪","♫","♬"];function Fh(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 Dh(e){const t=Fh(42),n=[];for(let r=0;r<e;r++){const o=t()<.15?0:-1;n.push({x:t(),lineIdx:t()*(ct+1)-.5,char:bs[Math.floor(t()*bs.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:o})}return n.sort((r,a)=>r.x-a.x),n}const Je=Dh(fr),on=new Float32Array(fr),On=new Float32Array(fr),Sn=new Float32Array(fr);let Gr=!1;const Oh=(ct-1)/2;function _h(){if(!Gr){Gr=!0;for(let e=0;e<Je.length;e++)Sn[e]=Je[e].lineIdx}}let Br=[],vs="";function zh(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function Gh(e){const t=zh(e);t===vs&&Br.length===Je.length||(vs=t,Br=Je.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 hi({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),h=u.useRef(!1),f=u.useCallback((v,x,b)=>{const w=wh+v*Hn,y=x/b*Math.PI*2;return w+Math.sin(y)*Ch},[]),m=u.useCallback(v=>{const x=t.current;if(!x)return;if(l.current++,us>0&&l.current%(us+1)!==0){a.current=v,n.current=requestAnimationFrame(m);return}const b=x.getContext("2d");if(!b)return;const w=Math.min(window.devicePixelRatio||1,$h),y=x.getBoundingClientRect(),k=y.width,M=y.height;(x.width!==Math.round(k*w)||x.height!==Math.round(M*w))&&(x.width=Math.round(k*w),x.height=Math.round(M*w),b.setTransform(w,0,0,w,0,0));const N=a.current?(v-a.current)/1e3:0;a.current=v,r.current=(r.current+kh*N)%k,b.clearRect(0,0,k,M),i.current++,(!o.current||i.current%60===0)&&(o.current=di());const R=o.current;Gh(R),b.strokeStyle=R.staffLine,b.lineWidth=.7;for(let W=0;W<ct;W++){b.beginPath();for(let j=0;j<=k;j+=Rh){const L=f(W,j,k);j===0?b.moveTo(j,L):b.lineTo(j,L)}b.stroke()}const _=r.current,E=(e==null?void 0:e.current)??null;if(E!==null){_h();const W=Nh(E),j=ms*N;for(let L=0;L<Je.length;L++){const q=(Je[L].lineIdx-Oh)*Ih,O=W*gs+(W+q)*(1-gs)-Sn[L];Sn[L]+=O>0?Math.min(j,O):Math.max(-j,O)}}else if(Gr){const W=ms*.4*N;for(let j=0;j<Je.length;j++){const I=Je[j].lineIdx-Sn[j];Sn[j]+=I>0?Math.min(W,I):Math.max(-W,I)}}const U=c.current;U&&(U.timer-=N,U.timer<=0&&(c.current=null));for(let W=0;W<Je.length;W++){const j=Je[W];if(On[W]>0){On[W]-=N;const q=Math.max(0,On[W]/hs);on[W]+=Th*q*N,on[W]>k&&(on[W]-=k)}const L=Br[W];if(!L)continue;const I=j.lineIdx;for(let q=0;q<2;q++){let O=((j.x*k-_-on[W]+q*k)%k+k)%k;const Z=f(Math.max(0,Math.min(ct-1,Math.round(I))),O,k),H=(I-Math.round(I))*Hn;let te=Z+H;if(U&&U.timer>0){const G=O-U.x,z=te-U.y,S=Math.sqrt(G*G+z*z);if(S<fs&&S>.1){const P=U.timer/ps,$=Ph*(1-S/fs)*P;O+=G/S*$,te+=z/S*$}}b.drawImage(L.canvas,O-L.ox,te-L.oy)}}n.current=requestAnimationFrame(m)},[f]),g=u.useCallback(v=>{const x=t.current;if(!x)return;const b=x.getBoundingClientRect(),w=v.clientX-b.left,y=v.clientY-b.top,k=b.width,M=r.current;let N=1/0,R=-1;for(let _=0;_<Je.length;_++){const E=Je[_],W=((E.x*k-M-on[_])%k+k)%k,j=f(Math.max(0,Math.min(ct-1,Math.round(E.lineIdx))),W,k),L=(E.lineIdx-Math.round(E.lineIdx))*Hn,I=j+L,q=W-w,Y=I-y,O=q*q+Y*Y;O<N&&(N=O,R=_)}if(R>=0&&Math.sqrt(N)<Eh){On[R]=hs;const _=Je[R],E=Ah(_.lineIdx);try{Et();const U=li(),W=va[U];W!=null&&W.dir&&(Kn!==U||!h.current?(h.current=!0,Lh(U).then(()=>ys(E))):ys(E))}catch{}}c.current={x:w,y,timer:ps}},[f]),p=u.useCallback(v=>{const x=t.current;if(!x)return;const b=x.getBoundingClientRect(),w=v.clientX-b.left,y=v.clientY-b.top;d.current={x:w,y},c.current&&c.current.timer>0&&(c.current.x=w,c.current.y=y)},[]);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:g,onMouseMove:p,style:{display:"block",width:"100%",height:ui,marginBottom:5,cursor:"pointer",background:"transparent"}})}const Bh=14,Wh=.9,Uh=320,Vh=160,qh=6,xs=8,Hh=14,Ss=["♪","♫","♬","𝅘𝅥𝅮","𝅘𝅥𝅯"];function fi(){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,h)=>{for(let f=0;f<Bh;f++){const m=Math.random()*Math.PI*2,g=Vh*(.4+Math.random()*.6),p=Wh*(.6+Math.random()*.4),v=Math.random()<.15?0:-1;t.current.push({x:d,y:h,vx:Math.cos(m)*g,vy:Math.sin(m)*g-60,rot:Math.random()*Math.PI*2,vr:(Math.random()-.5)*qh*2,size:xs+Math.random()*(Hh-xs),char:Ss[Math.floor(Math.random()*Ss.length)],life:p,maxLife:p,colorIdx:v})}},[]),c=u.useCallback(d=>{const h=e.current;if(!h){n.current=requestAnimationFrame(c);return}const f=h.getContext("2d");if(!f){n.current=requestAnimationFrame(c);return}const m=window.devicePixelRatio||1,g=window.innerWidth,p=window.innerHeight;(h.width!==Math.round(g*m)||h.height!==Math.round(p*m))&&(h.width=Math.round(g*m),h.height=Math.round(p*m),h.style.width=`${g}px`,h.style.height=`${p}px`,f.setTransform(m,0,0,m,0,0));const v=r.current?Math.min((d-r.current)/1e3,.05):0;r.current=d,f.clearRect(0,0,g,p),i.current++,(!o.current||i.current%60===0)&&(o.current=di());const x=o.current;if(navigator.getGamepads){const w=navigator.getGamepads();for(let y=0;y<w.length;y++){const k=w[y];if(k)for(let M=0;M<k.buttons.length;M++){const N=y*100+M,R=k.buttons[M].pressed;R&&!a.current[N]&&l(g/2,p/2),a.current[N]=R}}}const b=[];f.textAlign="center",f.textBaseline="middle";for(const w of t.current){if(w.life-=v,w.life<=0)continue;w.vy+=Uh*v,w.x+=w.vx*v,w.y+=w.vy*v,w.rot+=w.vr*v;const y=Math.max(0,w.life/w.maxLife),k=.5+.5*y;f.save(),f.globalAlpha=y,f.translate(w.x,w.y),f.rotate(w.rot),f.font=`${w.size*k}px serif`,f.lineWidth=1.4,f.strokeStyle=x.notesDark?`rgba(255,255,255,${y*.8})`:`rgba(0,0,0,${y*.55})`,f.strokeText(w.char,0,0);const M=w.colorIdx<0?x.base:x.accents[w.colorIdx%x.accents.length];f.fillStyle=M.replace(/[\d.]+\)$/,`${y})`),f.fillText(w.char,0,0),f.restore(),b.push(w)}t.current=b,n.current=requestAnimationFrame(c)},[l]);return u.useEffect(()=>{const d=f=>{l(f.clientX,f.clientY)},h=f=>{if(f.key!=="Enter")return;const m=document.activeElement;if(m){const g=m.getBoundingClientRect();l(g.left+g.width/2,g.top+g.height/2)}else l(window.innerWidth/2,window.innerHeight/2)};return window.addEventListener("click",d,!0),window.addEventListener("keydown",h,!0),n.current=requestAnimationFrame(c),()=>{window.removeEventListener("click",d,!0),window.removeEventListener("keydown",h,!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 pi{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 h=n;return c.gain.setValueAtTime(0,h),c.gain.linearRampToValueAtTime(d,h+.01),c.gain.exponentialRampToValueAtTime(d*.7,h+.1),c.gain.setValueAtTime(d*.7,h+r-.05),c.gain.exponentialRampToValueAtTime(.001,h+r),l.start(h),l.stop(h+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 ws=et.scoped("AudioPlaybackEngine");class Kh{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){ws.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 h=d*2/a-1;o[d]=(3+r)*h*20*i/(Math.PI+r*Math.abs(h))}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 ws.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 pi(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 h of t.effectChain){const f=this.createEffectNode(h);if(f)if("input"in f&&"output"in f){const m=f;i.connect(m.input),i=m.output,"dry"in f&&a.connect(m.dry)}else i.connect(f),i=f}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,h=o.value,f=l.value,m=o.handleType||"linear",g=Math.max(2,Math.ceil((d-c)*20));for(let p=0;p<=g;++p){const v=p/g;let x=h;if(m==="linear")x=h+(f-h)*v;else if(m==="step")x=v<1?h:f;else if(m==="exp"){const k=Math.max(h/127,.001),M=Math.max(f/127,.001);x=k*Math.pow(M/k,v)*127}const b=c+(d-c)*v,w=this.audioContext.currentTime+(b-this.currentTime);w>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(l.cc,x,w)}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 Yh=[{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 pr(e={}){const{channelFilter:t,sysex:n=!1,onEvent:r,inputNameIncludes:a,onInputsChanged:o}=e,[i,l]=u.useState(null),[c,d]=u.useState(!1),[h,f]=u.useState([]),m=u.useRef(null),g=u.useCallback((p,v)=>{const x=p.data??new Uint8Array(0),b=x[0]??0,w=x[1]??0,y=x[2]??0,k=p.timeStamp,M=b&240,N=b&15,R=v.id,_=v.name??"MIDI Input",E=t===void 0||t===N;if((M===144||M===128)&&E){const U=M===144&&y>0;return{type:U?"noteon":"noteoff",note:w,velocity:U?y:0,channel:N,ts:k,deviceId:R,deviceName:_}}return M===176&&E?{type:"cc",controller:w,value:y,channel:N,ts:k,deviceId:R,deviceName:_}:M===208&&E?{type:"aftertouch",pressure:w,channel:N,ts:k,deviceId:R,deviceName:_}:M===224&&E?{type:"pitchbend",value:(w|y<<7)-8192,channel:N,ts:k,deviceId:R,deviceName:_}:M===192&&E?{type:"program",program:w,channel:N,ts:k,deviceId:R,deviceName:_}:{type:"unknown",status:b,data1:w,data2:y,channel:N,ts:k,deviceId:R,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()),w=a?b.filter(y=>(y.name||"").toUpperCase().includes(a.toUpperCase())):b;f(w),o==null||o(w),b.forEach(y=>y.onmidimessage=null),w.forEach(y=>{y.onmidimessage=k=>r==null?void 0:r(g(k,y))})};x(),v.onstatechange=()=>x()}),()=>{p=!0;const v=m.current;v&&(v.inputs.forEach(x=>x.onmidimessage=null),v.onstatechange=null)}},[a,r,o,g,n]),{supported:i,granted:c,inputs:h}}const xa="nice2dev.midiLearn";function Zh(){try{const e=localStorage.getItem(xa);return e?JSON.parse(e):{}}catch{return{}}}function Cs(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(xa,JSON.stringify(t))}function Xh(e){const{parameters:t,onParameterChange:n}=e,[r,a]=u.useState(()=>{const y=Zh();return t.map(k=>{const M=y[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 h=u.useRef(n);h.current=n;const f=u.useRef(o);f.current=o;const m=u.useCallback(y=>{var M;c(y);const k=f.current;if(k.learning&&k.targetId){if(!d.current.find(_=>_.id===k.targetId))return;let R={};switch(y.type){case"cc":R={type:"cc",number:y.controller,channel:y.channel};break;case"noteon":R={type:"note",number:y.note,channel:y.channel};break;case"pitchbend":R={type:"pitchbend",channel:y.channel};break;case"aftertouch":R={type:"aftertouch",channel:y.channel};break;default:return}a(_=>{const E=_.map(U=>U.id===k.targetId?{...U,...R}:U);return Cs(E),E}),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&&y.channel!==N.channel)continue;let R=null,_=127;if(N.type==="cc"&&y.type==="cc"&&y.controller===N.number?R=y.value:N.type==="note"&&y.type==="noteon"&&y.note===N.number?R=y.velocity:N.type==="pitchbend"&&y.type==="pitchbend"?(R=y.value+8192,_=16383):N.type==="aftertouch"&&y.type==="aftertouch"&&(R=y.pressure),R!==null){const E=R/_,U=N.min+E*(N.max-N.min);a(W=>W.map(j=>j.id===N.id?{...j,value:E}:j)),(M=h.current)==null||M.call(h,N.id,U,E)}}},[]),{supported:g,granted:p}=pr({onEvent:m}),v=u.useCallback(y=>{i({learning:!0,targetId:y})},[]),x=u.useCallback(()=>{i({learning:!1,targetId:null})},[]),b=u.useCallback(y=>{a(k=>{const M=k.map(N=>N.id===y?{...N,type:"cc",number:void 0,channel:void 0}:N);return Cs(M),M})},[]),w=u.useCallback(()=>{a(y=>{const k=y.map(M=>({...M,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(xa),k})},[]);return{bindings:r,startLearn:v,cancelLearn:x,removeBinding:b,clearAll:w,learnState:o,midiSupported:g,midiGranted:p,lastEvent:l}}const Qh={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function Jh(e={}){const{lowerZone:t=Qh,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 h=u.useRef(a);h.current=a;const f=u.useRef(new Set(t.memberChannels));u.useEffect(()=>{f.current=new Set(t.memberChannels)},[t.memberChannels]);const m=u.useCallback(v=>{var b,w,y,k,M;if(!f.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())),(w=h.current)==null||w.call(h,v.channel,v.note);break}case"pitchbend":{const N=l.current.get(x);N&&(N.pitchBend=v.value,N.lastUpdate=v.ts,(y=c.current)==null||y.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:g,granted:p}=pr({onEvent:m,sysex:!1});return{activeNotes:o,midiSupported:g,midiGranted:p}}const ef={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 tf(e={},t=ef){const[n,r]=u.useState(()=>{const g=localStorage.getItem("oxygen25.layout");return g?JSON.parse(g):t}),[a,o]=u.useState([]),i=u.useRef({mode:"idle"}),l=u.useCallback(g=>{r(p=>{const v={...p,...g};return localStorage.setItem("oxygen25.layout",JSON.stringify(v)),v})},[]),c=u.useCallback(g=>{var x,b,w,y,k,M,N,R,_;const p=g.deviceName||"MIDI";o(E=>E.includes(p)?E:[...E,p]);const v=i.current;if(v.mode!=="idle"){if(v.mode==="knob"&&g.type==="cc"){const E=v.index;l({knobs:n.knobs.map(U=>U.index===E?{...U,cc:g.controller}:U)}),i.current={mode:"idle"};return}if(v.mode==="fader"&&g.type==="cc"){l({fader:{cc:g.controller,label:"Fader"}}),i.current={mode:"idle"};return}if(v.mode==="pad"&&g.type==="noteon"){const E=n.pads.slice();E[v.padIdx]={...E[v.padIdx],note:g.note},l({pads:E}),i.current={mode:"idle"};return}if(v.mode==="transport"&&g.type==="cc"){const E={...n.transport};E[v.action]=g.controller,l({transport:E}),i.current={mode:"idle"};return}}switch(g.type){case"noteon":{n.pads.findIndex(U=>U.note===g.note)>=0?(x=e.onPad)==null||x.call(e,{note:g.note,velocity:g.velocity,ts:g.ts,device:p}):(b=e.onKey)==null||b.call(e,{note:g.note,velocity:g.velocity,ts:g.ts,device:p});break}case"cc":{if(n.fader&&g.controller===n.fader.cc){(w=e.onFader)==null||w.call(e,{cc:g.controller,value:g.value,ts:g.ts,device:p});break}const E=n.knobs.find(W=>W.cc===g.controller);if(E){(y=e.onKnob)==null||y.call(e,{index:E.index,cc:g.controller,value:g.value,ts:g.ts,device:p});break}const U=Object.keys(n.transport).find(W=>n.transport[W]===g.controller);if(U){(k=e.onTransport)==null||k.call(e,{action:U,value:g.value,ts:g.ts,device:p});break}(M=e.onUnknown)==null||M.call(e,g);break}case"pitchbend":(N=e.onPitchBend)==null||N.call(e,{value:g.value,ts:g.ts,device:p});break;case"aftertouch":(R=e.onAftertouch)==null||R.call(e,{pressure:g.pressure,ts:g.ts,device:p});break;default:(_=e.onUnknown)==null||_.call(e,g)}},[l,e,n]),{supported:d,granted:h,inputs:f}=pr({inputNameIncludes:void 0,onEvent:c,sysex:!1,channelFilter:void 0,onInputsChanged:g=>o(g.map(p=>p.name||"MIDI"))}),m=u.useMemo(()=>({knob:g=>i.current={mode:"knob",index:g},fader:()=>i.current={mode:"fader"},pad:g=>i.current={mode:"pad",padIdx:g},transport:g=>i.current={mode:"transport",action:g},cancel:()=>i.current={mode:"idle"},state:()=>i.current}),[]);return{supported:d,granted:h,inputs:f,layout:n,setLayout:l,learn:m,inputsInfo:a}}const Wr={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],mixolydian:[0,2,4,5,7,9,10],pentatonic:[0,2,4,7,9],minorPenta:[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11]},nf=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Ur={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]]},_t=36,ln=38,pt=42,zt=51,rf=49,Vr={basic:[{step:0,pitch:_t,vel:110},{step:0,pitch:pt,vel:80},{step:2,pitch:pt,vel:70},{step:4,pitch:ln,vel:100},{step:4,pitch:pt,vel:80},{step:6,pitch:pt,vel:70},{step:8,pitch:_t,vel:100},{step:10,pitch:pt,vel:70},{step:12,pitch:ln,vel:100},{step:12,pitch:pt,vel:80},{step:14,pitch:pt,vel:70}],rock:[{step:0,pitch:_t,vel:120},{step:0,pitch:rf,vel:90},{step:4,pitch:ln,vel:110},{step:4,pitch:pt,vel:80},{step:8,pitch:_t,vel:110},{step:8,pitch:pt,vel:80},{step:10,pitch:_t,vel:90},{step:12,pitch:ln,vel:110},{step:12,pitch:pt,vel:80}],swing:[{step:0,pitch:zt,vel:90},{step:3,pitch:zt,vel:70},{step:4,pitch:zt,vel:80},{step:8,pitch:zt,vel:90},{step:11,pitch:zt,vel:70},{step:12,pitch:zt,vel:80},{step:4,pitch:_t,vel:80},{step:12,pitch:ln,vel:70}]},mi={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function af(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 gi=1;const _n=()=>gi++,yi=e=>60/e,sf=e=>yi(e)/4;function Rr(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 bi(e=mi){gi=1;const t=e.seed>0?af(e.seed):Math.random,n=Wr[e.scale]??Wr.pentatonic,r=Ur[e.progression]??Ur.pop,a=Vr[e.drumPattern]??Vr.basic,o=yi(e.tempo),i=sf(e.tempo),l=Math.max(1,e.bars),c=16,d=[],h=[],f=[],m=[];let g=0;for(let p=0;p<l;p++){const v=p*4*o,x=p%r.length,b=r[x];for(const y of b)f.push({id:_n(),pitch:Rr(e.root,n,y,e.octave-1),start:v,duration:4*o-.01,velocity:70+Math.floor(t()*20)});const w=b[0];for(let y=0;y<4;y++){const k=y===2?w+(t()>.5?2:0):w;h.push({id:_n(),pitch:Rr(e.root,n,k,e.octave-2),start:v+y*o,duration:o*.9,velocity:80+Math.floor(t()*30)})}for(let y=0;y<c;y++){if(t()>e.density)continue;const k=v+y*i,M=t()>.8?t()>.5?2:-2:t()>.5?1:-1;g=Math.max(-3,Math.min(n.length+3,g+M));const N=1+Math.floor(t()*3);d.push({id:_n(),pitch:Rr(e.root,n,g,e.octave),start:k,duration:N*i*.95,velocity:85+Math.floor(t()*30)})}for(const y of a)m.push({id:_n(),pitch:y.pitch,start:v+y.step*i,duration:i*.8,velocity:y.vel+Math.floor(t()*10-5)})}return{melody:d,bass:h,chords:f,drums:m,config:e}}const of=Object.keys(Wr),lf=Object.keys(Ur),cf=Object.keys(Vr),df=bi;function Le(e,t,n){return{cc:e,paramId:n,label:`Knob ${t}`,controlType:"knob",min:0,max:127,inverted:!1}}function jn(e,t,n){return{cc:e,paramId:n,label:t,controlType:"fader",min:0,max:127,inverted:!1}}function Gt(e,t,n){return{cc:e,paramId:n,label:t,controlType:"button",min:0,max:127,inverted:!1}}const vi={id:"oxygen25",name:"M-Audio Oxygen 25 (MkIV)",deviceMatch:"OXYGEN",mappings:[Le(21,1,"mixer.volume"),Le(22,2,"mixer.pan"),Le(23,3,"fx.reverb"),Le(24,4,"fx.delay"),Le(25,5,"fx.chorus"),Le(26,6,"fx.filter"),Le(27,7,"fx.drive"),Le(28,8,"fx.eq"),jn(7,"Master Fader","mixer.master"),Gt(115,"Play","transport.play"),Gt(114,"Stop","transport.stop"),Gt(117,"Record","transport.record"),Gt(112,"Rewind","transport.rewind"),Gt(113,"Forward","transport.forward"),Gt(116,"Loop","transport.loop")]},xi={id:"mpk-mini",name:"Akai MPK Mini",deviceMatch:"MPK",mappings:[Le(1,1,"mixer.volume"),Le(2,2,"mixer.pan"),Le(3,3,"fx.reverb"),Le(4,4,"fx.delay"),Le(5,5,"fx.chorus"),Le(6,6,"fx.filter"),Le(7,7,"fx.drive"),Le(8,8,"fx.eq")]},Si={id:"minilab",name:"Arturia MiniLab",deviceMatch:"Arturia MiniLab",mappings:[Le(7,1,"mixer.volume"),Le(74,2,"mixer.pan"),Le(71,3,"fx.reverb"),Le(76,4,"fx.delay"),Le(77,5,"fx.chorus"),Le(93,6,"fx.filter"),Le(73,7,"fx.drive"),Le(75,8,"fx.eq"),jn(1,"Mod Wheel","mixer.master")]},wi={id:"launch-control-xl",name:"Novation Launch Control XL",deviceMatch:"Launch Control",mappings:[...Array.from({length:8},(e,t)=>Le(13+t,t+1,`mixer.send${t+1}`)),...Array.from({length:8},(e,t)=>jn(77+t,`Fader ${t+1}`,`mixer.track${t+1}`))]},Sa={id:"generic",name:"Generic MIDI Controller",deviceMatch:"",mappings:[Le(1,1,"mixer.modWheel"),jn(7,"Volume","mixer.volume"),Le(10,2,"mixer.pan"),jn(11,"Expression","mixer.expression")]},Ci=[vi,xi,Si,wi,Sa];class uf{constructor(t){this.ccMap=new Map,this.onChange=null,this.profile=t??Sa,this.rebuildMap()}setProfile(t){this.profile=t,this.rebuildMap()}getProfile(){return this.profile}autoDetect(t){const n=t.toUpperCase(),r=Ci.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 ki(e){return{past:[],present:e,future:[]}}function Mi(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function ji(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 Ri(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 $i(e){return e.past.length>0}function Ti(e){return e.future.length>0}function qr(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>({...n}))}function Pi(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 Ei(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 Ai(e,t){return e.filter(n=>n.time<t.start||n.time>t.end)}function hf(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>n.id)}function Ni(e,t,n,r){const a={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:r};return[...e,a]}function Ii(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 Li(e){return JSON.stringify(e,null,2)}function Fi(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 rt(e,t){var n;return((n=e.find(r=>r.layerId===t))==null?void 0:n.events)??[]}function mt(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 ff(e,t){switch(t.type){case"UNDO":return ji(e);case"REDO":return Ri(e);default:{let n=e.present;switch(t.type){case"ADD_EVENT":{const r=[...rt(n,t.layerId),t.event];n=mt(n,t.layerId,r);break}case"UPDATE_EVENT":{const r=rt(n,t.layerId).map(a=>a.id===t.id?{...a,value:t.value,time:t.time,handleType:t.handleType??a.handleType}:a);n=mt(n,t.layerId,r);break}case"REMOVE_EVENT":{const r=rt(n,t.layerId).filter(a=>a.id!==t.id);n=mt(n,t.layerId,r);break}case"SET_EVENTS":n=mt(n,t.layerId,t.events);break;case"PASTE":{const r=rt(n,t.layerId),a=Pi(r,t.clipboard,t.targetTime);n=mt(n,t.layerId,a);break}case"CUT":{const r=rt(n,t.layerId),{remaining:a}=Ei(r,t.range);n=mt(n,t.layerId,a);break}case"DELETE_RANGE":{const r=rt(n,t.layerId),a=Ai(r,t.range);n=mt(n,t.layerId,a);break}case"RECORD":{const r=rt(n,t.layerId),a=Ni(r,t.cc,t.value,t.time);n=mt(n,t.layerId,a);break}case"THIN":{const r=rt(n,t.layerId),a=Ii(r,t.keepEveryN);n=mt(n,t.layerId,a);break}case"IMPORT":{const r=Fi(t.json);r.length>0&&(n=mt(n,t.layerId,r));break}}return Mi(e,n)}}}function pf(e=[]){const[t,n]=u.useReducer(ff,ki(e)),r=u.useRef([]),a=u.useCallback(y=>rt(t.present,y),[t.present]),o=u.useCallback((y,k)=>n({type:"ADD_EVENT",layerId:y,event:k}),[]),i=u.useCallback((y,k,M,N,R)=>n({type:"UPDATE_EVENT",layerId:y,id:k,value:M,time:N,handleType:R}),[]),l=u.useCallback((y,k)=>n({type:"REMOVE_EVENT",layerId:y,id:k}),[]),c=u.useCallback((y,k)=>n({type:"SET_EVENTS",layerId:y,events:k}),[]),d=u.useCallback(()=>n({type:"UNDO"}),[]),h=u.useCallback(()=>n({type:"REDO"}),[]),f=u.useCallback((y,k)=>{r.current=qr(rt(t.present,y),k)},[t.present]),m=u.useCallback((y,k)=>{r.current=qr(rt(t.present,y),k),n({type:"CUT",layerId:y,range:k})},[t.present]),g=u.useCallback((y,k)=>{r.current.length>0&&n({type:"PASTE",layerId:y,clipboard:r.current,targetTime:k})},[]),p=u.useCallback((y,k)=>n({type:"DELETE_RANGE",layerId:y,range:k}),[]),v=u.useCallback((y,k,M,N)=>n({type:"RECORD",layerId:y,cc:k,value:M,time:N}),[]),x=u.useCallback((y,k)=>n({type:"THIN",layerId:y,keepEveryN:k}),[]),b=u.useCallback(y=>Li(rt(t.present,y)),[t.present]),w=u.useCallback((y,k)=>n({type:"IMPORT",layerId:y,json:k}),[]);return{snapshots:t.present,getEvents:a,addEvent:o,updateEvent:i,removeEvent:l,setEvents:c,undo:d,redo:h,canUndo:$i(t),canRedo:Ti(t),copy:f,cut:m,paste:g,clipboard:r.current,deleteRange:p,record:v,thin:x,exportLane:b,importLane:w}}function wa(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function Nt(e="New Pattern",t=16,n=120){return{name:e,length:t,steps:Array.from({length:t},()=>wa()),bpm:n,swing:0,rootNote:60}}function Di(e,t){const n=e.steps.map((r,a)=>a===t?{...r,active:!r.active}:r);return{...e,steps:n}}function Oi(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 _i(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 zi(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 Gi(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 Bi(e,t){const n=e.steps.map((r,a)=>a===t?{...r,slide:!r.slide}:r);return{...e,steps:n}}function Wi(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 Ui(e){return{...e,steps:[...e.steps].reverse()}}function Vi(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 qi(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 Hi(e){return{...e,steps:e.steps.map(()=>wa(e.rootNote))}}function Ca(e,t=4){return 60/e/t}function Ki(e,t,n=0,r=4){const a=Ca(t,r),o=e*a;return e%2===1&&n>0?o+a*n*.5:o}function Yi(e){return e.active&&Math.random()<e.probability}function mf(){const e=Nt("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function gf(){const e=Nt("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function yf(){const e=Nt("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 bf(e=60){const t=Nt("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 vf(e=36){const t=Nt("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 xf(e){return JSON.stringify(e,null,2)}function Sf(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function wf(e={}){const{onTrigger:t,onLFOOutput:n,initialPattern:r}=e,[a,o]=u.useState(()=>r??Nt()),[i,l]=u.useState(-1),[c,d]=u.useState(!1),[h,f]=u.useState([]),m=u.useRef(a);m.current=a;const g=u.useRef(h);g.current=h;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),w=u.useRef(0),y=u.useRef(0),k=u.useCallback(()=>{var Q,J;if(!p.current)return;const $=m.current,T=w.current%$.length,C=$.steps[T];if(Yi(C)){const ae=Ki(w.current,$.bpm,$.swing);(Q=v.current)==null||Q.call(v,C,T,ae)}const A=(Date.now()-y.current)/1e3;for(let ae=0;ae<g.current.length;ae++){const re=g.current[ae];if(re.enabled&&re.targetCC!==void 0){const ee=Xr(re,A,$.bpm);(J=x.current)==null||J.call(x,ae,re.targetCC,ee)}}l(T),w.current++;const D=Ca($.bpm)*1e3,V=T%2===0?0:D*$.swing*.5;b.current=setTimeout(k,D+V)},[]),M=u.useCallback(()=>{p.current||(w.current=0,y.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)},[]),R=u.useCallback(()=>{p.current?N():M()},[M,N]);u.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const _=u.useCallback($=>o(T=>Di(T,$)),[]),E=u.useCallback(($,T)=>o(C=>Oi(C,$,T)),[]),U=u.useCallback(($,T)=>o(C=>_i(C,$,T)),[]),W=u.useCallback(($,T)=>o(C=>zi(C,$,T)),[]),j=u.useCallback(($,T)=>o(C=>Gi(C,$,T)),[]),L=u.useCallback($=>o(T=>Bi(T,$)),[]),I=u.useCallback($=>o(T=>Wi(T,$)),[]),q=u.useCallback(()=>o($=>Ui($)),[]),Y=u.useCallback($=>o(T=>Vi(T,$)),[]),O=u.useCallback(($,T)=>o(C=>qi(C,$,T)),[]),Z=u.useCallback(()=>o($=>Hi($)),[]),H=u.useCallback($=>o(T=>({...T,bpm:Math.max(20,Math.min(300,$))})),[]),te=u.useCallback($=>o(T=>({...T,swing:Math.max(0,Math.min(1,$))})),[]),G=u.useCallback($=>{o(T=>{if(T.length===$)return T;const C=Array.from({length:$},(A,D)=>D<T.steps.length?T.steps[D]:{active:!1,note:T.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...T,length:$,steps:C}})},[]),z=u.useCallback($=>{f(T=>[...T,$??ir()])},[]),S=u.useCallback($=>{f(T=>T.filter((C,A)=>A!==$))},[]),P=u.useCallback(($,T)=>{f(C=>C.map((A,D)=>D===$?{...A,...T}:A))},[]);return{pattern:a,currentStep:i,playing:c,lfos:h,play:M,stop:N,togglePlayback:R,toggle:_,setNote:E,setVelocity:U,setGate:W,setProbability:j,toggleSlide:L,transpose:I,reverse:q,shift:Y,randomizeVel:O,clear:Z,setPattern:o,setBpm:H,setSwing:te,setLength:G,addLFO:z,removeLFO:S,updateLFO:P}}function ka(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(()=>()=>{var i;(i=t.current)==null||i.terminate(),t.current=null;for(const[,l]of n.current)l.reject(new Error("Worker terminated on unmount"));n.current.clear()},[]),u.useCallback((i,l)=>{const c=r.current++,d=a();return new Promise((h,f)=>{n.current.set(c,{resolve:h,reject:f}),d.postMessage({...i,id:c},l??[])})},[a])}function Cf(){const e=ka(u.useCallback(()=>new Worker(new URL("/assets/pitchWorker-BgAp5Z97.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:st&&st.tagName.toUpperCase()==="SCRIPT"&&st.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 kf(){const e=ka(u.useCallback(()=>new Worker(new URL("/assets/scoringWorker-B1PkYu_m.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:st&&st.tagName.toUpperCase()==="SCRIPT"&&st.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 Mf={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function Zi(){return`
54
54
  /**
55
55
  * NiceAudioProcessor — Main audio analysis processor.
56
56
  */
@@ -386,7 +386,7 @@ registerProcessor('nice-audio-processor', NiceAudioProcessor);
386
386
  registerProcessor('nice-gain-processor', NiceGainProcessor);
387
387
  registerProcessor('nice-compressor-processor', NiceCompressorProcessor);
388
388
  registerProcessor('nice-vocoder-processor', NiceVocoderProcessor);
389
- `}let ks=!1,zn=null;async function Xi(e){if(!ks)return zn||(zn=(async()=>{const t=Zi(),n=new Blob([t],{type:"application/javascript"}),r=URL.createObjectURL(n);try{await e.audioWorklet.addModule(r),ks=!0}finally{URL.revokeObjectURL(r)}})(),zn)}function Qi(e,t,n){const r=new AudioWorkletNode(e,"nice-audio-processor",{processorOptions:{...Mf,...t}});return n&&(r.port.onmessage=a=>{a.data.type==="analysis"&&n(a.data.payload)}),r}function Ji(e,t=1){const n=new AudioWorkletNode(e,"nice-gain-processor");return n.parameters.get("gain").value=t,n}function el(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 tl(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 jf(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,[h,f]=u.useState(!1),[m,g]=u.useState(null),[p,v]=u.useState(null),x=u.useRef(null),b=u.useRef(null),w=u.useRef(null),y=u.useRef(null),k=u.useRef(null),M=u.useRef(null),N=u.useRef(null),R=u.useRef(null);u.useEffect(()=>{let I=!0;return(async()=>{try{const Y=new AudioContext;if(x.current=Y,await Xi(Y),!I){Y.close();return}const O=[];if(t){const Z=Qi(Y,n,H=>{I&&(v(H),d==null||d(H))});b.current=Z,O.push(Z)}if(r){const Z=Ji(Y,a);w.current=Z,O.push(Z)}if(o){const Z=el(Y,i);y.current=Z,O.push(Z)}if(l){const Z=tl(Y,c);k.current=Z,O.push(Z)}if(O.length>0){N.current=O[0],R.current=O[O.length-1];for(let Z=0;Z<O.length-1;Z++)O[Z].connect(O[Z+1])}f(!0)}catch(Y){I&&g(Y)}})(),()=>{var Y,O,Z,H,te;I=!1,(Y=b.current)==null||Y.disconnect(),(O=w.current)==null||O.disconnect(),(Z=y.current)==null||Z.disconnect(),(H=k.current)==null||H.disconnect(),(te=x.current)==null||te.close()}},[t,r,o,l]);const _=u.useCallback(I=>{M.current&&M.current.disconnect(),M.current=I,N.current&&I.connect(N.current)},[]),E=u.useCallback(()=>{M.current&&(M.current.disconnect(),M.current=null)},[]),U=u.useCallback(()=>R.current,[]),W=u.useCallback(I=>{var Y;const q=(Y=w.current)==null?void 0:Y.parameters.get("gain");q&&(q.value=Math.max(0,Math.min(2,I)))},[]),j=u.useCallback((I,q)=>{var O;const Y=(O=y.current)==null?void 0:O.parameters.get(I);Y&&(Y.value=q)},[]),L=u.useCallback((I,q)=>{var O;const Y=(O=k.current)==null?void 0:O.parameters.get(I);Y&&(Y.value=q)},[]);return{isReady:h,error:m,analysis:p,connectSource:_,disconnectSource:E,getOutputNode:U,setGain:W,setCompressorParam:j,setVocoderParam:L,audioContext:x.current}}function nl(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function rl(e){return e>=50?3:e>=30?2.5:e>=20?2:e>=10?1.5:1}function Rf(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,h=!!n.disableGoldNotes;let f=0,m=0,g=0;const p=[];let v=0,x=0,b=0;const w=new Map;e.forEach((E,U)=>{const W=E.startTime,j=E.startTime+E.duration,L=W-a,I=j+o,q=t.filter(S=>S.t>=L&&S.t<=I&&S.hz>0);if(!q||q.length===0)return;const Y=Math.max(1,Math.ceil((E.duration||.25)/i)),O=Math.max(10,Math.round(100*(E.duration||1))),Z=Math.max(1,Math.round(O/Y));let H=0;const te=[];for(let S=0;S<Y;S++){const P=W+S*(E.duration/Y),$=W+(S+1)*(E.duration/Y),T=Math.min(.06,E.duration/Y*.2),C=P-T,A=$+T,D=t.filter(ee=>ee.t>=C&&ee.t<=A&&ee.hz>0);if(!D||D.length===0)continue;let V=0;D.forEach(ee=>{let K=((12*Math.log2(ee.hz/440)+69)%12+12)%12;for(;K-E.pitch>6;)K-=12;for(;K-E.pitch<-6;)K+=12;const se=Math.abs(K-E.pitch);V+=se});const Q=V/D.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=!h&&E.isGold?2:1,re=Math.round(Z*ae*J);re>0&&(f+=re,H+=re,te.push({segIndex:S,frac:J,add:re,segStart:C,segEnd:A,visualStart:P,visualEnd:$}))}const B=E.line??0;w.has(B)||w.set(B,{total:0,hit:0,comboBonus:0});const z=w.get(B);if(z.total++,H>0){v++,v>x&&(x=v),z.hit++;const S=rl(v),P=S>1?Math.round(H*(S-1)):0;b+=P,z.comboBonus+=P;const $=Math.max(1,Math.ceil((E.duration||.25)/i)),C=te.length>=$,A=C?Math.round(Math.max(10,Math.round(100*(E.duration||1)))*l*(!h&&E.isGold?1.5:1)*d):0,D=C&&!h&&E.isGold?Math.round(Math.max(10,Math.round(100*(E.duration||1)))*c*d):0;m+=A,g+=D,p.push({noteKey:`${E.line??0}-${E.idx??0}`,segments:te,totalAdded:H,completed:C,completionBonus:A,goldFullBonus:D})}else v=0});const y=[];for(const[E,U]of w.entries()){const W=U.total>0?U.hit/U.total:0;y.push({verseIndex:E,hitFraction:W,label:nl(W),comboBonus:U.comboBonus})}const k={maxCombo:x,currentCombo:0,totalComboBonus:b},M=b+m+g,N=p.length,R=p.filter(E=>E.completed).length,_={hits:N,misses:e.length-N,good:N-R,perfect:R,maxCombo:x};return{classicScore:f,bonusScore:M,totalScore:f+M,total:f,perNote:p,combo:k,verseRatings:y,noteStats:_}}function al(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 sl(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function $f(e,t,n){const r=al(t,n);if(r<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0,total:0};const a=sl(e.classicScore,r),o=Math.round(e.bonusScore/r*1e4);return{...e,classicScore:a,bonusScore:o,totalScore:a+o,total:a}}function ol(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 Tf(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 Pf(e,t="/backgrounds"){return e.backgroundImage?`${t}/${e.backgroundImage}`:""}function Ef(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 Af(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 Nf(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 If(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 Lf(e,t,n){const a=Date.parse(e)-n;return Math.max(0,Math.round(t-a))}const il={crepe:"#a78bfa",librosa:"#34d399",pitchy:"#60a5fa",autocorr:"#555555"};function Ff(e){return e==="autocorr"?"Ultrastar":e.charAt(0).toUpperCase()+e.slice(1)}function Df(e){return il[e]??"#555555"}function Of(e){const t=il[e]??"#555555";return`var(--algo-${e}, ${t})`}function _f(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=ol(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 zf(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 Bf(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 Gf(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 Wf(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 Uf(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 Vf(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 qf(e,t,n,r){e(a=>({...a,[n]:(a[n]||[]).filter(o=>o.id!==r)})),t(null)}function Hf(e,t,n){e(r=>({...r,[n]:[]})),t(null)}function Kf(e,t,n){e(r=>({...r,[t]:n}))}function Yf(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 Zf(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 Xf(e,t,n){e(r=>({...r,[t]:(r[t]||[]).filter(a=>a.id!==n)}))}function Bn(e){if(!e||e<=0)return null;const t=12*Math.log2(e/440)+69;return Math.round(t-12)}function Qf(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 Jf(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 h=0;h<r;h++)d+=Math.abs(e[h]-e[h+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 ep(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 f=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(d),m=f.getChannelData(0),g=f.sampleRate,p=Math.floor(g*.1),v=p,x=[];if(t==="pitchy"){const b=Pr.PitchDetector.forFloat32Array(p),w=Math.max(1,Math.floor((m.length-p)/v));let y=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 W=0;W<M.length;W++)M[W]*=.5*(1-Math.cos(2*Math.PI*W/(M.length-1)));const[N,R]=b.findPitch(M,g),_=Bn(N);let E=0;for(let W=0;W<M.length;W++)E+=M[W]*M[W];E=Math.sqrt(E/M.length);const U=typeof o=="number"?o:.01;_&&N>50&&N<2e3&&R>.7&&E>U&&x.push({start:k/g,duration:p/g,pitch:_,freq:N}),y++,a&&a(y/w)}}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 w=Array.isArray(b.track)?b.track:[];w.length>0&&w.forEach((y,k)=>{var N;const M=Bn(y.hz);if(M&&y.hz>50&&y.hz<2e3){const R=((N=w[k+1])==null?void 0:N.t)??y.t+.1;x.push({start:y.t,duration:k<w.length-1?R-y.t:.1,pitch:M,freq:y.hz})}}),a&&a(1)}else if(t==="ultrastar-wp"){const b=Math.max(1,Math.floor((m.length-p)/v));let w=0;for(let y=0;y<m.length-p;y+=v){if(r!=null&&r.aborted)throw new Error("aborted");const k=m.slice(y,y+p);if(i)for(let _=0;_<k.length;_++)k[_]*=.5*(1-Math.cos(2*Math.PI*_/(k.length-1)));const N=Jf(k,g,typeof o=="number"?o:.01),R=Bn(N);R&&N>50&&N<2e3&&x.push({start:y/g,duration:p/g,pitch:R,freq:N}),w++,a&&a(w/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 w=Array.isArray(b.track)?b.track:[];w.length>0&&w.forEach((y,k)=>{var N;const M=Bn(y.hz);if(M&&y.hz>50&&y.hz<2e3){const R=((N=w[k+1])==null?void 0:N.t)??y.t+.1;x.push({start:y.t,duration:k<w.length-1?R-y.t:.1,pitch:M,freq:y.hz})}}),a&&a(1)}return Qf(x)}function tp(e){switch(e){case"pitchy":return`#TITLE:Analyzed Song
389
+ `}let ks=!1,zn=null;async function Xi(e){if(!ks)return zn||(zn=(async()=>{const t=Zi(),n=new Blob([t],{type:"application/javascript"}),r=URL.createObjectURL(n);try{await e.audioWorklet.addModule(r),ks=!0}finally{URL.revokeObjectURL(r)}})(),zn)}function Qi(e,t,n){const r=new AudioWorkletNode(e,"nice-audio-processor",{processorOptions:{...Mf,...t}});return n&&(r.port.onmessage=a=>{a.data.type==="analysis"&&n(a.data.payload)}),r}function Ji(e,t=1){const n=new AudioWorkletNode(e,"nice-gain-processor");return n.parameters.get("gain").value=t,n}function el(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 tl(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 jf(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,[h,f]=u.useState(!1),[m,g]=u.useState(null),[p,v]=u.useState(null),x=u.useRef(null),b=u.useRef(null),w=u.useRef(null),y=u.useRef(null),k=u.useRef(null),M=u.useRef(null),N=u.useRef(null),R=u.useRef(null);u.useEffect(()=>{let I=!0;return(async()=>{try{const Y=new AudioContext;if(x.current=Y,await Xi(Y),!I){Y.close();return}const O=[];if(t){const Z=Qi(Y,n,H=>{I&&(v(H),d==null||d(H))});b.current=Z,O.push(Z)}if(r){const Z=Ji(Y,a);w.current=Z,O.push(Z)}if(o){const Z=el(Y,i);y.current=Z,O.push(Z)}if(l){const Z=tl(Y,c);k.current=Z,O.push(Z)}if(O.length>0){N.current=O[0],R.current=O[O.length-1];for(let Z=0;Z<O.length-1;Z++)O[Z].connect(O[Z+1])}f(!0)}catch(Y){I&&g(Y)}})(),()=>{var Y,O,Z,H,te;I=!1,(Y=b.current)==null||Y.disconnect(),(O=w.current)==null||O.disconnect(),(Z=y.current)==null||Z.disconnect(),(H=k.current)==null||H.disconnect(),(te=x.current)==null||te.close()}},[t,r,o,l]);const _=u.useCallback(I=>{M.current&&M.current.disconnect(),M.current=I,N.current&&I.connect(N.current)},[]),E=u.useCallback(()=>{M.current&&(M.current.disconnect(),M.current=null)},[]),U=u.useCallback(()=>R.current,[]),W=u.useCallback(I=>{var Y;const q=(Y=w.current)==null?void 0:Y.parameters.get("gain");q&&(q.value=Math.max(0,Math.min(2,I)))},[]),j=u.useCallback((I,q)=>{var O;const Y=(O=y.current)==null?void 0:O.parameters.get(I);Y&&(Y.value=q)},[]),L=u.useCallback((I,q)=>{var O;const Y=(O=k.current)==null?void 0:O.parameters.get(I);Y&&(Y.value=q)},[]);return{isReady:h,error:m,analysis:p,connectSource:_,disconnectSource:E,getOutputNode:U,setGain:W,setCompressorParam:j,setVocoderParam:L,audioContext:x.current}}function nl(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function rl(e){return e>=50?3:e>=30?2.5:e>=20?2:e>=10?1.5:1}function Rf(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,h=!!n.disableGoldNotes;let f=0,m=0,g=0;const p=[];let v=0,x=0,b=0;const w=new Map;e.forEach((E,U)=>{const W=E.startTime,j=E.startTime+E.duration,L=W-a,I=j+o,q=t.filter(S=>S.t>=L&&S.t<=I&&S.hz>0);if(!q||q.length===0)return;const Y=Math.max(1,Math.ceil((E.duration||.25)/i)),O=Math.max(10,Math.round(100*(E.duration||1))),Z=Math.max(1,Math.round(O/Y));let H=0;const te=[];for(let S=0;S<Y;S++){const P=W+S*(E.duration/Y),$=W+(S+1)*(E.duration/Y),T=Math.min(.06,E.duration/Y*.2),C=P-T,A=$+T,D=t.filter(ee=>ee.t>=C&&ee.t<=A&&ee.hz>0);if(!D||D.length===0)continue;let V=0;D.forEach(ee=>{let K=((12*Math.log2(ee.hz/440)+69)%12+12)%12;for(;K-E.pitch>6;)K-=12;for(;K-E.pitch<-6;)K+=12;const se=Math.abs(K-E.pitch);V+=se});const Q=V/D.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=!h&&E.isGold?2:1,re=Math.round(Z*ae*J);re>0&&(f+=re,H+=re,te.push({segIndex:S,frac:J,add:re,segStart:C,segEnd:A,visualStart:P,visualEnd:$}))}const G=E.line??0;w.has(G)||w.set(G,{total:0,hit:0,comboBonus:0});const z=w.get(G);if(z.total++,H>0){v++,v>x&&(x=v),z.hit++;const S=rl(v),P=S>1?Math.round(H*(S-1)):0;b+=P,z.comboBonus+=P;const $=Math.max(1,Math.ceil((E.duration||.25)/i)),C=te.length>=$,A=C?Math.round(Math.max(10,Math.round(100*(E.duration||1)))*l*(!h&&E.isGold?1.5:1)*d):0,D=C&&!h&&E.isGold?Math.round(Math.max(10,Math.round(100*(E.duration||1)))*c*d):0;m+=A,g+=D,p.push({noteKey:`${E.line??0}-${E.idx??0}`,segments:te,totalAdded:H,completed:C,completionBonus:A,goldFullBonus:D})}else v=0});const y=[];for(const[E,U]of w.entries()){const W=U.total>0?U.hit/U.total:0;y.push({verseIndex:E,hitFraction:W,label:nl(W),comboBonus:U.comboBonus})}const k={maxCombo:x,currentCombo:0,totalComboBonus:b},M=b+m+g,N=p.length,R=p.filter(E=>E.completed).length,_={hits:N,misses:e.length-N,good:N-R,perfect:R,maxCombo:x};return{classicScore:f,bonusScore:M,totalScore:f+M,total:f,perNote:p,combo:k,verseRatings:y,noteStats:_}}function al(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 sl(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function $f(e,t,n){const r=al(t,n);if(r<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0,total:0};const a=sl(e.classicScore,r),o=Math.round(e.bonusScore/r*1e4);return{...e,classicScore:a,bonusScore:o,totalScore:a+o,total:a}}function ol(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 Tf(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 Pf(e,t="/backgrounds"){return e.backgroundImage?`${t}/${e.backgroundImage}`:""}function Ef(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 Af(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 Nf(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 If(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 Lf(e,t,n){const a=Date.parse(e)-n;return Math.max(0,Math.round(t-a))}const il={crepe:"var(--nice-accent, #a78bfa)",librosa:"var(--nice-success-light, #34d399)",pitchy:"var(--nice-primary-light, #60a5fa)",autocorr:"var(--nice-text-secondary, #555555)"};function Ff(e){return e==="autocorr"?"Ultrastar":e.charAt(0).toUpperCase()+e.slice(1)}function Df(e){return il[e]??"var(--nice-text-secondary, #555555)"}function Of(e){const t=il[e]??"var(--nice-text-secondary, #555555)";return`var(--algo-${e}, ${t})`}function _f(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=ol(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 zf(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 Gf(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 Bf(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 Wf(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 Uf(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 Vf(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 qf(e,t,n,r){e(a=>({...a,[n]:(a[n]||[]).filter(o=>o.id!==r)})),t(null)}function Hf(e,t,n){e(r=>({...r,[n]:[]})),t(null)}function Kf(e,t,n){e(r=>({...r,[t]:n}))}function Yf(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 Zf(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 Xf(e,t,n){e(r=>({...r,[t]:(r[t]||[]).filter(a=>a.id!==n)}))}function Gn(e){if(!e||e<=0)return null;const t=12*Math.log2(e/440)+69;return Math.round(t-12)}function Qf(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 Jf(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 h=0;h<r;h++)d+=Math.abs(e[h]-e[h+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 ep(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 f=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(d),m=f.getChannelData(0),g=f.sampleRate,p=Math.floor(g*.1),v=p,x=[];if(t==="pitchy"){const b=Pr.PitchDetector.forFloat32Array(p),w=Math.max(1,Math.floor((m.length-p)/v));let y=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 W=0;W<M.length;W++)M[W]*=.5*(1-Math.cos(2*Math.PI*W/(M.length-1)));const[N,R]=b.findPitch(M,g),_=Gn(N);let E=0;for(let W=0;W<M.length;W++)E+=M[W]*M[W];E=Math.sqrt(E/M.length);const U=typeof o=="number"?o:.01;_&&N>50&&N<2e3&&R>.7&&E>U&&x.push({start:k/g,duration:p/g,pitch:_,freq:N}),y++,a&&a(y/w)}}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 w=Array.isArray(b.track)?b.track:[];w.length>0&&w.forEach((y,k)=>{var N;const M=Gn(y.hz);if(M&&y.hz>50&&y.hz<2e3){const R=((N=w[k+1])==null?void 0:N.t)??y.t+.1;x.push({start:y.t,duration:k<w.length-1?R-y.t:.1,pitch:M,freq:y.hz})}}),a&&a(1)}else if(t==="ultrastar-wp"){const b=Math.max(1,Math.floor((m.length-p)/v));let w=0;for(let y=0;y<m.length-p;y+=v){if(r!=null&&r.aborted)throw new Error("aborted");const k=m.slice(y,y+p);if(i)for(let _=0;_<k.length;_++)k[_]*=.5*(1-Math.cos(2*Math.PI*_/(k.length-1)));const N=Jf(k,g,typeof o=="number"?o:.01),R=Gn(N);R&&N>50&&N<2e3&&x.push({start:y/g,duration:p/g,pitch:R,freq:N}),w++,a&&a(w/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 w=Array.isArray(b.track)?b.track:[];w.length>0&&w.forEach((y,k)=>{var N;const M=Gn(y.hz);if(M&&y.hz>50&&y.hz<2e3){const R=((N=w[k+1])==null?void 0:N.t)??y.t+.1;x.push({start:y.t,duration:k<w.length-1?R-y.t:.1,pitch:M,freq:y.hz})}}),a&&a(1)}return Qf(x)}function tp(e){switch(e){case"pitchy":return`#TITLE:Analyzed Song
390
390
  #ARTIST:AI
391
391
  #ALGO:Pitchy
392
392
  : 0 4 40 Pitchy
@@ -409,4 +409,4 @@ E`;case"ultrastarws":return`#TITLE:Analyzed Song
409
409
  E`;default:return`#TITLE:Analyzed Song
410
410
  #ARTIST:AI
411
411
  : 0 2 40 Test
412
- E`}}function np(e,t){return`${e}:${t}`}function rp(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 ap(e){return e.length===0?[]:e.flat()}function sp(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const Ma=[{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 op(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function ll(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 cl(e,t){const n=t.seed!=null?op(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 dl(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 ip(e,t){let n=[...e.map(r=>({...r}))];return t.template&&t.grooveStrength>0&&(n=dl(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=ll(n,t.swing)),t.humanize&&(n=cl(n,t.humanize)),n}function lp(e){return Ma.find(t=>t.id===e)}function cp(){return Ma.map(({id:e,name:t})=>({id:e,name:t}))}const dp=[{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 Ms(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 Gn(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 up{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),h=t.createOscillator(),f=t.createOscillator(),m=t.createGain(),g=t.createGain(),p=n-1,v=Math.abs(p)*5+2,x=Math.abs(p)*.015;h.type="sawtooth",h.frequency.value=v,m.gain.value=x,h.connect(m),m.connect(c.delayTime),c.delayTime.value=.02,f.type="sawtooth",f.frequency.value=v,g.gain.value=x,f.connect(g),g.connect(d.delayTime),d.delayTime.value=.02+x;const b=t.createGain();b.gain.value=.5;const w=t.createGain();return w.gain.value=.5,a.connect(c),a.connect(d),c.connect(b),d.connect(w),b.connect(i),w.connect(i),a.connect(l),i.connect(o),l.connect(o),h.start(),f.start(),{type:"chipmunk",nodes:[a,c,d,h,f,m,g,b,w,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 h=t.createGain();return h.gain.value=.3,r.connect(h),h.connect(a),o.start(),c.start(),{type:"alien",nodes:[r,o,i,l,c,d,h,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 h=t.createGain();return h.gain.value=1,o.connect(l),l.connect(c),c.connect(l),l.connect(d),o.connect(h),d.connect(i),h.connect(i),{type:"echo",nodes:[o,l,c,d,h,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 h=t.createGain();h.gain.value=.25;const f=t.createConvolver();f.buffer=Ms(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(h),h.connect(l),o.connect(m),i.connect(m),l.connect(m),r.connect(f),f.connect(m);const g=t.createGain();return g.gain.value=.7,r.connect(g),g.connect(a),m.connect(a),{type:"cave",nodes:[r,o,i,l,c,d,h,f,m,g,a],input:r,output:a}}buildReverb(t,n,r,a){const o=t.createGain(),i=t.createGain(),l=t.createConvolver();l.buffer=Ms(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 h=t.createOscillator();h.type="sine",h.frequency.value=c.lfoFreq;const f=t.createGain();f.gain.value=c.depth*(.5+n),h.connect(f),f.connect(d.delayTime);const m=t.createGain();m.gain.value=.3+n*.2,r.connect(d),d.connect(m),m.connect(a),h.start(),i.push(d,h,f,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 h=t.createGain();return h.gain.value=1,r.connect(o),o.connect(c),c.connect(o),o.connect(d),r.connect(h),d.connect(a),h.connect(a),i.start(),{type:"flanger",nodes:[r,o,i,l,c,d,h,a],input:r,output:a}}buildDistortion(t,n,r){const a=t.createGain(),o=t.createGain(),i=t.createWaveShaper();i.curve=Gn(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=Gn(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=Gn(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 h=d/255*2-1;l[d]=Math.sign(h)*Math.pow(Math.abs(h),.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=Gn(20+n*50),c.oversample="2x";const d=t.createBiquadFilter();d.type="lowshelf",d.frequency.value=200,d.gain.value=8+n*8;const h=t.createGain();h.gain.value=.7+n*.3;const f=t.createGain();return f.gain.value=.3,r.connect(o),o.connect(c),c.connect(d),d.connect(h),r.connect(f),h.connect(a),f.connect(a),i.start(),{type:"demon",nodes:[r,o,i,l,c,d,h,f,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],h=t.createGain();h.gain.value=.15;for(const g of d){const p=t.createBiquadFilter();p.type="peaking",p.frequency.value=g,p.Q.value=8+n*15,p.gain.value=4+n*8,r.connect(p),p.connect(h),c.push(p)}const f=t.createGain();f.gain.value=.7;const m=t.createGain();return m.gain.value=.5+n*.3,r.connect(o),o.connect(m),h.connect(m),r.connect(f),m.connect(a),f.connect(a),i.start(),{type:"autotune",nodes:[r,o,i,l,...c,h,m,f,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 f=0;f<l;f++){const m=200*Math.pow(2,f*.5),g=t.createBiquadFilter();g.type="bandpass",g.frequency.value=m,g.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(g),g.connect(v.gain),o.connect(p),p.connect(v),v.connect(d),c.push(g,p,v)}d.connect(a);const h=t.createGain();return h.gain.value=.3-n*.2,r.connect(h),h.connect(a),c.push(h),o.start(),{type:"vocoder",nodes:c,input:r,output:a}}}const ul=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Ut(e){return 12*Math.log2(e/440)+69}function Wn(e){const t=ul[Math.round(e)%12],n=Math.floor(Math.round(e)/12)-1;return`${t}${n}`}function $r(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 hp(e){const{playerName:t,playerColor:n,songTitle:r,songArtist:a,songBpm:o,difficulty:i,pitchPoints:l,notes:c,verseRatings:d,combo:h,classicScore:f,bonusScore:m,totalScore:g,micSettings:p}=e,v=l.filter(ne=>ne.hz>0),x=v.map(ne=>Ut(ne.hz)),b=[],w=[],y=[],k=[...c].sort((ne,oe)=>ne.startTime-oe.startTime);function M(ne){let oe=0,Ne=k.length-1;for(;oe<=Ne;){const De=oe+Ne>>>1,Pe=k[De];if(ne<Pe.startTime)Ne=De-1;else if(ne>Pe.startTime+Pe.duration)oe=De+1;else return Pe.pitch}return 0}for(const ne of l){const oe=ne.hz>0?Ut(ne.hz):0,Ne=M(ne.t);if(w.push({t:ne.t,sung:oe,expected:Ne}),oe>0&&Ne>0){const De=(oe-Ne)*100;b.push(De)}}let N=0;for(const ne of k){const oe=ne.startTime-.3,Ne=ne.startTime+ne.duration;for(;N<v.length&&v[N].t<oe;)N++;N<v.length&&v[N].t<=Ne&&y.push((v[N].t-ne.startTime)*1e3)}const R=b.map(Math.abs),_=[...R].sort((ne,oe)=>ne-oe),E=R.length>0?R.reduce((ne,oe)=>ne+oe,0)/R.length:0,U=$r(_,50),W=R.length>1?Math.sqrt(R.reduce((ne,oe)=>ne+(oe-E)**2,0)/(R.length-1)):0,j=R.filter(ne=>ne<=50).length,L=R.filter(ne=>ne<=15).length,I=R.length>0?j/R.length*100:0,q=R.length>0?L/R.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,B=H.length>0?H[H.length-1]:0,z=te>0?Ut(te):0,S=B>0?Ut(B):0,P=S-z,$=[...x].sort((ne,oe)=>ne-oe),T=$r($,10),C=$r($,90),A=new Array(12).fill(0);for(const ne of x){const oe=Math.round(ne)%12;oe>=0&&oe<12&&A[oe]++}const D=A.reduce((ne,oe)=>ne+oe,0),V=ul.map((ne,oe)=>({note:ne,count:A[oe],pct:D>0?A[oe]/D*100:0})),Q=fp(v),J=y.length>0?y.reduce((ne,oe)=>ne+oe,0)/y.length:0,ae=y.length>1?Math.sqrt(y.reduce((ne,oe)=>ne+(oe-J)**2,0)/(y.length-1)):0,re=ae>0?Math.max(0,Math.min(100,100-ae/2)):100;let ee=0,F=0;for(let ne=1;ne<x.length;ne++){const oe=Math.abs(x[ne]-x[ne-1]);ee+=oe,F++}const K=F>0?ee/F*100/12:0,se=l.filter(ne=>ne.hz<=0).length,ce=l.length>0?(1-se/l.length)*100:0,fe=new Map;for(const ne of c){const oe=ne.line??0;fe.has(oe)||fe.set(oe,[]),fe.get(oe).push(ne)}const X=new Map;for(const ne of v){const oe=M(ne.t);if(oe<=0)continue;let Ne=0,De=k.length-1,Pe=-1;for(;Ne<=De;){const we=Ne+De>>>1,dt=k[we];if(ne.t<dt.startTime)De=we-1;else if(ne.t>dt.startTime+dt.duration)Ne=we+1;else{Pe=dt.line??0;break}}if(Pe<0)continue;const tt=Math.abs((Ut(ne.hz)-oe)*100);X.has(Pe)||X.set(Pe,[]),X.get(Pe).push(tt)}const ue=d.map(ne=>{const oe=fe.get(ne.verseIndex)??[],Ne=X.get(ne.verseIndex)??[],De=Ne.length>0?Ne.reduce((Pe,tt)=>Pe+tt,0)/Ne.length:0;return{verseIndex:ne.verseIndex,label:ne.label,hitFraction:ne.hitFraction,avgCentDeviation:Math.round(De*10)/10,noteCount:oe.length,notesHit:Math.round(ne.hitFraction*oe.length),comboBonus:ne.comboBonus}}),ye=2,je=.5,Fe=l.length>0?l[l.length-1].t:0,Re=[],Se=w.filter(ne=>ne.sung>0&&ne.expected>0);if(Se.length>0){let ne=0,oe=0,Ne=0;for(let De=0;De<=Fe;De+=je){const Pe=De-ye/2,tt=De+ye/2;for(;oe<Se.length&&Se[oe].t<tt;)Math.abs(Se[oe].sung-Se[oe].expected)<=.5&&Ne++,oe++;for(;ne<oe&&Se[ne].t<Pe;)Math.abs(Se[ne].sung-Se[ne].expected)<=.5&&Ne--,ne++;const we=oe-ne;Re.push({t:De,accuracy:we>0?Ne/we*100:0})}}else for(let ne=0;ne<=Fe;ne+=je)Re.push({t:ne,accuracy:0});return{playerName:t,playerColor:n,songTitle:r,songArtist:a,songBpm:o,difficulty:i,timestamp:new Date().toISOString(),classicScore:f,bonusScore:m,totalScore:g,maxCombo:(h==null?void 0:h.maxCombo)??0,totalComboBonus:(h==null?void 0:h.totalComboBonus)??0,totalPitchPoints:l.length,avgCentDeviation:Math.round(E*10)/10,medianCentDeviation:Math.round(U*10)/10,stdDevCents:Math.round(W*10)/10,intonationAccuracyPct:Math.round(I*10)/10,perfectHitPct:Math.round(q*10)/10,pitchDeviationHistogram:Z,lowestHz:Math.round(te*10)/10,highestHz:Math.round(B*10)/10,lowestNote:z>0?Wn(z):"—",highestNote:S>0?Wn(S):"—",rangeInSemitones:Math.round(P*10)/10,tessituraLow:T>0?Wn(T):"—",tessituraHigh:C>0?Wn(C):"—",pitchClassDistribution:V,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:ue,micSettings:p,pitchOverTime:w,accuracyOverTime:Re}}function fp(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(g=>Ut(g.hz)),n=e.map(g=>g.t),r=.5,a=[],o=[];let i=0,l=0,c=0;for(let g=0;g<e.length;g++){for(l+=t[g],c++;i<g&&n[g]-n[i]>=r;)l-=t[i],c--,i++;if(c<6||(g-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<=g;k++){const M=t[k]-p;M*x<0&&v++,x=M;const N=Math.abs(M);N>b&&(b=N)}const w=n[g]-n[i];if(w<=0)continue;const y=v/2/w;y>=3&&y<=12&&(a.push(y),o.push(b*100))}if(a.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const d=a.reduce((g,p)=>g+p,0)/a.length,h=o.reduce((g,p)=>g+p,0)/o.length,f=Math.sqrt(a.reduce((g,p)=>g+(p-d)**2,0)/a.length),m=Math.max(0,Math.min(100,100-f*20));return{detected:!0,avgRateHz:Math.round(d*10)/10,avgExtentCents:Math.round(h*10)/10,regularityPct:Math.round(m)}}function hl(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))),h=o+c-Math.floor(i/2);h>=0&&h<a&&(l[h]=d)}return l}function js(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 h=0;for(let f=c;f<d;f++)h+=Math.abs(e[f]);o[l]=h/(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 pp(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 g=m+i+Math.floor((r-n)/2);if(g<0||g>=r)continue;const p=e[m],v=t[g];l+=p*v,c+=p*p,d+=v*v}const h=Math.sqrt(Math.max(1e-9,c*d)),f=l/h;f>a.score&&(a={lag:i,score:f})}return a.lag}function mp(e,t,n=50,r=30){try{const a=Math.max(300,Math.round(e.length/t*1e3)),o=hl(a,t,n,r),i=js(e,t,1e3),l=js(o,t,1e3),d=pp(l.env,i.env)*1e3/1e3;return Math.round(d)}catch{return null}}function fl(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 ja(e,t){return fl(e)*60/t}function Hr(e,t,n){const r=ja(t,n);return Math.round(e/r)*r}function gp(e,t){const{value:n,bpm:r,strength:a=1,quantizeStarts:o=!0,quantizeDurations:i=!1}=t,l=ja(n,r);return e.map(c=>{let{start:d,duration:h}=c;if(o){const f=Math.round(d/l)*l;d=d+(f-d)*a}if(i){const f=Math.max(l,Math.round(h/l)*l);h=h+(f-h)*a}return d===c.start&&h===c.duration?c:{...c,start:d,duration:h}})}function yp(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function bp(e,t={}){const{timingRange:n=.02,velocityRange:r=10,seed:a}=t,o=a!=null?yp(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 vp(){return{start:0,end:0,enabled:!1}}function xp(e,t){return{...e<t?{start:e,end:t}:{start:t,end:e},enabled:!0}}function Sp(e,t,n){return{start:Hr(e.start,t,n),end:Hr(e.end,t,n),enabled:e.enabled}}function wp(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function Cp(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 Kr(e){return e.length===1?e.toLowerCase():e}function Yn(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(Kr(e.key)),t.join("+")}function kp(e,t){var l,c,d,h;const n=Kr(e.key)===Kr(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==!!((h=t.modifiers)!=null&&h.meta);return n&&r&&a&&o&&i}class pl{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];Yn(o.binding)===Yn(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?Yn(n.binding):""}handleKeyDown(t){if(!this.enabled)return!1;for(const n of this.actions.values())if(n.enabled&&this.activeScopes.has(n.scope)&&kp(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 Mp(e={}){const t=new pl,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 jp(e){return Yn(e)}const Rp=["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"],$p=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],Tp=500*1024*1024,Pp=20;function jt(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function Ep(e,t){return!!(e.type&&t.some(n=>e.type.startsWith(n.replace("*","")))||e.type.startsWith("audio/"))}function Ap(e,t){const n=jt(e.name);return n!==""&&t.includes(n)}function Ra(e,t={}){const n=t.maxSize??Tp,r=t.allowedTypes??Rp,a=t.allowedExtensions??$p,o=t.maxFiles??Pp,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(!Ep(d,r)&&!Ap(d,a)){l.push({file:d,reason:"type",message:`Unsupported file type: ${d.type||jt(d.name)}`});continue}i.push(d)}return{valid:i,errors:l}}async function ml(e){const t={file:e,name:e.name.replace(/\.[^.]+$/,""),extension:jt(e.name),sizeBytes:e.size,mimeType:e.type||`audio/${jt(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 Np(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,h;n.preventDefault(),n.stopPropagation(),t=0,(d=e.onDragLeave)==null||d.call(e);const r="dataTransfer"in n?n.dataTransfer:null;if(!((h=r==null?void 0:r.files)!=null&&h.length))return;const a=Array.from(r.files),{valid:o,errors:i}=Ra(a,e.validation),l=[],c=[...i];for(const f of o)if(e.probe)try{l.push(await ml(f))}catch{c.push({file:f,reason:"decode",message:"Failed to decode audio"})}else l.push({file:f,name:f.name.replace(/\.[^.]+$/,""),extension:jt(f.name),sizeBytes:f.size,mimeType:f.type||`audio/${jt(f.name)}`});e.onDrop({accepted:l,rejected:c})}}}function Ip(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}=Ra(r,e.validation),i=a.map(c=>({file:c,name:c.name.replace(/\.[^.]+$/,""),extension:jt(c.name),sizeBytes:c.size,mimeType:c.type||`audio/${jt(c.name)}`}));t({accepted:i,rejected:o})},n.click()})}var gl=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(gl||{}),kt=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(kt||{}),yl=(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))(yl||{}),bl=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(bl||{});const Lp=["#4caf50","#2196f3","#ff9800","#e91e63","#9c27b0","#00bcd4","#8bc34a","#ffc107"],Pt=["#2196f3","#e53935","#ffeb3b","#43a047","#ff9800","#9c27b0","#00bcd4","#ffc107","#8bc34a","#f44336","#3f51b5","#607d8b","#795548","#cddc39","#673ab7","#009688"];function Fp(e){for(const t of Pt)if(!e.includes(t))return t;return Pt[Math.floor(Math.random()*Pt.length)]}const Zn=Pt.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function Dp(e){for(let t=0;t<Pt.length;t++){const n=Pt[t],r=Zn[t];if(!e.includes(n)&&!e.includes(r))return r}return Zn[Math.floor(Math.random()*Zn.length)]}const or=["off","no function","brak"],Op=e=>e.segments.some(t=>t.isOff||or.some(n=>t.name.toLowerCase().includes(n))),_p=e=>e.segments.find(t=>t.isOff||or.some(n=>t.name.toLowerCase().includes(n))),vl=e=>Math.floor((e.valueFrom+e.valueTo)/2),zp=e=>{const t=_p(e);return t?vl(t):0},Bp=(e,t)=>e.segments.find(n=>t>=n.valueFrom&&t<=n.valueTo),cn=(e,t=0,n=255)=>Math.max(t,Math.min(n,Math.round(e))),kn=({channel:e,value:t,onChange:n,onCommit:r,showDirectionHint:a})=>{const[o,i]=u.useState(cn(t)),l=u.useMemo(()=>Bp(e,o),[e,o]);u.useEffect(()=>i(cn(t)),[t]);const c=d=>{const h=cn(d);i(h),n(h),r==null||r(h)};return s.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid #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:"#6b7280"},children:l.name})]}),s.jsx("input",{type:"range",min:0,max:255,value:o,onChange:d=>{const h=cn(Number(d.target.value));i(h),n(h)},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 h=cn(Number(d.target.value));i(h),n(h)},onBlur:()=>r==null?void 0:r(o),style:{width:80,padding:6,border:"1px solid #d1d5db",borderRadius:6}})}),Op(e)&&s.jsx("button",{type:"button",onClick:()=>c(zp(e)),style:{width:"100%",marginTop:8,padding:"6px 10px",borderRadius:6,border:"1px solid #d1d5db",background:"#f9fafb",cursor:"pointer"},children:"OFF"})]})},$a=({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)+(or.some(f=>l.name.toLowerCase().includes(f))?-1:0),h=(c.isOff?-1:0)+(or.some(f=>c.name.toLowerCase().includes(f))?-1:0);return d!==h?d-h:l.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),i},[e]),o=i=>{const l=vl(i);n(l),r==null||r(l)};return s.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid #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 #2563eb":"1px solid #d1d5db",background:c?"#eff6ff":"#fff",textAlign:"left",cursor:"pointer",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:`${i.name} [${i.valueFrom}..${i.valueTo}]`,children:i.name},`${i.name}-${l}`)})})]})},Ta=e=>{switch(e.channel.type){case kt.Dimmer:case kt.DimmerWithOff:return s.jsx(kn,{...e});case kt.RotationWithOff:case kt.RotationWithOffAndCcw:return s.jsx(kn,{...e,showDirectionHint:!0});case kt.Options:return s.jsx($a,{...e});default:return s.jsx(kn,{...e})}},Tr=e=>Math.max(0,Math.min(255,Math.round(e)));function xl({service:e,pollInterval:t=500,className:n,style:r,channels:a,onChannelChange:o,fixtures:i}){if(!e)return s.jsx("div",{className:n,style:r,children:s.jsx("small",{children:"Provide a `service` prop (DmxService) to control hardware."})});const[l,c]=u.useState([]),[d,h]=u.useState(null),[f,m]=u.useState(()=>Array(513).fill(0)),[g,p]=u.useState(30),[v,x]=u.useState(0),[b,w]=u.useState(!1),y=u.useRef(null);u.useEffect(()=>{let j=!1;return e.getDevices().then(L=>{j||(c(L),L.length>0&&h(L[0]))}).catch(()=>{}),()=>{j=!0}},[e]),u.useEffect(()=>{if(y.current&&window.clearInterval(y.current),!(t<=0))return y.current=window.setInterval(async()=>{try{const j=await e.getState();Array.isArray(j.frontSnapshot)&&j.frontSnapshot.length>=513&&m(j.frontSnapshot.slice(0,513)),typeof j.fps=="number"&&p(j.fps),typeof j.startCode=="number"&&x(j.startCode)}catch{}},t),()=>{y.current&&window.clearInterval(y.current)}},[e,t]);const k=async()=>{d&&(await e.openPort(d.serialNumber||d.description),w(!0))},M=async()=>{await e.closePort(),w(!1)},N=async()=>{await e.blackout(),m(j=>{const L=[...j];for(let I=1;I<L.length;I++)L[I]=0;return L})},R=()=>e.configure(g,v),_=(j,L)=>{const I=Tr(L);m(q=>{const Y=[...q];return Y[j]=I,Y})},E=(j,L)=>e.setChannel(j,Tr(L)),U=(d==null?void 0:d.deviceInfo)??null,W=u.useMemo(()=>{var j;return(j=U==null?void 0:U.channels)!=null&&j.length?U.channels:Array.from({length:16},(L,I)=>({channel:I+1,name:`Channel ${I+1}`,type:kt.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[U]);return s.jsxs("div",{className:`ntd-dmx-editor ${n??""}`,style:{padding:16,display:"grid",gap:16,...r},children:[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:(d==null?void 0:d.serialNumber)||"",onChange:j=>h(l.find(L=>L.serialNumber===j.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid #d1d5db"},children:l.map(j=>{var L,I;return s.jsxs("option",{value:j.serialNumber,children:[((L=j.deviceInfo)==null?void 0:L.manufacturer)??""," ",((I=j.deviceInfo)==null?void 0:I.model)??j.description," (",j.serialNumber||j.description,")"]},j.serialNumber||j.description)})}),U&&s.jsxs("div",{style:{marginTop:6,fontSize:12,color:"#6b7280"},children:["Mode: ",s.jsx("b",{children:U.modeName}),", footprint: ",s.jsx("b",{children:U.footprint})]})]}),s.jsx("button",{onClick:k,disabled:!d||b,style:{padding:"10px 14px",borderRadius:8,border:"1px solid #10b981",background:"#ecfdf5",cursor:"pointer"},children:"Open port"}),s.jsx("button",{onClick:M,disabled:!b,style:{padding:"10px 14px",borderRadius:8,border:"1px solid #ef4444",background:"#fef2f2",cursor:"pointer"},children:"Close port"}),s.jsx("button",{onClick:N,style:{padding:"10px 14px",borderRadius:8,border:"1px solid #4b5563",background:"#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:g,onChange:j=>p(Number(j.target.value)),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid #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:v,onChange:j=>x(Tr(Number(j.target.value))),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid #d1d5db"}})]}),s.jsx("div",{children:s.jsx("button",{onClick:R,style:{padding:"10px 14px",borderRadius:8,border:"1px solid #3b82f6",background:"#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:W.map(j=>s.jsx(Ta,{channel:j,value:f[j.channel]??0,onChange:L=>_(j.channel,L),onCommit:L=>E(j.channel,L)},j.channel))})]})]})}const Sl=[{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 wl{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,Sl.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,h)=>{d.name.toLowerCase().includes("red")?c[h]=n:d.name.toLowerCase().includes("green")?c[h]=r:d.name.toLowerCase().includes("blue")?c[h]=a:d.name.toLowerCase().includes("white")&&(c[h]=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 h=performance.now()-c,f=Math.min(1,h/r);let m=f;switch(a){case"ease-in":m=f*f;break;case"ease-out":m=1-(1-f)*(1-f);break;case"ease-in-out":m=f<.5?2*f*f:1-Math.pow(-2*f+2,2)/2;break}const g=l.map((p,v)=>{const x=n[v]??p;return Math.round(p+(x-p)*m)});this.setFixtureValues(t,g),f<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 Gp=6454,Wp=new Uint8Array([65,114,116,45,78,101,116,0]);function Up(e,t){const n=new Uint8Array(18+t.length);return n.set(Wp,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 Vp=5568;function qp(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 h=i-16;c.setUint16(16,28672|h&4095,!1),c.setUint32(18,4,!1);for(let p=0;p<16;p++)l[22+p]=p+1;const f=i-38;c.setUint16(38,28672|f&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 g=o+11;return c.setUint16(115,28672|g&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 Hp(e){const t=e>>8&255,n=e&255;return`239.255.${t}.${n}`}class Kp{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 Yp=({engine:e,tracks:t=[],scenes:n=[],duration:r=3e5,currentTime:a=0,bpm:o=120,onTimeChange:i,onCueAdd:l,onCueUpdate:c,onCueDelete:d,onTrackAdd:h,onTrackUpdate:f,onPlay:m,onPause:g,onStop:p,className:v=""})=>{const[x,b]=u.useState(1),[w,y]=u.useState(0),[k,M]=u.useState(!1),[N,R]=u.useState(null),[_,E]=u.useState(null),[U,W]=u.useState(!0),[j,L]=u.useState(1e3),I=u.useRef(null),q=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(!U)return C;const A=6e4/o;return Math.round(C/A)*A},[U,o]);u.useEffect(()=>{if(k){const C=performance.now(),A=a,D=()=>{const V=performance.now()-C,Q=A+V;if(Q>=r){M(!1),i==null||i(0),p==null||p();return}B(Q),i==null||i(Q),q.current=requestAnimationFrame(D)};q.current=requestAnimationFrame(D),m==null||m()}else q.current!==null&&(cancelAnimationFrame(q.current),q.current=null),g==null||g();return()=>{q.current!==null&&cancelAnimationFrame(q.current)}},[k,a,r,i,m,g,p]);const B=u.useCallback(C=>{t.forEach(A=>{A.muted||A.cues.forEach(D=>{const V=D.startTime,Q=V+D.duration;if(C>=V&&C<Q&&Y.current<V){const J=n.find(ae=>ae.id===D.sceneId);J&&J.fixtures.forEach(ae=>{D.fadeIn&&D.fadeIn>0?e.fadeFixture(ae.fixtureId,ae.values,D.fadeIn):e.setFixtureValues(ae.fixtureId,ae.values)})}if(Y.current<Q&&C>=Q){const J=n.find(ae=>ae.id===D.sceneId);J&&J.fixtures.forEach(ae=>{if(e.getFixture(ae.fixtureId)&&D.fadeOut&&D.fadeOut>0){const ee=new Array(ae.values.length).fill(0);e.fadeFixture(ae.fixtureId,ee,D.fadeOut)}})}})}),Y.current=C},[t,n,e]),z=C=>{const A=Math.floor(C/1e3),D=Math.floor(A/60),V=A%60,Q=Math.floor(C%1e3/(1e3/30));return`${D}:${V.toString().padStart(2,"0")}:${Q.toString().padStart(2,"0")}`},S=u.useCallback(C=>{if(!I.current)return;const A=I.current.getBoundingClientRect(),D=C.clientX-A.left+w,V=te(H(D));i==null||i(Math.max(0,Math.min(r,V)))},[w,H,te,r,i]),P=u.useCallback((C,A,D)=>{const V=t.find(ae=>ae.id===A),Q=V==null?void 0:V.cues.find(ae=>ae.id===C);if(!Q)return;const J=te(Math.max(0,Q.startTime+H(D)));c==null||c({...Q,startTime:J})},[t,H,te,c]),$=()=>{const C=6e4/o,A=Math.ceil(r/C),D=[];for(let V=0;V<=A;V++){const Q=V*C,J=Z(Q),ae=V%4===0;D.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:V/4+1})},V))}return D},T=(C,A)=>{const D=Z(C.startTime),V=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:D,width:V,backgroundColor:(Q==null?void 0:Q.color)||A.color||"#8b5cf6"},onClick:J=>{J.stopPropagation(),R(C.id)},draggable:!A.locked,onDragEnd:J=>{var re;const ae=(re=J.target.parentElement)==null?void 0:re.getBoundingClientRect();ae&&P(C.id,A.id,J.clientX-ae.left-D)},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:z(a)}),s.jsxs("div",{className:"nice-dmx-timeline__tools",children:[s.jsx("button",{type:"button",className:U?"active":"",onClick:()=>W(!U),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:()=>E(C.id),children:[s.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:C.color||"#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:A=>{A.stopPropagation(),f==null||f({...C,muted:!C.muted})},title:"Mute",children:"M"}),s.jsx("button",{type:"button",className:C.locked?"active":"",onClick:A=>{A.stopPropagation(),f==null||f({...C,locked:!C.locked})},title:"Lock",children:"🔒"})]})]},C.id)),s.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"})]}),s.jsxs("div",{className:"nice-dmx-timeline__tracks",ref:I,onClick:S,onScroll:C=>y(C.currentTarget.scrollLeft),children:[s.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:Z(r)},children:$()}),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(A=>T(A,C))},C.id)),s.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:Z(a)}})]})]})]})};function Zp(){const[e]=u.useState(()=>new wl);return u.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function Xp(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 Qp=[{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 Cl(){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),[h,f]=u.useState(null),m=u.useRef(null),g=u.useRef(null),p=u.useRef(null),v=u.useRef(null),x=u.useRef([]),b=u.useRef(null),w=u.useRef(null),y=u.useCallback(()=>{if(g.current)return;const I=new AudioContext;g.current=I;const q=I.createGain();q.gain.value=n,v.current=q;const Y=I.createAnalyser();Y.fftSize=256,b.current=Y,q.connect(Y).connect(I.destination)},[]),k=u.useCallback(()=>{const I=m.current,q=g.current,Y=v.current;if(!I||!q||!Y||p.current)return;const O=q.createMediaElementSource(I);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 q;const I=m.current;!I||!w.current||(Et(),y(),k(),((q=g.current)==null?void 0:q.state)==="suspended"&&g.current.resume(),I.play().catch(Y=>d(String(Y))))},[y,k]),N=u.useCallback(()=>{var I;(I=m.current)==null||I.pause()},[]),R=u.useCallback(()=>{e?N():M()},[e,M,N]),_=u.useCallback(I=>{const q=Math.max(0,Math.min(1,I));r(q),v.current&&(v.current.gain.value=q),m.current&&(m.current.volume=q)},[]),E=u.useCallback(I=>{w.current=I,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=I.streamUrl,m.current.load(),l({genre:I.genre,bitrate:I.bitrate})},[]),U=u.useCallback(I=>{g.current||y();const Y=g.current;x.current.forEach(Z=>Z.disconnect());const O=I.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)),f(I.name)},[y]),W=u.useCallback(()=>{x.current.forEach(I=>I.disconnect()),x.current=[],p.current&&v.current&&(p.current.disconnect(),p.current.connect(v.current)),f(null)},[]);return u.useEffect(()=>()=>{var I,q,Y;(I=m.current)==null||I.pause(),m.current=null,x.current.forEach(O=>O.disconnect()),(q=p.current)==null||q.disconnect(),(Y=g.current)==null||Y.close()},[]),[{isPlaying:e,volume:n,isBuffering:a,metadata:i,error:c,activePreset:h},{play:M,pause:N,toggle:R,setVolume:_,setStation:E,applyEQPreset:U,clearEQ:W}]}function kl({stations:e,activeStationId:t,onSelect:n,onToggleFavorite:r,className:a}){const{t:o}=xe(),[i,l]=u.useState(""),[c,d]=u.useState(null),[h,f]=u.useState(!1),m=u.useMemo(()=>[...new Set(e.map(p=>p.genre).filter(Boolean))],[e]),g=u.useMemo(()=>e.filter(p=>{var v,x;if(h&&!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,h]);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${h?" nice-station-browser__fav-toggle--active":""}`,onClick:()=>f(!h),title:(o==null?void 0:o("favorites"))??"Favorites",children:"★"})]}),s.jsxs("div",{className:"nice-station-browser__list",children:[g.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)),g.length===0&&s.jsx("div",{className:"nice-station-browser__empty",children:(o==null?void 0:o("no_stations_found"))??"No stations found"})]})]})}function Jp({stations:e,initialStationId:t,autoPlay:n=!1,eqPresets:r=Qp,onStationChange:a,onPlayingChange:o,onMetadata:i,onToggleFavorite:l,onRecordingStart:c,onRecordingStop:d,showBrowser:h=!0,showEqualizer:f=!1,showVisualizer:m=!1,showMetadataHistory:g=!1,showRecording:p=!1,showSleepTimer:v=!1,className:x,style:b}){var T,C;const{t:w}=xe(),[y,k]=Cl(),[M,N]=u.useState(()=>t?e.find(A=>A.id===t)??null:null),[R,_]=u.useState(f),E=u.useRef(null),U=u.useRef(0),[W,j]=u.useState([]),[L,I]=u.useState(!1),q=u.useRef(null),Y=u.useRef([]),[O,Z]=u.useState(0),H=u.useRef(null),[te,B]=u.useState(0),[z,S]=u.useState(null),P=u.useRef(null);u.useEffect(()=>{o==null||o(y.isPlaying)},[y.isPlaying,o]),u.useEffect(()=>{y.metadata&&(i==null||i(y.metadata),(y.metadata.title||y.metadata.artist)&&j(A=>[{time:new Date,meta:y.metadata},...A.slice(0,49)]))},[y.metadata,i]);const $=u.useCallback(A=>{N(A),k.setStation(A),a==null||a(A),n&&setTimeout(()=>k.play(),100)},[k,a,n]);return u.useEffect(()=>{if(t&&!M){const A=e.find(D=>D.id===t);A&&$(A)}},[t,e]),u.useEffect(()=>{if(!m||!E.current)return;const A=E.current,D=A.getContext("2d");if(!D)return;const V=()=>{U.current=requestAnimationFrame(V),D.clearRect(0,0,A.width,A.height);const Q=D.createLinearGradient(0,A.height,0,0);if(Q.addColorStop(0,"rgba(99,102,241,0.8)"),Q.addColorStop(.5,"rgba(168,85,247,0.6)"),Q.addColorStop(1,"rgba(236,72,153,0.4)"),!y.isPlaying){const ee=A.width/32;for(let F=0;F<32;F++){const K=4+Math.sin(Date.now()/1e3+F*.3)*3;D.fillStyle=Q,D.fillRect(F*ee+1,A.height-K,ee-2,K)}return}const J=32,ae=A.width/J;for(let re=0;re<J;re++){const ee=re/J,K=(Math.sin(Date.now()/200+re*.5)*.3+.5)*A.height*(1-ee*.5)*(.5+Math.random()*.5);D.fillStyle=Q,D.fillRect(re*ae+1,A.height-K,ae-2,K)}};return V(),()=>cancelAnimationFrame(U.current)},[m,y.isPlaying]),u.useCallback(()=>{if(y.isPlaying)try{const D=new AudioContext().createMediaStreamDestination();Y.current=[];const V=new MediaRecorder(D.stream,{mimeType:"audio/webm"});V.ondataavailable=Q=>{Q.data.size>0&&Y.current.push(Q.data)},V.onstop=()=>{const Q=new Blob(Y.current,{type:"audio/webm"});d==null||d(Q),Z(0),H.current&&window.clearInterval(H.current)},V.start(1e3),q.current=V,I(!0),Z(0),H.current=window.setInterval(()=>{Z(Q=>Q+1)},1e3),c==null||c()}catch{}},[y.isPlaying,c,d]),u.useCallback(()=>{q.current&&L&&(q.current.stop(),I(!1),H.current&&window.clearInterval(H.current))},[L]),u.useCallback(A=>{P.current&&window.clearInterval(P.current),B(A),S(A*60),P.current=window.setInterval(()=>{S(D=>!D||D<=1?(P.current&&window.clearInterval(P.current),P.current=null,k.pause(),null):D-1)},1e3)},[k]),u.useCallback(()=>{P.current&&window.clearInterval(P.current),P.current=null,S(null),B(0)},[]),u.useEffect(()=>()=>{H.current&&window.clearInterval(H.current),P.current&&window.clearInterval(P.current),cancelAnimationFrame(U.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=y.metadata)==null?void 0:T.title)&&s.jsx("span",{className:"nice-radio-player__track",children:y.metadata.artist?`${y.metadata.artist} — ${y.metadata.title}`:y.metadata.title}),((C=y.metadata)==null?void 0:C.genre)&&s.jsx("span",{className:"nice-radio-player__genre",children:y.metadata.genre}),y.isBuffering&&s.jsx("span",{className:"nice-radio-player__buffering",children:(w==null?void 0:w("buffering"))??"Buffering..."})]})]}):s.jsx("div",{className:"nice-radio-player__placeholder",children:(w==null?void 0:w("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":y.isPlaying?"Pause":"Play",children:y.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:y.volume,onChange:A=>k.setVolume(parseFloat(A.target.value)),className:"nice-radio-player__volume-slider","aria-label":"Volume"})]}),s.jsx("button",{className:`nice-radio-player__eq-btn${R?" nice-radio-player__eq-btn--active":""}`,onClick:()=>_(!R),title:"Equalizer",children:"EQ"})]}),y.error&&s.jsx("div",{className:"nice-radio-player__error",children:y.error}),R&&s.jsx("div",{className:"nice-radio-player__equalizer",children:s.jsxs("div",{className:"nice-radio-player__eq-presets",children:[r.map(A=>s.jsx("button",{className:`nice-radio-player__eq-preset${y.activePreset===A.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>k.applyEQPreset(A),children:A.name},A.name)),y.activePreset&&s.jsx("button",{className:"nice-radio-player__eq-preset",onClick:k.clearEQ,children:(w==null?void 0:w("clear"))??"Clear"})]})}),h&&s.jsx(kl,{stations:e,activeStationId:M==null?void 0:M.id,onSelect:$})]})}const e0=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],t0={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class Ml{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??e0,audioConstraints:{...t0,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 n0(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function r0(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function a0(){return new AudioContext({sampleRate:48e3,latencyHint:"interactive"})}const Pa=u.forwardRef(function(t,n){const{mode:r="bars",width:a=300,height:o=100,barCount:i=32,barColor:l="#3b82f6",backgroundColor:c="transparent",fftSize:d=256,smoothing:h=.8,minDecibels:f=-90,maxDecibels:m=-10,deviceId:g,autoStart:p=!1,onStart:v,onStop:x,onAudioLevel:b,onError:w,className:y,style:k,barBorderRadius:M=2,barGap:N=2,lineWidth:R=2}=t,_=u.useRef(null),E=u.useRef(null),U=u.useRef(null),W=u.useRef(null),j=u.useRef(0),L=u.useRef(null),I=u.useRef(0),[q,Y]=u.useState(!1),O=u.useCallback(($,T,C=!0)=>{const A=C?$.createLinearGradient(0,o,0,0):$.createLinearGradient(0,0,a,0);return T.forEach((D,V)=>{A.addColorStop(V/(T.length-1),D)}),A},[a,o]),Z=u.useCallback(($,T)=>{const A=(a-(i-1)*N)/i,D=Math.floor(T.length/i),V=Array.isArray(l)?l:[l],Q=V.length>1?O($,V):V[0];$.fillStyle=Q;for(let J=0;J<i;J++){const re=T[J*D]/255*o,ee=J*(A+N),F=o-re;M>0?($.beginPath(),$.roundRect(ee,F,A,re,M),$.fill()):$.fillRect(ee,F,A,re)}},[i,l,N,M,a,o,O]),H=u.useCallback(($,T)=>{const C=o/2,D=(a-(i-1)*N)/i,V=Math.floor(T.length/i),Q=Array.isArray(l)?l:[l],J=Q.length>1?O($,Q):Q[0];$.fillStyle=J;for(let ae=0;ae<i;ae++){const ee=T[ae*V]/255*C,F=ae*(D+N);M>0?($.beginPath(),$.roundRect(F,C-ee,D,ee,M),$.fill(),$.beginPath(),$.roundRect(F,C,D,ee,M),$.fill()):($.fillRect(F,C-ee,D,ee),$.fillRect(F,C,D,ee))}},[i,l,N,M,a,o,O]),te=u.useCallback(($,T)=>{const C=Array.isArray(l)?l:[l];$.strokeStyle=C.length>1?O($,C,!1):C[0],$.lineWidth=R,$.lineCap="round",$.lineJoin="round",$.beginPath();const A=a/T.length;let D=0;for(let V=0;V<T.length;V++){const J=T[V]/128*o/2;V===0?$.moveTo(D,J):$.lineTo(D,J),D+=A}$.stroke()},[l,R,a,o,O]),B=u.useCallback(($,T)=>{const C=a/2,A=o/2,D=Math.min(a,o)/3,V=Array.isArray(l)?l:[l];$.strokeStyle=V.length>1?O($,V):V[0],$.lineWidth=R;const Q=Math.floor(T.length/64),J=Math.PI*2/64;$.beginPath();for(let ae=0;ae<64;ae++){const re=T[ae*Q]/255,ee=D+re*D*.5,F=ae*J-Math.PI/2,K=C+Math.cos(F)*ee,se=A+Math.sin(F)*ee;ae===0?$.moveTo(K,se):$.lineTo(K,se)}$.closePath(),$.stroke()},[l,R,a,o,O]),z=u.useCallback(()=>{const $=_.current,T=U.current,C=L.current;if(!$||!T||!C)return;const A=$.getContext("2d");if(!A)return;r==="waveform"?T.getByteTimeDomainData(C):T.getByteFrequencyData(C);let D=0;for(let V=0;V<C.length;V++)D+=C[V];switch(I.current=D/(C.length*255),b==null||b(I.current),A.clearRect(0,0,a,o),c!=="transparent"&&(A.fillStyle=c,A.fillRect(0,0,a,o)),r){case"bars":Z(A,C);break;case"mirror-bars":H(A,C);break;case"waveform":te(A,C);break;case"circle":B(A,C);break}j.current=requestAnimationFrame(z)},[r,a,o,c,Z,H,te,B,b]),S=u.useCallback(async()=>{try{if(q)return;const $=await navigator.mediaDevices.getUserMedia({audio:g?{deviceId:{exact:g}}:!0,video:!1});W.current=$;const T=new AudioContext;E.current=T;const C=T.createMediaStreamSource($),A=T.createAnalyser();A.fftSize=d,A.smoothingTimeConstant=h,A.minDecibels=f,A.maxDecibels=m,C.connect(A),U.current=A,L.current=new Uint8Array(A.frequencyBinCount),Y(!0),v==null||v(),z()}catch($){w==null||w($ instanceof Error?$:new Error(String($)))}},[q,g,d,h,f,m,v,w,z]),P=u.useCallback(()=>{cancelAnimationFrame(j.current),W.current&&(W.current.getTracks().forEach(T=>T.stop()),W.current=null),E.current&&(E.current.close(),E.current=null),U.current=null,L.current=null,I.current=0,Y(!1),x==null||x();const $=_.current;if($){const T=$.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:S,stop:P,isCapturing:()=>q,getAudioLevel:()=>I.current}),[S,P,q]),u.useEffect(()=>(p&&S(),()=>{P()}),[p]),s.jsx("canvas",{ref:_,width:a,height:o,className:y,style:{display:"block",...k},"aria-label":"Audio visualizer"})}),Rs=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}}},s0={position:"fixed",display:"flex",flexDirection:"column",gap:8,padding:12,borderRadius:12,boxShadow:"0 4px 20px 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"},o0={background:"rgba(255, 255, 255, 0.95)",text:"#1a1a1a",textSecondary:"#666",border:"rgba(0, 0, 0, 0.1)",speakingRing:"#22c55e",mutedBg:"#fee2e2",mutedIcon:"#ef4444",activeBg:"#dcfce7",activeIcon:"#22c55e",hoverBg:"rgba(0, 0, 0, 0.05)"},i0={background:"rgba(30, 30, 30, 0.95)",text:"#ffffff",textSecondary:"#a0a0a0",border:"rgba(255, 255, 255, 0.1)",speakingRing:"#22c55e",mutedBg:"#7f1d1d",mutedIcon:"#fca5a5",activeBg:"#14532d",activeIcon:"#86efac",hoverBg:"rgba(255, 255, 255, 0.1)"},jl=u.forwardRef(function(t,n){const{userId:r,userName:a,userAvatarUrl:o,participants:i=[],rtcConfig:l,position:c="bottom-right",expanded:d=!0,onSignalingMessage:h,onMuteToggle:f,onLeave:m,onSpeakingChange:g,speakingThreshold:p=.1,theme:v="auto",className:x,style:b,zIndex:w=1e3}=t,y=u.useRef(null),k=u.useRef(null),M=u.useRef(new Map);u.useRef(new Map);const[N,R]=u.useState(!1),[_,E]=u.useState(!1),[U,W]=u.useState(!1),[j,L]=u.useState(d),q=u.useMemo(()=>v==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":v,[v])==="dark"?i0:o0;u.useEffect(()=>{const z=new Ml(r,l);return z.onRemoteStream=(S,P)=>{let $=M.current.get(S);$||($=new Audio,$.autoplay=!0,M.current.set(S,$)),$.srcObject=P},z.onSignalingMessage=S=>{h==null||h(S)},z.onPeerStateChange=(S,P)=>{P==="connected"&&E(!0)},y.current=z,z.initialize().then(()=>{var S;(S=k.current)==null||S.start()}),()=>{z.disconnect(),M.current.forEach(S=>{S.srcObject=null}),M.current.clear()}},[r,l,h]);const Y=u.useCallback(()=>{var S;const z=!N;R(z),(S=y.current)==null||S.setMuted(z),f==null||f(z)},[N,f]),O=u.useCallback(()=>{var z,S;(z=y.current)==null||z.disconnect(),(S=k.current)==null||S.stop(),E(!1),m==null||m()},[m]),Z=u.useCallback(z=>{const S=z>p;S!==U&&(W(S),g==null||g(r,S))},[p,U,r,g]),H=u.useCallback(async z=>{var S;await((S=y.current)==null?void 0:S.createOffer(z))},[]),te=u.useCallback(async z=>{var S;await((S=y.current)==null?void 0:S.handleSignalingMessage(z))},[]);u.useImperativeHandle(n,()=>({connectToPeer:H,handleSignalingMessage:te,toggleMute:Y,isMuted:()=>N,leave:O,getManager:()=>y.current}),[H,te,Y,N,O]);const B=({participant:z,isLocal:S,isSpeaking:P})=>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:q.hoverBg,border:`2px solid ${P?q.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:q.text,transition:"border-color 0.15s ease"},children:z.avatarUrl?s.jsx("img",{src:z.avatarUrl,alt:z.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):z.name.charAt(0).toUpperCase()}),s.jsx("div",{style:{flex:1,minWidth:0},children:s.jsxs("div",{style:{color:q.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[z.name,S&&s.jsx("span",{style:{color:q.textSecondary,fontWeight:400},children:" (You)"})]})}),z.isMuted&&s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:q.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 j?s.jsxs("div",{className:x,style:{...s0,...Rs(c),backgroundColor:q.background,border:`1px solid ${q.border}`,zIndex:w,...b},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${q.border}`},children:[s.jsx("span",{style:{color:q.text,fontWeight:600},children:"Voice Chat"}),s.jsx("button",{onClick:()=>L(!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:q.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(B,{participant:{id:r,name:a,avatarUrl:o,isMuted:N},isLocal:!0,isSpeaking:U&&!N}),i.map(z=>s.jsx(B,{participant:z,isSpeaking:z.isSpeaking},z.id))]}),s.jsx(Pa,{ref:k,mode:"bars",width:256,height:32,barCount:24,barColor:N?"#9ca3af":["#3b82f6","#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?q.mutedBg:q.activeBg,color:N?q.mutedIcon:q.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:"#fef2f2",color:"#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",...Rs(c),zIndex:w,...b},children:s.jsxs("button",{onClick:()=>L(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:q.background,boxShadow:"0 4px 12px 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:q.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:q.speakingRing,color:"#fff",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:i.length+1})]})})});function l0(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 c0(e){return e.undoIndex<0?e:{...e,undoIndex:e.undoIndex-1}}function d0(e){return e.undoIndex>=e.operations.length-1?e:{...e,undoIndex:e.undoIndex+1}}function u0(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 h0(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 Rl={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 f0(e,t,n){const r=Rl[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 p0(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 m0(e){return e>=95?"S":e>=85?"A":e>=70?"B":e>=55?"C":e>=40?"D":"F"}const g0={"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]}},y0={"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=Cn;exports.ALL_EFFECTS=dp;exports.ALL_TEXTURES=ko;exports.ARTNET_PORT=Gp;exports.ASYMMETRIC_CAPS=po;exports.ArpeggiatorPanel=Vs;exports.AudioEffectType=yl;exports.AudioPitchAnalyzer=jo;exports.AudioPlaybackEngine=Kh;exports.AudioRecorder=Js;exports.AudioTimeline=Ls;exports.AutoSavePanel=Ks;exports.BarFillEditor=Mo;exports.CCAutomationLaneEditor=zs;exports.CCLane=Es;exports.CONTROLLER_PROFILES=Ci;exports.ChaseRunner=Kp;exports.CollaboratorPermission=bl;exports.DEFAULT_ARP_CONFIG=Ar;exports.DEFAULT_BAR_FILL=At;exports.DEFAULT_CAP_STYLE=go;exports.DEFAULT_EMPTY_BAR_FILL=lr;exports.DEFAULT_FONT_SETTINGS=ur;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=cr;exports.DEFAULT_GOLD_FILLED_BAR_FILL=dr;exports.DEFAULT_KARAOKE_SETTINGS=yo;exports.DEFAULT_PLAYER_BAR_STYLE=Xt;exports.DEFAULT_SEED_CONFIG=mi;exports.DMXEngine=wl;exports.DRUM_PATTERN_NAMES=cf;exports.DefaultScoringPresets=ta;exports.DmxChannelControl=Ta;exports.DmxChannelType=kt;exports.DmxEditor=xl;exports.DmxOptionsControl=$a;exports.DmxSliderControl=kn;exports.DynamicRuleEditor=Zo;exports.DynamicRuleField=Ye;exports.DynamicRuleOperator=Ze;exports.EditorTrackProvider=Qr;exports.EditorUndoManager=ed;exports.FIXTURE_PROFILES=Sl;exports.GENERIC_PROFILE=Sa;exports.GM_DRUM_MAP=y0;exports.GRADIENT_PRESETS=Ro;exports.GROOVE_TEMPLATES=Ma;exports.GenericPlayer=Do;exports.GenericPlayerControls=_o;exports.GenericPlayerStage=zo;exports.GenericPlayerStageVisualizer=Bo;exports.GenericPlaylist=Wo;exports.GenericPlaylistItem=pa;exports.KARAOKE_FONT_OPTIONS=Hd;exports.KEY_MAPS=Po;exports.KaraokeEditorManager=Io;exports.KaraokeFormat=gl;exports.KaraokeLyrics=ao;exports.KaraokePhaserRenderer=Lo;exports.KaraokeTimeline=wo;exports.LANE_COLORS=yn;exports.LAUNCH_CONTROL_PROFILE=wi;exports.LAYER_COLORS=Lp;exports.LFOPanel=qs;exports.MINILAB_PROFILE=Si;exports.MPK_MINI_PROFILE=xi;exports.MasterFXPanel=Xs;exports.MidiCCMapper=uf;exports.ModeSwitcher=ha;exports.NOTE_NAMES=nf;exports.NiceArpeggiatorPanel=Vs;exports.NiceAudioErrorBoundary=Ol;exports.NiceAudioPitchAnalyzer=jo;exports.NiceAudioTimeline=Ls;exports.NiceAutoSavePanel=Ks;exports.NiceBarFillEditor=Mo;exports.NiceCCAutomationLaneEditor=zs;exports.NiceCCLane=Es;exports.NiceDMXTimeline=Yp;exports.NiceDmxChannelControl=Ta;exports.NiceDmxEditor=xl;exports.NiceDmxOptionsControl=$a;exports.NiceDmxSliderControl=kn;exports.NiceDynamicRuleEditor=Zo;exports.NiceEditorTrackProvider=Qr;exports.NiceGenericPlayer=Do;exports.NiceGenericPlayerControls=_o;exports.NiceGenericPlayerStage=zo;exports.NiceGenericPlayerStageVisualizer=Bo;exports.NiceGenericPlaylist=Wo;exports.NiceGenericPlaylistItem=pa;exports.NiceI18nProvider=Dl;exports.NiceKaraokeEditorManager=Io;exports.NiceKaraokeLyrics=ao;exports.NiceKaraokePhaserRenderer=Lo;exports.NiceKaraokeTimeline=wo;exports.NiceLFOPanel=qs;exports.NiceMasterFXPanel=Xs;exports.NiceModeSwitcher=ha;exports.NiceNoteParticles=fi;exports.NiceNoteRiver=hi;exports.NicePianoRoll=Ps;exports.NicePlaylistBrowser=ei;exports.NicePlaylistDualPane=Xo;exports.NicePlaylistGridView=ri;exports.NicePlaylistImportWizard=ii;exports.NicePlaylistList=ba;exports.NicePlaylistOverview=ai;exports.NicePlaylistSearchBar=si;exports.NicePlaylistSidebar=ni;exports.NicePlaylistTagEditor=Uo;exports.NicePlaylistTrackList=ga;exports.NiceRadioPlayer=Jp;exports.NiceRecordingOptionsPanel=Qs;exports.NiceStageVisualizer=fa;exports.NiceStationBrowser=kl;exports.NiceStepSequencerPanel=Hs;exports.NiceStreamingVisualizer=Pa;exports.NiceUndoRedoPanel=Ys;exports.NiceVoiceChatOverlay=jl;exports.NiceWaveform=Ts;exports.NiceYouTubePlayer=Go;exports.NiceZoomSnapControls=Zs;exports.NoteParticles=fi;exports.NoteRiver=hi;exports.OVERLAY_PATTERNS=nr;exports.OXYGEN25_PROFILE=vi;exports.PLAYER_COLORS=Pt;exports.PLAYER_COLOR_VARS=Zn;exports.PROGRESSION_NAMES=lf;exports.PadNotePlayer=Xd;exports.PaneSide=qo;exports.PianoRoll=Ps;exports.PlaylistBrowser=ei;exports.PlaylistDualPane=Xo;exports.PlaylistGridView=ri;exports.PlaylistImportWizard=ii;exports.PlaylistList=ba;exports.PlaylistOverview=ai;exports.PlaylistSearchBar=si;exports.PlaylistSidebar=ni;exports.PlaylistTagEditor=Uo;exports.PlaylistTrackList=ga;exports.PlaylistType=ma;exports.RecordingOptionsPanel=Qs;exports.SACN_PORT=Vp;exports.SCALE_INTERVALS=Rl;exports.SCALE_NAMES=of;exports.SKEW_CAPS=mo;exports.STANDARD_TUNINGS=g0;exports.SYMMETRIC_CAPS=ia;exports.ShortcutManager=pl;exports.SimpleSynth=pi;exports.SortDirection=qt;exports.SortField=Ho;exports.StageVisualizer=fa;exports.StepSequencerPanel=Hs;exports.StreamingVisualizer=Pa;exports.TEXTURE_CATEGORIES=ca;exports.TrackSource=lt;exports.UndoRedoPanel=Ys;exports.ViewMode=Vo;exports.VocalEffectsEngine=up;exports.VoiceChatOverlay=jl;exports.Waveform=Ts;exports.WebRTCAudioManager=Ml;exports.YouTubePlayer=Go;exports.ZoomSnapControls=Zs;exports.addEffectToLayer=Bf;exports.addMidiNote=Vf;exports.analyzeAudioFileWithAlgorithm=ep;exports.applyGroove=ip;exports.applyGrooveTemplate=dl;exports.applyHumanize=cl;exports.applyKaraokeDisplayVars=ua;exports.applyMidiTransform=p0;exports.applySwing=ll;exports.arrow_L=Mt;exports.arrow_R=gt;exports.autoCorrelate=Ef;exports.bracket_L=ra;exports.bracket_R=ho;exports.buildArpSequence=Gs;exports.buildLanes=Eo;exports.buildNoteDescriptors=Af;exports.buildPadNoteEvents=No;exports.buildSegmentScores=Nf;exports.canRedo=Ti;exports.canUndo=$i;exports.chamfer_L=Qn;exports.chamfer_R=Zt;exports.clearMidiNotes=Hf;exports.clearPattern=Hi;exports.computeGrade=m0;exports.computeTheoreticalMax=al;exports.computeVocalPerformanceReport=hp;exports.convertBrowserSongToKaraokeSongFile=zf;exports.copyCCEvents=qr;exports.createAnalyserNode=Qi;exports.createArpPattern=bf;exports.createArtNetPacket=Up;exports.createBasslinePattern=vf;exports.createCCHistory=ki;exports.createCompressorNode=el;exports.createDefaultLFO=ir;exports.createDefaultShortcuts=Mp;exports.createDropZoneHandlers=Np;exports.createEmptyPattern=Nt;exports.createEmptyStep=wa;exports.createGainNode=Ji;exports.createHiHatPattern=yf;exports.createKickPattern=mf;exports.createLoopRegion=vp;exports.createSACNPacket=qp;exports.createSnarePattern=gf;exports.createVocoderNode=tl;exports.createVoiceChatAudioContext=a0;exports.cutCCEvents=Ei;exports.deleteCCEventsInRange=Ai;exports.deserializeLFO=dc;exports.deserializePattern=Sf;exports.detectChord=h0;exports.downsampleAndQuantizePitchPoints=If;exports.drawGlossyBarOnCanvas=hn;exports.drawTimeline=Dr;exports.estimateLatencyMs=Lf;exports.estimateLatencyMsFromRecording=mp;exports.evaluateLFO=Zr;exports.evaluateLFOAsCC=Xr;exports.exportCCLane=Li;exports.extractBpmFromNotes=so;exports.findTextureByUrl=Ud;exports.formatShortcut=jp;exports.generateArpEvents=fc;exports.generatePlaceholderWaveform=sp;exports.generateSeed=bi;exports.generateUltrastarText=tp;exports.getActiveGradient=To;exports.getActiveLyrics=od;exports.getActiveWords=id;exports.getAlgorithmColor=Df;exports.getAlgorithmCssVar=Of;exports.getAlgorithmLabel=Ff;exports.getArpModes=Ws;exports.getArpRates=Us;exports.getAudioContext=tn;exports.getAudioInputDevices=r0;exports.getAudioWorkletProcessorCode=Zi;exports.getBackgroundUrl=Pf;exports.getCachedImage=Bd;exports.getCapStyleByName=dn;exports.getComboMultiplier=rl;exports.getCoverUrl=Tf;exports.getGrooveTemplate=lp;exports.getGrooveTemplateNames=cp;exports.getLaneForPitch=Ao;exports.getNextPlayerColor=Fp;exports.getNextPlayerColorCss=Dp;exports.getOverlayCanvasPattern=gn;exports.getPatternByName=un;exports.getSACNMulticastAddress=Hp;exports.getScoringPreset=lo;exports.getTexturePattern=pn;exports.getVerseRatingLabel=nl;exports.handleAddCCEvent=Yf;exports.handleRedo=Jc;exports.handleRemoveCCEvent=Xf;exports.handleSelectCCLane=Kf;exports.handleUndo=Qc;exports.handleUpdateCCEvent=Zf;exports.hexToHsl=rr;exports.humanizeMidiNotes=bp;exports.hydrateKaraokeDisplayFromBackend=Kd;exports.hydratePlayerKaraokeSettingsFromBackend=vd;exports.hzToUltrastarPitch=oo;exports.importCCLane=Fi;exports.initKaraokeDisplaySettings=Zd;exports.instrumentPresets=Yh;exports.isAudioContextRunning=As;exports.isInLoopRegion=wp;exports.isWebRTCSupported=n0;exports.loadAllKaraokeSettings=xd;exports.loadAudioWorkletModule=Xi;exports.loadKaraokeDisplaySettings=$o;exports.loadKaraokeSettings=bo;exports.loadPlayerBarStyle=vo;exports.loadPlayerBarStyles=wd;exports.loadRemoteScoringPresets=md;exports.makeClickReference=hl;exports.makeClipSelectionId=np;exports.mergeWaveforms=ap;exports.midiSeedGenerator=df;exports.midiToHz=Or;exports.normalizeHex=ar;exports.openAudioFilePicker=Ip;exports.ornate_L=sa;exports.ornate_R=tr;exports.parseLyrics=ad;exports.parseNotes=ea;exports.parseVersesWithSyllables=ro;exports.parseVersesWithWords=sd;exports.parseVideoMetadata=ol;exports.pasteCCEvents=Pi;exports.pill_L=$t;exports.pill_R=Ct;exports.preloadTexture=la;exports.preloadTextures=Gd;exports.probeAudioFile=ml;exports.pushCCState=Mi;exports.pushOperation=l0;exports.quantizeMidiNotes=gp;exports.quantizeNotes=u0;exports.quantizeStepInBeats=fl;exports.quantizeStepInSeconds=ja;exports.randomizeVelocity=qi;exports.recordCCEvent=Ni;exports.redoCC=Ri;exports.redoOperation=d0;exports.removeEffectFromLayer=Gf;exports.removeMidiNote=qf;exports.renderGlossyBarSvg=xo;exports.resumeAudioContext=Et;exports.reversePattern=Ui;exports.sampleLFOForDisplay=_s;exports.sampleLFOToCCEvents=Os;exports.saveKaraokeDisplaySettings=Yd;exports.saveKaraokeSettings=bd;exports.savePlayerBarStyle=Sd;exports.scaleResult=$f;exports.scaleTo10k=sl;exports.scoreNotesWithPitchPoints=Rf;exports.selectCCEventsInRange=hf;exports.serializeLFO=cc;exports.serializePattern=xf;exports.setLoopFromSelection=xp;exports.setProjectWithUndo=to;exports.setStepGate=zi;exports.setStepNote=Oi;exports.setStepProbability=Bi;exports.setStepVelocity=_i;exports.sharp_L=Kt;exports.sharp_R=Yt;exports.shield_L=Jn;exports.shield_R=uo;exports.shiftPattern=Vi;exports.shouldTrigger=Yi;exports.skewTL_L=Un;exports.skewTL_R=Fr;exports.skewTR_L=Lr;exports.skewTR_R=Vn;exports.snapLoopToGrid=Sp;exports.snapTimeToQuantize=Hr;exports.snapToGrid=rp;exports.snapToScale=f0;exports.soft_L=na;exports.soft_R=co;exports.stepDuration=Ca;exports.stepTimeOffset=Ki;exports.syncDivisionToHz=Fs;exports.tab_L=aa;exports.tab_R=fo;exports.thinCCEvents=Ii;exports.toTrack=_f;exports.toggleEffectBypass=Wf;exports.toggleStep=Di;exports.toggleStepSlide=Gi;exports.transposePattern=Wi;exports.undoCC=ji;exports.undoOperation=c0;exports.updateEffectParams=Uf;exports.useAudioWorklet=jf;exports.useAutoSave=Kc;exports.useCCAutomation=pf;exports.useDMXAudioSync=Xp;exports.useDMXEngine=Zp;exports.useEditorTrack=rd;exports.useLocalPlaylists=ya;exports.useMPE=Jh;exports.useMidiLearn=Xh;exports.useNiceTranslation=xe;exports.useOxygen25=tf;exports.usePitchWorker=Cf;exports.usePlaybackEngine=Yc;exports.useProjectCRUD=nd;exports.useRadioStream=Cl;exports.useRecording=Zc;exports.useScoringWorker=kf;exports.useStepSequencer=wf;exports.useWebMidi=pr;exports.useWorker=ka;exports.validateAudioFiles=Ra;exports.wave_L=er;exports.wave_R=oa;exports.waveformValue=Ds;exports.wrapTimeInLoop=Cp;
412
+ E`}}function np(e,t){return`${e}:${t}`}function rp(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 ap(e){return e.length===0?[]:e.flat()}function sp(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const Ma=[{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 op(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function ll(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 cl(e,t){const n=t.seed!=null?op(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 dl(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 ip(e,t){let n=[...e.map(r=>({...r}))];return t.template&&t.grooveStrength>0&&(n=dl(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=ll(n,t.swing)),t.humanize&&(n=cl(n,t.humanize)),n}function lp(e){return Ma.find(t=>t.id===e)}function cp(){return Ma.map(({id:e,name:t})=>({id:e,name:t}))}const dp=[{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 Ms(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 Bn(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 up{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),h=t.createOscillator(),f=t.createOscillator(),m=t.createGain(),g=t.createGain(),p=n-1,v=Math.abs(p)*5+2,x=Math.abs(p)*.015;h.type="sawtooth",h.frequency.value=v,m.gain.value=x,h.connect(m),m.connect(c.delayTime),c.delayTime.value=.02,f.type="sawtooth",f.frequency.value=v,g.gain.value=x,f.connect(g),g.connect(d.delayTime),d.delayTime.value=.02+x;const b=t.createGain();b.gain.value=.5;const w=t.createGain();return w.gain.value=.5,a.connect(c),a.connect(d),c.connect(b),d.connect(w),b.connect(i),w.connect(i),a.connect(l),i.connect(o),l.connect(o),h.start(),f.start(),{type:"chipmunk",nodes:[a,c,d,h,f,m,g,b,w,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 h=t.createGain();return h.gain.value=.3,r.connect(h),h.connect(a),o.start(),c.start(),{type:"alien",nodes:[r,o,i,l,c,d,h,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 h=t.createGain();return h.gain.value=1,o.connect(l),l.connect(c),c.connect(l),l.connect(d),o.connect(h),d.connect(i),h.connect(i),{type:"echo",nodes:[o,l,c,d,h,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 h=t.createGain();h.gain.value=.25;const f=t.createConvolver();f.buffer=Ms(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(h),h.connect(l),o.connect(m),i.connect(m),l.connect(m),r.connect(f),f.connect(m);const g=t.createGain();return g.gain.value=.7,r.connect(g),g.connect(a),m.connect(a),{type:"cave",nodes:[r,o,i,l,c,d,h,f,m,g,a],input:r,output:a}}buildReverb(t,n,r,a){const o=t.createGain(),i=t.createGain(),l=t.createConvolver();l.buffer=Ms(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 h=t.createOscillator();h.type="sine",h.frequency.value=c.lfoFreq;const f=t.createGain();f.gain.value=c.depth*(.5+n),h.connect(f),f.connect(d.delayTime);const m=t.createGain();m.gain.value=.3+n*.2,r.connect(d),d.connect(m),m.connect(a),h.start(),i.push(d,h,f,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 h=t.createGain();return h.gain.value=1,r.connect(o),o.connect(c),c.connect(o),o.connect(d),r.connect(h),d.connect(a),h.connect(a),i.start(),{type:"flanger",nodes:[r,o,i,l,c,d,h,a],input:r,output:a}}buildDistortion(t,n,r){const a=t.createGain(),o=t.createGain(),i=t.createWaveShaper();i.curve=Bn(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=Bn(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=Bn(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 h=d/255*2-1;l[d]=Math.sign(h)*Math.pow(Math.abs(h),.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=Bn(20+n*50),c.oversample="2x";const d=t.createBiquadFilter();d.type="lowshelf",d.frequency.value=200,d.gain.value=8+n*8;const h=t.createGain();h.gain.value=.7+n*.3;const f=t.createGain();return f.gain.value=.3,r.connect(o),o.connect(c),c.connect(d),d.connect(h),r.connect(f),h.connect(a),f.connect(a),i.start(),{type:"demon",nodes:[r,o,i,l,c,d,h,f,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],h=t.createGain();h.gain.value=.15;for(const g of d){const p=t.createBiquadFilter();p.type="peaking",p.frequency.value=g,p.Q.value=8+n*15,p.gain.value=4+n*8,r.connect(p),p.connect(h),c.push(p)}const f=t.createGain();f.gain.value=.7;const m=t.createGain();return m.gain.value=.5+n*.3,r.connect(o),o.connect(m),h.connect(m),r.connect(f),m.connect(a),f.connect(a),i.start(),{type:"autotune",nodes:[r,o,i,l,...c,h,m,f,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 f=0;f<l;f++){const m=200*Math.pow(2,f*.5),g=t.createBiquadFilter();g.type="bandpass",g.frequency.value=m,g.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(g),g.connect(v.gain),o.connect(p),p.connect(v),v.connect(d),c.push(g,p,v)}d.connect(a);const h=t.createGain();return h.gain.value=.3-n*.2,r.connect(h),h.connect(a),c.push(h),o.start(),{type:"vocoder",nodes:c,input:r,output:a}}}const ul=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Ut(e){return 12*Math.log2(e/440)+69}function Wn(e){const t=ul[Math.round(e)%12],n=Math.floor(Math.round(e)/12)-1;return`${t}${n}`}function $r(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 hp(e){const{playerName:t,playerColor:n,songTitle:r,songArtist:a,songBpm:o,difficulty:i,pitchPoints:l,notes:c,verseRatings:d,combo:h,classicScore:f,bonusScore:m,totalScore:g,micSettings:p}=e,v=l.filter(ne=>ne.hz>0),x=v.map(ne=>Ut(ne.hz)),b=[],w=[],y=[],k=[...c].sort((ne,oe)=>ne.startTime-oe.startTime);function M(ne){let oe=0,Ne=k.length-1;for(;oe<=Ne;){const De=oe+Ne>>>1,Pe=k[De];if(ne<Pe.startTime)Ne=De-1;else if(ne>Pe.startTime+Pe.duration)oe=De+1;else return Pe.pitch}return 0}for(const ne of l){const oe=ne.hz>0?Ut(ne.hz):0,Ne=M(ne.t);if(w.push({t:ne.t,sung:oe,expected:Ne}),oe>0&&Ne>0){const De=(oe-Ne)*100;b.push(De)}}let N=0;for(const ne of k){const oe=ne.startTime-.3,Ne=ne.startTime+ne.duration;for(;N<v.length&&v[N].t<oe;)N++;N<v.length&&v[N].t<=Ne&&y.push((v[N].t-ne.startTime)*1e3)}const R=b.map(Math.abs),_=[...R].sort((ne,oe)=>ne-oe),E=R.length>0?R.reduce((ne,oe)=>ne+oe,0)/R.length:0,U=$r(_,50),W=R.length>1?Math.sqrt(R.reduce((ne,oe)=>ne+(oe-E)**2,0)/(R.length-1)):0,j=R.filter(ne=>ne<=50).length,L=R.filter(ne=>ne<=15).length,I=R.length>0?j/R.length*100:0,q=R.length>0?L/R.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,z=te>0?Ut(te):0,S=G>0?Ut(G):0,P=S-z,$=[...x].sort((ne,oe)=>ne-oe),T=$r($,10),C=$r($,90),A=new Array(12).fill(0);for(const ne of x){const oe=Math.round(ne)%12;oe>=0&&oe<12&&A[oe]++}const D=A.reduce((ne,oe)=>ne+oe,0),V=ul.map((ne,oe)=>({note:ne,count:A[oe],pct:D>0?A[oe]/D*100:0})),Q=fp(v),J=y.length>0?y.reduce((ne,oe)=>ne+oe,0)/y.length:0,ae=y.length>1?Math.sqrt(y.reduce((ne,oe)=>ne+(oe-J)**2,0)/(y.length-1)):0,re=ae>0?Math.max(0,Math.min(100,100-ae/2)):100;let ee=0,F=0;for(let ne=1;ne<x.length;ne++){const oe=Math.abs(x[ne]-x[ne-1]);ee+=oe,F++}const K=F>0?ee/F*100/12:0,se=l.filter(ne=>ne.hz<=0).length,ce=l.length>0?(1-se/l.length)*100:0,fe=new Map;for(const ne of c){const oe=ne.line??0;fe.has(oe)||fe.set(oe,[]),fe.get(oe).push(ne)}const X=new Map;for(const ne of v){const oe=M(ne.t);if(oe<=0)continue;let Ne=0,De=k.length-1,Pe=-1;for(;Ne<=De;){const we=Ne+De>>>1,dt=k[we];if(ne.t<dt.startTime)De=we-1;else if(ne.t>dt.startTime+dt.duration)Ne=we+1;else{Pe=dt.line??0;break}}if(Pe<0)continue;const tt=Math.abs((Ut(ne.hz)-oe)*100);X.has(Pe)||X.set(Pe,[]),X.get(Pe).push(tt)}const ue=d.map(ne=>{const oe=fe.get(ne.verseIndex)??[],Ne=X.get(ne.verseIndex)??[],De=Ne.length>0?Ne.reduce((Pe,tt)=>Pe+tt,0)/Ne.length:0;return{verseIndex:ne.verseIndex,label:ne.label,hitFraction:ne.hitFraction,avgCentDeviation:Math.round(De*10)/10,noteCount:oe.length,notesHit:Math.round(ne.hitFraction*oe.length),comboBonus:ne.comboBonus}}),ye=2,je=.5,Fe=l.length>0?l[l.length-1].t:0,Re=[],Se=w.filter(ne=>ne.sung>0&&ne.expected>0);if(Se.length>0){let ne=0,oe=0,Ne=0;for(let De=0;De<=Fe;De+=je){const Pe=De-ye/2,tt=De+ye/2;for(;oe<Se.length&&Se[oe].t<tt;)Math.abs(Se[oe].sung-Se[oe].expected)<=.5&&Ne++,oe++;for(;ne<oe&&Se[ne].t<Pe;)Math.abs(Se[ne].sung-Se[ne].expected)<=.5&&Ne--,ne++;const we=oe-ne;Re.push({t:De,accuracy:we>0?Ne/we*100:0})}}else for(let ne=0;ne<=Fe;ne+=je)Re.push({t:ne,accuracy:0});return{playerName:t,playerColor:n,songTitle:r,songArtist:a,songBpm:o,difficulty:i,timestamp:new Date().toISOString(),classicScore:f,bonusScore:m,totalScore:g,maxCombo:(h==null?void 0:h.maxCombo)??0,totalComboBonus:(h==null?void 0:h.totalComboBonus)??0,totalPitchPoints:l.length,avgCentDeviation:Math.round(E*10)/10,medianCentDeviation:Math.round(U*10)/10,stdDevCents:Math.round(W*10)/10,intonationAccuracyPct:Math.round(I*10)/10,perfectHitPct:Math.round(q*10)/10,pitchDeviationHistogram:Z,lowestHz:Math.round(te*10)/10,highestHz:Math.round(G*10)/10,lowestNote:z>0?Wn(z):"—",highestNote:S>0?Wn(S):"—",rangeInSemitones:Math.round(P*10)/10,tessituraLow:T>0?Wn(T):"—",tessituraHigh:C>0?Wn(C):"—",pitchClassDistribution:V,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:ue,micSettings:p,pitchOverTime:w,accuracyOverTime:Re}}function fp(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(g=>Ut(g.hz)),n=e.map(g=>g.t),r=.5,a=[],o=[];let i=0,l=0,c=0;for(let g=0;g<e.length;g++){for(l+=t[g],c++;i<g&&n[g]-n[i]>=r;)l-=t[i],c--,i++;if(c<6||(g-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<=g;k++){const M=t[k]-p;M*x<0&&v++,x=M;const N=Math.abs(M);N>b&&(b=N)}const w=n[g]-n[i];if(w<=0)continue;const y=v/2/w;y>=3&&y<=12&&(a.push(y),o.push(b*100))}if(a.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const d=a.reduce((g,p)=>g+p,0)/a.length,h=o.reduce((g,p)=>g+p,0)/o.length,f=Math.sqrt(a.reduce((g,p)=>g+(p-d)**2,0)/a.length),m=Math.max(0,Math.min(100,100-f*20));return{detected:!0,avgRateHz:Math.round(d*10)/10,avgExtentCents:Math.round(h*10)/10,regularityPct:Math.round(m)}}function hl(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))),h=o+c-Math.floor(i/2);h>=0&&h<a&&(l[h]=d)}return l}function js(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 h=0;for(let f=c;f<d;f++)h+=Math.abs(e[f]);o[l]=h/(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 pp(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 g=m+i+Math.floor((r-n)/2);if(g<0||g>=r)continue;const p=e[m],v=t[g];l+=p*v,c+=p*p,d+=v*v}const h=Math.sqrt(Math.max(1e-9,c*d)),f=l/h;f>a.score&&(a={lag:i,score:f})}return a.lag}function mp(e,t,n=50,r=30){try{const a=Math.max(300,Math.round(e.length/t*1e3)),o=hl(a,t,n,r),i=js(e,t,1e3),l=js(o,t,1e3),d=pp(l.env,i.env)*1e3/1e3;return Math.round(d)}catch{return null}}function fl(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 ja(e,t){return fl(e)*60/t}function Hr(e,t,n){const r=ja(t,n);return Math.round(e/r)*r}function gp(e,t){const{value:n,bpm:r,strength:a=1,quantizeStarts:o=!0,quantizeDurations:i=!1}=t,l=ja(n,r);return e.map(c=>{let{start:d,duration:h}=c;if(o){const f=Math.round(d/l)*l;d=d+(f-d)*a}if(i){const f=Math.max(l,Math.round(h/l)*l);h=h+(f-h)*a}return d===c.start&&h===c.duration?c:{...c,start:d,duration:h}})}function yp(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function bp(e,t={}){const{timingRange:n=.02,velocityRange:r=10,seed:a}=t,o=a!=null?yp(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 vp(){return{start:0,end:0,enabled:!1}}function xp(e,t){return{...e<t?{start:e,end:t}:{start:t,end:e},enabled:!0}}function Sp(e,t,n){return{start:Hr(e.start,t,n),end:Hr(e.end,t,n),enabled:e.enabled}}function wp(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function Cp(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 Kr(e){return e.length===1?e.toLowerCase():e}function Yn(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(Kr(e.key)),t.join("+")}function kp(e,t){var l,c,d,h;const n=Kr(e.key)===Kr(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==!!((h=t.modifiers)!=null&&h.meta);return n&&r&&a&&o&&i}class pl{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];Yn(o.binding)===Yn(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?Yn(n.binding):""}handleKeyDown(t){if(!this.enabled)return!1;for(const n of this.actions.values())if(n.enabled&&this.activeScopes.has(n.scope)&&kp(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 Mp(e={}){const t=new pl,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 jp(e){return Yn(e)}const Rp=["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"],$p=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],Tp=500*1024*1024,Pp=20;function jt(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function Ep(e,t){return!!(e.type&&t.some(n=>e.type.startsWith(n.replace("*","")))||e.type.startsWith("audio/"))}function Ap(e,t){const n=jt(e.name);return n!==""&&t.includes(n)}function Ra(e,t={}){const n=t.maxSize??Tp,r=t.allowedTypes??Rp,a=t.allowedExtensions??$p,o=t.maxFiles??Pp,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(!Ep(d,r)&&!Ap(d,a)){l.push({file:d,reason:"type",message:`Unsupported file type: ${d.type||jt(d.name)}`});continue}i.push(d)}return{valid:i,errors:l}}async function ml(e){const t={file:e,name:e.name.replace(/\.[^.]+$/,""),extension:jt(e.name),sizeBytes:e.size,mimeType:e.type||`audio/${jt(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 Np(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,h;n.preventDefault(),n.stopPropagation(),t=0,(d=e.onDragLeave)==null||d.call(e);const r="dataTransfer"in n?n.dataTransfer:null;if(!((h=r==null?void 0:r.files)!=null&&h.length))return;const a=Array.from(r.files),{valid:o,errors:i}=Ra(a,e.validation),l=[],c=[...i];for(const f of o)if(e.probe)try{l.push(await ml(f))}catch{c.push({file:f,reason:"decode",message:"Failed to decode audio"})}else l.push({file:f,name:f.name.replace(/\.[^.]+$/,""),extension:jt(f.name),sizeBytes:f.size,mimeType:f.type||`audio/${jt(f.name)}`});e.onDrop({accepted:l,rejected:c})}}}function Ip(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}=Ra(r,e.validation),i=a.map(c=>({file:c,name:c.name.replace(/\.[^.]+$/,""),extension:jt(c.name),sizeBytes:c.size,mimeType:c.type||`audio/${jt(c.name)}`}));t({accepted:i,rejected:o})},n.click()})}var gl=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(gl||{}),kt=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(kt||{}),yl=(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))(yl||{}),bl=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(bl||{});const Lp=["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)"],Pt=["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 Fp(e){for(const t of Pt)if(!e.includes(t))return t;return Pt[Math.floor(Math.random()*Pt.length)]}const Zn=Pt.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function Dp(e){for(let t=0;t<Pt.length;t++){const n=Pt[t],r=Zn[t];if(!e.includes(n)&&!e.includes(r))return r}return Zn[Math.floor(Math.random()*Zn.length)]}const or=["off","no function","brak"],Op=e=>e.segments.some(t=>t.isOff||or.some(n=>t.name.toLowerCase().includes(n))),_p=e=>e.segments.find(t=>t.isOff||or.some(n=>t.name.toLowerCase().includes(n))),vl=e=>Math.floor((e.valueFrom+e.valueTo)/2),zp=e=>{const t=_p(e);return t?vl(t):0},Gp=(e,t)=>e.segments.find(n=>t>=n.valueFrom&&t<=n.valueTo),cn=(e,t=0,n=255)=>Math.max(t,Math.min(n,Math.round(e))),kn=({channel:e,value:t,onChange:n,onCommit:r,showDirectionHint:a})=>{const[o,i]=u.useState(cn(t)),l=u.useMemo(()=>Gp(e,o),[e,o]);u.useEffect(()=>i(cn(t)),[t]);const c=d=>{const h=cn(d);i(h),n(h),r==null||r(h)};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 h=cn(Number(d.target.value));i(h),n(h)},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 h=cn(Number(d.target.value));i(h),n(h)},onBlur:()=>r==null?void 0:r(o),style:{width:80,padding:6,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:6}})}),Op(e)&&s.jsx("button",{type:"button",onClick:()=>c(zp(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"})]})},$a=({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)+(or.some(f=>l.name.toLowerCase().includes(f))?-1:0),h=(c.isOff?-1:0)+(or.some(f=>c.name.toLowerCase().includes(f))?-1:0);return d!==h?d-h:l.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),i},[e]),o=i=>{const l=vl(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}`)})})]})},Ta=e=>{switch(e.channel.type){case kt.Dimmer:case kt.DimmerWithOff:return s.jsx(kn,{...e});case kt.RotationWithOff:case kt.RotationWithOffAndCcw:return s.jsx(kn,{...e,showDirectionHint:!0});case kt.Options:return s.jsx($a,{...e});default:return s.jsx(kn,{...e})}},Tr=e=>Math.max(0,Math.min(255,Math.round(e)));function xl({service:e,pollInterval:t=500,className:n,style:r,channels:a,onChannelChange:o,fixtures:i}){if(!e)return s.jsx("div",{className:n,style:r,children:s.jsx("small",{children:"Provide a `service` prop (DmxService) to control hardware."})});const[l,c]=u.useState([]),[d,h]=u.useState(null),[f,m]=u.useState(()=>Array(513).fill(0)),[g,p]=u.useState(30),[v,x]=u.useState(0),[b,w]=u.useState(!1),y=u.useRef(null);u.useEffect(()=>{let j=!1;return e.getDevices().then(L=>{j||(c(L),L.length>0&&h(L[0]))}).catch(()=>{}),()=>{j=!0}},[e]),u.useEffect(()=>{if(y.current&&window.clearInterval(y.current),!(t<=0))return y.current=window.setInterval(async()=>{try{const j=await e.getState();Array.isArray(j.frontSnapshot)&&j.frontSnapshot.length>=513&&m(j.frontSnapshot.slice(0,513)),typeof j.fps=="number"&&p(j.fps),typeof j.startCode=="number"&&x(j.startCode)}catch{}},t),()=>{y.current&&window.clearInterval(y.current)}},[e,t]);const k=async()=>{d&&(await e.openPort(d.serialNumber||d.description),w(!0))},M=async()=>{await e.closePort(),w(!1)},N=async()=>{await e.blackout(),m(j=>{const L=[...j];for(let I=1;I<L.length;I++)L[I]=0;return L})},R=()=>e.configure(g,v),_=(j,L)=>{const I=Tr(L);m(q=>{const Y=[...q];return Y[j]=I,Y})},E=(j,L)=>e.setChannel(j,Tr(L)),U=(d==null?void 0:d.deviceInfo)??null,W=u.useMemo(()=>{var j;return(j=U==null?void 0:U.channels)!=null&&j.length?U.channels:Array.from({length:16},(L,I)=>({channel:I+1,name:`Channel ${I+1}`,type:kt.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[U]);return s.jsxs("div",{className:`ntd-dmx-editor ${n??""}`,style:{padding:16,display:"grid",gap:16,...r},children:[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:(d==null?void 0:d.serialNumber)||"",onChange:j=>h(l.find(L=>L.serialNumber===j.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"},children:l.map(j=>{var L,I;return s.jsxs("option",{value:j.serialNumber,children:[((L=j.deviceInfo)==null?void 0:L.manufacturer)??""," ",((I=j.deviceInfo)==null?void 0:I.model)??j.description," (",j.serialNumber||j.description,")"]},j.serialNumber||j.description)})}),U&&s.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:["Mode: ",s.jsx("b",{children:U.modeName}),", footprint: ",s.jsx("b",{children:U.footprint})]})]}),s.jsx("button",{onClick:k,disabled:!d||b,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:M,disabled:!b,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:N,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-text-secondary, #4b5563)",background:"var(--nice-bg-secondary, #f3f4f6)",cursor:"pointer"},children:"Blackout"})]}),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:g,onChange:j=>p(Number(j.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:v,onChange:j=>x(Tr(Number(j.target.value))),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),s.jsx("div",{children:s.jsx("button",{onClick:R,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:W.map(j=>s.jsx(Ta,{channel:j,value:f[j.channel]??0,onChange:L=>_(j.channel,L),onCommit:L=>E(j.channel,L)},j.channel))})]})]})}const Sl=[{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 wl{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,Sl.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,h)=>{d.name.toLowerCase().includes("red")?c[h]=n:d.name.toLowerCase().includes("green")?c[h]=r:d.name.toLowerCase().includes("blue")?c[h]=a:d.name.toLowerCase().includes("white")&&(c[h]=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 h=performance.now()-c,f=Math.min(1,h/r);let m=f;switch(a){case"ease-in":m=f*f;break;case"ease-out":m=1-(1-f)*(1-f);break;case"ease-in-out":m=f<.5?2*f*f:1-Math.pow(-2*f+2,2)/2;break}const g=l.map((p,v)=>{const x=n[v]??p;return Math.round(p+(x-p)*m)});this.setFixtureValues(t,g),f<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 Bp=6454,Wp=new Uint8Array([65,114,116,45,78,101,116,0]);function Up(e,t){const n=new Uint8Array(18+t.length);return n.set(Wp,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 Vp=5568;function qp(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 h=i-16;c.setUint16(16,28672|h&4095,!1),c.setUint32(18,4,!1);for(let p=0;p<16;p++)l[22+p]=p+1;const f=i-38;c.setUint16(38,28672|f&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 g=o+11;return c.setUint16(115,28672|g&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 Hp(e){const t=e>>8&255,n=e&255;return`239.255.${t}.${n}`}class Kp{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 Yp=({engine:e,tracks:t=[],scenes:n=[],duration:r=3e5,currentTime:a=0,bpm:o=120,onTimeChange:i,onCueAdd:l,onCueUpdate:c,onCueDelete:d,onTrackAdd:h,onTrackUpdate:f,onPlay:m,onPause:g,onStop:p,className:v=""})=>{const[x,b]=u.useState(1),[w,y]=u.useState(0),[k,M]=u.useState(!1),[N,R]=u.useState(null),[_,E]=u.useState(null),[U,W]=u.useState(!0),[j,L]=u.useState(1e3),I=u.useRef(null),q=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(!U)return C;const A=6e4/o;return Math.round(C/A)*A},[U,o]);u.useEffect(()=>{if(k){const C=performance.now(),A=a,D=()=>{const V=performance.now()-C,Q=A+V;if(Q>=r){M(!1),i==null||i(0),p==null||p();return}G(Q),i==null||i(Q),q.current=requestAnimationFrame(D)};q.current=requestAnimationFrame(D),m==null||m()}else q.current!==null&&(cancelAnimationFrame(q.current),q.current=null),g==null||g();return()=>{q.current!==null&&cancelAnimationFrame(q.current)}},[k,a,r,i,m,g,p]);const G=u.useCallback(C=>{t.forEach(A=>{A.muted||A.cues.forEach(D=>{const V=D.startTime,Q=V+D.duration;if(C>=V&&C<Q&&Y.current<V){const J=n.find(ae=>ae.id===D.sceneId);J&&J.fixtures.forEach(ae=>{D.fadeIn&&D.fadeIn>0?e.fadeFixture(ae.fixtureId,ae.values,D.fadeIn):e.setFixtureValues(ae.fixtureId,ae.values)})}if(Y.current<Q&&C>=Q){const J=n.find(ae=>ae.id===D.sceneId);J&&J.fixtures.forEach(ae=>{if(e.getFixture(ae.fixtureId)&&D.fadeOut&&D.fadeOut>0){const ee=new Array(ae.values.length).fill(0);e.fadeFixture(ae.fixtureId,ee,D.fadeOut)}})}})}),Y.current=C},[t,n,e]),z=C=>{const A=Math.floor(C/1e3),D=Math.floor(A/60),V=A%60,Q=Math.floor(C%1e3/(1e3/30));return`${D}:${V.toString().padStart(2,"0")}:${Q.toString().padStart(2,"0")}`},S=u.useCallback(C=>{if(!I.current)return;const A=I.current.getBoundingClientRect(),D=C.clientX-A.left+w,V=te(H(D));i==null||i(Math.max(0,Math.min(r,V)))},[w,H,te,r,i]),P=u.useCallback((C,A,D)=>{const V=t.find(ae=>ae.id===A),Q=V==null?void 0:V.cues.find(ae=>ae.id===C);if(!Q)return;const J=te(Math.max(0,Q.startTime+H(D)));c==null||c({...Q,startTime:J})},[t,H,te,c]),$=()=>{const C=6e4/o,A=Math.ceil(r/C),D=[];for(let V=0;V<=A;V++){const Q=V*C,J=Z(Q),ae=V%4===0;D.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:V/4+1})},V))}return D},T=(C,A)=>{const D=Z(C.startTime),V=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:D,width:V,backgroundColor:(Q==null?void 0:Q.color)||A.color||"var(--nice-accent, #8b5cf6)"},onClick:J=>{J.stopPropagation(),R(C.id)},draggable:!A.locked,onDragEnd:J=>{var re;const ae=(re=J.target.parentElement)==null?void 0:re.getBoundingClientRect();ae&&P(C.id,A.id,J.clientX-ae.left-D)},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:z(a)}),s.jsxs("div",{className:"nice-dmx-timeline__tools",children:[s.jsx("button",{type:"button",className:U?"active":"",onClick:()=>W(!U),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:()=>E(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:A=>{A.stopPropagation(),f==null||f({...C,muted:!C.muted})},title:"Mute",children:"M"}),s.jsx("button",{type:"button",className:C.locked?"active":"",onClick:A=>{A.stopPropagation(),f==null||f({...C,locked:!C.locked})},title:"Lock",children:"🔒"})]})]},C.id)),s.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"})]}),s.jsxs("div",{className:"nice-dmx-timeline__tracks",ref:I,onClick:S,onScroll:C=>y(C.currentTarget.scrollLeft),children:[s.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:Z(r)},children:$()}),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(A=>T(A,C))},C.id)),s.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:Z(a)}})]})]})]})};function Zp(){const[e]=u.useState(()=>new wl);return u.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function Xp(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 Qp=[{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 Cl(){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),[h,f]=u.useState(null),m=u.useRef(null),g=u.useRef(null),p=u.useRef(null),v=u.useRef(null),x=u.useRef([]),b=u.useRef(null),w=u.useRef(null),y=u.useCallback(()=>{if(g.current)return;const I=new AudioContext;g.current=I;const q=I.createGain();q.gain.value=n,v.current=q;const Y=I.createAnalyser();Y.fftSize=256,b.current=Y,q.connect(Y).connect(I.destination)},[]),k=u.useCallback(()=>{const I=m.current,q=g.current,Y=v.current;if(!I||!q||!Y||p.current)return;const O=q.createMediaElementSource(I);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 q;const I=m.current;!I||!w.current||(Et(),y(),k(),((q=g.current)==null?void 0:q.state)==="suspended"&&g.current.resume(),I.play().catch(Y=>d(String(Y))))},[y,k]),N=u.useCallback(()=>{var I;(I=m.current)==null||I.pause()},[]),R=u.useCallback(()=>{e?N():M()},[e,M,N]),_=u.useCallback(I=>{const q=Math.max(0,Math.min(1,I));r(q),v.current&&(v.current.gain.value=q),m.current&&(m.current.volume=q)},[]),E=u.useCallback(I=>{w.current=I,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=I.streamUrl,m.current.load(),l({genre:I.genre,bitrate:I.bitrate})},[]),U=u.useCallback(I=>{g.current||y();const Y=g.current;x.current.forEach(Z=>Z.disconnect());const O=I.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)),f(I.name)},[y]),W=u.useCallback(()=>{x.current.forEach(I=>I.disconnect()),x.current=[],p.current&&v.current&&(p.current.disconnect(),p.current.connect(v.current)),f(null)},[]);return u.useEffect(()=>()=>{var I,q,Y;(I=m.current)==null||I.pause(),m.current=null,x.current.forEach(O=>O.disconnect()),(q=p.current)==null||q.disconnect(),(Y=g.current)==null||Y.close()},[]),[{isPlaying:e,volume:n,isBuffering:a,metadata:i,error:c,activePreset:h},{play:M,pause:N,toggle:R,setVolume:_,setStation:E,applyEQPreset:U,clearEQ:W}]}function kl({stations:e,activeStationId:t,onSelect:n,onToggleFavorite:r,className:a}){const{t:o}=xe(),[i,l]=u.useState(""),[c,d]=u.useState(null),[h,f]=u.useState(!1),m=u.useMemo(()=>[...new Set(e.map(p=>p.genre).filter(Boolean))],[e]),g=u.useMemo(()=>e.filter(p=>{var v,x;if(h&&!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,h]);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${h?" nice-station-browser__fav-toggle--active":""}`,onClick:()=>f(!h),title:(o==null?void 0:o("favorites"))??"Favorites",children:"★"})]}),s.jsxs("div",{className:"nice-station-browser__list",children:[g.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)),g.length===0&&s.jsx("div",{className:"nice-station-browser__empty",children:(o==null?void 0:o("no_stations_found"))??"No stations found"})]})]})}function Jp({stations:e,initialStationId:t,autoPlay:n=!1,eqPresets:r=Qp,onStationChange:a,onPlayingChange:o,onMetadata:i,onToggleFavorite:l,onRecordingStart:c,onRecordingStop:d,showBrowser:h=!0,showEqualizer:f=!1,showVisualizer:m=!1,showMetadataHistory:g=!1,showRecording:p=!1,showSleepTimer:v=!1,className:x,style:b}){var T,C;const{t:w}=xe(),[y,k]=Cl(),[M,N]=u.useState(()=>t?e.find(A=>A.id===t)??null:null),[R,_]=u.useState(f),E=u.useRef(null),U=u.useRef(0),[W,j]=u.useState([]),[L,I]=u.useState(!1),q=u.useRef(null),Y=u.useRef([]),[O,Z]=u.useState(0),H=u.useRef(null),[te,G]=u.useState(0),[z,S]=u.useState(null),P=u.useRef(null);u.useEffect(()=>{o==null||o(y.isPlaying)},[y.isPlaying,o]),u.useEffect(()=>{y.metadata&&(i==null||i(y.metadata),(y.metadata.title||y.metadata.artist)&&j(A=>[{time:new Date,meta:y.metadata},...A.slice(0,49)]))},[y.metadata,i]);const $=u.useCallback(A=>{N(A),k.setStation(A),a==null||a(A),n&&setTimeout(()=>k.play(),100)},[k,a,n]);return u.useEffect(()=>{if(t&&!M){const A=e.find(D=>D.id===t);A&&$(A)}},[t,e]),u.useEffect(()=>{if(!m||!E.current)return;const A=E.current,D=A.getContext("2d");if(!D)return;const V=()=>{U.current=requestAnimationFrame(V),D.clearRect(0,0,A.width,A.height);const Q=D.createLinearGradient(0,A.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)"),!y.isPlaying){const ee=A.width/32;for(let F=0;F<32;F++){const K=4+Math.sin(Date.now()/1e3+F*.3)*3;D.fillStyle=Q,D.fillRect(F*ee+1,A.height-K,ee-2,K)}return}const J=32,ae=A.width/J;for(let re=0;re<J;re++){const ee=re/J,K=(Math.sin(Date.now()/200+re*.5)*.3+.5)*A.height*(1-ee*.5)*(.5+Math.random()*.5);D.fillStyle=Q,D.fillRect(re*ae+1,A.height-K,ae-2,K)}};return V(),()=>cancelAnimationFrame(U.current)},[m,y.isPlaying]),u.useCallback(()=>{if(y.isPlaying)try{const D=new AudioContext().createMediaStreamDestination();Y.current=[];const V=new MediaRecorder(D.stream,{mimeType:"audio/webm"});V.ondataavailable=Q=>{Q.data.size>0&&Y.current.push(Q.data)},V.onstop=()=>{const Q=new Blob(Y.current,{type:"audio/webm"});d==null||d(Q),Z(0),H.current&&window.clearInterval(H.current)},V.start(1e3),q.current=V,I(!0),Z(0),H.current=window.setInterval(()=>{Z(Q=>Q+1)},1e3),c==null||c()}catch{}},[y.isPlaying,c,d]),u.useCallback(()=>{q.current&&L&&(q.current.stop(),I(!1),H.current&&window.clearInterval(H.current))},[L]),u.useCallback(A=>{P.current&&window.clearInterval(P.current),G(A),S(A*60),P.current=window.setInterval(()=>{S(D=>!D||D<=1?(P.current&&window.clearInterval(P.current),P.current=null,k.pause(),null):D-1)},1e3)},[k]),u.useCallback(()=>{P.current&&window.clearInterval(P.current),P.current=null,S(null),G(0)},[]),u.useEffect(()=>()=>{H.current&&window.clearInterval(H.current),P.current&&window.clearInterval(P.current),cancelAnimationFrame(U.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=y.metadata)==null?void 0:T.title)&&s.jsx("span",{className:"nice-radio-player__track",children:y.metadata.artist?`${y.metadata.artist} — ${y.metadata.title}`:y.metadata.title}),((C=y.metadata)==null?void 0:C.genre)&&s.jsx("span",{className:"nice-radio-player__genre",children:y.metadata.genre}),y.isBuffering&&s.jsx("span",{className:"nice-radio-player__buffering",children:(w==null?void 0:w("buffering"))??"Buffering..."})]})]}):s.jsx("div",{className:"nice-radio-player__placeholder",children:(w==null?void 0:w("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":y.isPlaying?"Pause":"Play",children:y.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:y.volume,onChange:A=>k.setVolume(parseFloat(A.target.value)),className:"nice-radio-player__volume-slider","aria-label":"Volume"})]}),s.jsx("button",{className:`nice-radio-player__eq-btn${R?" nice-radio-player__eq-btn--active":""}`,onClick:()=>_(!R),title:"Equalizer",children:"EQ"})]}),y.error&&s.jsx("div",{className:"nice-radio-player__error",children:y.error}),R&&s.jsx("div",{className:"nice-radio-player__equalizer",children:s.jsxs("div",{className:"nice-radio-player__eq-presets",children:[r.map(A=>s.jsx("button",{className:`nice-radio-player__eq-preset${y.activePreset===A.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>k.applyEQPreset(A),children:A.name},A.name)),y.activePreset&&s.jsx("button",{className:"nice-radio-player__eq-preset",onClick:k.clearEQ,children:(w==null?void 0:w("clear"))??"Clear"})]})}),h&&s.jsx(kl,{stations:e,activeStationId:M==null?void 0:M.id,onSelect:$})]})}const e0=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],t0={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class Ml{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??e0,audioConstraints:{...t0,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 n0(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function r0(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function a0(){return new AudioContext({sampleRate:48e3,latencyHint:"interactive"})}const Pa=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:h=.8,minDecibels:f=-90,maxDecibels:m=-10,deviceId:g,autoStart:p=!1,onStart:v,onStop:x,onAudioLevel:b,onError:w,className:y,style:k,barBorderRadius:M=2,barGap:N=2,lineWidth:R=2}=t,_=u.useRef(null),E=u.useRef(null),U=u.useRef(null),W=u.useRef(null),j=u.useRef(0),L=u.useRef(null),I=u.useRef(0),[q,Y]=u.useState(!1),O=u.useCallback(($,T,C=!0)=>{const A=C?$.createLinearGradient(0,o,0,0):$.createLinearGradient(0,0,a,0);return T.forEach((D,V)=>{A.addColorStop(V/(T.length-1),D)}),A},[a,o]),Z=u.useCallback(($,T)=>{const A=(a-(i-1)*N)/i,D=Math.floor(T.length/i),V=Array.isArray(l)?l:[l],Q=V.length>1?O($,V):V[0];$.fillStyle=Q;for(let J=0;J<i;J++){const re=T[J*D]/255*o,ee=J*(A+N),F=o-re;M>0?($.beginPath(),$.roundRect(ee,F,A,re,M),$.fill()):$.fillRect(ee,F,A,re)}},[i,l,N,M,a,o,O]),H=u.useCallback(($,T)=>{const C=o/2,D=(a-(i-1)*N)/i,V=Math.floor(T.length/i),Q=Array.isArray(l)?l:[l],J=Q.length>1?O($,Q):Q[0];$.fillStyle=J;for(let ae=0;ae<i;ae++){const ee=T[ae*V]/255*C,F=ae*(D+N);M>0?($.beginPath(),$.roundRect(F,C-ee,D,ee,M),$.fill(),$.beginPath(),$.roundRect(F,C,D,ee,M),$.fill()):($.fillRect(F,C-ee,D,ee),$.fillRect(F,C,D,ee))}},[i,l,N,M,a,o,O]),te=u.useCallback(($,T)=>{const C=Array.isArray(l)?l:[l];$.strokeStyle=C.length>1?O($,C,!1):C[0],$.lineWidth=R,$.lineCap="round",$.lineJoin="round",$.beginPath();const A=a/T.length;let D=0;for(let V=0;V<T.length;V++){const J=T[V]/128*o/2;V===0?$.moveTo(D,J):$.lineTo(D,J),D+=A}$.stroke()},[l,R,a,o,O]),G=u.useCallback(($,T)=>{const C=a/2,A=o/2,D=Math.min(a,o)/3,V=Array.isArray(l)?l:[l];$.strokeStyle=V.length>1?O($,V):V[0],$.lineWidth=R;const Q=Math.floor(T.length/64),J=Math.PI*2/64;$.beginPath();for(let ae=0;ae<64;ae++){const re=T[ae*Q]/255,ee=D+re*D*.5,F=ae*J-Math.PI/2,K=C+Math.cos(F)*ee,se=A+Math.sin(F)*ee;ae===0?$.moveTo(K,se):$.lineTo(K,se)}$.closePath(),$.stroke()},[l,R,a,o,O]),z=u.useCallback(()=>{const $=_.current,T=U.current,C=L.current;if(!$||!T||!C)return;const A=$.getContext("2d");if(!A)return;r==="waveform"?T.getByteTimeDomainData(C):T.getByteFrequencyData(C);let D=0;for(let V=0;V<C.length;V++)D+=C[V];switch(I.current=D/(C.length*255),b==null||b(I.current),A.clearRect(0,0,a,o),c!=="transparent"&&(A.fillStyle=c,A.fillRect(0,0,a,o)),r){case"bars":Z(A,C);break;case"mirror-bars":H(A,C);break;case"waveform":te(A,C);break;case"circle":G(A,C);break}j.current=requestAnimationFrame(z)},[r,a,o,c,Z,H,te,G,b]),S=u.useCallback(async()=>{try{if(q)return;const $=await navigator.mediaDevices.getUserMedia({audio:g?{deviceId:{exact:g}}:!0,video:!1});W.current=$;const T=new AudioContext;E.current=T;const C=T.createMediaStreamSource($),A=T.createAnalyser();A.fftSize=d,A.smoothingTimeConstant=h,A.minDecibels=f,A.maxDecibels=m,C.connect(A),U.current=A,L.current=new Uint8Array(A.frequencyBinCount),Y(!0),v==null||v(),z()}catch($){w==null||w($ instanceof Error?$:new Error(String($)))}},[q,g,d,h,f,m,v,w,z]),P=u.useCallback(()=>{cancelAnimationFrame(j.current),W.current&&(W.current.getTracks().forEach(T=>T.stop()),W.current=null),E.current&&(E.current.close(),E.current=null),U.current=null,L.current=null,I.current=0,Y(!1),x==null||x();const $=_.current;if($){const T=$.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:S,stop:P,isCapturing:()=>q,getAudioLevel:()=>I.current}),[S,P,q]),u.useEffect(()=>(p&&S(),()=>{P()}),[p]),s.jsx("canvas",{ref:_,width:a,height:o,className:y,style:{display:"block",...k},"aria-label":"Audio visualizer"})}),Rs=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}}},s0={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"},o0={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))"},i0={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))"},jl=u.forwardRef(function(t,n){const{userId:r,userName:a,userAvatarUrl:o,participants:i=[],rtcConfig:l,position:c="bottom-right",expanded:d=!0,onSignalingMessage:h,onMuteToggle:f,onLeave:m,onSpeakingChange:g,speakingThreshold:p=.1,theme:v="auto",className:x,style:b,zIndex:w=1e3}=t,y=u.useRef(null),k=u.useRef(null),M=u.useRef(new Map);u.useRef(new Map);const[N,R]=u.useState(!1),[_,E]=u.useState(!1),[U,W]=u.useState(!1),[j,L]=u.useState(d),q=u.useMemo(()=>v==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":v,[v])==="dark"?i0:o0;u.useEffect(()=>{const z=new Ml(r,l);return z.onRemoteStream=(S,P)=>{let $=M.current.get(S);$||($=new Audio,$.autoplay=!0,M.current.set(S,$)),$.srcObject=P},z.onSignalingMessage=S=>{h==null||h(S)},z.onPeerStateChange=(S,P)=>{P==="connected"&&E(!0)},y.current=z,z.initialize().then(()=>{var S;(S=k.current)==null||S.start()}),()=>{z.disconnect(),M.current.forEach(S=>{S.srcObject=null}),M.current.clear()}},[r,l,h]);const Y=u.useCallback(()=>{var S;const z=!N;R(z),(S=y.current)==null||S.setMuted(z),f==null||f(z)},[N,f]),O=u.useCallback(()=>{var z,S;(z=y.current)==null||z.disconnect(),(S=k.current)==null||S.stop(),E(!1),m==null||m()},[m]),Z=u.useCallback(z=>{const S=z>p;S!==U&&(W(S),g==null||g(r,S))},[p,U,r,g]),H=u.useCallback(async z=>{var S;await((S=y.current)==null?void 0:S.createOffer(z))},[]),te=u.useCallback(async z=>{var S;await((S=y.current)==null?void 0:S.handleSignalingMessage(z))},[]);u.useImperativeHandle(n,()=>({connectToPeer:H,handleSignalingMessage:te,toggleMute:Y,isMuted:()=>N,leave:O,getManager:()=>y.current}),[H,te,Y,N,O]);const G=({participant:z,isLocal:S,isSpeaking:P})=>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:q.hoverBg,border:`2px solid ${P?q.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:q.text,transition:"border-color 0.15s ease"},children:z.avatarUrl?s.jsx("img",{src:z.avatarUrl,alt:z.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):z.name.charAt(0).toUpperCase()}),s.jsx("div",{style:{flex:1,minWidth:0},children:s.jsxs("div",{style:{color:q.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[z.name,S&&s.jsx("span",{style:{color:q.textSecondary,fontWeight:400},children:" (You)"})]})}),z.isMuted&&s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:q.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 j?s.jsxs("div",{className:x,style:{...s0,...Rs(c),backgroundColor:q.background,border:`1px solid ${q.border}`,zIndex:w,...b},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${q.border}`},children:[s.jsx("span",{style:{color:q.text,fontWeight:600},children:"Voice Chat"}),s.jsx("button",{onClick:()=>L(!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:q.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:U&&!N}),i.map(z=>s.jsx(G,{participant:z,isSpeaking:z.isSpeaking},z.id))]}),s.jsx(Pa,{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?q.mutedBg:q.activeBg,color:N?q.mutedIcon:q.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",...Rs(c),zIndex:w,...b},children:s.jsxs("button",{onClick:()=>L(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:q.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:q.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:q.speakingRing,color:"var(--nice-bg, #fff)",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:i.length+1})]})})});function l0(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 c0(e){return e.undoIndex<0?e:{...e,undoIndex:e.undoIndex-1}}function d0(e){return e.undoIndex>=e.operations.length-1?e:{...e,undoIndex:e.undoIndex+1}}function u0(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 h0(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 Rl={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 f0(e,t,n){const r=Rl[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 p0(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 m0(e){return e>=95?"S":e>=85?"A":e>=70?"B":e>=55?"C":e>=40?"D":"F"}const g0={"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]}},y0={"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=Cn;exports.ALL_EFFECTS=dp;exports.ALL_TEXTURES=ko;exports.ARTNET_PORT=Bp;exports.ASYMMETRIC_CAPS=po;exports.ArpeggiatorPanel=Vs;exports.AudioEffectType=yl;exports.AudioPitchAnalyzer=jo;exports.AudioPlaybackEngine=Kh;exports.AudioRecorder=Js;exports.AudioTimeline=Ls;exports.AutoSavePanel=Ks;exports.BarFillEditor=Mo;exports.CCAutomationLaneEditor=zs;exports.CCLane=Es;exports.CONTROLLER_PROFILES=Ci;exports.ChaseRunner=Kp;exports.CollaboratorPermission=bl;exports.DEFAULT_ARP_CONFIG=Ar;exports.DEFAULT_BAR_FILL=At;exports.DEFAULT_CAP_STYLE=go;exports.DEFAULT_EMPTY_BAR_FILL=lr;exports.DEFAULT_FONT_SETTINGS=ur;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=cr;exports.DEFAULT_GOLD_FILLED_BAR_FILL=dr;exports.DEFAULT_KARAOKE_SETTINGS=yo;exports.DEFAULT_PLAYER_BAR_STYLE=Xt;exports.DEFAULT_SEED_CONFIG=mi;exports.DMXEngine=wl;exports.DRUM_PATTERN_NAMES=cf;exports.DefaultScoringPresets=ta;exports.DmxChannelControl=Ta;exports.DmxChannelType=kt;exports.DmxEditor=xl;exports.DmxOptionsControl=$a;exports.DmxSliderControl=kn;exports.DynamicRuleEditor=Zo;exports.DynamicRuleField=Ye;exports.DynamicRuleOperator=Ze;exports.EditorTrackProvider=Qr;exports.EditorUndoManager=ed;exports.FIXTURE_PROFILES=Sl;exports.GENERIC_PROFILE=Sa;exports.GM_DRUM_MAP=y0;exports.GRADIENT_PRESETS=Ro;exports.GROOVE_TEMPLATES=Ma;exports.GenericPlayer=Do;exports.GenericPlayerControls=_o;exports.GenericPlayerStage=zo;exports.GenericPlayerStageVisualizer=Go;exports.GenericPlaylist=Wo;exports.GenericPlaylistItem=pa;exports.KARAOKE_FONT_OPTIONS=Hd;exports.KEY_MAPS=Po;exports.KaraokeEditorManager=Io;exports.KaraokeFormat=gl;exports.KaraokeLyrics=ao;exports.KaraokePhaserRenderer=Lo;exports.KaraokeTimeline=wo;exports.LANE_COLORS=yn;exports.LAUNCH_CONTROL_PROFILE=wi;exports.LAYER_COLORS=Lp;exports.LFOPanel=qs;exports.MINILAB_PROFILE=Si;exports.MPK_MINI_PROFILE=xi;exports.MasterFXPanel=Xs;exports.MidiCCMapper=uf;exports.ModeSwitcher=ha;exports.NOTE_NAMES=nf;exports.NiceArpeggiatorPanel=Vs;exports.NiceAudioErrorBoundary=Ol;exports.NiceAudioPitchAnalyzer=jo;exports.NiceAudioTimeline=Ls;exports.NiceAutoSavePanel=Ks;exports.NiceBarFillEditor=Mo;exports.NiceCCAutomationLaneEditor=zs;exports.NiceCCLane=Es;exports.NiceDMXTimeline=Yp;exports.NiceDmxChannelControl=Ta;exports.NiceDmxEditor=xl;exports.NiceDmxOptionsControl=$a;exports.NiceDmxSliderControl=kn;exports.NiceDynamicRuleEditor=Zo;exports.NiceEditorTrackProvider=Qr;exports.NiceGenericPlayer=Do;exports.NiceGenericPlayerControls=_o;exports.NiceGenericPlayerStage=zo;exports.NiceGenericPlayerStageVisualizer=Go;exports.NiceGenericPlaylist=Wo;exports.NiceGenericPlaylistItem=pa;exports.NiceI18nProvider=Dl;exports.NiceKaraokeEditorManager=Io;exports.NiceKaraokeLyrics=ao;exports.NiceKaraokePhaserRenderer=Lo;exports.NiceKaraokeTimeline=wo;exports.NiceLFOPanel=qs;exports.NiceMasterFXPanel=Xs;exports.NiceModeSwitcher=ha;exports.NiceNoteParticles=fi;exports.NiceNoteRiver=hi;exports.NicePianoRoll=Ps;exports.NicePlaylistBrowser=ei;exports.NicePlaylistDualPane=Xo;exports.NicePlaylistGridView=ri;exports.NicePlaylistImportWizard=ii;exports.NicePlaylistList=ba;exports.NicePlaylistOverview=ai;exports.NicePlaylistSearchBar=si;exports.NicePlaylistSidebar=ni;exports.NicePlaylistTagEditor=Uo;exports.NicePlaylistTrackList=ga;exports.NiceRadioPlayer=Jp;exports.NiceRecordingOptionsPanel=Qs;exports.NiceStageVisualizer=fa;exports.NiceStationBrowser=kl;exports.NiceStepSequencerPanel=Hs;exports.NiceStreamingVisualizer=Pa;exports.NiceUndoRedoPanel=Ys;exports.NiceVoiceChatOverlay=jl;exports.NiceWaveform=Ts;exports.NiceYouTubePlayer=Bo;exports.NiceZoomSnapControls=Zs;exports.NoteParticles=fi;exports.NoteRiver=hi;exports.OVERLAY_PATTERNS=nr;exports.OXYGEN25_PROFILE=vi;exports.PLAYER_COLORS=Pt;exports.PLAYER_COLOR_VARS=Zn;exports.PROGRESSION_NAMES=lf;exports.PadNotePlayer=Xd;exports.PaneSide=qo;exports.PianoRoll=Ps;exports.PlaylistBrowser=ei;exports.PlaylistDualPane=Xo;exports.PlaylistGridView=ri;exports.PlaylistImportWizard=ii;exports.PlaylistList=ba;exports.PlaylistOverview=ai;exports.PlaylistSearchBar=si;exports.PlaylistSidebar=ni;exports.PlaylistTagEditor=Uo;exports.PlaylistTrackList=ga;exports.PlaylistType=ma;exports.RecordingOptionsPanel=Qs;exports.SACN_PORT=Vp;exports.SCALE_INTERVALS=Rl;exports.SCALE_NAMES=of;exports.SKEW_CAPS=mo;exports.STANDARD_TUNINGS=g0;exports.SYMMETRIC_CAPS=ia;exports.ShortcutManager=pl;exports.SimpleSynth=pi;exports.SortDirection=qt;exports.SortField=Ho;exports.StageVisualizer=fa;exports.StepSequencerPanel=Hs;exports.StreamingVisualizer=Pa;exports.TEXTURE_CATEGORIES=ca;exports.TrackSource=lt;exports.UndoRedoPanel=Ys;exports.ViewMode=Vo;exports.VocalEffectsEngine=up;exports.VoiceChatOverlay=jl;exports.Waveform=Ts;exports.WebRTCAudioManager=Ml;exports.YouTubePlayer=Bo;exports.ZoomSnapControls=Zs;exports.addEffectToLayer=Gf;exports.addMidiNote=Vf;exports.analyzeAudioFileWithAlgorithm=ep;exports.applyGroove=ip;exports.applyGrooveTemplate=dl;exports.applyHumanize=cl;exports.applyKaraokeDisplayVars=ua;exports.applyMidiTransform=p0;exports.applySwing=ll;exports.arrow_L=Mt;exports.arrow_R=gt;exports.autoCorrelate=Ef;exports.bracket_L=ra;exports.bracket_R=ho;exports.buildArpSequence=Bs;exports.buildLanes=Eo;exports.buildNoteDescriptors=Af;exports.buildPadNoteEvents=No;exports.buildSegmentScores=Nf;exports.canRedo=Ti;exports.canUndo=$i;exports.chamfer_L=Qn;exports.chamfer_R=Zt;exports.clearMidiNotes=Hf;exports.clearPattern=Hi;exports.computeGrade=m0;exports.computeTheoreticalMax=al;exports.computeVocalPerformanceReport=hp;exports.convertBrowserSongToKaraokeSongFile=zf;exports.copyCCEvents=qr;exports.createAnalyserNode=Qi;exports.createArpPattern=bf;exports.createArtNetPacket=Up;exports.createBasslinePattern=vf;exports.createCCHistory=ki;exports.createCompressorNode=el;exports.createDefaultLFO=ir;exports.createDefaultShortcuts=Mp;exports.createDropZoneHandlers=Np;exports.createEmptyPattern=Nt;exports.createEmptyStep=wa;exports.createGainNode=Ji;exports.createHiHatPattern=yf;exports.createKickPattern=mf;exports.createLoopRegion=vp;exports.createSACNPacket=qp;exports.createSnarePattern=gf;exports.createVocoderNode=tl;exports.createVoiceChatAudioContext=a0;exports.cutCCEvents=Ei;exports.deleteCCEventsInRange=Ai;exports.deserializeLFO=dc;exports.deserializePattern=Sf;exports.detectChord=h0;exports.downsampleAndQuantizePitchPoints=If;exports.drawGlossyBarOnCanvas=hn;exports.drawTimeline=Dr;exports.estimateLatencyMs=Lf;exports.estimateLatencyMsFromRecording=mp;exports.evaluateLFO=Zr;exports.evaluateLFOAsCC=Xr;exports.exportCCLane=Li;exports.extractBpmFromNotes=so;exports.findTextureByUrl=Ud;exports.formatShortcut=jp;exports.generateArpEvents=fc;exports.generatePlaceholderWaveform=sp;exports.generateSeed=bi;exports.generateUltrastarText=tp;exports.getActiveGradient=To;exports.getActiveLyrics=od;exports.getActiveWords=id;exports.getAlgorithmColor=Df;exports.getAlgorithmCssVar=Of;exports.getAlgorithmLabel=Ff;exports.getArpModes=Ws;exports.getArpRates=Us;exports.getAudioContext=tn;exports.getAudioInputDevices=r0;exports.getAudioWorkletProcessorCode=Zi;exports.getBackgroundUrl=Pf;exports.getCachedImage=Gd;exports.getCapStyleByName=dn;exports.getComboMultiplier=rl;exports.getCoverUrl=Tf;exports.getGrooveTemplate=lp;exports.getGrooveTemplateNames=cp;exports.getLaneForPitch=Ao;exports.getNextPlayerColor=Fp;exports.getNextPlayerColorCss=Dp;exports.getOverlayCanvasPattern=gn;exports.getPatternByName=un;exports.getSACNMulticastAddress=Hp;exports.getScoringPreset=lo;exports.getTexturePattern=pn;exports.getVerseRatingLabel=nl;exports.handleAddCCEvent=Yf;exports.handleRedo=Jc;exports.handleRemoveCCEvent=Xf;exports.handleSelectCCLane=Kf;exports.handleUndo=Qc;exports.handleUpdateCCEvent=Zf;exports.hexToHsl=rr;exports.humanizeMidiNotes=bp;exports.hydrateKaraokeDisplayFromBackend=Kd;exports.hydratePlayerKaraokeSettingsFromBackend=vd;exports.hzToUltrastarPitch=oo;exports.importCCLane=Fi;exports.initKaraokeDisplaySettings=Zd;exports.instrumentPresets=Yh;exports.isAudioContextRunning=As;exports.isInLoopRegion=wp;exports.isWebRTCSupported=n0;exports.loadAllKaraokeSettings=xd;exports.loadAudioWorkletModule=Xi;exports.loadKaraokeDisplaySettings=$o;exports.loadKaraokeSettings=bo;exports.loadPlayerBarStyle=vo;exports.loadPlayerBarStyles=wd;exports.loadRemoteScoringPresets=md;exports.makeClickReference=hl;exports.makeClipSelectionId=np;exports.mergeWaveforms=ap;exports.midiSeedGenerator=df;exports.midiToHz=Or;exports.normalizeHex=ar;exports.openAudioFilePicker=Ip;exports.ornate_L=sa;exports.ornate_R=tr;exports.parseLyrics=ad;exports.parseNotes=ea;exports.parseVersesWithSyllables=ro;exports.parseVersesWithWords=sd;exports.parseVideoMetadata=ol;exports.pasteCCEvents=Pi;exports.pill_L=$t;exports.pill_R=Ct;exports.preloadTexture=la;exports.preloadTextures=Bd;exports.probeAudioFile=ml;exports.pushCCState=Mi;exports.pushOperation=l0;exports.quantizeMidiNotes=gp;exports.quantizeNotes=u0;exports.quantizeStepInBeats=fl;exports.quantizeStepInSeconds=ja;exports.randomizeVelocity=qi;exports.recordCCEvent=Ni;exports.redoCC=Ri;exports.redoOperation=d0;exports.removeEffectFromLayer=Bf;exports.removeMidiNote=qf;exports.renderGlossyBarSvg=xo;exports.resumeAudioContext=Et;exports.reversePattern=Ui;exports.sampleLFOForDisplay=_s;exports.sampleLFOToCCEvents=Os;exports.saveKaraokeDisplaySettings=Yd;exports.saveKaraokeSettings=bd;exports.savePlayerBarStyle=Sd;exports.scaleResult=$f;exports.scaleTo10k=sl;exports.scoreNotesWithPitchPoints=Rf;exports.selectCCEventsInRange=hf;exports.serializeLFO=cc;exports.serializePattern=xf;exports.setLoopFromSelection=xp;exports.setProjectWithUndo=to;exports.setStepGate=zi;exports.setStepNote=Oi;exports.setStepProbability=Gi;exports.setStepVelocity=_i;exports.sharp_L=Kt;exports.sharp_R=Yt;exports.shield_L=Jn;exports.shield_R=uo;exports.shiftPattern=Vi;exports.shouldTrigger=Yi;exports.skewTL_L=Un;exports.skewTL_R=Fr;exports.skewTR_L=Lr;exports.skewTR_R=Vn;exports.snapLoopToGrid=Sp;exports.snapTimeToQuantize=Hr;exports.snapToGrid=rp;exports.snapToScale=f0;exports.soft_L=na;exports.soft_R=co;exports.stepDuration=Ca;exports.stepTimeOffset=Ki;exports.syncDivisionToHz=Fs;exports.tab_L=aa;exports.tab_R=fo;exports.thinCCEvents=Ii;exports.toTrack=_f;exports.toggleEffectBypass=Wf;exports.toggleStep=Di;exports.toggleStepSlide=Bi;exports.transposePattern=Wi;exports.undoCC=ji;exports.undoOperation=c0;exports.updateEffectParams=Uf;exports.useAudioWorklet=jf;exports.useAutoSave=Kc;exports.useCCAutomation=pf;exports.useDMXAudioSync=Xp;exports.useDMXEngine=Zp;exports.useEditorTrack=rd;exports.useLocalPlaylists=ya;exports.useMPE=Jh;exports.useMidiLearn=Xh;exports.useNiceTranslation=xe;exports.useOxygen25=tf;exports.usePitchWorker=Cf;exports.usePlaybackEngine=Yc;exports.useProjectCRUD=nd;exports.useRadioStream=Cl;exports.useRecording=Zc;exports.useScoringWorker=kf;exports.useStepSequencer=wf;exports.useWebMidi=pr;exports.useWorker=ka;exports.validateAudioFiles=Ra;exports.wave_L=er;exports.wave_R=oa;exports.waveformValue=Ds;exports.wrapTimeInLoop=Cp;