@nice2dev/ui-audio 1.0.2 → 1.0.4

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.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
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"),Er=require("pitchy"),Ll=require("react-window"),Yr=require("react-youtube"),Fl=require("@fortawesome/react-fontawesome"),Ia=require("@fortawesome/free-brands-svg-icons"),xr=require("@fortawesome/free-solid-svg-icons");var st=typeof document<"u"?document.currentScript:null;const Dl=(e,t)=>t??e,Ts=u.createContext(Dl),Ol=({t:e,children:t})=>s.jsx(Ts.Provider,{value:e,children:t});function ve(){return{t:u.useContext(Ts)}}class _l 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={},Ar={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function zl(){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 Ar?e:"WARN"}const Bl=zl();function $n(e){return Ar[e]>=Ar[Bl]}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)}}},La=et.scoped("Waveform"),Gl=["audio/","video/"],Ps=({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:g="#007bff",progressColor:m="rgba(255,0,0,0.8)",backgroundColor:p="transparent",showRuler:y=!1,showChannelLabels:x=!0,showPeakMeter:v=!1,className:C})=>{const b=u.useRef(null),k=u.useRef(null),R=u.useRef(null),[A,$]=u.useState(0),[W,w]=u.useState(!1),[D,_]=u.useState(null),[P,B]=u.useState(null),[z,K]=u.useState(0),Z=Math.max(r,r*o),O=y?24:0;u.useEffect(()=>{if(!e||e.size===0){R.current=null;return}e.type&&!Gl.some(T=>e.type.startsWith(T))&&La.warn("Unexpected blob MIME type:",e.type);let L=!1;return(async()=>{let T=null;try{const S=await e.arrayBuffer();if(S.byteLength===0||L)return;T=new AudioContext;const I=await T.decodeAudioData(S);L||(R.current=I)}catch(S){La.error("Failed to decode audio:",S)}finally{T==null||T.close().catch(()=>{})}})(),()=>{L=!0}},[e]),u.useEffect(()=>{if(o>1&&n>0){const L=t/n*Z;(L<A||L>A+r)&&$(Math.max(0,L-r/2))}},[t,n,o,r,Z,A]),u.useEffect(()=>{const L=b.current,T=R.current;if(!L||!n||n===1/0)return;const S=L.getContext("2d");if(!S)return;const I=Z,M=a;if(L.width=I,L.height=M+O,S.clearRect(0,0,I,M+O),p!=="transparent"&&(S.fillStyle=p,S.fillRect(0,0,I,M+O)),y){S.fillStyle="rgba(128,128,128,0.15)",S.fillRect(0,0,I,O),S.fillStyle="#888",S.font="10px monospace",S.textAlign="center";const F=Math.max(1,Math.floor(n/(Z/80)));for(let j=0;j<=n;j+=F){const E=j/n*I;S.fillText(ql(j),E,O-4),S.fillStyle="rgba(128,128,128,0.3)",S.fillRect(E,O,1,M),S.fillStyle="#888"}}for(const F of d){const j=F.start/n*I,E=F.end/n*I;S.fillStyle=F.color??"rgba(99,102,241,0.15)",S.fillRect(j,O,E-j,M),F.label&&(S.fillStyle=F.color??"#6366f1",S.font="10px sans-serif",S.textAlign="left",S.fillText(F.label,j+2,O+12))}if(D!==null&&P!==null){const F=Math.min(D,P),j=Math.max(D,P);S.fillStyle="rgba(255,200,0,0.2)",S.fillRect(F,O,j-F,M)}if(T){const F=f?T.numberOfChannels:1,j=M/F;let E=0;for(let H=0;H<F;H++){const Y=T.getChannelData(H),J=O+H*j;if(h==="waveform"?Wl(S,Y,I,j,J,g):h==="bars"?Ul(S,Y,I,j,J,g):h==="spectrogram"&&Vl(S,Y,I,j,J,T.sampleRate),v&&n>0){const ne=Math.floor(t/n*Y.length),ae=Math.floor(T.sampleRate*.05);let re=0;for(let q=Math.max(0,ne-ae);q<Math.min(Y.length,ne+ae);q++)re+=Y[q]*Y[q];const G=Math.sqrt(re/(ae*2));E=Math.max(E,G)}f&&x&&F>1&&(S.fillStyle="rgba(255,255,255,0.6)",S.font="bold 11px sans-serif",S.textAlign="left",S.fillText(H===0?"L":H===1?"R":`Ch${H+1}`,4,J+14))}K(E)}if(n>0){const F=Math.max(0,Math.min(t/n*I,I));S.beginPath(),S.strokeStyle=m,S.lineWidth=2,S.moveTo(F,O),S.lineTo(F,M+O),S.stroke()}for(const F of c){const j=F.time/n*I;S.beginPath(),S.strokeStyle=F.color??"#f59e0b",S.lineWidth=2,S.setLineDash([4,4]),S.moveTo(j,O),S.lineTo(j,M+O),S.stroke(),S.setLineDash([]),F.label&&(S.fillStyle=F.color??"#f59e0b",S.font="bold 10px sans-serif",S.textAlign="center",S.fillText(F.label,j,O+M-4))}},[e,R.current,t,n,Z,a,o,h,f,g,m,p,y,c,d,D,P,v,x,O]);const X=u.useCallback(L=>{var I;if(!n)return;const T=(I=b.current)==null?void 0:I.getBoundingClientRect();if(!T)return;const S=L.clientX-T.left+A;w(!0),_(S),B(S)},[n,A]),N=u.useCallback(L=>{if(!W||!b.current)return;const T=b.current.getBoundingClientRect(),S=L.clientX-T.left+A;B(S)},[W,A]),U=u.useCallback(()=>{if(!W||D===null||P===null||!n){w(!1),_(null),B(null);return}const L=Math.min(D,P),T=Math.max(D,P),S=(T-L)/Z*n;if(w(!1),_(null),B(null),S<.2){const I=L/Z*n;i==null||i(I)}else{const I=L/Z*n,M=T/Z*n;l==null||l({start:I,end:M})}},[W,D,P,n,Z,i,l]);return s.jsxs("div",{ref:k,className:`nice-waveform${C?` ${C}`:""}`,style:{position:"relative",width:r,overflow:o>1?"auto":"hidden",cursor:i?"crosshair":"default"},onScroll:L=>$(L.target.scrollLeft),children:[s.jsx("canvas",{ref:b,width:Z,height:a+O,style:{display:"block"},role:"img","aria-label":"Waveform canvas",onMouseDown:X,onMouseMove:N,onMouseUp:U,onMouseLeave:U}),v&&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,z*300)}%`,background:z>.8?"#ef4444":z>.5?"#f59e0b":"#22c55e",borderRadius:4,transition:"height 50ms"}})})]})};function Wl(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,g=0;for(let y=0;y<h.length;y++)h[y]<f&&(f=h[y]),h[y]>g&&(g=h[y]);const m=l-g*(r/2),p=l-f*(r/2);e.moveTo(c,m),e.lineTo(c,p)}e.stroke()}function Ul(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 g=0;for(let x=0;x<f.length;x++)g+=Math.abs(f[x]);const p=g/f.length*r*.9,y=d*i;e.fillStyle=o,e.fillRect(y+1,a+r-p,i-2,p)}}function Vl(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,g=new Float32Array(256/2);for(let p=0;p<256/2;p++){let y=0,x=0;for(let v=0;v<256&&f+v<t.length;v++){const C=2*Math.PI*p*v/256;y+=t[f+v]*Math.cos(C),x-=t[f+v]*Math.sin(C)}g[p]=Math.sqrt(y*y+x*x)/256}const m=r/g.length;for(let p=0;p<g.length;p++){const y=Math.min(1,g[p]*10),x=Math.floor(y*255),v=Math.floor(y*100),C=Math.floor((1-y)*200);e.fillStyle=`rgb(${x},${v},${C})`,e.fillRect(h*d,a+r-(p+1)*m,d+1,m+1)}}}function ql(e){const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const Fa=88,Ft=16,Pn=16,Hl=320;function Kl(e){return e-21}function Yl(e){return e+21}const Es=({notes:e,onAddNote:t,onRemoveNote:n,selectedNoteId:r,setSelectedNoteId:a,duration:o=4,zoom:i=1})=>{const l=u.useRef(null),c=Hl*i,d=Fa*Ft,h=u.useRef(null);u.useEffect(()=>{},[e,i,o]);const f=m=>{const p=m.target.getBoundingClientRect(),y=m.clientX-p.left,x=m.clientY-p.top,v=Math.floor(x/Ft),C=Yl(v),b=y/c*o;h.current={drawing:!0,startX:y,key:v},t(C,b,o/Pn)},g=(m,p)=>{p.stopPropagation(),a==null||a(m)};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(Fa)].map((m,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((m,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(m=>{const p=Kl(m.pitch),y=m.start/o*c,x=m.duration/o*c;return s.jsx("rect",{x:y,y:p*Ft,width:Math.max(6,x),height:Ft-2,fill:m.id===r?"var(--accent, #1976d2)":"var(--accent-light, #90caf9)",stroke:"var(--accent, #1976d2)",strokeWidth:m.id===r?2:1,rx:3,onClick:v=>g(m.id,v),onDoubleClick:()=>n(m.id),style:{cursor:"pointer"}},m.id)})]})},As=({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}=ve(),[f,g]=u.useState(null),[m,p]=u.useState(null),[y,x]=u.useState(null),v=[...e].sort((B,z)=>B.time-z.time),C=B=>[B.time/o*i,(127-B.value)/127*l],b=(B,z,K)=>Math.max(z,Math.min(K,B)),k=B=>{var N;if(B.target instanceof SVGCircleElement)return;const z=(N=d.current)==null?void 0:N.getBoundingClientRect();if(!z)return;const K=B.clientX-z.left,Z=B.clientY-z.top,O=b(K/i*o,0,o),X=b(127-Math.round(Z/l*127),0,127);t(a,X,O)},R=(B,z)=>{var X;z.stopPropagation(),g(B.id),x(B.id);const[K,Z]=C(B),O=(X=d.current)==null?void 0:X.getBoundingClientRect();O&&p({dx:z.clientX-O.left-K,dy:z.clientY-O.top-Z})},A=B=>{var N;if(f==null||!m)return;const z=(N=d.current)==null?void 0:N.getBoundingClientRect();if(!z)return;const K=b(B.clientX-z.left-m.dx,0,i),Z=b(B.clientY-z.top-m.dy,0,l),O=b(K/i*o,0,o),X=b(127-Math.round(Z/l*127),0,127);n(f,X,O)},$=()=>{g(null),p(null)};u.useEffect(()=>{const B=z=>{(z.key==="Delete"||z.key==="Backspace")&&y!=null&&(r(y),x(null))};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[y,r]),u.useEffect(()=>{if(f!=null)return window.addEventListener("mousemove",A),window.addEventListener("mouseup",$),()=>{window.removeEventListener("mousemove",A),window.removeEventListener("mouseup",$)}});const[W,w]=u.useState(null),D=(B,z)=>{const[K,Z]=C(B);w({x:K+10,y:Z-10,text:`Val: ${B.value}, Time: ${B.time.toFixed(2)}s`})},_=()=>w(null),P=B=>{var N;const z=(N=d.current)==null?void 0:N.getBoundingClientRect();if(!z)return;const K=B.clientX-z.left,Z=B.clientY-z.top,O=b(K/i*o,0,o),X=b(127-Math.round(Z/l*127),0,127);t(a,X,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:P,tabIndex:0,children:[[...Array(9)].map((B,z)=>s.jsx("line",{x1:0,y1:z*l/8,x2:i,y2:z*l/8,stroke:"var(--border-muted, #ddd)",strokeWidth:z===0||z===8?2:1},z)),v.length>1&&s.jsx("polyline",{fill:"none",stroke:"var(--accent, #1976d2)",strokeWidth:2,points:v.map(B=>C(B).join(",")).join(" ")}),v.map(B=>{const[z,K]=C(B);return s.jsxs("g",{children:[s.jsx("circle",{cx:z,cy:K,r:y===B.id?8:6,fill:y===B.id?"var(--accent, #1976d2)":"var(--accent-light, #90caf9)",stroke:"var(--accent, #1976d2)",strokeWidth:y===B.id?3:2,style:{cursor:"pointer"},onMouseDown:Z=>R(B,Z),onContextMenu:Z=>{Z.preventDefault(),r(B.id)},onClick:Z=>{Z.stopPropagation(),x(B.id)},onMouseOver:Z=>D(B),onMouseOut:_}),y===B.id&&s.jsx("foreignObject",{x:z+10,y:K-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:B.handleType||c||"linear",onChange:Z=>{n(B.id,B.value,B.time,Z.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")})]})]})})]},B.id)}),W&&s.jsxs("g",{pointerEvents:"none",children:[s.jsx("rect",{x:W.x,y:W.y-18,width:90,height:20,fill:"var(--surface-bg, #fff)",stroke:"var(--accent, #1976d2)",rx:4}),s.jsx("text",{x:W.x+6,y:W.y-4,fontSize:13,fill:"var(--accent, #1976d2)",children:W.text})]}),s.jsxs("text",{x:6,y:16,fontSize:14,fill:"var(--accent, #1976d2)",children:["CC",a]})]})},Zl=et.scoped("audioContext");let wn=null;function tn(){if(!wn)try{wn=new(window.AudioContext||window.webkitAudioContext)}catch(e){Zl.error("Error initializing AudioContext:",e)}return wn}async function Et(){const e=tn();e&&e.state==="suspended"&&await e.resume()}function Ns(){return!!wn&&wn.state==="running"}function Is(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 Xl(e,t){if(!t.snapEnabled)return e;const n=Is(t);return Math.round(e/n)*n}function Ql(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 Jl(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 Ls(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?Jl(c,t.bpm):Ql(c);r.fillText(f,d,12)}}if(t.snapEnabled){const c=Is(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 ec(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;Ls(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 tc(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,g=l-d*c;h===0?a.moveTo(f,g):a.lineTo(f,g)}),a.stroke(),a.restore()}const Fs=({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 g=u.useRef(null),m=u.useRef(null),p=u.useRef(null),[y,x]=u.useState(!1),v={zoom:e,duration:t,bpm:o,snapEnabled:i,snapMode:l};u.useEffect(()=>{Et(),C()},[e,t,a,r,o,i,l,c]),u.useEffect(()=>{n?(p.current=performance.now(),b()):m.current&&cancelAnimationFrame(m.current)},[n]);const C=()=>{g.current&&(Ls(g.current,v),c!=null&&c.length&&tc(g.current,v,c,d),ec(g.current,v,a,r))},b=()=>{if(!n)return;const w=D=>{if(p.current!==null){const _=(D-p.current)/1e3;p.current=D;const P=Math.min(a+_,t);h(P)}a<t&&(m.current=requestAnimationFrame(w))};m.current=requestAnimationFrame(w)},k=w=>{x(!0),$(w)},R=w=>{y&&$(w)},A=()=>{x(!1)},$=w=>{if(!g.current)return;const D=g.current.getBoundingClientRect();let P=(w.clientX-D.left)/D.width*t;P=Xl(P,v),h(Math.min(Math.max(P,0),t))},W=w=>{if(!f)return;w.preventDefault();const D=w.deltaY>0?-.1:.1,_=Math.max(.5,Math.min(5,e+D));f(_)};return s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:s.jsx("canvas",{ref:g,style:{border:"1px solid black",backgroundColor:"white",width:`${30*e*t}px`,height:`${Math.max(80,30*e)}px`,cursor:y?"grabbing":"pointer"},onMouseDown:k,onMouseMove:R,onMouseUp:A,onMouseLeave:A,onWheel:W,role:"img","aria-label":"Audio timeline canvas"})})};let nc=Date.now();function en(){return nc++}function rc(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 Da(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 ac(e,t,n,r,a=48){const o=[];for(let i=0;i<=a;i++){const l=i/a,c=Oa(e.time,t.time,n.time,l),d=Oa(e.value,t.value,n.value,l);o.push({id:en(),cc:r,value:nn(d),time:c})}return o}function sc(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 oc(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 ic(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 lc(e,t){let n;switch(e.mode){case"pencil":n=rc(t,e.cc,e.resolution);break;case"line":n=t.length>=2?Da(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?n=ac(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?n=Da(t[0],t[t.length-1],e.cc):n=[];break;case"step":n=t.length>=2?sc(t[0],t[t.length-1],e.cc):[];break;case"ramp":n=t.length>=2?oc(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=ic(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 Oa(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 cc={"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 Ds(e,t){return e/60*cc[t]/4}function Os(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?Ds(n,e.syncDivision):e.rate,a=t*r+e.phase/(2*Math.PI),o=Os(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 _s(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 zs(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 dc(e){return JSON.stringify(e,null,2)}function uc(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const Sr=140,rn=24,hc=[{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"}],Bs=({layerId:e,ccNumber:t,duration:n,zoom:r,automation:a,onChangeCCNumber:o})=>{const{t:i}=ve(),l=u.useRef(null),[c,d]=u.useState("pencil"),[h,f]=u.useState(!1),g=u.useRef([]),[m,p]=u.useState(null),[y,x]=u.useState(!1),[v,C]=u.useState(ir()),b=u.useRef(null),k=a.getEvents(e),R=k.filter(N=>N.cc===t),A=Math.max(400,n*30*r),$=u.useCallback(N=>N/A*n,[A,n]),W=u.useCallback(N=>Math.round(Math.max(0,Math.min(127,127-(N-rn)/Sr*127))),[]),w=u.useCallback(N=>N/n*A,[A,n]),D=u.useCallback(N=>rn+(127-N)/127*Sr,[]),_=u.useCallback(()=>{const N=l.current;if(!N)return;const U=N.getContext("2d");if(!U)return;const L=N.width,T=N.height;U.clearRect(0,0,L,T),U.fillStyle="#1a1a2e",U.fillRect(0,0,L,T),U.strokeStyle="rgba(255,255,255,0.06)",U.lineWidth=1;for(let M=0;M<=127;M+=16){const F=D(M);U.beginPath(),U.moveTo(0,F),U.lineTo(L,F),U.stroke()}U.fillStyle="rgba(255,255,255,0.3)",U.font="10px monospace",U.textBaseline="middle";for(const M of[0,32,64,96,127])U.fillText(String(M),2,D(M));U.strokeStyle="rgba(255,255,255,0.04)";for(let M=0;M<=n;M++){const F=w(M);U.beginPath(),U.moveTo(F,0),U.lineTo(F,T),U.stroke()}const S=[...R].sort((M,F)=>M.time-F.time);if(S.length>0){U.beginPath(),U.moveTo(w(S[0].time),T-rn);for(const M of S)U.lineTo(w(M.time),D(M.value));U.lineTo(w(S[S.length-1].time),T-rn),U.closePath(),U.fillStyle="rgba(59, 130, 246, 0.15)",U.fill(),U.beginPath(),U.strokeStyle="#3b82f6",U.lineWidth=2;for(let M=0;M<S.length;M++){const F=w(S[M].time),j=D(S[M].value);M===0?U.moveTo(F,j):((S[M].handleType??"linear")==="step"&&U.lineTo(F,D(S[M-1].value)),U.lineTo(F,j))}U.stroke();for(const M of S){const F=w(M.time),j=D(M.value),E=m===M.id;U.beginPath(),U.arc(F,j,E?6:4,0,Math.PI*2),U.fillStyle=E?"#60a5fa":"#3b82f6",U.fill(),U.strokeStyle="#fff",U.lineWidth=1.5,U.stroke()}}U.strokeStyle="rgba(255,255,255,0.15)",U.lineWidth=1,U.setLineDash([4,4]);const I=D(0);U.beginPath(),U.moveTo(0,I),U.lineTo(L,I),U.stroke(),U.setLineDash([])},[R,n,A,w,D,m]);u.useEffect(()=>{_()},[_]);const P=N=>{var S;const U=(S=l.current)==null?void 0:S.getBoundingClientRect();if(!U)return;const L=N.clientX-U.left,T=N.clientY-U.top;c==="pencil"?(f(!0),g.current=[{time:$(L),value:W(T)}]):(f(!0),g.current=[{time:$(L),value:W(T)}])},B=N=>{var M;const U=(M=l.current)==null?void 0:M.getBoundingClientRect();if(!U)return;const L=N.clientX-U.left,T=N.clientY-U.top;h&&g.current.push({time:$(L),value:W(T)});const S=[...R].sort((F,j)=>F.time-j.time);let I=null;for(const F of S){const j=w(F.time),E=D(F.value);if(Math.abs(L-j)<8&&Math.abs(T-E)<8){I=F.id;break}}p(I)},z=()=>{if(!h)return;f(!1);const N=g.current;if(N.length===0)return;const U=lc({mode:c,cc:t,resolution:.02,smoothing:c==="pencil"?.3:0},N);U.length>0&&a.setEvents(e,[...k,...U]),g.current=[]},K=N=>{var S;const U=(S=l.current)==null?void 0:S.getBoundingClientRect();if(!U)return;const L=N.clientX-U.left,T=N.clientY-U.top;for(const I of R){const M=w(I.time),F=D(I.value);if(Math.abs(L-M)<8&&Math.abs(T-F)<8){a.removeEvent(e,I.id);return}}a.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:W(T),time:$(L)})},Z=()=>{const U=_s(v,0,n,t,Math.ceil(n*20),120).map((L,T)=>({...L,id:Date.now()+T}));a.setEvents(e,[...k,...U]),x(!1)},O=()=>{const N=a.exportLane(e),U=new Blob([N],{type:"application/json"}),L=URL.createObjectURL(U),T=document.createElement("a");T.href=L,T.download=`cc-lane-${t}-layer-${e}.json`,document.body.appendChild(T),T.click(),T.remove(),URL.revokeObjectURL(L)},X=N=>{var L;const U=(L=N.target.files)==null?void 0:L[0];U&&(U.text().then(T=>{a.importLane(e,T)}),b.current&&(b.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:i("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:N=>o(Number(N.target.value)),children:hc.map(N=>s.jsxs("option",{value:N.cc,children:[N.label," (CC",N.cc,")"]},N.cc))}),s.jsx("div",{className:"btn-group btn-group-sm",children:["pencil","line","curve","step","ramp"].map(N=>s.jsx("button",{className:`btn ${c===N?"btn-primary":"btn-outline-secondary"}`,onClick:()=>d(N),style:{fontSize:11,textTransform:"capitalize"},children:N},N))}),s.jsxs("div",{className:"btn-group btn-group-sm",children:[s.jsx("button",{className:"btn btn-outline-secondary",onClick:a.undo,disabled:!a.canUndo,title:"Undo",children:"↩"}),s.jsx("button",{className:"btn btn-outline-secondary",onClick:a.redo,disabled:!a.canRedo,title:"Redo",children:"↪"})]}),s.jsx("button",{className:"btn btn-sm btn-outline-info",onClick:()=>x(!y),title:"Apply LFO modulation",children:"LFO"}),s.jsx("button",{className:"btn btn-sm btn-outline-warning",onClick:O,title:"Export CC lane as JSON",children:"Export"}),s.jsx("button",{className:"btn btn-sm btn-outline-success",onClick:()=>{var N;return(N=b.current)==null?void 0:N.click()},title:"Import CC lane from JSON",children:"Import"}),s.jsx("input",{ref:b,type:"file",accept:".json",style:{display:"none"},onChange:X}),s.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:()=>a.setEvents(e,k.filter(N=>N.cc!==t)),title:"Clear all CC events for this lane",children:"Clear"}),s.jsxs("span",{style:{fontSize:11,color:"#8b949e",marginLeft:"auto"},children:[R.length," ",i("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:v.waveform,onChange:N=>C(U=>({...U,waveform:N.target.value})),children:["sine","triangle","sawtooth","square","random","sample-hold"].map(N=>s.jsx("option",{value:N,children:N},N))})]}),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:v.rate,onChange:N=>C(U=>({...U,rate:Number(N.target.value)}))})]}),s.jsxs("label",{style:{fontSize:12},children:["Depth:",s.jsx("input",{type:"range",min:0,max:1,step:.01,value:v.depth,onChange:N=>C(U=>({...U,depth:Number(N.target.value)})),style:{width:80}}),s.jsx("span",{style:{fontSize:11,marginLeft:4},children:v.depth.toFixed(2)})]}),s.jsxs("label",{style:{fontSize:12},children:["Center:",s.jsx("input",{type:"range",min:0,max:1,step:.01,value:v.center,onChange:N=>C(U=>({...U,center:Number(N.target.value)})),style:{width:80}}),s.jsx("span",{style:{fontSize:11,marginLeft:4},children:v.center.toFixed(2)})]}),s.jsx("button",{className:"btn btn-sm btn-primary",onClick:Z,children:"Apply LFO"}),s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>x(!1),children:"Cancel"})]})}),s.jsx("div",{style:{overflowX:"auto",borderRadius:6},children:s.jsx("canvas",{ref:l,width:A,height:Sr+rn*2,style:{cursor:h?"crosshair":m?"pointer":"crosshair",display:"block",borderRadius:6},onMouseDown:P,onMouseMove:B,onMouseUp:z,onMouseLeave:()=>{h&&z()},onDoubleClick:K,role:"img","aria-label":"CC automation lane editor canvas"})}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:4},children:i("ccLane.hint","Click to draw. Double-click to add/remove points. Drag to draw curves.")})]})},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},Ws={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function fc(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 Us(e,t){if(e.length===0)return[];const n=fc(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 pc(e,t,n,r=0,a=1){const o=Us(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 g=0;g<f;g++){const m=g%2===1?l*t.swing*.5:0,p=r+g*l+m;if(h)for(const y of o){const x=t.velocityPattern?t.velocityPattern[g%t.velocityPattern.length]:y.velocity;d.push({pitch:y.pitch,velocity:x,startTime:p,duration:c,step:g})}else{const y=g%o.length,x=o[y],v=t.velocityPattern?t.velocityPattern[g%t.velocityPattern.length]:x.velocity;d.push({pitch:x.pitch,velocity:v,startTime:p,duration:c,step:g})}}return d}function Vs(){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 qs(){return Object.keys(Gs)}const Hs=({config:e,onChange:t,active:n,onToggleActive:r})=>{const{t:a}=ve(),o=Vs(),i=qs(),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(Ws),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)})})]})]})]})},mc=["sine","triangle","sawtooth","square","random","sample-hold"],gc=["1/1","1/2","1/4","1/8","1/16","1/32"],an=200,Dt=48,Ks=({config:e,onChange:t,index:n,onRemove:r})=>{const{t:a}=ve(),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=zs(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 g=h[f].x,m=h[f].y;f===0?d.moveTo(g,m):d.lineTo(g,m)}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:mc.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:gc.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)})})]})]})]})]})]})},yc=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function bc(e){const t=Math.floor(e/12)-1;return`${yc[e%12]}${t}`}const Ys=({seq:e})=>{const{t}=ve(),{pattern:n,currentStep:r,playing:a}=e,o=u.useMemo(()=>n.steps.slice(0,n.length),[n]);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:t("stepSeq.title","Step Sequencer")}),s.jsx("button",{className:`btn btn-sm ${a?"btn-danger":"btn-success"}`,onClick:e.togglePlayback,style:{minWidth:60},children:a?"■ 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:n.bpm,onChange:i=>e.setBpm(Number(i.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:n.swing,onChange:i=>e.setSwing(Number(i.target.value)),style:{width:60}}),s.jsxs("span",{style:{fontSize:11,minWidth:28},children:[Math.round(n.swing*100),"%"]})]}),s.jsx("div",{className:"btn-group btn-group-sm",children:[16,32,64].map(i=>s.jsx("button",{className:`btn ${n.length===i?"btn-primary":"btn-outline-secondary"}`,onClick:()=>e.setLength(i),style:{fontSize:11},children:i},i))})]}),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:n.length*36},children:o.map((i,l)=>{const c=i.active,d=r===l,h=l%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:h?"#8b949e":"#30363d"},children:l+1}),s.jsx("button",{onClick:()=>e.toggle(l),style:{width:32,height:32,borderRadius:4,border:d?"2px solid #f0c040":"1px solid #30363d",background:c?`hsl(${210+i.velocity/127*40}, 80%, ${35+i.velocity/127*20}%)`:h?"#21262d":"#161b22",cursor:"pointer",padding:0,color:c?"#fff":"#484f58",fontSize:8,fontWeight:600,transition:"background 0.1s"},children:c?bc(i.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:`${i.velocity/127*100}%`,background:c?"rgba(59, 130, 246, 0.6)":"rgba(59, 130, 246, 0.15)",borderRadius:2,cursor:"ns-resize"},title:`Vel: ${i.velocity}`,onMouseDown:f=>{f.preventDefault();const g=f.target.parentElement.getBoundingClientRect(),m=y=>{const x=y.clientY-g.top,v=Math.round(Math.max(1,Math.min(127,(1-x/g.height)*127)));e.setVelocity(l,v)},p=()=>{document.removeEventListener("mousemove",m),document.removeEventListener("mouseup",p)};document.addEventListener("mousemove",m),document.addEventListener("mouseup",p)}})}),c&&i.probability<1&&s.jsxs("span",{style:{fontSize:8,color:"#f0c040"},children:[Math.round(i.probability*100),"%"]})]},l)})})}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:6},children:t("stepSeq.hint","Click steps to toggle. Drag velocity bars vertically.")})]})},xc="_panelNarrow_se2i3_3",vc="_panelWide_se2i3_9",Sc="_smallLabel_se2i3_19",wc="_noteText_se2i3_29",Cc="_buttonRow_se2i3_41",kc="_noteTextMargin_se2i3_49",Mc="_rangeW100_se2i3_63",jc="_zoomValue_se2i3_69",Rc="_selectW100_se2i3_77",$c="_inputW70_se2i3_83",Tc="_masterVolGroup_se2i3_93",Pc="_rangeW140_se2i3_99",Ec="_volumeValue_se2i3_105",Ac="_selectW140_se2i3_115",Nc="_freqGroup_se2i3_121",Ic="_freqValue_se2i3_127",Lc="_narrowGroup_se2i3_137",Fc="_rangeW120_se2i3_143",Dc="_smallValue_se2i3_149",Oc="_presetDivider_se2i3_159",_c="_presetLabel_se2i3_165",zc="_presetBtn_se2i3_175",Bc="_deletePresetSelect_se2i3_183",Gc="_presetNameInput_se2i3_191",Wc="_savePresetBtn_se2i3_199",Uc="_countInAlert_se2i3_211",Vc="_inputW80_se2i3_219",qc="_levelLabel_se2i3_225",Hc="_levelMeter_se2i3_233",Kc="_levelBar_se2i3_249",pe={panelNarrow:xc,panelWide:vc,smallLabel:Sc,noteText:wc,buttonRow:Cc,noteTextMargin:kc,rangeW100:Mc,zoomValue:jc,selectW100:Rc,inputW70:$c,masterVolGroup:Tc,rangeW140:Pc,volumeValue:Ec,selectW140:Ac,freqGroup:Nc,freqValue:Ic,narrowGroup:Lc,rangeW120:Fc,smallValue:Dc,presetDivider:Oc,presetLabel:_c,presetBtn:zc,deletePresetSelect:Bc,presetNameInput:Gc,savePresetBtn:Wc,countInAlert:Uc,inputW80:Vc,levelLabel:qc,levelMeter:Hc,levelBar:Kc},Zs=({autoSaveMode:e,setAutoSaveMode:t,autoSaveInterval:n,setAutoSaveInterval:r})=>{const{t:a}=ve();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.")]})]})},Xs=({undoCount:e,redoCount:t,onUndo:n,onRedo:r})=>{const{t:a}=ve();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.")})]})},Qs=({zoom:e,setZoom:t,uiZoom:n,setUiZoom:r,snapEnabled:a,onToggleSnap:o,snapMode:i,onSnapModeChange:l,bpm:c,setBpm:d})=>{const{t:h}=ve();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"})]})]})})},Js=({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:g}=ve();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:m=>t(Number(m.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:m=>i({type:m.target.value}),children:["peaking","lowpass","highpass","lowshelf","highshelf","notch","bandpass"].map(m=>s.jsx("option",{value:m,children:m},m))})]}),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:m=>i({frequency:Number(m.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:m=>i({q:Number(m.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:m=>i({gain:Number(m.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:[g("editorPanels.eqPresets","EQ Presets"),":"]}),[...l,...c].map(m=>s.jsx("button",{className:`btn btn-sm btn-outline-secondary ${pe.presetBtn}`,onClick:()=>d(m),children:m.name},m.name)),c.length>0&&s.jsxs("select",{className:`form-select form-select-sm ${pe.deletePresetSelect}`,onChange:m=>{m.target.value&&(f(m.target.value),m.target.value="")},defaultValue:"",children:[s.jsx("option",{value:"",children:g("editorPanels.deletePreset","Delete preset...")}),c.map(m=>s.jsx("option",{value:m.name,children:m.name},m.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:g("editorPanels.presetName","Preset name..."),id:"presetNameInput"}),s.jsx("button",{className:`btn btn-sm btn-success ${pe.savePresetBtn}`,onClick:()=>{const m=document.getElementById("presetNameInput");m!=null&&m.value.trim()&&(h(m.value.trim()),m.value="")},children:g("editorPanels.saveCurrent","Save Current")})]})]})]})},eo=({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}=ve();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:g=>t(Number(g.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:g=>o(g.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:g=>l(g.target.value===""?null:Number(g.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:g=>d(g.target.value===""?null:Number(g.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 Yc(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 Zc(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),[g,m]=u.useState(120),p=u.useCallback(($,W)=>`L${$}-C${W}`,[]),y=u.useCallback(($,W)=>{if(!r.current||!W.audioBuffer)return;const w=p($,W.id),D=e[$];r.current.addClip({id:w,buffer:W.audioBuffer,startTime:W.start,offset:0,duration:W.duration,layerId:$,volume:(D==null?void 0:D.volume)??1,pan:(D==null?void 0:D.pan)??0,stretchFactor:W.stretchFactor||1,effectChain:(D==null?void 0:D.effectChain)||[]})},[e,p]),x=u.useCallback(($,W)=>{var w;(w=r.current)==null||w.removeClip(p($,W))},[p]);u.useEffect(()=>{Object.entries(t).forEach(([$,W])=>{const w=Number($);W==null||W.forEach(D=>y(w,D))})},[t,e,y]),u.useEffect(()=>{r.current&&Object.entries(n).forEach(([$,W])=>{const w=Number($);r.current.setMidiCCEvents(w,W)})},[n]);const v=u.useCallback(()=>{r.current&&(a?r.current.pause():r.current.play())},[a]),C=u.useCallback(()=>{var $;($=r.current)==null||$.stop()},[]),b=u.useCallback($=>{var W;(W=r.current)==null||W.seek($)},[]),k=u.useCallback(()=>{if(!r.current)return;const $=!h;f($),r.current.setLoopRegion(0,c,$)},[h,c]),R=u.useCallback($=>{var w;const W=Math.max(1,c+$);d(W),(w=r.current)==null||w.setLoopRegion(0,W,h)},[c,h]),A=u.useCallback(async($,W=1024)=>{const w=await $.arrayBuffer(),D=new(window.AudioContext||window.webkitAudioContext),_=await D.decodeAudioData(w.slice(0)),P=_.getChannelData(0),B=P.length,z=Math.max(1,Math.floor(B/W)),K=[];for(let Z=0;Z<W;Z++){const O=Z*z;if(O>=B)break;K.push(P[O])}return D.close(),{waveform:K.map(Z=>Math.max(-1,Math.min(1,Z))),duration:_.duration,buffer:_}},[]);return{engineRef:r,isPlaying:a,setIsPlaying:o,currentTime:i,setCurrentTime:l,duration:c,setDuration:d,isLooping:h,setIsLooping:f,bpm:g,setBpm:m,handlePlayPause:v,handleStop:C,handleSeek:b,handleToggleLoop:k,handleAdjustDuration:R,upsertEngineClip:y,removeEngineClip:x,makeEngineClipId:p,blobToWaveform:A}}class to{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 Xc(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),g=u.useRef(null),m=u.useRef(0),p=u.useRef(null),y=u.useRef(null),x=u.useCallback(()=>{p.current&&(clearInterval(p.current),p.current=null),y.current&&(clearTimeout(y.current),y.current=null)},[]),v=u.useCallback(async()=>{if(!e.activeLayer){e.showToast("Select a layer to record.","error");return}t||(f.current||(f.current=new to),m.current=g.current??e.currentTime,n(!0),i(0),await f.current.startRecording({onLevel:i}))},[e,t]),C=u.useCallback(async()=>{var P;if(x(),a(!1),c(0),g.current=null,!f.current){n(!1),i(0);return}const R=await f.current.stopRecording();if(n(!1),i(0),!R||!e.activeLayer)return;const{waveform:A,duration:$,buffer:W}=await e.blobToWaveform(R),w=e.activeLayer.id;e.setWaveforms(B=>({...B,[w]:A}));const D=Math.max(0,m.current||0),_={id:Date.now(),label:"Recording",start:D,duration:$,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:(P=e.layerSettings[w])==null?void 0:P.color,blob:R,blobUrl:URL.createObjectURL(R),audioBuffer:W};e.setLayerClips(B=>({...B,[w]:[...B[w]||[],_]})),e.upsertEngineClip(w,_),e.setSelectedClip({layerId:w,clipId:_.id})},[e,x]),b=u.useCallback(R=>{if(R<=0){v();return}a(!0),c(R);const A=performance.now();p.current=window.setInterval(()=>{const $=(performance.now()-A)/1e3;c(Math.max(0,R-$))},100),y.current=window.setTimeout(()=>{x(),a(!1),c(0),g.current||v()},R*1e3)},[v,x]),k=u.useCallback(async()=>{if(t||r){await C();return}if(!e.activeLayer){e.showToast("Select a layer before recording","error");return}const R=Math.max(0,e.countInBars)*4*(60/e.bpm),A=e.punchIn!=null&&e.punchIn>e.currentTime?e.punchIn:null;A&&(g.current=A),e.overdubEnabled&&!e.isPlaying&&e.playEngine(),A?R>0&&b(R):b(R)},[t,r,e,C,b]);return{isRecording:t,isCountIn:r,monitorLevel:o,countInRemaining:l,punchOut:d,setPunchOut:h,armedPunchInRef:g,recorderRef:f,clearCountInTimers:x,startRecordingNow:v,stopRecordingFlow:C,handleRecord:k}}var no=(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))(no||{});const Qc={};class En{constructor(t,n,r,a={}){this.type=t,this.name=n,this.component=Qc[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 ro(e,t,n,r,a){n(o=>t?[...o,t]:o),r([]),a(e)}function Jc(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 ed(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 td{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 nd=et.scoped("useProjectCRUD");function rd(e){const{project:t,activeSection:n,setProject:r,setActiveSection:a,setLayers:o,setActiveLayer:i,setUndoStack:l,setRedoStack:c}=e,d=u.useCallback(x=>ro(x,t,l,c,r),[t,l,c,r]),h=u.useCallback(async()=>{var b;if(!t)return;const x=(((b=t.sections)==null?void 0:b.length)??0)+1,C={id:await e.addSection(t.id,"Section",x),projectId:t.id,name:"Section",orderNumber:x,layers:[]};d({...t,sections:[...t.sections||[],C]}),a(C)},[t,d,a]),f=u.useCallback(async x=>{var b,k,R;if(!t||!await e.confirm("Delete this section?"))return;await e.deleteSection(x);const C=(t.sections??[]).filter(A=>A.id!==x);d({...t,sections:C}),a(C[0]??null),o(((b=C[0])==null?void 0:b.layers)??[]),i(((R=(k=C[0])==null?void 0:k.layers)==null?void 0:R[0])??null)},[t,d,a,o,i,e]),g=u.useCallback(async()=>{var v;if(!n)return;const x={id:-Date.now(),name:"New Layer",sectionId:n.id,audioSource:no.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};o(C=>[...C,x]),i(x);try{const C=await e.addLayer(n.id,x.name,x.audioSource,x.audioSourceParameters);o(b=>b.map(k=>k.id===x.id?{...x,id:C}:k)),t&&d({...t,sections:((v=t.sections)==null?void 0:v.map(b=>b.id===n.id?{...b,layers:[...(b.layers??[]).filter(k=>k.id!==C),{...x,id:C}]}:b))??[]})}catch(C){o(b=>b.filter(k=>k.id!==x.id)),nd.error("Failed to add layer:",C)}},[n,t,d,o,i]),m=u.useCallback(async x=>{var C,b;if((C=e.layerSettings[x])!=null&&C.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 R={...k};return delete R[x],R}),await e.deleteLayer(x),o(k=>k.filter(R=>R.id!==x)),i(k=>(k==null?void 0:k.id)===x?null:k),t&&d({...t,sections:((b=t.sections)==null?void 0:b.map(k=>k.id===(n==null?void 0:n.id)?{...k,layers:(k.layers??[]).filter(R=>R.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]),y=u.useCallback(async()=>{var C;if(!n)return;const x=e.sectionName||n.name,v=e.sectionOrder===""?n.orderNumber:Number(e.sectionOrder);if(!x.trim()){e.setStatusType("error"),e.setStatusMessage("Section name cannot be empty");return}if(Number.isNaN(v)){e.setStatusType("error"),e.setStatusMessage("Order musi byc liczba");return}await e.updateSection(n.id,{name:x,orderNumber:v}),a({...n,name:x,orderNumber:v}),t&&d({...t,sections:((C=t.sections)==null?void 0:C.map(b=>b.id===n.id?{...b,name:x,orderNumber:v}:b))??[]}),e.setStatusType("success"),e.setStatusMessage("Section saved")},[n,t,e,d,a]);return{handleAddSection:h,handleDeleteSection:f,handleAddLayer:g,handleDeleteLayer:m,handleSaveProject:p,handleSaveSection:y}}const ao=u.createContext(null);function ad(){const e=u.useContext(ao);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const Qr=({value:e,children:t})=>s.jsx(ao.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},sd=(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),g=d.indexOf(" ",f+1),m=d.indexOf(" ",g+1);if(m===-1)return;const p=Ht(parseFloat(d.substring(h+1,f)),n);a===""&&(o=p);const y=d.substring(m+1);if(y.trim()==="~")return;let x=y;x.startsWith("~")&&(x=x.substring(1)),l?(c(),i=x.trimEnd()):i+=x.trimEnd(),l=y.endsWith(" ")}}}),c(),a.trim().length>0&&r.push({text:a.trim(),timestamp:o}),r},od=(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 g=f.startsWith("*"),m=f.indexOf(" "),p=f.indexOf(" ",m+1),y=f.indexOf(" ",p+1),x=f.indexOf(" ",y+1);if(x===-1)return;const v=Ht(parseFloat(f.substring(m+1,p)),n),C=Ht(parseFloat(f.substring(p+1,y)),n),b=v+C;o===""&&(i=v);const k=f.substring(x+1);if(k.trim()==="~"){c&&(c.endTime=b);return}let R=k;R.startsWith("~")&&(R=R.substring(1)),l?(h(),d=R.trimEnd(),c={text:"",startTime:v,endTime:b,isGolden:g}):c?(d+=R.trimEnd(),c.endTime=b,g&&(c.isGolden=!0)):(d=R.trimEnd(),c={text:"",startTime:v,endTime:b,isGolden:g}),l=k.endsWith(" ")}}}),h(),o.trim().length>0&&r.push({text:o.trim(),timestamp:i,words:a}),r},so=(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),g=l.indexOf(" ",f+1);if(g===-1)return;const m=parseFloat(l.substring(d+1,h)),p=parseFloat(l.substring(h+1,f)),y=Ht(m,n),x=y+Ht(p,n);a.length===0&&(o=y);const v=l.substring(g+1);if(v.trim()==="~"){a.length>0&&(a[a.length-1].endTime=x);return}let C=v;C.startsWith("~")&&(C=C.substring(1));const b=v.endsWith(" "),k=b?C.slice(0,-1):C;a.push({text:k,startTime:y,endTime:x,isGolden:c,hasTrailingSpace:b})}}}),i(),r},id=(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},ld=(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},_a="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",za="var(--karaoke-gold-glow-first, 0 0 12px #FFD700)",cd="var(--karaoke-active-glow, 0 0 10px rgba(0,229,255,0.6), 0 0 4px rgba(255,230,0,0.4))",dd="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",ud=({song:e,currentTime:t})=>{const n=u.useMemo(()=>!e||!e.notes.length?[]:so(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:cd,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?" ":""),g=d>0&&d<1,m=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:m?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":_a,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:m?`drop-shadow(${za})`:"none",transition:"filter 0.2s ease"},children:f},c):s.jsxs("span",{style:{position:"relative",display:"inline",filter:g?m?`drop-shadow(${za})`:`drop-shadow(${dd})`:"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:m?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":_a,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..."})})},oo=u.memo(ud),io=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},Ba=(e,t)=>t&&t>0?e*15/t:e/10,ea=(e,t)=>{const n=t??io(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:Ba(parseFloat(i[1]),n),duration:Ba(parseFloat(i[2]),n),pitch:parseInt(i[3],10),isGold:c})}}),a.length>0&&r.push(a),r},lo=(e,t)=>{let r=(Math.round(12*Math.log2(e/440)+69)%12+12)%12;if(t!==null){for(;r-t>6;)r-=12;for(;r-t<-6;)r+=12}return r};function Nr(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 hd(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 fd=1e3,pd=20,md=70,gd=5,Ga=26,Wa="rgba(255,215,70,0.98)",Ua=new Map,yd=(e,t,n,r,a)=>{const o=`g${a}`,i=`<?xml version="1.0" encoding="UTF-8"?>
1
+ "use strict";var Pl=Object.create;var Na=Object.defineProperty;var El=Object.getOwnPropertyDescriptor;var Al=Object.getOwnPropertyNames;var Nl=Object.getPrototypeOf,Il=Object.prototype.hasOwnProperty;var Ll=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Al(t))!Il.call(e,a)&&a!==n&&Na(e,a,{get:()=>t[a],enumerable:!(r=El(t,a))||r.enumerable});return e};var br=(e,t,n)=>(n=e!=null?Pl(Nl(e)):{},Ll(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"),Er=require("pitchy"),Fl=require("react-window"),Yr=require("react-youtube"),Dl=require("@fortawesome/react-fontawesome"),Ia=require("@fortawesome/free-brands-svg-icons"),vr=require("@fortawesome/free-solid-svg-icons");var st=typeof document<"u"?document.currentScript:null;const Ol=(e,t)=>t??e,Ts=u.createContext(Ol),_l=({t:e,children:t})=>s.jsx(Ts.Provider,{value:e,children:t});function xe(){return{t:u.useContext(Ts)}}class zl extends u.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){var a,o;const r=this.props.componentName?`[${this.props.componentName}]`:"[AudioErrorBoundary]";console.error(`${r} Caught error:`,t,n),(o=(a=this.props).onError)==null||o.call(a,t,n)}render(){return this.state.hasError&&this.state.error?typeof this.props.fallback=="function"?this.props.fallback(this.state.error,this.reset):this.props.fallback?this.props.fallback:s.jsx("div",{className:"nice-audio-error-boundary",role:"alert",children:s.jsxs("div",{className:"nice-audio-error-boundary__content",children:[s.jsx("h3",{className:"nice-audio-error-boundary__title",children:this.props.componentName?`${this.props.componentName} encountered an error`:"Something went wrong"}),s.jsx("p",{className:"nice-audio-error-boundary__message",children:this.state.error.message}),s.jsx("button",{className:"nice-audio-error-boundary__retry",onClick:this.reset,children:"Try Again"})]})}):this.props.children}}const xr={},Ar={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function Bl(){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"?xr==null?void 0:xr.VITE_LOG_LEVEL:void 0;return e&&e in Ar?e:"WARN"}const Gl=Bl();function $n(e){return Ar[e]>=Ar[Gl]}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)}}},La=et.scoped("Waveform"),Wl=["audio/","video/"],Ps=({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:g="#007bff",progressColor:m="rgba(255,0,0,0.8)",backgroundColor:p="transparent",showRuler:y=!1,showChannelLabels:v=!0,showPeakMeter:x=!1,className:C})=>{const b=u.useRef(null),k=u.useRef(null),R=u.useRef(null),[A,$]=u.useState(0),[W,w]=u.useState(!1),[D,_]=u.useState(null),[P,B]=u.useState(null),[z,K]=u.useState(0),Z=Math.max(r,r*o),O=y?24:0;u.useEffect(()=>{if(!e||e.size===0){R.current=null;return}e.type&&!Wl.some(T=>e.type.startsWith(T))&&La.warn("Unexpected blob MIME type:",e.type);let L=!1;return(async()=>{let T=null;try{const S=await e.arrayBuffer();if(S.byteLength===0||L)return;T=new AudioContext;const I=await T.decodeAudioData(S);L||(R.current=I)}catch(S){La.error("Failed to decode audio:",S)}finally{T==null||T.close().catch(()=>{})}})(),()=>{L=!0}},[e]),u.useEffect(()=>{if(o>1&&n>0){const L=t/n*Z;(L<A||L>A+r)&&$(Math.max(0,L-r/2))}},[t,n,o,r,Z,A]),u.useEffect(()=>{const L=b.current,T=R.current;if(!L||!n||n===1/0)return;const S=L.getContext("2d");if(!S)return;const I=Z,M=a;if(L.width=I,L.height=M+O,S.clearRect(0,0,I,M+O),p!=="transparent"&&(S.fillStyle=p,S.fillRect(0,0,I,M+O)),y){S.fillStyle="rgba(128,128,128,0.15)",S.fillRect(0,0,I,O),S.fillStyle="#888",S.font="10px monospace",S.textAlign="center";const F=Math.max(1,Math.floor(n/(Z/80)));for(let j=0;j<=n;j+=F){const E=j/n*I;S.fillText(Hl(j),E,O-4),S.fillStyle="rgba(128,128,128,0.3)",S.fillRect(E,O,1,M),S.fillStyle="#888"}}for(const F of d){const j=F.start/n*I,E=F.end/n*I;S.fillStyle=F.color??"rgba(99,102,241,0.15)",S.fillRect(j,O,E-j,M),F.label&&(S.fillStyle=F.color??"#6366f1",S.font="10px sans-serif",S.textAlign="left",S.fillText(F.label,j+2,O+12))}if(D!==null&&P!==null){const F=Math.min(D,P),j=Math.max(D,P);S.fillStyle="rgba(255,200,0,0.2)",S.fillRect(F,O,j-F,M)}if(T){const F=f?T.numberOfChannels:1,j=M/F;let E=0;for(let H=0;H<F;H++){const Y=T.getChannelData(H),J=O+H*j;if(h==="waveform"?Ul(S,Y,I,j,J,g):h==="bars"?Vl(S,Y,I,j,J,g):h==="spectrogram"&&ql(S,Y,I,j,J,T.sampleRate),x&&n>0){const ne=Math.floor(t/n*Y.length),ae=Math.floor(T.sampleRate*.05);let re=0;for(let q=Math.max(0,ne-ae);q<Math.min(Y.length,ne+ae);q++)re+=Y[q]*Y[q];const G=Math.sqrt(re/(ae*2));E=Math.max(E,G)}f&&v&&F>1&&(S.fillStyle="rgba(255,255,255,0.6)",S.font="bold 11px sans-serif",S.textAlign="left",S.fillText(H===0?"L":H===1?"R":`Ch${H+1}`,4,J+14))}K(E)}if(n>0){const F=Math.max(0,Math.min(t/n*I,I));S.beginPath(),S.strokeStyle=m,S.lineWidth=2,S.moveTo(F,O),S.lineTo(F,M+O),S.stroke()}for(const F of c){const j=F.time/n*I;S.beginPath(),S.strokeStyle=F.color??"#f59e0b",S.lineWidth=2,S.setLineDash([4,4]),S.moveTo(j,O),S.lineTo(j,M+O),S.stroke(),S.setLineDash([]),F.label&&(S.fillStyle=F.color??"#f59e0b",S.font="bold 10px sans-serif",S.textAlign="center",S.fillText(F.label,j,O+M-4))}},[e,R.current,t,n,Z,a,o,h,f,g,m,p,y,c,d,D,P,x,v,O]);const X=u.useCallback(L=>{var I;if(!n)return;const T=(I=b.current)==null?void 0:I.getBoundingClientRect();if(!T)return;const S=L.clientX-T.left+A;w(!0),_(S),B(S)},[n,A]),N=u.useCallback(L=>{if(!W||!b.current)return;const T=b.current.getBoundingClientRect(),S=L.clientX-T.left+A;B(S)},[W,A]),U=u.useCallback(()=>{if(!W||D===null||P===null||!n){w(!1),_(null),B(null);return}const L=Math.min(D,P),T=Math.max(D,P),S=(T-L)/Z*n;if(w(!1),_(null),B(null),S<.2){const I=L/Z*n;i==null||i(I)}else{const I=L/Z*n,M=T/Z*n;l==null||l({start:I,end:M})}},[W,D,P,n,Z,i,l]);return s.jsxs("div",{ref:k,className:`nice-waveform${C?` ${C}`:""}`,style:{position:"relative",width:r,overflow:o>1?"auto":"hidden",cursor:i?"crosshair":"default"},onScroll:L=>$(L.target.scrollLeft),children:[s.jsx("canvas",{ref:b,width:Z,height:a+O,style:{display:"block"},role:"img","aria-label":"Waveform canvas",onMouseDown:X,onMouseMove:N,onMouseUp:U,onMouseLeave:U}),x&&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,z*300)}%`,background:z>.8?"#ef4444":z>.5?"#f59e0b":"#22c55e",borderRadius:4,transition:"height 50ms"}})})]})};function Ul(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,g=0;for(let y=0;y<h.length;y++)h[y]<f&&(f=h[y]),h[y]>g&&(g=h[y]);const m=l-g*(r/2),p=l-f*(r/2);e.moveTo(c,m),e.lineTo(c,p)}e.stroke()}function Vl(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 g=0;for(let v=0;v<f.length;v++)g+=Math.abs(f[v]);const p=g/f.length*r*.9,y=d*i;e.fillStyle=o,e.fillRect(y+1,a+r-p,i-2,p)}}function ql(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,g=new Float32Array(256/2);for(let p=0;p<256/2;p++){let y=0,v=0;for(let x=0;x<256&&f+x<t.length;x++){const C=2*Math.PI*p*x/256;y+=t[f+x]*Math.cos(C),v-=t[f+x]*Math.sin(C)}g[p]=Math.sqrt(y*y+v*v)/256}const m=r/g.length;for(let p=0;p<g.length;p++){const y=Math.min(1,g[p]*10),v=Math.floor(y*255),x=Math.floor(y*100),C=Math.floor((1-y)*200);e.fillStyle=`rgb(${v},${x},${C})`,e.fillRect(h*d,a+r-(p+1)*m,d+1,m+1)}}}function Hl(e){const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const Fa=88,Ft=16,Pn=16,Kl=320;function Yl(e){return e-21}function Zl(e){return e+21}const Es=({notes:e,onAddNote:t,onRemoveNote:n,selectedNoteId:r,setSelectedNoteId:a,duration:o=4,zoom:i=1})=>{const l=u.useRef(null),c=Kl*i,d=Fa*Ft,h=u.useRef(null);u.useEffect(()=>{},[e,i,o]);const f=m=>{const p=m.target.getBoundingClientRect(),y=m.clientX-p.left,v=m.clientY-p.top,x=Math.floor(v/Ft),C=Zl(x),b=y/c*o;h.current={drawing:!0,startX:y,key:x},t(C,b,o/Pn)},g=(m,p)=>{p.stopPropagation(),a==null||a(m)};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(Fa)].map((m,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((m,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(m=>{const p=Yl(m.pitch),y=m.start/o*c,v=m.duration/o*c;return s.jsx("rect",{x:y,y:p*Ft,width:Math.max(6,v),height:Ft-2,fill:m.id===r?"var(--accent, #1976d2)":"var(--accent-light, #90caf9)",stroke:"var(--accent, #1976d2)",strokeWidth:m.id===r?2:1,rx:3,onClick:x=>g(m.id,x),onDoubleClick:()=>n(m.id),style:{cursor:"pointer"}},m.id)})]})},As=({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,g]=u.useState(null),[m,p]=u.useState(null),[y,v]=u.useState(null),x=[...e].sort((B,z)=>B.time-z.time),C=B=>[B.time/o*i,(127-B.value)/127*l],b=(B,z,K)=>Math.max(z,Math.min(K,B)),k=B=>{var N;if(B.target instanceof SVGCircleElement)return;const z=(N=d.current)==null?void 0:N.getBoundingClientRect();if(!z)return;const K=B.clientX-z.left,Z=B.clientY-z.top,O=b(K/i*o,0,o),X=b(127-Math.round(Z/l*127),0,127);t(a,X,O)},R=(B,z)=>{var X;z.stopPropagation(),g(B.id),v(B.id);const[K,Z]=C(B),O=(X=d.current)==null?void 0:X.getBoundingClientRect();O&&p({dx:z.clientX-O.left-K,dy:z.clientY-O.top-Z})},A=B=>{var N;if(f==null||!m)return;const z=(N=d.current)==null?void 0:N.getBoundingClientRect();if(!z)return;const K=b(B.clientX-z.left-m.dx,0,i),Z=b(B.clientY-z.top-m.dy,0,l),O=b(K/i*o,0,o),X=b(127-Math.round(Z/l*127),0,127);n(f,X,O)},$=()=>{g(null),p(null)};u.useEffect(()=>{const B=z=>{(z.key==="Delete"||z.key==="Backspace")&&y!=null&&(r(y),v(null))};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[y,r]),u.useEffect(()=>{if(f!=null)return window.addEventListener("mousemove",A),window.addEventListener("mouseup",$),()=>{window.removeEventListener("mousemove",A),window.removeEventListener("mouseup",$)}});const[W,w]=u.useState(null),D=(B,z)=>{const[K,Z]=C(B);w({x:K+10,y:Z-10,text:`Val: ${B.value}, Time: ${B.time.toFixed(2)}s`})},_=()=>w(null),P=B=>{var N;const z=(N=d.current)==null?void 0:N.getBoundingClientRect();if(!z)return;const K=B.clientX-z.left,Z=B.clientY-z.top,O=b(K/i*o,0,o),X=b(127-Math.round(Z/l*127),0,127);t(a,X,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:P,tabIndex:0,children:[[...Array(9)].map((B,z)=>s.jsx("line",{x1:0,y1:z*l/8,x2:i,y2:z*l/8,stroke:"var(--border-muted, #ddd)",strokeWidth:z===0||z===8?2:1},z)),x.length>1&&s.jsx("polyline",{fill:"none",stroke:"var(--accent, #1976d2)",strokeWidth:2,points:x.map(B=>C(B).join(",")).join(" ")}),x.map(B=>{const[z,K]=C(B);return s.jsxs("g",{children:[s.jsx("circle",{cx:z,cy:K,r:y===B.id?8:6,fill:y===B.id?"var(--accent, #1976d2)":"var(--accent-light, #90caf9)",stroke:"var(--accent, #1976d2)",strokeWidth:y===B.id?3:2,style:{cursor:"pointer"},onMouseDown:Z=>R(B,Z),onContextMenu:Z=>{Z.preventDefault(),r(B.id)},onClick:Z=>{Z.stopPropagation(),v(B.id)},onMouseOver:Z=>D(B),onMouseOut:_}),y===B.id&&s.jsx("foreignObject",{x:z+10,y:K-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:B.handleType||c||"linear",onChange:Z=>{n(B.id,B.value,B.time,Z.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")})]})]})})]},B.id)}),W&&s.jsxs("g",{pointerEvents:"none",children:[s.jsx("rect",{x:W.x,y:W.y-18,width:90,height:20,fill:"var(--surface-bg, #fff)",stroke:"var(--accent, #1976d2)",rx:4}),s.jsx("text",{x:W.x+6,y:W.y-4,fontSize:13,fill:"var(--accent, #1976d2)",children:W.text})]}),s.jsxs("text",{x:6,y:16,fontSize:14,fill:"var(--accent, #1976d2)",children:["CC",a]})]})},Xl=et.scoped("audioContext");let wn=null;function tn(){if(!wn)try{wn=new(window.AudioContext||window.webkitAudioContext)}catch(e){Xl.error("Error initializing AudioContext:",e)}return wn}async function Et(){const e=tn();e&&e.state==="suspended"&&await e.resume()}function Ns(){return!!wn&&wn.state==="running"}function Is(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 Ql(e,t){if(!t.snapEnabled)return e;const n=Is(t);return Math.round(e/n)*n}function Jl(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 ec(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 Ls(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?ec(c,t.bpm):Jl(c);r.fillText(f,d,12)}}if(t.snapEnabled){const c=Is(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 tc(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;Ls(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 nc(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,g=l-d*c;h===0?a.moveTo(f,g):a.lineTo(f,g)}),a.stroke(),a.restore()}const Fs=({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 g=u.useRef(null),m=u.useRef(null),p=u.useRef(null),[y,v]=u.useState(!1),x={zoom:e,duration:t,bpm:o,snapEnabled:i,snapMode:l};u.useEffect(()=>{Et(),C()},[e,t,a,r,o,i,l,c]),u.useEffect(()=>{n?(p.current=performance.now(),b()):m.current&&cancelAnimationFrame(m.current)},[n]);const C=()=>{g.current&&(Ls(g.current,x),c!=null&&c.length&&nc(g.current,x,c,d),tc(g.current,x,a,r))},b=()=>{if(!n)return;const w=D=>{if(p.current!==null){const _=(D-p.current)/1e3;p.current=D;const P=Math.min(a+_,t);h(P)}a<t&&(m.current=requestAnimationFrame(w))};m.current=requestAnimationFrame(w)},k=w=>{v(!0),$(w)},R=w=>{y&&$(w)},A=()=>{v(!1)},$=w=>{if(!g.current)return;const D=g.current.getBoundingClientRect();let P=(w.clientX-D.left)/D.width*t;P=Ql(P,x),h(Math.min(Math.max(P,0),t))},W=w=>{if(!f)return;w.preventDefault();const D=w.deltaY>0?-.1:.1,_=Math.max(.5,Math.min(5,e+D));f(_)};return s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:s.jsx("canvas",{ref:g,style:{border:"1px solid black",backgroundColor:"white",width:`${30*e*t}px`,height:`${Math.max(80,30*e)}px`,cursor:y?"grabbing":"pointer"},onMouseDown:k,onMouseMove:R,onMouseUp:A,onMouseLeave:A,onWheel:W,role:"img","aria-label":"Audio timeline canvas"})})};let rc=Date.now();function en(){return rc++}function ac(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 Da(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 sc(e,t,n,r,a=48){const o=[];for(let i=0;i<=a;i++){const l=i/a,c=Oa(e.time,t.time,n.time,l),d=Oa(e.value,t.value,n.value,l);o.push({id:en(),cc:r,value:nn(d),time:c})}return o}function oc(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 ic(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 lc(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 cc(e,t){let n;switch(e.mode){case"pencil":n=ac(t,e.cc,e.resolution);break;case"line":n=t.length>=2?Da(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?n=sc(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?n=Da(t[0],t[t.length-1],e.cc):n=[];break;case"step":n=t.length>=2?oc(t[0],t[t.length-1],e.cc):[];break;case"ramp":n=t.length>=2?ic(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=lc(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 Oa(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 dc={"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 Ds(e,t){return e/60*dc[t]/4}function Os(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?Ds(n,e.syncDivision):e.rate,a=t*r+e.phase/(2*Math.PI),o=Os(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 _s(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 zs(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 uc(e){return JSON.stringify(e,null,2)}function hc(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const Sr=140,rn=24,fc=[{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"}],Bs=({layerId:e,ccNumber:t,duration:n,zoom:r,automation:a,onChangeCCNumber:o})=>{const{t:i}=xe(),l=u.useRef(null),[c,d]=u.useState("pencil"),[h,f]=u.useState(!1),g=u.useRef([]),[m,p]=u.useState(null),[y,v]=u.useState(!1),[x,C]=u.useState(ir()),b=u.useRef(null),k=a.getEvents(e),R=k.filter(N=>N.cc===t),A=Math.max(400,n*30*r),$=u.useCallback(N=>N/A*n,[A,n]),W=u.useCallback(N=>Math.round(Math.max(0,Math.min(127,127-(N-rn)/Sr*127))),[]),w=u.useCallback(N=>N/n*A,[A,n]),D=u.useCallback(N=>rn+(127-N)/127*Sr,[]),_=u.useCallback(()=>{const N=l.current;if(!N)return;const U=N.getContext("2d");if(!U)return;const L=N.width,T=N.height;U.clearRect(0,0,L,T),U.fillStyle="#1a1a2e",U.fillRect(0,0,L,T),U.strokeStyle="rgba(255,255,255,0.06)",U.lineWidth=1;for(let M=0;M<=127;M+=16){const F=D(M);U.beginPath(),U.moveTo(0,F),U.lineTo(L,F),U.stroke()}U.fillStyle="rgba(255,255,255,0.3)",U.font="10px monospace",U.textBaseline="middle";for(const M of[0,32,64,96,127])U.fillText(String(M),2,D(M));U.strokeStyle="rgba(255,255,255,0.04)";for(let M=0;M<=n;M++){const F=w(M);U.beginPath(),U.moveTo(F,0),U.lineTo(F,T),U.stroke()}const S=[...R].sort((M,F)=>M.time-F.time);if(S.length>0){U.beginPath(),U.moveTo(w(S[0].time),T-rn);for(const M of S)U.lineTo(w(M.time),D(M.value));U.lineTo(w(S[S.length-1].time),T-rn),U.closePath(),U.fillStyle="rgba(59, 130, 246, 0.15)",U.fill(),U.beginPath(),U.strokeStyle="#3b82f6",U.lineWidth=2;for(let M=0;M<S.length;M++){const F=w(S[M].time),j=D(S[M].value);M===0?U.moveTo(F,j):((S[M].handleType??"linear")==="step"&&U.lineTo(F,D(S[M-1].value)),U.lineTo(F,j))}U.stroke();for(const M of S){const F=w(M.time),j=D(M.value),E=m===M.id;U.beginPath(),U.arc(F,j,E?6:4,0,Math.PI*2),U.fillStyle=E?"#60a5fa":"#3b82f6",U.fill(),U.strokeStyle="#fff",U.lineWidth=1.5,U.stroke()}}U.strokeStyle="rgba(255,255,255,0.15)",U.lineWidth=1,U.setLineDash([4,4]);const I=D(0);U.beginPath(),U.moveTo(0,I),U.lineTo(L,I),U.stroke(),U.setLineDash([])},[R,n,A,w,D,m]);u.useEffect(()=>{_()},[_]);const P=N=>{var S;const U=(S=l.current)==null?void 0:S.getBoundingClientRect();if(!U)return;const L=N.clientX-U.left,T=N.clientY-U.top;c==="pencil"?(f(!0),g.current=[{time:$(L),value:W(T)}]):(f(!0),g.current=[{time:$(L),value:W(T)}])},B=N=>{var M;const U=(M=l.current)==null?void 0:M.getBoundingClientRect();if(!U)return;const L=N.clientX-U.left,T=N.clientY-U.top;h&&g.current.push({time:$(L),value:W(T)});const S=[...R].sort((F,j)=>F.time-j.time);let I=null;for(const F of S){const j=w(F.time),E=D(F.value);if(Math.abs(L-j)<8&&Math.abs(T-E)<8){I=F.id;break}}p(I)},z=()=>{if(!h)return;f(!1);const N=g.current;if(N.length===0)return;const U=cc({mode:c,cc:t,resolution:.02,smoothing:c==="pencil"?.3:0},N);U.length>0&&a.setEvents(e,[...k,...U]),g.current=[]},K=N=>{var S;const U=(S=l.current)==null?void 0:S.getBoundingClientRect();if(!U)return;const L=N.clientX-U.left,T=N.clientY-U.top;for(const I of R){const M=w(I.time),F=D(I.value);if(Math.abs(L-M)<8&&Math.abs(T-F)<8){a.removeEvent(e,I.id);return}}a.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:W(T),time:$(L)})},Z=()=>{const U=_s(x,0,n,t,Math.ceil(n*20),120).map((L,T)=>({...L,id:Date.now()+T}));a.setEvents(e,[...k,...U]),v(!1)},O=()=>{const N=a.exportLane(e),U=new Blob([N],{type:"application/json"}),L=URL.createObjectURL(U),T=document.createElement("a");T.href=L,T.download=`cc-lane-${t}-layer-${e}.json`,document.body.appendChild(T),T.click(),T.remove(),URL.revokeObjectURL(L)},X=N=>{var L;const U=(L=N.target.files)==null?void 0:L[0];U&&(U.text().then(T=>{a.importLane(e,T)}),b.current&&(b.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:i("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:N=>o(Number(N.target.value)),children:fc.map(N=>s.jsxs("option",{value:N.cc,children:[N.label," (CC",N.cc,")"]},N.cc))}),s.jsx("div",{className:"btn-group btn-group-sm",children:["pencil","line","curve","step","ramp"].map(N=>s.jsx("button",{className:`btn ${c===N?"btn-primary":"btn-outline-secondary"}`,onClick:()=>d(N),style:{fontSize:11,textTransform:"capitalize"},children:N},N))}),s.jsxs("div",{className:"btn-group btn-group-sm",children:[s.jsx("button",{className:"btn btn-outline-secondary",onClick:a.undo,disabled:!a.canUndo,title:"Undo",children:"↩"}),s.jsx("button",{className:"btn btn-outline-secondary",onClick:a.redo,disabled:!a.canRedo,title:"Redo",children:"↪"})]}),s.jsx("button",{className:"btn btn-sm btn-outline-info",onClick:()=>v(!y),title:"Apply LFO modulation",children:"LFO"}),s.jsx("button",{className:"btn btn-sm btn-outline-warning",onClick:O,title:"Export CC lane as JSON",children:"Export"}),s.jsx("button",{className:"btn btn-sm btn-outline-success",onClick:()=>{var N;return(N=b.current)==null?void 0:N.click()},title:"Import CC lane from JSON",children:"Import"}),s.jsx("input",{ref:b,type:"file",accept:".json",style:{display:"none"},onChange:X}),s.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:()=>a.setEvents(e,k.filter(N=>N.cc!==t)),title:"Clear all CC events for this lane",children:"Clear"}),s.jsxs("span",{style:{fontSize:11,color:"#8b949e",marginLeft:"auto"},children:[R.length," ",i("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:x.waveform,onChange:N=>C(U=>({...U,waveform:N.target.value})),children:["sine","triangle","sawtooth","square","random","sample-hold"].map(N=>s.jsx("option",{value:N,children:N},N))})]}),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:x.rate,onChange:N=>C(U=>({...U,rate:Number(N.target.value)}))})]}),s.jsxs("label",{style:{fontSize:12},children:["Depth:",s.jsx("input",{type:"range",min:0,max:1,step:.01,value:x.depth,onChange:N=>C(U=>({...U,depth:Number(N.target.value)})),style:{width:80}}),s.jsx("span",{style:{fontSize:11,marginLeft:4},children:x.depth.toFixed(2)})]}),s.jsxs("label",{style:{fontSize:12},children:["Center:",s.jsx("input",{type:"range",min:0,max:1,step:.01,value:x.center,onChange:N=>C(U=>({...U,center:Number(N.target.value)})),style:{width:80}}),s.jsx("span",{style:{fontSize:11,marginLeft:4},children:x.center.toFixed(2)})]}),s.jsx("button",{className:"btn btn-sm btn-primary",onClick:Z,children:"Apply LFO"}),s.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>v(!1),children:"Cancel"})]})}),s.jsx("div",{style:{overflowX:"auto",borderRadius:6},children:s.jsx("canvas",{ref:l,width:A,height:Sr+rn*2,style:{cursor:h?"crosshair":m?"pointer":"crosshair",display:"block",borderRadius:6},onMouseDown:P,onMouseMove:B,onMouseUp:z,onMouseLeave:()=>{h&&z()},onDoubleClick:K,role:"img","aria-label":"CC automation lane editor canvas"})}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:4},children:i("ccLane.hint","Click to draw. Double-click to add/remove points. Drag to draw curves.")})]})},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},Ws={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function pc(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 Us(e,t){if(e.length===0)return[];const n=pc(e,t.octaves),r=[...n].sort((i,l)=>i.pitch-l.pitch),a=[...n].sort((i,l)=>l.pitch-i.pitch);let o;switch(t.mode){case"up":o=r;break;case"down":o=a;break;case"updown":o=[...r,...a.slice(1,-1)];break;case"downup":o=[...a,...r.slice(1,-1)];break;case"random":o=[...n].sort(()=>Math.random()-.5);break;case"as-played":o=[...n].sort((i,l)=>i.originalOrder-l.originalOrder);break;case"chord":o=n;break;default:o=r}if(t.repeats>1){const i=[];for(const l of o)for(let c=0;c<t.repeats;c++)i.push(l);o=i}return o}function mc(e,t,n,r=0,a=1){const o=Us(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 g=0;g<f;g++){const m=g%2===1?l*t.swing*.5:0,p=r+g*l+m;if(h)for(const y of o){const v=t.velocityPattern?t.velocityPattern[g%t.velocityPattern.length]:y.velocity;d.push({pitch:y.pitch,velocity:v,startTime:p,duration:c,step:g})}else{const y=g%o.length,v=o[y],x=t.velocityPattern?t.velocityPattern[g%t.velocityPattern.length]:v.velocity;d.push({pitch:v.pitch,velocity:x,startTime:p,duration:c,step:g})}}return d}function Vs(){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 qs(){return Object.keys(Gs)}const Hs=({config:e,onChange:t,active:n,onToggleActive:r})=>{const{t:a}=xe(),o=Vs(),i=qs(),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(Ws),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)})})]})]})]})},gc=["sine","triangle","sawtooth","square","random","sample-hold"],yc=["1/1","1/2","1/4","1/8","1/16","1/32"],an=200,Dt=48,Ks=({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=zs(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 g=h[f].x,m=h[f].y;f===0?d.moveTo(g,m):d.lineTo(g,m)}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:gc.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:yc.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)})})]})]})]})]})]})},bc=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function vc(e){const t=Math.floor(e/12)-1;return`${bc[e%12]}${t}`}const Ys=({seq:e})=>{const{t}=xe(),{pattern:n,currentStep:r,playing:a}=e,o=u.useMemo(()=>n.steps.slice(0,n.length),[n]);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:t("stepSeq.title","Step Sequencer")}),s.jsx("button",{className:`btn btn-sm ${a?"btn-danger":"btn-success"}`,onClick:e.togglePlayback,style:{minWidth:60},children:a?"■ 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:n.bpm,onChange:i=>e.setBpm(Number(i.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:n.swing,onChange:i=>e.setSwing(Number(i.target.value)),style:{width:60}}),s.jsxs("span",{style:{fontSize:11,minWidth:28},children:[Math.round(n.swing*100),"%"]})]}),s.jsx("div",{className:"btn-group btn-group-sm",children:[16,32,64].map(i=>s.jsx("button",{className:`btn ${n.length===i?"btn-primary":"btn-outline-secondary"}`,onClick:()=>e.setLength(i),style:{fontSize:11},children:i},i))})]}),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:n.length*36},children:o.map((i,l)=>{const c=i.active,d=r===l,h=l%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:h?"#8b949e":"#30363d"},children:l+1}),s.jsx("button",{onClick:()=>e.toggle(l),style:{width:32,height:32,borderRadius:4,border:d?"2px solid #f0c040":"1px solid #30363d",background:c?`hsl(${210+i.velocity/127*40}, 80%, ${35+i.velocity/127*20}%)`:h?"#21262d":"#161b22",cursor:"pointer",padding:0,color:c?"#fff":"#484f58",fontSize:8,fontWeight:600,transition:"background 0.1s"},children:c?vc(i.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:`${i.velocity/127*100}%`,background:c?"rgba(59, 130, 246, 0.6)":"rgba(59, 130, 246, 0.15)",borderRadius:2,cursor:"ns-resize"},title:`Vel: ${i.velocity}`,onMouseDown:f=>{f.preventDefault();const g=f.target.parentElement.getBoundingClientRect(),m=y=>{const v=y.clientY-g.top,x=Math.round(Math.max(1,Math.min(127,(1-v/g.height)*127)));e.setVelocity(l,x)},p=()=>{document.removeEventListener("mousemove",m),document.removeEventListener("mouseup",p)};document.addEventListener("mousemove",m),document.addEventListener("mouseup",p)}})}),c&&i.probability<1&&s.jsxs("span",{style:{fontSize:8,color:"#f0c040"},children:[Math.round(i.probability*100),"%"]})]},l)})})}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:6},children:t("stepSeq.hint","Click steps to toggle. Drag velocity bars vertically.")})]})},xc="_panelNarrow_se2i3_3",Sc="_panelWide_se2i3_9",wc="_smallLabel_se2i3_19",Cc="_noteText_se2i3_29",kc="_buttonRow_se2i3_41",Mc="_noteTextMargin_se2i3_49",jc="_rangeW100_se2i3_63",Rc="_zoomValue_se2i3_69",$c="_selectW100_se2i3_77",Tc="_inputW70_se2i3_83",Pc="_masterVolGroup_se2i3_93",Ec="_rangeW140_se2i3_99",Ac="_volumeValue_se2i3_105",Nc="_selectW140_se2i3_115",Ic="_freqGroup_se2i3_121",Lc="_freqValue_se2i3_127",Fc="_narrowGroup_se2i3_137",Dc="_rangeW120_se2i3_143",Oc="_smallValue_se2i3_149",_c="_presetDivider_se2i3_159",zc="_presetLabel_se2i3_165",Bc="_presetBtn_se2i3_175",Gc="_deletePresetSelect_se2i3_183",Wc="_presetNameInput_se2i3_191",Uc="_savePresetBtn_se2i3_199",Vc="_countInAlert_se2i3_211",qc="_inputW80_se2i3_219",Hc="_levelLabel_se2i3_225",Kc="_levelMeter_se2i3_233",Yc="_levelBar_se2i3_249",pe={panelNarrow:xc,panelWide:Sc,smallLabel:wc,noteText:Cc,buttonRow:kc,noteTextMargin:Mc,rangeW100:jc,zoomValue:Rc,selectW100:$c,inputW70:Tc,masterVolGroup:Pc,rangeW140:Ec,volumeValue:Ac,selectW140:Nc,freqGroup:Ic,freqValue:Lc,narrowGroup:Fc,rangeW120:Dc,smallValue:Oc,presetDivider:_c,presetLabel:zc,presetBtn:Bc,deletePresetSelect:Gc,presetNameInput:Wc,savePresetBtn:Uc,countInAlert:Vc,inputW80:qc,levelLabel:Hc,levelMeter:Kc,levelBar:Yc},Zs=({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.")]})]})},Xs=({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.")})]})},Qs=({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"})]})]})})},Js=({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:g}=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:m=>t(Number(m.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:m=>i({type:m.target.value}),children:["peaking","lowpass","highpass","lowshelf","highshelf","notch","bandpass"].map(m=>s.jsx("option",{value:m,children:m},m))})]}),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:m=>i({frequency:Number(m.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:m=>i({q:Number(m.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:m=>i({gain:Number(m.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:[g("editorPanels.eqPresets","EQ Presets"),":"]}),[...l,...c].map(m=>s.jsx("button",{className:`btn btn-sm btn-outline-secondary ${pe.presetBtn}`,onClick:()=>d(m),children:m.name},m.name)),c.length>0&&s.jsxs("select",{className:`form-select form-select-sm ${pe.deletePresetSelect}`,onChange:m=>{m.target.value&&(f(m.target.value),m.target.value="")},defaultValue:"",children:[s.jsx("option",{value:"",children:g("editorPanels.deletePreset","Delete preset...")}),c.map(m=>s.jsx("option",{value:m.name,children:m.name},m.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:g("editorPanels.presetName","Preset name..."),id:"presetNameInput"}),s.jsx("button",{className:`btn btn-sm btn-success ${pe.savePresetBtn}`,onClick:()=>{const m=document.getElementById("presetNameInput");m!=null&&m.value.trim()&&(h(m.value.trim()),m.value="")},children:g("editorPanels.saveCurrent","Save Current")})]})]})]})},eo=({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:g=>t(Number(g.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:g=>o(g.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:g=>l(g.target.value===""?null:Number(g.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:g=>d(g.target.value===""?null:Number(g.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 Zc(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 Xc(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),[g,m]=u.useState(120),p=u.useCallback(($,W)=>`L${$}-C${W}`,[]),y=u.useCallback(($,W)=>{if(!r.current||!W.audioBuffer)return;const w=p($,W.id),D=e[$];r.current.addClip({id:w,buffer:W.audioBuffer,startTime:W.start,offset:0,duration:W.duration,layerId:$,volume:(D==null?void 0:D.volume)??1,pan:(D==null?void 0:D.pan)??0,stretchFactor:W.stretchFactor||1,effectChain:(D==null?void 0:D.effectChain)||[]})},[e,p]),v=u.useCallback(($,W)=>{var w;(w=r.current)==null||w.removeClip(p($,W))},[p]);u.useEffect(()=>{Object.entries(t).forEach(([$,W])=>{const w=Number($);W==null||W.forEach(D=>y(w,D))})},[t,e,y]),u.useEffect(()=>{r.current&&Object.entries(n).forEach(([$,W])=>{const w=Number($);r.current.setMidiCCEvents(w,W)})},[n]);const x=u.useCallback(()=>{r.current&&(a?r.current.pause():r.current.play())},[a]),C=u.useCallback(()=>{var $;($=r.current)==null||$.stop()},[]),b=u.useCallback($=>{var W;(W=r.current)==null||W.seek($)},[]),k=u.useCallback(()=>{if(!r.current)return;const $=!h;f($),r.current.setLoopRegion(0,c,$)},[h,c]),R=u.useCallback($=>{var w;const W=Math.max(1,c+$);d(W),(w=r.current)==null||w.setLoopRegion(0,W,h)},[c,h]),A=u.useCallback(async($,W=1024)=>{const w=await $.arrayBuffer(),D=new(window.AudioContext||window.webkitAudioContext),_=await D.decodeAudioData(w.slice(0)),P=_.getChannelData(0),B=P.length,z=Math.max(1,Math.floor(B/W)),K=[];for(let Z=0;Z<W;Z++){const O=Z*z;if(O>=B)break;K.push(P[O])}return D.close(),{waveform:K.map(Z=>Math.max(-1,Math.min(1,Z))),duration:_.duration,buffer:_}},[]);return{engineRef:r,isPlaying:a,setIsPlaying:o,currentTime:i,setCurrentTime:l,duration:c,setDuration:d,isLooping:h,setIsLooping:f,bpm:g,setBpm:m,handlePlayPause:x,handleStop:C,handleSeek:b,handleToggleLoop:k,handleAdjustDuration:R,upsertEngineClip:y,removeEngineClip:v,makeEngineClipId:p,blobToWaveform:A}}class to{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 Qc(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),g=u.useRef(null),m=u.useRef(0),p=u.useRef(null),y=u.useRef(null),v=u.useCallback(()=>{p.current&&(clearInterval(p.current),p.current=null),y.current&&(clearTimeout(y.current),y.current=null)},[]),x=u.useCallback(async()=>{if(!e.activeLayer){e.showToast("Select a layer to record.","error");return}t||(f.current||(f.current=new to),m.current=g.current??e.currentTime,n(!0),i(0),await f.current.startRecording({onLevel:i}))},[e,t]),C=u.useCallback(async()=>{var P;if(v(),a(!1),c(0),g.current=null,!f.current){n(!1),i(0);return}const R=await f.current.stopRecording();if(n(!1),i(0),!R||!e.activeLayer)return;const{waveform:A,duration:$,buffer:W}=await e.blobToWaveform(R),w=e.activeLayer.id;e.setWaveforms(B=>({...B,[w]:A}));const D=Math.max(0,m.current||0),_={id:Date.now(),label:"Recording",start:D,duration:$,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:(P=e.layerSettings[w])==null?void 0:P.color,blob:R,blobUrl:URL.createObjectURL(R),audioBuffer:W};e.setLayerClips(B=>({...B,[w]:[...B[w]||[],_]})),e.upsertEngineClip(w,_),e.setSelectedClip({layerId:w,clipId:_.id})},[e,v]),b=u.useCallback(R=>{if(R<=0){x();return}a(!0),c(R);const A=performance.now();p.current=window.setInterval(()=>{const $=(performance.now()-A)/1e3;c(Math.max(0,R-$))},100),y.current=window.setTimeout(()=>{v(),a(!1),c(0),g.current||x()},R*1e3)},[x,v]),k=u.useCallback(async()=>{if(t||r){await C();return}if(!e.activeLayer){e.showToast("Select a layer before recording","error");return}const R=Math.max(0,e.countInBars)*4*(60/e.bpm),A=e.punchIn!=null&&e.punchIn>e.currentTime?e.punchIn:null;A&&(g.current=A),e.overdubEnabled&&!e.isPlaying&&e.playEngine(),A?R>0&&b(R):b(R)},[t,r,e,C,b]);return{isRecording:t,isCountIn:r,monitorLevel:o,countInRemaining:l,punchOut:d,setPunchOut:h,armedPunchInRef:g,recorderRef:f,clearCountInTimers:v,startRecordingNow:x,stopRecordingFlow:C,handleRecord:k}}var no=(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))(no||{});const Jc={};class En{constructor(t,n,r,a={}){this.type=t,this.name=n,this.component=Jc[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 ro(e,t,n,r,a){n(o=>t?[...o,t]:o),r([]),a(e)}function ed(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 td(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 nd{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 rd=et.scoped("useProjectCRUD");function ad(e){const{project:t,activeSection:n,setProject:r,setActiveSection:a,setLayers:o,setActiveLayer:i,setUndoStack:l,setRedoStack:c}=e,d=u.useCallback(v=>ro(v,t,l,c,r),[t,l,c,r]),h=u.useCallback(async()=>{var b;if(!t)return;const v=(((b=t.sections)==null?void 0:b.length)??0)+1,C={id:await e.addSection(t.id,"Section",v),projectId:t.id,name:"Section",orderNumber:v,layers:[]};d({...t,sections:[...t.sections||[],C]}),a(C)},[t,d,a]),f=u.useCallback(async v=>{var b,k,R;if(!t||!await e.confirm("Delete this section?"))return;await e.deleteSection(v);const C=(t.sections??[]).filter(A=>A.id!==v);d({...t,sections:C}),a(C[0]??null),o(((b=C[0])==null?void 0:b.layers)??[]),i(((R=(k=C[0])==null?void 0:k.layers)==null?void 0:R[0])??null)},[t,d,a,o,i,e]),g=u.useCallback(async()=>{var x;if(!n)return;const v={id:-Date.now(),name:"New Layer",sectionId:n.id,audioSource:no.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};o(C=>[...C,v]),i(v);try{const C=await e.addLayer(n.id,v.name,v.audioSource,v.audioSourceParameters);o(b=>b.map(k=>k.id===v.id?{...v,id:C}:k)),t&&d({...t,sections:((x=t.sections)==null?void 0:x.map(b=>b.id===n.id?{...b,layers:[...(b.layers??[]).filter(k=>k.id!==C),{...v,id:C}]}:b))??[]})}catch(C){o(b=>b.filter(k=>k.id!==v.id)),rd.error("Failed to add layer:",C)}},[n,t,d,o,i]),m=u.useCallback(async v=>{var C,b;if((C=e.layerSettings[v])!=null&&C.locked){e.showToast("Layer is locked. Unlock to delete.","error");return}await e.confirm("Delete this layer?")&&((e.layerClips[v]||[]).forEach(k=>e.removeEngineClip(v,k.id)),e.setLayerMidiNotes(k=>{const R={...k};return delete R[v],R}),await e.deleteLayer(v),o(k=>k.filter(R=>R.id!==v)),i(k=>(k==null?void 0:k.id)===v?null:k),t&&d({...t,sections:((b=t.sections)==null?void 0:b.map(k=>k.id===(n==null?void 0:n.id)?{...k,layers:(k.layers??[]).filter(R=>R.id!==v)}:k))??[]}))},[t,n,d,o,i,e]),p=u.useCallback(async()=>{if(!t)return;const v=e.projectVolume===""?void 0:Number(e.projectVolume);if(Number.isNaN(v)){e.setStatusType("error"),e.setStatusMessage("Volume musi byc liczba");return}if(!e.projectName.trim()){e.setStatusType("error"),e.setStatusMessage("Nazwa projektu nie moze byc pusta");return}await e.updateProject(t.id,{name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:v}),d({...t,name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:v}),e.setStatusType("success"),e.setStatusMessage("Project saved")},[t,e,d]),y=u.useCallback(async()=>{var C;if(!n)return;const v=e.sectionName||n.name,x=e.sectionOrder===""?n.orderNumber:Number(e.sectionOrder);if(!v.trim()){e.setStatusType("error"),e.setStatusMessage("Section name cannot be empty");return}if(Number.isNaN(x)){e.setStatusType("error"),e.setStatusMessage("Order musi byc liczba");return}await e.updateSection(n.id,{name:v,orderNumber:x}),a({...n,name:v,orderNumber:x}),t&&d({...t,sections:((C=t.sections)==null?void 0:C.map(b=>b.id===n.id?{...b,name:v,orderNumber:x}:b))??[]}),e.setStatusType("success"),e.setStatusMessage("Section saved")},[n,t,e,d,a]);return{handleAddSection:h,handleDeleteSection:f,handleAddLayer:g,handleDeleteLayer:m,handleSaveProject:p,handleSaveSection:y}}const ao=u.createContext(null);function sd(){const e=u.useContext(ao);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const Qr=({value:e,children:t})=>s.jsx(ao.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},od=(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),g=d.indexOf(" ",f+1),m=d.indexOf(" ",g+1);if(m===-1)return;const p=Ht(parseFloat(d.substring(h+1,f)),n);a===""&&(o=p);const y=d.substring(m+1);if(y.trim()==="~")return;let v=y;v.startsWith("~")&&(v=v.substring(1)),l?(c(),i=v.trimEnd()):i+=v.trimEnd(),l=y.endsWith(" ")}}}),c(),a.trim().length>0&&r.push({text:a.trim(),timestamp:o}),r},id=(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 g=f.startsWith("*"),m=f.indexOf(" "),p=f.indexOf(" ",m+1),y=f.indexOf(" ",p+1),v=f.indexOf(" ",y+1);if(v===-1)return;const x=Ht(parseFloat(f.substring(m+1,p)),n),C=Ht(parseFloat(f.substring(p+1,y)),n),b=x+C;o===""&&(i=x);const k=f.substring(v+1);if(k.trim()==="~"){c&&(c.endTime=b);return}let R=k;R.startsWith("~")&&(R=R.substring(1)),l?(h(),d=R.trimEnd(),c={text:"",startTime:x,endTime:b,isGolden:g}):c?(d+=R.trimEnd(),c.endTime=b,g&&(c.isGolden=!0)):(d=R.trimEnd(),c={text:"",startTime:x,endTime:b,isGolden:g}),l=k.endsWith(" ")}}}),h(),o.trim().length>0&&r.push({text:o.trim(),timestamp:i,words:a}),r},so=(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),g=l.indexOf(" ",f+1);if(g===-1)return;const m=parseFloat(l.substring(d+1,h)),p=parseFloat(l.substring(h+1,f)),y=Ht(m,n),v=y+Ht(p,n);a.length===0&&(o=y);const x=l.substring(g+1);if(x.trim()==="~"){a.length>0&&(a[a.length-1].endTime=v);return}let C=x;C.startsWith("~")&&(C=C.substring(1));const b=x.endsWith(" "),k=b?C.slice(0,-1):C;a.push({text:k,startTime:y,endTime:v,isGolden:c,hasTrailingSpace:b})}}}),i(),r},ld=(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},cd=(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},_a="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",za="var(--karaoke-gold-glow-first, 0 0 12px #FFD700)",dd="var(--karaoke-active-glow, 0 0 10px rgba(0,229,255,0.6), 0 0 4px rgba(255,230,0,0.4))",ud="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",hd=({song:e,currentTime:t})=>{const n=u.useMemo(()=>!e||!e.notes.length?[]:so(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:dd,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?" ":""),g=d>0&&d<1,m=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:m?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":_a,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:m?`drop-shadow(${za})`:"none",transition:"filter 0.2s ease"},children:f},c):s.jsxs("span",{style:{position:"relative",display:"inline",filter:g?m?`drop-shadow(${za})`:`drop-shadow(${ud})`:"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:m?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":_a,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..."})})},oo=u.memo(hd),io=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},Ba=(e,t)=>t&&t>0?e*15/t:e/10,ea=(e,t)=>{const n=t??io(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:Ba(parseFloat(i[1]),n),duration:Ba(parseFloat(i[2]),n),pitch:parseInt(i[3],10),isGold:c})}}),a.length>0&&r.push(a),r},lo=(e,t)=>{let r=(Math.round(12*Math.log2(e/440)+69)%12+12)%12;if(t!==null){for(;r-t>6;)r-=12;for(;r-t<-6;)r+=12}return r};function Nr(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 fd(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 pd=1e3,md=20,gd=70,yd=5,Ga=26,Wa="rgba(255,215,70,0.98)",Ua=new Map,bd=(e,t,n,r,a)=>{const o=`g${a}`,i=`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <svg xmlns='http://www.w3.org/2000/svg' width='${r}' height='${r}' viewBox='0 0 ${r} ${r}'>
3
3
  <defs>
4
4
  <radialGradient id='g${o}' cx='50%' cy='40%' r='60%'>
@@ -10,47 +10,47 @@
10
10
  <g transform='translate(${r/2}, ${r/2})'>
11
11
  <circle cx='0' cy='0' r='${r*.45}' fill='url(#g${o})' />
12
12
  </g>
13
- </svg>`;return`data:image/svg+xml;utf8,${encodeURIComponent(i)}`},bd=(e,t,n,r,a)=>{const o=`${e}-${t}-${n}-${Math.round(r)}-${a}`;let i=Ua.get(o);return i||(i=new Image,i.src=yd(e,t,n,r,a),Ua.set(o,i),i)},xd=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)}},vd=(e,t,n,r=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(n)}%, ${r})`;function An(e){try{const t=Nr(e),[n,r,a]=hd(t),o=i=>i.toString(16).padStart(2,"0");return`#${o(n)}${o(r)}${o(a)}`.toLowerCase()}catch{return"#ffcc00"}}function Sd(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()}function wd(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 Cd(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 g=0;g<c;g++){const m=(h+g*2.1)%(Math.PI*2),p=Math.sin(m)*.5+.5,y=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,y,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 g of e.visibleNotes){if(!g.isSung)continue;const m=(l*6+g.x*.01)%(Math.PI*2),p=.15+Math.sin(m)*.1;t.globalAlpha=p,t.fillStyle=g.isGold?"#FFD700":o,t.fillRect(g.x,g.y,g.w,g.h)}t.restore()}function kd(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 g=1-Math.abs(h)/(c+20);t.beginPath(),t.ellipse(n,r+a*.5,a*g*1.5,a*.3*g,0,0,Math.PI*2),t.fill(),t.restore(),t.save();const m=5;for(let x=0;x<m;x++){const v=(x+1)*.04,C=(l-v)*5%(Math.PI*2),b=r+-Math.abs(Math.sin(C))*c,k=.15*(1-x/m),R=a*(.6-x*.08);t.globalAlpha=k,t.fillStyle=o,t.beginPath(),t.arc(n-x*3,b,Math.max(2,R),0,Math.PI*2),t.fill()}t.restore(),t.save();const p=1+Math.abs(Math.sin(d))*.15,y=1/p;if(t.translate(n,f),t.scale(y,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 v=x/4*Math.PI*2+l,C=n+Math.cos(v)*(a+4),b=r+Math.sin(v)*2;t.beginPath(),t.arc(C,b,2,0,Math.PI*2),t.fill()}t.restore()}}function Md(e,t){switch(e){case"wipe":return wd(t),!0;case"pulse":return Cd(t),!0;case"bounce":return kd(t),!0;case"ball":default:return!1}}const jd=3,V=jd;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} ${V}V${e-V}A${t-V} ${t-V} 0 0 1 ${V} ${t}A${t-V} ${t-V} 0 0 1 ${t} ${V}Z`}}function Kt(e){return{w:V+1,out:`M0 0H${V+1}V${e}H0Z`,inn:`M${V} ${V}H${V+1}V${e-V}H${V}Z`}}function ta(e){const t=Math.min(14,e*.22)|0,n=t+2,r=Math.max(t-V,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${V+r} ${V}H${n}V${e-V}H${V+r}Q${V} ${e-V} ${V} ${e-V-r}V${V+r}Q${V} ${V} ${V+r} ${V}Z`}}function Qn(e){const t=e*.3|0,n=t+2,r=Math.max(t-V,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e-t}V${t}Z`,inn:`M${V+r} ${V}H${n}V${e-V}H${V+r}L${V} ${e-V-r}V${V+r}Z`}}function Mt(e){const t=e*.42|0,n=t+2,r=Math.max(t-(V*1.4|0),2);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e/2}Z`,inn:`M${V+r} ${V}H${n}V${e-V}H${V+r}L${V} ${e/2}Z`}}function Jn(e){const t=e*.3|0,n=t+4,r=Math.max(t-V,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${V+r} ${V}H${n}V${e-V}H${V+(r*.6|0)}L${V} ${e-V-r}V${V+r}Q${V} ${V} ${V+r} ${V}Z`}}function na(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${V+(t*1.2|0)} ${V}H${n}V${e-V}H${V+(t*1.2|0)}C${V+(t*2.2|0)} ${e*.37|0} ${V+(t*2.2|0)} ${e*.63|0} ${V+(t*1.2|0)} ${e-V}Z`}}function ra(e){const t=e*.32|0,n=t+3,r=Math.max(t-V,1);return{w:n,out:`M0 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}Z`,inn:`M${V} ${V}H${n}V${e-V}H${V+r}Q${V} ${e-V} ${V} ${e-V-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${V+(t*1.8|0)} ${V}H${n}V${e-V}H${V+(t*1.8|0)}C${V+(t*.4|0)} ${e*.78|0} ${V+(t*2.8|0)} ${e*.55|0} ${V+(t*.4|0)} ${e*.37|0}S${V+(t*.9|0)} ${V} ${V+(t*1.8|0)} ${V}Z`}}function aa(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${V+(t*2.5|0)} ${V}H${n}V${e-V}H${V+(t*2.5|0)}L${V+(t*.7|0)} ${e-V-(t*1.6|0)}L${V+(t*1.7|0)} ${e*.64|0}L${V} ${e/2|0}L${V+(t*1.7|0)} ${e*.36|0}L${V+(t*.7|0)} ${V+(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${V+t-(V*1.3|0)} ${V}H${n}V${e-V}H${V+1}Z`}}function Ir(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}V${e}H${t}Z`,inn:`M${V} ${V}H${n}V${e-V}H${V+t-(V*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 ${V}A${t-V} ${t-V} 0 0 1 ${t-V} ${t}A${t-V} ${t-V} 0 0 1 0 ${e-V}Z`}}function Yt(e){return{w:V+1,out:`M0 0H${V+1}V${e}H0Z`,inn:`M0 ${V}H1V${e-V}H0Z`}}function co(e){const t=Math.min(14,e*.22)|0,n=t+2,r=Math.max(t-V,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 ${V}H${n-V-r}Q${n-V} ${V} ${n-V} ${V+r}V${e-V-r}Q${n-V} ${e-V} ${n-V-r} ${e-V}H0Z`}}function Zt(e){const t=e*.3|0,n=t+2,r=Math.max(t-V,1);return{w:n,out:`M0 0H${n-t}L${n} ${t}V${e-t}L${n-t} ${e}H0Z`,inn:`M0 ${V}H${n-V-r}L${n-V} ${V+r}V${e-V-r}L${n-V-r} ${e-V}H0Z`}}function gt(e){const t=e*.42|0,n=t+2,r=Math.max(t-(V*1.4|0),2);return{w:n,out:`M0 0H${n-t}L${n} ${e/2}L${n-t} ${e}H0Z`,inn:`M0 ${V}H${n-V-r}L${n-V} ${e/2}L${n-V-r} ${e-V}H0Z`}}function uo(e){const t=e*.3|0,n=t+4,r=Math.max(t-V,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 ${V}H${n-V-r}Q${n-V} ${V} ${n-V} ${V+r}V${e-V-r}L${n-V-(r*.6|0)} ${e-V}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 ${V}H${n-V-(t*1.2|0)}C${n-V-(t*2.2|0)} ${e*.37|0} ${n-V-(t*2.2|0)} ${e*.63|0} ${n-V-(t*1.2|0)} ${e-V}H0Z`}}function fo(e){const t=e*.32|0,n=t+3,r=Math.max(t-V,1);return{w:n,out:`M0 0H${n}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${V}H${n-V}V${e-V-r}Q${n-V} ${e-V} ${n-V-r} ${e-V}H0Z`}}function sa(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 ${V}H${n-V-(t*1.8|0)}C${n-V-(t*.9|0)} ${V} ${n-V+(t*.1|0)} ${e*.22|0} ${n-V-(t*.4|0)} ${e*.37|0}S${n-V-(t*.4|0)} ${e*.78|0} ${n-V-(t*1.8|0)} ${e-V}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 ${V}H${n-V-(t*2.5|0)}L${n-V-(t*.7|0)} ${V+(t*1.6|0)}L${n-V-(t*1.7|0)} ${e*.36|0}L${n-V} ${e/2|0}L${n-V-(t*1.7|0)} ${e*.64|0}L${n-V-(t*.7|0)} ${e-V-(t*1.6|0)}L${n-V-(t*2.5|0)} ${e-V}H0Z`}}function Lr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}L${n-t} ${e}H0Z`,inn:`M0 ${V}H${n-V}L${n-V-t+(V*1.3|0)} ${e-V}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 ${V}H${n-V-t+(V*1.3|0)}L${n-V} ${e-V}H0Z`}}const oa=[{name:"Pill",L:$t,R:Ct},{name:"Sharp",L:Kt,R:Yt},{name:"Soft",L:ta,R:co},{name:"Chamfer",L:Qn,R:Zt},{name:"Arrow",L:Mt,R:gt},{name:"Shield",L:Jn,R:uo},{name:"Bracket",L:na,R:ho},{name:"Tab",L:ra,R:fo},{name:"Wave",L:er,R:sa},{name:"Ornate",L:aa,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:ta,R:gt},{name:"Shield→Chamfer",L:Jn,R:Zt},{name:"Pill→Wave",L:$t,R:sa},{name:"Wave→Arrow",L:er,R:gt},{name:"Tab→Pill",L:ra,R:Ct},{name:"Ornate→Sharp",L:aa,R:Yt},{name:"Sharp→Ornate",L:Kt,R:tr},{name:"Bracket→Arrow",L:na,R:gt},{name:"Shield→Pill",L:Jn,R:Ct},{name:"Wave→Ornate",L:er,R:tr}],mo=[{name:"Skew ╲",L:Un,R:Lr},{name:"Skew ╱",L:Ir,R:Vn},{name:"◇ Romb",L:Mt,R:gt},{name:"╲→Pill",L:Un,R:Ct},{name:"Pill→╲",L:$t,R:Lr},{name:"╱→Sharp",L:Ir,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=[...oa,...po,...mo],go=oa[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},Va="nice2dev-player-bar-style",qa="nice2dev-player-karaoke-settings";function Qt(e){return e!=null?`${qa}-${e}`:qa}function Mn(e){return e!=null?`${Va}-${e}`:Va}function Ha(e){return{filledBar:{color:null,capStyleName:e.capStyleName,patternName:e.patternName,patternColor:e.patternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.filledTextureUrl,textureScale:e.textureScale},emptyBar:{color:null,capStyleName:e.capStyleName,patternName:e.patternName,patternColor:e.patternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:e.emptyGlass,textureUrl:e.emptyTextureUrl,textureScale:e.textureScale},goldFilledBar:{color:null,capStyleName:e.capStyleName,patternName:e.goldHitPatternName,patternColor:e.goldHitPatternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.goldFilledTextureUrl,textureScale:e.textureScale},goldEmptyBar:{color:null,capStyleName:e.capStyleName,patternName:e.goldPatternName,patternColor:e.goldPatternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.goldEmptyTextureUrl,textureScale:e.textureScale},font:{fontFamily:e.fontFamily,fontSize:e.fontSize,fontColor:e.fontColor,outlineColor:e.fontOutlineColor,outlineWidth:e.fontOutlineWidth,shadow:e.fontShadow}}}function Ka(e){const t=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 Ka(r)}const n=localStorage.getItem(Mn(e));if(n){const r=JSON.parse(n),a=Ha({...Xt,...r});return localStorage.setItem(Qt(e),JSON.stringify(a)),a}if(e!=null){const r=localStorage.getItem(Qt());if(r)return Ka(JSON.parse(r));const a=localStorage.getItem(Mn());if(a)return Ha({...Xt,...JSON.parse(a)})}}catch{}return{filledBar:{...At},emptyBar:{...lr},goldFilledBar:{...dr},goldEmptyBar:{...cr},font:{...ur}}}function Rd(e,t){const n=JSON.stringify(e);localStorage.setItem(Qt(t),n)}let Ya=!1;async function $d(e){if(Ya||(Ya=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(Qt())||localStorage.setItem(Qt(),t)}catch{}}function Td(e){const t=new Map;for(const n of e)t.set(n,bo(n));return t}function xo(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 Pd(e,t){localStorage.setItem(Mn(t),JSON.stringify(e))}function Ed(e){const t=new Map;for(const n of e)t.set(n,xo(n));return t}const Ad={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Nd=/[&<>"']/g;function Id(e){return e.replace(Nd,t=>Ad[t])}function Ld(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 Fd=3,Be=Fd;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,`
13
+ </svg>`;return`data:image/svg+xml;utf8,${encodeURIComponent(i)}`},vd=(e,t,n,r,a)=>{const o=`${e}-${t}-${n}-${Math.round(r)}-${a}`;let i=Ua.get(o);return i||(i=new Image,i.src=bd(e,t,n,r,a),Ua.set(o,i),i)},xd=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)}},Sd=(e,t,n,r=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(n)}%, ${r})`;function An(e){try{const t=Nr(e),[n,r,a]=fd(t),o=i=>i.toString(16).padStart(2,"0");return`#${o(n)}${o(r)}${o(a)}`.toLowerCase()}catch{return"#ffcc00"}}function wd(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()}function Cd(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 kd(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 g=0;g<c;g++){const m=(h+g*2.1)%(Math.PI*2),p=Math.sin(m)*.5+.5,y=d+p*a*3,v=(1-p)*.5;t.globalAlpha=v,t.strokeStyle=i?"#FFD700":o,t.lineWidth=2-p,t.beginPath(),t.arc(n,r,y,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 g of e.visibleNotes){if(!g.isSung)continue;const m=(l*6+g.x*.01)%(Math.PI*2),p=.15+Math.sin(m)*.1;t.globalAlpha=p,t.fillStyle=g.isGold?"#FFD700":o,t.fillRect(g.x,g.y,g.w,g.h)}t.restore()}function Md(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 g=1-Math.abs(h)/(c+20);t.beginPath(),t.ellipse(n,r+a*.5,a*g*1.5,a*.3*g,0,0,Math.PI*2),t.fill(),t.restore(),t.save();const m=5;for(let v=0;v<m;v++){const x=(v+1)*.04,C=(l-x)*5%(Math.PI*2),b=r+-Math.abs(Math.sin(C))*c,k=.15*(1-v/m),R=a*(.6-v*.08);t.globalAlpha=k,t.fillStyle=o,t.beginPath(),t.arc(n-v*3,b,Math.max(2,R),0,Math.PI*2),t.fill()}t.restore(),t.save();const p=1+Math.abs(Math.sin(d))*.15,y=1/p;if(t.translate(n,f),t.scale(y,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 v=0;v<4;v++){const x=v/4*Math.PI*2+l,C=n+Math.cos(x)*(a+4),b=r+Math.sin(x)*2;t.beginPath(),t.arc(C,b,2,0,Math.PI*2),t.fill()}t.restore()}}function jd(e,t){switch(e){case"wipe":return Cd(t),!0;case"pulse":return kd(t),!0;case"bounce":return Md(t),!0;case"ball":default:return!1}}const Rd=3,V=Rd;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} ${V}V${e-V}A${t-V} ${t-V} 0 0 1 ${V} ${t}A${t-V} ${t-V} 0 0 1 ${t} ${V}Z`}}function Kt(e){return{w:V+1,out:`M0 0H${V+1}V${e}H0Z`,inn:`M${V} ${V}H${V+1}V${e-V}H${V}Z`}}function ta(e){const t=Math.min(14,e*.22)|0,n=t+2,r=Math.max(t-V,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${V+r} ${V}H${n}V${e-V}H${V+r}Q${V} ${e-V} ${V} ${e-V-r}V${V+r}Q${V} ${V} ${V+r} ${V}Z`}}function Qn(e){const t=e*.3|0,n=t+2,r=Math.max(t-V,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e-t}V${t}Z`,inn:`M${V+r} ${V}H${n}V${e-V}H${V+r}L${V} ${e-V-r}V${V+r}Z`}}function Mt(e){const t=e*.42|0,n=t+2,r=Math.max(t-(V*1.4|0),2);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e/2}Z`,inn:`M${V+r} ${V}H${n}V${e-V}H${V+r}L${V} ${e/2}Z`}}function Jn(e){const t=e*.3|0,n=t+4,r=Math.max(t-V,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${V+r} ${V}H${n}V${e-V}H${V+(r*.6|0)}L${V} ${e-V-r}V${V+r}Q${V} ${V} ${V+r} ${V}Z`}}function na(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${V+(t*1.2|0)} ${V}H${n}V${e-V}H${V+(t*1.2|0)}C${V+(t*2.2|0)} ${e*.37|0} ${V+(t*2.2|0)} ${e*.63|0} ${V+(t*1.2|0)} ${e-V}Z`}}function ra(e){const t=e*.32|0,n=t+3,r=Math.max(t-V,1);return{w:n,out:`M0 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}Z`,inn:`M${V} ${V}H${n}V${e-V}H${V+r}Q${V} ${e-V} ${V} ${e-V-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${V+(t*1.8|0)} ${V}H${n}V${e-V}H${V+(t*1.8|0)}C${V+(t*.4|0)} ${e*.78|0} ${V+(t*2.8|0)} ${e*.55|0} ${V+(t*.4|0)} ${e*.37|0}S${V+(t*.9|0)} ${V} ${V+(t*1.8|0)} ${V}Z`}}function aa(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${V+(t*2.5|0)} ${V}H${n}V${e-V}H${V+(t*2.5|0)}L${V+(t*.7|0)} ${e-V-(t*1.6|0)}L${V+(t*1.7|0)} ${e*.64|0}L${V} ${e/2|0}L${V+(t*1.7|0)} ${e*.36|0}L${V+(t*.7|0)} ${V+(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${V+t-(V*1.3|0)} ${V}H${n}V${e-V}H${V+1}Z`}}function Ir(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}V${e}H${t}Z`,inn:`M${V} ${V}H${n}V${e-V}H${V+t-(V*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 ${V}A${t-V} ${t-V} 0 0 1 ${t-V} ${t}A${t-V} ${t-V} 0 0 1 0 ${e-V}Z`}}function Yt(e){return{w:V+1,out:`M0 0H${V+1}V${e}H0Z`,inn:`M0 ${V}H1V${e-V}H0Z`}}function co(e){const t=Math.min(14,e*.22)|0,n=t+2,r=Math.max(t-V,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 ${V}H${n-V-r}Q${n-V} ${V} ${n-V} ${V+r}V${e-V-r}Q${n-V} ${e-V} ${n-V-r} ${e-V}H0Z`}}function Zt(e){const t=e*.3|0,n=t+2,r=Math.max(t-V,1);return{w:n,out:`M0 0H${n-t}L${n} ${t}V${e-t}L${n-t} ${e}H0Z`,inn:`M0 ${V}H${n-V-r}L${n-V} ${V+r}V${e-V-r}L${n-V-r} ${e-V}H0Z`}}function gt(e){const t=e*.42|0,n=t+2,r=Math.max(t-(V*1.4|0),2);return{w:n,out:`M0 0H${n-t}L${n} ${e/2}L${n-t} ${e}H0Z`,inn:`M0 ${V}H${n-V-r}L${n-V} ${e/2}L${n-V-r} ${e-V}H0Z`}}function uo(e){const t=e*.3|0,n=t+4,r=Math.max(t-V,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 ${V}H${n-V-r}Q${n-V} ${V} ${n-V} ${V+r}V${e-V-r}L${n-V-(r*.6|0)} ${e-V}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 ${V}H${n-V-(t*1.2|0)}C${n-V-(t*2.2|0)} ${e*.37|0} ${n-V-(t*2.2|0)} ${e*.63|0} ${n-V-(t*1.2|0)} ${e-V}H0Z`}}function fo(e){const t=e*.32|0,n=t+3,r=Math.max(t-V,1);return{w:n,out:`M0 0H${n}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${V}H${n-V}V${e-V-r}Q${n-V} ${e-V} ${n-V-r} ${e-V}H0Z`}}function sa(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 ${V}H${n-V-(t*1.8|0)}C${n-V-(t*.9|0)} ${V} ${n-V+(t*.1|0)} ${e*.22|0} ${n-V-(t*.4|0)} ${e*.37|0}S${n-V-(t*.4|0)} ${e*.78|0} ${n-V-(t*1.8|0)} ${e-V}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 ${V}H${n-V-(t*2.5|0)}L${n-V-(t*.7|0)} ${V+(t*1.6|0)}L${n-V-(t*1.7|0)} ${e*.36|0}L${n-V} ${e/2|0}L${n-V-(t*1.7|0)} ${e*.64|0}L${n-V-(t*.7|0)} ${e-V-(t*1.6|0)}L${n-V-(t*2.5|0)} ${e-V}H0Z`}}function Lr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}L${n-t} ${e}H0Z`,inn:`M0 ${V}H${n-V}L${n-V-t+(V*1.3|0)} ${e-V}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 ${V}H${n-V-t+(V*1.3|0)}L${n-V} ${e-V}H0Z`}}const oa=[{name:"Pill",L:$t,R:Ct},{name:"Sharp",L:Kt,R:Yt},{name:"Soft",L:ta,R:co},{name:"Chamfer",L:Qn,R:Zt},{name:"Arrow",L:Mt,R:gt},{name:"Shield",L:Jn,R:uo},{name:"Bracket",L:na,R:ho},{name:"Tab",L:ra,R:fo},{name:"Wave",L:er,R:sa},{name:"Ornate",L:aa,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:ta,R:gt},{name:"Shield→Chamfer",L:Jn,R:Zt},{name:"Pill→Wave",L:$t,R:sa},{name:"Wave→Arrow",L:er,R:gt},{name:"Tab→Pill",L:ra,R:Ct},{name:"Ornate→Sharp",L:aa,R:Yt},{name:"Sharp→Ornate",L:Kt,R:tr},{name:"Bracket→Arrow",L:na,R:gt},{name:"Shield→Pill",L:Jn,R:Ct},{name:"Wave→Ornate",L:er,R:tr}],mo=[{name:"Skew ╲",L:Un,R:Lr},{name:"Skew ╱",L:Ir,R:Vn},{name:"◇ Romb",L:Mt,R:gt},{name:"╲→Pill",L:Un,R:Ct},{name:"Pill→╲",L:$t,R:Lr},{name:"╱→Sharp",L:Ir,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=[...oa,...po,...mo],go=oa[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},Va="nice2dev-player-bar-style",qa="nice2dev-player-karaoke-settings";function Qt(e){return e!=null?`${qa}-${e}`:qa}function Mn(e){return e!=null?`${Va}-${e}`:Va}function Ha(e){return{filledBar:{color:null,capStyleName:e.capStyleName,patternName:e.patternName,patternColor:e.patternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.filledTextureUrl,textureScale:e.textureScale},emptyBar:{color:null,capStyleName:e.capStyleName,patternName:e.patternName,patternColor:e.patternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:e.emptyGlass,textureUrl:e.emptyTextureUrl,textureScale:e.textureScale},goldFilledBar:{color:null,capStyleName:e.capStyleName,patternName:e.goldHitPatternName,patternColor:e.goldHitPatternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.goldFilledTextureUrl,textureScale:e.textureScale},goldEmptyBar:{color:null,capStyleName:e.capStyleName,patternName:e.goldPatternName,patternColor:e.goldPatternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.goldEmptyTextureUrl,textureScale:e.textureScale},font:{fontFamily:e.fontFamily,fontSize:e.fontSize,fontColor:e.fontColor,outlineColor:e.fontOutlineColor,outlineWidth:e.fontOutlineWidth,shadow:e.fontShadow}}}function Ka(e){const t=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 Ka(r)}const n=localStorage.getItem(Mn(e));if(n){const r=JSON.parse(n),a=Ha({...Xt,...r});return localStorage.setItem(Qt(e),JSON.stringify(a)),a}if(e!=null){const r=localStorage.getItem(Qt());if(r)return Ka(JSON.parse(r));const a=localStorage.getItem(Mn());if(a)return Ha({...Xt,...JSON.parse(a)})}}catch{}return{filledBar:{...At},emptyBar:{...lr},goldFilledBar:{...dr},goldEmptyBar:{...cr},font:{...ur}}}function $d(e,t){const n=JSON.stringify(e);localStorage.setItem(Qt(t),n)}let Ya=!1;async function Td(e){if(Ya||(Ya=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(Qt())||localStorage.setItem(Qt(),t)}catch{}}function Pd(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 Ed(e,t){localStorage.setItem(Mn(t),JSON.stringify(e))}function Ad(e){const t=new Map;for(const n of e)t.set(n,vo(n));return t}const Nd={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Id=/[&<>"']/g;function Ld(e){return e.replace(Id,t=>Nd[t])}function Fd(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 Dd=3,Be=Dd;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,`
14
14
  $1`).split(`
15
- `).filter(Boolean).map(n=>{const r=n[0],a=n.slice(1).trim().split(/[\s,]+/).map(Number);if(r==="H")return`H${a[0]+t}`;if(r==="V"||r==="Z")return n;if("MLCSQT".includes(r.toUpperCase())){for(let 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 vo(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:g=1}=e,m=f&&Ld(f)?Id(f):null,[p,y,x]=rr(ar(a)),v="c"+Math.random().toString(36).slice(2,7),C=r.L(n),b=r.R(n),k=t-C.w-b.w;if(k<4)return"";if(h&&c){const ne=`hsl(${p},${y}%,${x}%)`,ae=`hsl(${p},${Math.max(y-20,0)}%,${Math.min(x+30,95)}%)`,re=d||ae,G=C.w,q=C.w+k,ee=C.inn,oe=`M${G} ${Be}H${q}V${n-Be}H${G}Z`,ce=Qe(b.inn,q),fe=C.out,Q=`M${G} 0H${q}V${n}H${G}Z`,ue=Qe(b.out,q),ye=c.mk(v+"pat",re,d||void 0),je=Math.round(256*g),Fe=Math.round(256*g),Re=m?`<pattern id="${v}tex" patternUnits="userSpaceOnUse" width="${je}" height="${Fe}"><image href="${m}" width="${je}" height="${Fe}" preserveAspectRatio="none"/></pattern>`:"",Se=m?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${v}tex)" opacity=".85" clip-path="url(#${v}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
15
+ `).filter(Boolean).map(n=>{const r=n[0],a=n.slice(1).trim().split(/[\s,]+/).map(Number);if(r==="H")return`H${a[0]+t}`;if(r==="V"||r==="Z")return n;if("MLCSQT".includes(r.toUpperCase())){for(let 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:g=1}=e,m=f&&Fd(f)?Ld(f):null,[p,y,v]=rr(ar(a)),x="c"+Math.random().toString(36).slice(2,7),C=r.L(n),b=r.R(n),k=t-C.w-b.w;if(k<4)return"";if(h&&c){const ne=`hsl(${p},${y}%,${v}%)`,ae=`hsl(${p},${Math.max(y-20,0)}%,${Math.min(v+30,95)}%)`,re=d||ae,G=C.w,q=C.w+k,ee=C.inn,oe=`M${G} ${Be}H${q}V${n-Be}H${G}Z`,ce=Qe(b.inn,q),fe=C.out,Q=`M${G} 0H${q}V${n}H${G}Z`,ue=Qe(b.out,q),ye=c.mk(x+"pat",re,d||void 0),je=Math.round(256*g),Fe=Math.round(256*g),Re=m?`<pattern id="${x}tex" patternUnits="userSpaceOnUse" width="${je}" height="${Fe}"><image href="${m}" width="${je}" height="${Fe}" preserveAspectRatio="none"/></pattern>`:"",Se=m?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${x}tex)" opacity=".85" clip-path="url(#${x}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
16
16
  ${ye}
17
17
  ${Re}
18
- <clipPath id="${v}c"><path d="${ee}"/><path d="${oe}"/><path d="${ce}"/></clipPath>
18
+ <clipPath id="${x}c"><path d="${ee}"/><path d="${oe}"/><path d="${ce}"/></clipPath>
19
19
  </defs>
20
20
  <path d="${fe}" fill="rgba(255,255,255,.18)"/><path d="${Q}" fill="rgba(255,255,255,.18)"/><path d="${ue}" fill="rgba(255,255,255,.18)"/>
21
21
  <path d="${ee}" fill="${ne}" opacity=".22"/><path d="${oe}" fill="${ne}" opacity=".22"/><path d="${ce}" fill="${ne}" opacity=".22"/>
22
22
  ${Se}
23
- <rect x="0" y="0" width="${t}" height="${n}" fill="url(#${v}pat)" clip-path="url(#${v}c)"/>
24
- </svg>`}const R=`hsl(${p},${Math.min(y+10,100)}%,${Math.max(x-22,4)}%)`,A=`hsl(${p},${y}%,${x}%)`,$=`hsl(${p},${Math.max(y-12,0)}%,${Math.min(x+18,88)}%)`,W=`hsl(${p},${Math.min(y+20,100)}%,${Math.min(x+30,93)}%)`,w=`hsl(${p},${Math.max(y-20,0)}%,${Math.min(x+30,95)}%)`,D=d||w,_=o/100*.78,P=i/100*.65,B=1-l/100*.87,z=Be,K=n-Be,Z=z+(K-z)*.44,O=z+(K-z)*.58,X=C.w,N=C.w+k,U=C.out,L=`M${X} 0H${N}V${n}H${X}Z`,T=Qe(b.out,N),S=C.inn,I=`M${X} ${Be}H${N}V${n-Be}H${X}Z`,M=Qe(b.inn,N),F=c?c.mk(v+"pat",D,d||void 0):"",j=c?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${v}pat)" clip-path="url(#${v}c)"/>`:"",E=Math.round(256*g),H=Math.round(256*g),Y=m?`<pattern id="${v}tex" patternUnits="userSpaceOnUse" width="${E}" height="${H}"><image href="${m}" width="${E}" height="${H}" preserveAspectRatio="none"/></pattern>`:"",J=m?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${v}tex)" opacity="${B*.9}" clip-path="url(#${v}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
23
+ <rect x="0" y="0" width="${t}" height="${n}" fill="url(#${x}pat)" clip-path="url(#${x}c)"/>
24
+ </svg>`}const R=`hsl(${p},${Math.min(y+10,100)}%,${Math.max(v-22,4)}%)`,A=`hsl(${p},${y}%,${v}%)`,$=`hsl(${p},${Math.max(y-12,0)}%,${Math.min(v+18,88)}%)`,W=`hsl(${p},${Math.min(y+20,100)}%,${Math.min(v+30,93)}%)`,w=`hsl(${p},${Math.max(y-20,0)}%,${Math.min(v+30,95)}%)`,D=d||w,_=o/100*.78,P=i/100*.65,B=1-l/100*.87,z=Be,K=n-Be,Z=z+(K-z)*.44,O=z+(K-z)*.58,X=C.w,N=C.w+k,U=C.out,L=`M${X} 0H${N}V${n}H${X}Z`,T=Qe(b.out,N),S=C.inn,I=`M${X} ${Be}H${N}V${n-Be}H${X}Z`,M=Qe(b.inn,N),F=c?c.mk(x+"pat",D,d||void 0):"",j=c?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${x}pat)" clip-path="url(#${x}c)"/>`:"",E=Math.round(256*g),H=Math.round(256*g),Y=m?`<pattern id="${x}tex" patternUnits="userSpaceOnUse" width="${E}" height="${H}"><image href="${m}" width="${E}" height="${H}" preserveAspectRatio="none"/></pattern>`:"",J=m?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${x}tex)" opacity="${B*.9}" clip-path="url(#${x}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
25
25
  ${F}
26
26
  ${Y}
27
- <linearGradient id="${v}b" x1="0" y1="0" x2="0" y2="${n}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="rgba(255,255,255,.55)"/><stop offset=".3" stop-color="rgba(255,255,255,.35)"/><stop offset="1" stop-color="rgba(255,255,255,.08)"/></linearGradient>
28
- <linearGradient id="${v}f" x1="0" y1="${z}" x2="0" y2="${K}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${$}"/><stop offset=".5" stop-color="${A}"/><stop offset="1" stop-color="${R}"/></linearGradient>
29
- <linearGradient id="${v}h" x1="0" y1="${z}" x2="0" y2="${Z}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fff" stop-opacity="${_}"/><stop offset=".5" stop-color="#fff" stop-opacity="${_*.25}"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient>
30
- <linearGradient id="${v}g" x1="0" y1="${O}" x2="0" y2="${K}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${W}" stop-opacity="0"/><stop offset=".6" stop-color="${W}" stop-opacity="${P*.6}"/><stop offset="1" stop-color="${W}" stop-opacity="${P}"/></linearGradient>
31
- <clipPath id="${v}c"><path d="${S}"/><path d="${I}"/><path d="${M}"/></clipPath>
27
+ <linearGradient id="${x}b" x1="0" y1="0" x2="0" y2="${n}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="rgba(255,255,255,.55)"/><stop offset=".3" stop-color="rgba(255,255,255,.35)"/><stop offset="1" stop-color="rgba(255,255,255,.08)"/></linearGradient>
28
+ <linearGradient id="${x}f" x1="0" y1="${z}" x2="0" y2="${K}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${$}"/><stop offset=".5" stop-color="${A}"/><stop offset="1" stop-color="${R}"/></linearGradient>
29
+ <linearGradient id="${x}h" x1="0" y1="${z}" x2="0" y2="${Z}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fff" stop-opacity="${_}"/><stop offset=".5" stop-color="#fff" stop-opacity="${_*.25}"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient>
30
+ <linearGradient id="${x}g" x1="0" y1="${O}" x2="0" y2="${K}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${W}" stop-opacity="0"/><stop offset=".6" stop-color="${W}" stop-opacity="${P*.6}"/><stop offset="1" stop-color="${W}" stop-opacity="${P}"/></linearGradient>
31
+ <clipPath id="${x}c"><path d="${S}"/><path d="${I}"/><path d="${M}"/></clipPath>
32
32
  </defs>
33
- <path d="${U}" fill="url(#${v}b)"/><path d="${L}" fill="url(#${v}b)"/><path d="${T}" fill="url(#${v}b)"/>
34
- <path d="${S}" fill="url(#${v}f)" opacity="${B}"/><path d="${I}" fill="url(#${v}f)" opacity="${B}"/><path d="${M}" fill="url(#${v}f)" opacity="${B}"/>
33
+ <path d="${U}" fill="url(#${x}b)"/><path d="${L}" fill="url(#${x}b)"/><path d="${T}" fill="url(#${x}b)"/>
34
+ <path d="${S}" fill="url(#${x}f)" opacity="${B}"/><path d="${I}" fill="url(#${x}f)" opacity="${B}"/><path d="${M}" fill="url(#${x}f)" opacity="${B}"/>
35
35
  ${J}
36
36
  ${j}
37
- <rect x="0" y="${O}" width="${t}" height="${K-O}" fill="url(#${v}g)" clip-path="url(#${v}c)"/>
38
- <rect x="0" y="${z}" width="${t}" height="${Z-z}" fill="url(#${v}h)" clip-path="url(#${v}c)"/>
39
- </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,g=l[5],m=l[6],p=r,y=a;if(Math.abs(p-g)<.001&&Math.abs(y-m)<.001||c<.001||d<.001){e.lineTo(g,m),r=g,a=m;break}const x=(c+d)/2,v=(p-g)/2,C=(y-m)/2,b=v*v+C*C,k=b>x*x?Math.sqrt(b):x,R=k*k,A=Math.sqrt(Math.max(0,(R-b)/b)),$=h!==f?1:-1,W=(p+g)/2+$*A*C,w=(y+m)/2-$*A*v,D=Math.atan2(y-w,p-W),_=Math.atan2(m-w,g-W);e.arc(W,w,k,D,_,!f),r=g,a=m;break}case"Z":e.closePath();break}}}function hn(e,t,n,r,a,o,i,l=70,c=55,d=0,h,f,g=!1,m,p){const[y,x,v]=rr(ar(i)),C=o.L(a),b=o.R(a),k=r-C.w-b.w;if(k<0){const[S,,I]=rr(ar(i));e.save(),e.translate(t,n),e.globalAlpha=1-d/100*.87,e.fillStyle=`hsl(${S},50%,${Math.min(I+10,80)}%)`;const M=Math.min(r/2,a/2);e.beginPath(),e.moveTo(M,0),e.lineTo(r-M,0),e.quadraticCurveTo(r,0,r,M),e.lineTo(r,a-M),e.quadraticCurveTo(r,a,r-M,a),e.lineTo(M,a),e.quadraticCurveTo(0,a,0,a-M),e.lineTo(0,M),e.quadraticCurveTo(0,0,M,0),e.closePath(),e.fill(),e.restore();return}const R=C.w,A=C.w+k;if(g){const S=`hsla(${y},${x}%,${v}%,0.22)`;e.save(),e.translate(t,n),e.fillStyle="rgba(255,255,255,0.18)",e.beginPath(),Ue(e,C.out),e.fill(),e.fillRect(R,0,k,a),e.beginPath(),Ue(e,Qe(b.out,A)),e.fill(),e.fillStyle=S,e.beginPath(),Ue(e,C.inn),e.fill(),e.fillRect(R,Be,k,a-2*Be),e.beginPath(),Ue(e,Qe(b.inn,A)),e.fill(),m&&(e.save(),e.beginPath(),Ue(e,C.inn),e.rect(R,Be,k,a-2*Be),Ue(e,Qe(b.inn,A)),e.clip(),e.globalAlpha=.85,e.fillStyle=m,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),p&&(e.save(),e.beginPath(),Ue(e,C.inn),e.rect(R,Be,k,a-2*Be),Ue(e,Qe(b.inn,A)),e.clip(),e.globalAlpha=.85,e.fillStyle=p,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),e.restore();return}const $=`hsl(${y},${Math.min(x+10,100)}%,${Math.max(v-22,4)}%)`,W=`hsl(${y},${x}%,${v}%)`,w=`hsl(${y},${Math.max(x-12,0)}%,${Math.min(v+18,88)}%)`,D=`hsl(${y},${Math.min(x+20,100)}%,${Math.min(v+30,93)}%)`,_=l/100*.78,P=c/100*.65,B=1-d/100*.87,z=Be,K=a-Be,Z=K-z,O=z+Z*.44,X=z+Z*.58;e.save(),e.translate(t,n);const N=e.createLinearGradient(0,0,0,a);N.addColorStop(0,"rgba(255,255,255,0.55)"),N.addColorStop(.3,"rgba(255,255,255,0.35)"),N.addColorStop(1,"rgba(255,255,255,0.08)"),e.fillStyle=N,e.beginPath(),Ue(e,C.out),e.fill(),e.fillRect(R,0,k,a),e.beginPath(),Ue(e,Qe(b.out,A)),e.fill();const U=e.createLinearGradient(0,z,0,K);U.addColorStop(0,w),U.addColorStop(.5,W),U.addColorStop(1,$),e.globalAlpha=B,e.fillStyle=U,e.beginPath(),Ue(e,C.inn),e.fill(),e.fillRect(R,Be,k,a-2*Be),e.beginPath(),Ue(e,Qe(b.inn,A)),e.fill(),e.globalAlpha=1,m&&(e.save(),e.beginPath(),Ue(e,C.inn),e.rect(R,Be,k,a-2*Be),Ue(e,Qe(b.inn,A)),e.clip(),e.globalAlpha=B*.9,e.fillStyle=m,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),p&&(e.save(),e.beginPath(),Ue(e,C.inn),e.rect(R,Be,k,a-2*Be),Ue(e,Qe(b.inn,A)),e.clip(),e.globalAlpha=B*.85,e.fillStyle=p,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),e.save(),e.beginPath(),Ue(e,C.inn),e.rect(R,Be,k,a-2*Be),Ue(e,Qe(b.inn,A)),e.clip();const L=e.createLinearGradient(0,X,0,K);L.addColorStop(0,"transparent"),L.addColorStop(.6,D.replace(")",`, ${P*.6})`).replace("hsl","hsla")),L.addColorStop(1,D.replace(")",`, ${P})`).replace("hsl","hsla")),e.fillStyle=L,e.fillRect(0,X,r,K-X);const T=e.createLinearGradient(0,z,0,O);T.addColorStop(0,`rgba(255,255,255,${_})`),T.addColorStop(.5,`rgba(255,255,255,${_*.25})`),T.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=T,e.fillRect(0,z,r,O-z),e.restore(),e.restore()}const Vt=new Map,fn=new Set,qn=new Set;function ia(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 Dd(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)&&ia(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 Od(e){for(const t of e)t&&ia(t).catch(()=>{})}const mn=new Map,Gt=new Set;function So(e,t,n){return`${e}|${t}|${n??""}`}function _d(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,y)=>{const x=()=>{mn.has(r)?p(mn.get(r)):Gt.has(r)?requestAnimationFrame(x):y(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>`,g=new Blob([f],{type:"image/svg+xml;charset=utf-8"}),m=URL.createObjectURL(g);return new Promise((p,y)=>{const x=new Image;x.onload=()=>{mn.set(r,x),Gt.delete(r),URL.revokeObjectURL(m),p(x)},x.onerror=()=>{Gt.delete(r),URL.revokeObjectURL(m),y(new Error(`Failed to render pattern tile: ${e.name}`))},x.src=m})}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)||_d(t,n,r).catch(()=>{}),null)}const zd=et.scoped("karaokeScoringConfig"),la={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}},Bd="karaoke.scoringPresets";function Gd(){try{const e=localStorage.getItem(Bd);return e?JSON.parse(e):null}catch(e){return zd.warn("Failed to parse scoring presets overrides",e),null}}function wo(e){const t={...la},n=Gd();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=wo();const Wd=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=wo(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},Co=(e="normal")=>exports.ScoringPresets[e]||la.normal,wr={},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"&&(wr==null?void 0:wr.VITE_DEBUG_KARAOKE)==="true";function Fr(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)}let ft=null,qe=null,nt=null,St=null,it=null,Ae=null,Za="",Xa=0,Qa="";const Dr=(e,t,n,r,a,o,i,l,c,d,h,f,g,m,p,y,x,v,C,b,k,R,A,$)=>{e.clearRect(0,0,t,n);const W=$??null,w=(W==null?void 0:W.filledBar)??At,D=(W==null?void 0:W.emptyBar)??lr,_=(W==null?void 0:W.goldFilledBar)??dr,P=(W==null?void 0:W.goldEmptyBar)??cr,B=(W==null?void 0:W.font)??ur,z=dn(w.capStyleName),K=dn(D.capStyleName),Z=dn(_.capStyleName),O=dn(P.capStyleName),X=w.patternName?un(w.patternName):null,N=D.patternName?un(D.patternName):null,U=_.patternName?un(_.patternName):null,L=P.patternName?un(P.patternName):null,T=X?gn(e,X,w.patternColor??w.color??"#ffffff",w.patternColor):null,S=N?gn(e,N,D.patternColor??D.color??"#d1d5db",D.patternColor):null,I=U?gn(e,U,_.patternColor??"#FFD700",_.patternColor):null,M=L?gn(e,L,P.patternColor??"#FFD700",P.patternColor):null;Qa!==o&&(Qa=o,Fr("RENDER",`?? Renderer using settings for "${o}" � filled: cap=${w.capStyleName}, glass=${w.glass} | empty: cap=${D.capStyleName}, glass=${D.glass} | goldFilled: cap=${_.capStyleName}, pattern=${_.patternName??"none"} | goldEmpty: cap=${P.capStyleName}, pattern=${P.patternName??"none"} | hasSettings=${!!W}`,{filledBar:w,emptyBar:D,goldFilledBar:_,goldEmptyBar:P,filledOverlay:!!T,emptyOverlay:!!S,goldFilledOverlay:!!I,goldEmptyOverlay:!!M}));const F=w.textureUrl?pn(e,w.textureUrl,w.textureScale):null,j=D.textureUrl?pn(e,D.textureUrl,D.textureScale):null,E=_.textureUrl?pn(e,_.textureUrl,_.textureScale):null,H=P.textureUrl?pn(e,P.textureUrl,P.textureScale):null,Y=typeof document<"u"?Nr(l||"var(--accent-primary, #ffcc00)"):l||"var(--accent-primary, #ffcc00)",J=An(Y||"#ffcc00"),ne=ie=>Nr(ie),ae=B.fontFamily||"Arial",re=B.fontSize||18,G=ne(B.fontColor||"var(--btn-text, #fff)"),q=B.outlineColor?ne(B.outlineColor):null,ee=typeof B.outlineWidth=="number"?B.outlineWidth:0,oe=B.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=C?-C:0,fe=b||t;e.fillStyle=Y,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=G,oe){const ie=oe.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),q&&ee>0&&(e.lineWidth=ee,e.strokeStyle=q,e.strokeText(o,ce+20,22)),e.restore(),x){const ie=ne(v||"var(--text-secondary, #6b7280)");e.font=`bold 12px ${ae}`;const he=e.measureText(x).width,Oe=8,xe=ce+10+ue+6,me=20,ge=7,ke=he+Oe*2,$e=4;e.beginPath(),e.moveTo(xe+$e,ge),e.lineTo(xe+ke-$e,ge),e.quadraticCurveTo(xe+ke,ge,xe+ke,ge+$e),e.lineTo(xe+ke,ge+me-$e),e.quadraticCurveTo(xe+ke,ge+me,xe+ke-$e,ge+me),e.lineTo(xe+$e,ge+me),e.quadraticCurveTo(xe,ge+me,xe,ge+me-$e),e.lineTo(xe,ge+$e),e.quadraticCurveTo(xe,ge,xe+$e,ge),e.closePath(),e.fillStyle=ie,e.fill(),e.fillStyle=G,e.fillText(x,xe+Oe,ge+14),e.font=`bold ${re}px ${ae}`}const ye=120;if(e.fillStyle=Y,e.fillRect(ce+fe-ye-10,5,ye,25),e.fillStyle=G,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 xe=e.measureText(he).width+16,me=ce+fe-ye-10-xe-6;e.fillStyle=ne(k.currentCombo>=20?"var(--success, #FFD700)":"var(--warning, #ff9800)"),e.globalAlpha=.9,Sd(e,me,7,xe,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=ne(k.currentCombo>=20?"var(--text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(he,me+8,22),e.font=`bold 14px ${ae}`}if(R&&R.length>0){const ie=R[R.length-1];if(ie.label){const he=`${R.length}-${ie.label}`;he!==Za&&(Za=he,Xa=Date.now());const Oe=Date.now()-Xa;if(Oe<2500){const xe=Oe<2e3?1:1-(Oe-2e3)/500,me={Perfect:ne("var(--success, #00e676)"),Great:ne("var(--success, #66bb6a)"),Good:ne("var(--accent-primary, #ffeb3b)"),OK:ne("var(--warning, #ff9800)"),Bad:ne("var(--error, #ef5350)"),Awful:ne("var(--error, #b71c1c)")};e.save(),e.globalAlpha=xe,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]||G,e.shadowColor="rgba(0,0,0,0.5)",e.shadowBlur=6,e.fillText(ge,$e,58),q&&ee>0&&(e.lineWidth=ee,e.strokeStyle=q,e.strokeText(ge,$e,58)),e.restore()}}}const je=a-2,Fe=a+5,Re=40;let Se=1/0,te=-1/0;if(r.forEach(ie=>{ie.forEach(he=>{he.pitch<Se&&(Se=he.pitch),he.pitch>te&&(te=he.pitch)})}),c&&Array.isArray(c)&&c.length>0){let ie=null;isFinite(Se)&&isFinite(te)&&(ie=Math.round((Se+te)/2));let he=1/0,Oe=-1/0;c.forEach(({t:xe,hz:me})=>{if(!me||me<=0)return;let ge=ie;for(const $e of r)for(const We of $e)xe>=We.startTime&&xe<=We.startTime+We.duration&&(ge=We.pitch);const ke=lo(me,ge);ke<he&&(he=ke),ke>Oe&&(Oe=ke)}),he!==1/0&&Oe!==-1/0&&(he<Se&&(Se=Math.floor(he-2)),Oe>te&&(te=Math.ceil(Oe+2)))}(!isFinite(Se)||!isFinite(te))&&(Se=40,te=80),Se===te&&(Se=Math.max(0,Se-6),te=te+6);const se=ie=>{const he=n-Re-10;return Re+he-(ie-Se)/(te-Se)*he},De=Co(g||"normal"),tt=(n-Re-10)/Math.max(1,te-Se),we=Math.max(10,Math.round(tt*(1+2*De.semitoneTolerance)*.3)),dt=Math.max(5,Math.round(we*.45));((ie,he,Oe,xe,me,ge)=>{ie.lineWidth=1;for(let ke=Math.ceil(me);ke<=Math.floor(ge);ke++){const $e=se(ke);ie.strokeStyle=ne(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,te),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,xe,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);xe.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=se(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:Wa,Ie=p&&typeof p.glowBlur=="number"?p.glowBlur:Ga;ie.shadowColor=Ke,ie.shadowBlur=Math.max(4,Ie-12),ie.fillStyle=ne("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,P.color??ot,P.highlight,P.glow,P.glass,L,P.patternColor,P.patternOnly,H,M),ie.save(),$e(ie,Me,_e,Te,we,We),ie.clip(),ie.globalAlpha=.18,ie.fillStyle=ne("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,Z,_.color??"#FFD700",_.highlight,_.glow,_.glass,U,_.patternColor,_.patternOnly,E,I)}),ie.restore()),ze.length===0&&(ie.lineWidth=1,ie.strokeStyle=ne("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,K,D.color??Ke,D.highlight,D.glow,D.glass,N,D.patternColor,D.patternOnly,j,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,z,w.color??J,w.highlight,w.glow,w.glass,X,w.patternColor,w.patternOnly,F,T)}),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=se(he.pitch),It=!0,yt=!!he.isGold;break}}),!It){let ie=null,he=null;for(const Oe of r)for(const xe of Oe)xe.startTime>a&&(!ie||xe.startTime<ie.startTime)&&(ie=xe),xe.startTime<=a&&(!he||xe.startTime>he.startTime)&&(he=xe);ie?(Ge=se(ie.pitch),yt=!!ie.isGold):he?(Ge=se(he.pitch),yt=!!he.isGold):Ge=n*.5}const ut=Y||ne("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,xe=he.duration/(Fe-je)*t,me=se(he.pitch)-we/2,ge=he.startTime+he.duration<=a;Ce.push({x:Oe,y:me,w:xe,h:we,isGold:he.isGold,isSung:ge})}if(!Md(A||"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(),m&&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)),m&&Ae&&nt)try{const me=An(ut),{h:ge,s:ke,l:$e}=xd(me),be=vd(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:Wa,xe=p&&typeof p.glowBlur=="number"?p.glowBlur:Ga;e.save(),yt?(e.shadowColor=Oe,e.shadowBlur=xe,e.fillStyle=ne("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=ne("var(--shadow, rgba(0,0,0,0.35))"),e.stroke(),e.restore()}try{if(Array.isArray(y)&&y.length>0){const ie=Date.now(),he=p&&typeof p.lifeMs=="number"?p.lifeMs:fd,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()},xe=me=>{let ge=me>>>0;return()=>(ge=ge*1664525+1013904223>>>0,(ge&2147483647)/2147483647)};y.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=se(me.notePitch),be=xe(me.seed||Math.floor(me.createdAt%1e5)),Me=p&&typeof p.count=="number"?p.count:pd,Te=p&&typeof p.baseSpeed=="number"?p.baseSpeed:md,_e=p&&typeof p.baseSize=="number"?p.baseSize:gd;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=bd(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}},ko=({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:g="var(--karaoke-player-bg, #2196f3)",playerCount:m=2,gapDesaturation:p,goldSettings:y,difficultyLevel:x,algorithmLabel:v,algorithmColor:C,latencyMs:b=null,top:k,animationMode:R,karaokeSettings:A=null}=r,$=u.useRef(null),W=u.useRef(null),[w,D]=u.useState({width:600,height:150,top:250,visibleWidth:600}),[_,P]=u.useState(0),B=u.useRef(0),z=u.useRef(null),K=u.useRef(null),Z=u.useRef(null),O=u.useRef(t),X=u.useRef(performance.now()),N=u.useRef(e),U=u.useRef(w),L=u.useRef(a),T=u.useRef(d),S=u.useRef(0),I=u.useRef(!1),M=u.useRef(null),F=u.useRef(null),j=()=>{const E=(e==null?void 0:e.id)??null;if(E!==F.current||!M.current){F.current=E;const H=e.notes.map(G=>G.noteLine);M.current=ea(H,e.bpm??void 0);const Y=M.current.reduce((G,q)=>G+q.length,0),J=M.current.reduce((G,q)=>G+q.filter(ee=>ee.isGold).length,0),ne=M.current.flat().map(G=>G.pitch),ae=ne.length?Math.min(...ne):0,re=ne.length?Math.max(...ne):0;Fr("BARS",`?? Parsed notes for "${e.title}" — ${M.current.length} verses, ${Y} notes (including ${J} golden), pitch range: ${ae}–${re}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:H.length,verseCount:M.current.length,totalNotes:Y,goldCount:J,minPitch:ae,maxPitch:re})}return M.current};return u.useEffect(()=>{const E=(Y,J,ne)=>Y+(J-Y)*ne,H=Y=>{K.current===null&&(K.current=Y);const J=Math.min(.1,(Y-(K.current||Y))/1e3);K.current=Y;const ne=S.current,ae=B.current,re=1-Math.exp(-12*J),G=Math.abs(ae-ne)<.25?ae:E(ne,ae,re);Math.abs(G-ne)>1e-4&&(P(G),S.current=G,$.current&&($.current.style.transform=`translateX(${G}px)`)),z.current=requestAnimationFrame(H)};return z.current=requestAnimationFrame(H),()=>{z.current&&cancelAnimationFrame(z.current),z.current=null,K.current=null}},[]),u.useEffect(()=>{const E=()=>{if(!n.current)return;const H=n.current.getBoundingClientRect(),Y=2/Math.max(1,m),J=Math.round(H.width*Y),ne=Math.round(H.width),ae=J*(150/600);D({width:J,height:ae,top:30,visibleWidth:ne})};return E(),window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[n,m]),u.useEffect(()=>{var ne;if(d||!$.current)return;const E=$.current.getContext("2d");if(!E)return;const H=j(),Y=t-(e.gap??0)/1e3,J=Dr(E,w.width,w.height,H,Y,h,f,g,a,e.id,p??void 0,o,x??void 0,d,y??void 0,i,v,C,S.current,w.visibleWidth,l,c,R,A);if(J&&$.current){const ae=w.visibleWidth||(((ne=W.current)==null?void 0:ne.getBoundingClientRect().width)??w.width),re=w.width;let G=Math.round(ae/2-J.ballX);const q=ae-re;G=Math.max(q,Math.min(0,G)),B.current=G}},[t,e,w,a,d,o,i,R,A]),u.useEffect(()=>{O.current=t,X.current=performance.now()},[t]),u.useEffect(()=>{N.current=e},[e]),u.useEffect(()=>{U.current=w},[w]),u.useEffect(()=>{L.current=a},[a]),u.useEffect(()=>{T.current=d},[d]),u.useEffect(()=>{const E=()=>{var oe;const H=$.current,Y=N.current,J=U.current;if(!H||!Y||!J)return;const ne=H.getContext("2d");if(!ne)return;const ae=j(),re=Math.min(.5,(performance.now()-X.current)/1e3),q=(T.current?O.current+re:O.current)-(Y.gap??0)/1e3,ee=Dr(ne,J.width,J.height,ae,q,h,f,g,L.current,Y.id,p??void 0,o,x??void 0,T.current,y??void 0,i,v,C,S.current,J.visibleWidth,l,c,R,A);if(ee){const ce=J.visibleWidth||(((oe=W.current)==null?void 0:oe.getBoundingClientRect().width)??J.width),fe=J.width;let Q=Math.round(ce/2-ee.ballX);const ue=ce-fe;Q=Math.max(ue,Math.min(0,Q)),B.current=Q}};if(d){I.current||(I.current=!0,Fr("BARS",`? Drawing bars in RAF loop � canvas: ${U.current.width}�${U.current.height}px, player: ${h}`,{canvasSize:U.current}));const H=()=>{E(),Z.current=requestAnimationFrame(H)};return Z.current=requestAnimationFrame(H),()=>{Z.current&&cancelAnimationFrame(Z.current),Z.current=null}}I.current=!1},[d,h,f,g,p,o,x,y,i,R,A]),s.jsxs("div",{ref:W,style:{position:"absolute",left:"50%",top:`${k??w.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:w.visibleWidth,height:w.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 b<"u"&&b!==null?(()=>{const E=b,H=E<=120?"var(--latency-good, #10b981)":E<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",Y=`${E}ms`;return s.jsxs("div",{className:E>250?"av-latency-pulse":"",style:{background:H,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:Y})]})})():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:$,width:w.width,height:w.height,role:"img","aria-label":`Pitch timeline for ${h??"player"}. Score: ${f??0}`,style:{position:"absolute",left:0,top:0,transform:`translateX(${_}px)`,willChange:"transform"}})]})},Mo="/textures/seamless/256x256";function xt(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:`${Mo}/${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:`${Mo}/${e}/${e}_${o}-256x256.png`}})}}const ca=[xt("Fire",8,"🔥"),xt("Metal",8,"⚙️"),xt("Ice",8,"❄️"),xt("Stone",8,"🪨"),xt("Wood",8,"🪵"),xt("Tile",8,"🧱"),xt("Concrete",8,"🏗️"),xt("Trees",8,"🌲"),xt("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,"🎨")],jo=ca.flatMap(e=>e.entries);function Vd(e){return jo.find(t=>t.url===e)}const Ro=({fill:e,onChange:t,previewColor:n,accentColor:r="#0d6efd"})=>{const{t:a}=ve(),[o,i]=u.useState(null),l=(y,x)=>{t({...e,[y]:x})},c=u.useMemo(()=>{const y=e.color||n||"#2196f3";return(x,v,C)=>{const b=Cn.find(R=>R.name===x)||Cn[0],k=v?nr.find(R=>R.name===v)??null:null;return vo({width:80,height:22,capStyle:b,color:y,highlight:e.highlight,glow:e.glow,glass:e.glass,pattern:k,patternColor:e.patternColor,patternOnly:e.patternOnly,textureUrl:C??null,textureScale:e.textureScale})}},[e,n]),d=`2px solid ${r}`,h=r==="#d4a017"?"#fff8e1":"#e7f1ff",f=u.useRef(null),g=u.useRef(null),m=u.useCallback((y,x)=>{y.current&&y.current.scrollBy({left:x*180,behavior:"smooth"})},[]),p={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:a("playerForm.barColor","Color")}),s.jsx(Ve.Form.Check,{type:"checkbox",id:`bar-color-auto-${r}`,label:a("playerForm.auto","Auto"),checked:!e.color,onChange:y=>l("color",y.target.checked?null:n||"#2196f3"),className:"mb-0"}),e.color&&s.jsx("input",{type:"color",value:e.color,onChange:y=>l("color",y.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),s.jsx(Ve.Form.Label,{style:{fontSize:13,color:"#ccc"},children:a("playerForm.capShape","Cap shape")}),s.jsxs("div",{style:{position:"relative",marginBottom:10},children:[s.jsx("button",{type:"button",style:{...p,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>m(f,-1),children:"‹"}),s.jsx("button",{type:"button",style:{...p,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, rgba(30,30,30,0.9) 60%, transparent)"},onClick:()=>m(f,1),children:"›"}),s.jsx("div",{ref:f,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:Cn.map(y=>{const x=e.capStyleName===y.name;return s.jsx("div",{title:y.name,onClick:()=>l("capStyleName",y.name),style:{cursor:"pointer",flexShrink:0,border:x?d:"1px solid #555",borderRadius:6,padding:3,background:x?h:"#222"},dangerouslySetInnerHTML:{__html:c(y.name,null)}},y.name)})})]}),s.jsx(Ve.Form.Label,{style:{fontSize:13,color:"#ccc"},children:a("playerForm.pattern","Pattern")}),s.jsxs("div",{style:{position:"relative",marginBottom:10},children:[s.jsx("button",{type:"button",style:{...p,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>m(g,-1),children:"‹"}),s.jsx("button",{type:"button",style:{...p,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, rgba(30,30,30,0.9) 60%, transparent)"},onClick:()=>m(g,1),children:"›"}),s.jsxs("div",{ref:g,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:[s.jsx("div",{title:"None",onClick:()=>l("patternName",null),style:{cursor:"pointer",flexShrink:0,border:e.patternName?"1px solid #555":d,borderRadius:6,padding:"3px 8px",background:e.patternName?"#222":h,fontSize:12,lineHeight:"22px",color:"#ccc"},children:"—"}),nr.map(y=>{const x=e.patternName===y.name;return s.jsx("div",{title:y.name,onClick:()=>l("patternName",y.name),style:{cursor:"pointer",flexShrink:0,border:x?d:"1px solid #555",borderRadius:6,padding:3,background:x?h:"#222"},dangerouslySetInnerHTML:{__html:c(e.capStyleName,y.name)}},y.name)})]})]}),s.jsx(Ve.Form.Check,{type:"switch",id:`bar-pattern-only-${r}`,label:a("playerForm.patternOnly","Pattern only (flat, no 3D)"),checked:e.patternOnly,onChange:y=>l("patternOnly",y.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:a("playerForm.patternColor","Pattern color")}),s.jsx(Ve.Form.Check,{type:"checkbox",id:`bar-pattern-color-auto-${r}`,label:a("playerForm.auto","Auto"),checked:!e.patternColor,onChange:y=>l("patternColor",y.target.checked?null:n||"#ffffff"),className:"mb-0"}),e.patternColor&&s.jsx("input",{type:"color",value:e.patternColor,onChange:y=>l("patternColor",y.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:[a("playerForm.highlight","Highlight"),": ",e.highlight,"%"]}),s.jsx(Ve.Form.Range,{min:0,max:100,value:e.highlight,onChange:y=>l("highlight",parseInt(y.target.value)),className:"mb-2"}),s.jsxs(Ve.Form.Label,{style:{fontSize:13,color:"#ccc"},children:[a("playerForm.glow","Glow"),": ",e.glow,"%"]}),s.jsx(Ve.Form.Range,{min:0,max:100,value:e.glow,onChange:y=>l("glow",parseInt(y.target.value)),className:"mb-2"})]}),s.jsxs(Ve.Form.Label,{style:{fontSize:13,color:"#ccc"},children:[a("playerForm.glass","Transparency (glass)"),": ",e.glass,"%"]}),s.jsx(Ve.Form.Range,{min:0,max:100,value:e.glass,onChange:y=>l("glass",parseInt(y.target.value)),className:"mb-2"}),s.jsx(Ve.Form.Label,{style:{fontSize:13,fontWeight:600,marginTop:4,color:"#ccc"},children:a("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:()=>{l("textureUrl",null),i(null)},children:a("playerForm.texNone","None")}),ca.map(y=>s.jsx("button",{type:"button",className:`btn btn-sm ${(o==null?void 0:o.name)===y.name?"btn-primary":"btn-outline-secondary"}`,onClick:()=>i(x=>(x==null?void 0:x.name)===y.name?null:y),title:y.name,children:y.icon},y.name))]}),o&&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:o.entries.map(y=>{const x=e.textureUrl===y.url;return s.jsx("div",{title:y.label,onClick:()=>l("textureUrl",x?null:y.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:x?`3px solid ${r}`:"1px solid #bbb",backgroundImage:`url(${y.url})`,backgroundSize:"cover",boxShadow:x?`0 0 6px ${r}`:void 0}},y.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:[a("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:y=>l("textureScale",parseInt(y.target.value)/100),className:"mb-2"})]})]})},He=et.scoped("AudioPitchAnalyzer");function $o({onSegments:e,defaultCompareAll:t=!1,externalFile:n=null,postPitch:r,postLibrosaPitchTrack:a}){const{t:o}=ve(),[i,l]=u.useState("pitchy"),[c,d]=u.useState(null),[h,f]=u.useState(t),[g,m]=u.useState({}),[p,y]=u.useState({}),[x,v]=u.useState([]),[C,b]=u.useState([]),[k,R]=u.useState(!1),[A,$]=u.useState(null),[W]=u.useState(null),[w]=u.useState(null),[D,_]=u.useState(null),P=u.useRef(null);function B(L){try{if(L instanceof Error){let S=`${L.message}
37
+ <rect x="0" y="${O}" width="${t}" height="${K-O}" fill="url(#${x}g)" clip-path="url(#${x}c)"/>
38
+ <rect x="0" y="${z}" width="${t}" height="${Z-z}" fill="url(#${x}h)" clip-path="url(#${x}c)"/>
39
+ </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,g=l[5],m=l[6],p=r,y=a;if(Math.abs(p-g)<.001&&Math.abs(y-m)<.001||c<.001||d<.001){e.lineTo(g,m),r=g,a=m;break}const v=(c+d)/2,x=(p-g)/2,C=(y-m)/2,b=x*x+C*C,k=b>v*v?Math.sqrt(b):v,R=k*k,A=Math.sqrt(Math.max(0,(R-b)/b)),$=h!==f?1:-1,W=(p+g)/2+$*A*C,w=(y+m)/2-$*A*x,D=Math.atan2(y-w,p-W),_=Math.atan2(m-w,g-W);e.arc(W,w,k,D,_,!f),r=g,a=m;break}case"Z":e.closePath();break}}}function hn(e,t,n,r,a,o,i,l=70,c=55,d=0,h,f,g=!1,m,p){const[y,v,x]=rr(ar(i)),C=o.L(a),b=o.R(a),k=r-C.w-b.w;if(k<0){const[S,,I]=rr(ar(i));e.save(),e.translate(t,n),e.globalAlpha=1-d/100*.87,e.fillStyle=`hsl(${S},50%,${Math.min(I+10,80)}%)`;const M=Math.min(r/2,a/2);e.beginPath(),e.moveTo(M,0),e.lineTo(r-M,0),e.quadraticCurveTo(r,0,r,M),e.lineTo(r,a-M),e.quadraticCurveTo(r,a,r-M,a),e.lineTo(M,a),e.quadraticCurveTo(0,a,0,a-M),e.lineTo(0,M),e.quadraticCurveTo(0,0,M,0),e.closePath(),e.fill(),e.restore();return}const R=C.w,A=C.w+k;if(g){const S=`hsla(${y},${v}%,${x}%,0.22)`;e.save(),e.translate(t,n),e.fillStyle="rgba(255,255,255,0.18)",e.beginPath(),Ue(e,C.out),e.fill(),e.fillRect(R,0,k,a),e.beginPath(),Ue(e,Qe(b.out,A)),e.fill(),e.fillStyle=S,e.beginPath(),Ue(e,C.inn),e.fill(),e.fillRect(R,Be,k,a-2*Be),e.beginPath(),Ue(e,Qe(b.inn,A)),e.fill(),m&&(e.save(),e.beginPath(),Ue(e,C.inn),e.rect(R,Be,k,a-2*Be),Ue(e,Qe(b.inn,A)),e.clip(),e.globalAlpha=.85,e.fillStyle=m,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),p&&(e.save(),e.beginPath(),Ue(e,C.inn),e.rect(R,Be,k,a-2*Be),Ue(e,Qe(b.inn,A)),e.clip(),e.globalAlpha=.85,e.fillStyle=p,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),e.restore();return}const $=`hsl(${y},${Math.min(v+10,100)}%,${Math.max(x-22,4)}%)`,W=`hsl(${y},${v}%,${x}%)`,w=`hsl(${y},${Math.max(v-12,0)}%,${Math.min(x+18,88)}%)`,D=`hsl(${y},${Math.min(v+20,100)}%,${Math.min(x+30,93)}%)`,_=l/100*.78,P=c/100*.65,B=1-d/100*.87,z=Be,K=a-Be,Z=K-z,O=z+Z*.44,X=z+Z*.58;e.save(),e.translate(t,n);const N=e.createLinearGradient(0,0,0,a);N.addColorStop(0,"rgba(255,255,255,0.55)"),N.addColorStop(.3,"rgba(255,255,255,0.35)"),N.addColorStop(1,"rgba(255,255,255,0.08)"),e.fillStyle=N,e.beginPath(),Ue(e,C.out),e.fill(),e.fillRect(R,0,k,a),e.beginPath(),Ue(e,Qe(b.out,A)),e.fill();const U=e.createLinearGradient(0,z,0,K);U.addColorStop(0,w),U.addColorStop(.5,W),U.addColorStop(1,$),e.globalAlpha=B,e.fillStyle=U,e.beginPath(),Ue(e,C.inn),e.fill(),e.fillRect(R,Be,k,a-2*Be),e.beginPath(),Ue(e,Qe(b.inn,A)),e.fill(),e.globalAlpha=1,m&&(e.save(),e.beginPath(),Ue(e,C.inn),e.rect(R,Be,k,a-2*Be),Ue(e,Qe(b.inn,A)),e.clip(),e.globalAlpha=B*.9,e.fillStyle=m,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),p&&(e.save(),e.beginPath(),Ue(e,C.inn),e.rect(R,Be,k,a-2*Be),Ue(e,Qe(b.inn,A)),e.clip(),e.globalAlpha=B*.85,e.fillStyle=p,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),e.save(),e.beginPath(),Ue(e,C.inn),e.rect(R,Be,k,a-2*Be),Ue(e,Qe(b.inn,A)),e.clip();const L=e.createLinearGradient(0,X,0,K);L.addColorStop(0,"transparent"),L.addColorStop(.6,D.replace(")",`, ${P*.6})`).replace("hsl","hsla")),L.addColorStop(1,D.replace(")",`, ${P})`).replace("hsl","hsla")),e.fillStyle=L,e.fillRect(0,X,r,K-X);const T=e.createLinearGradient(0,z,0,O);T.addColorStop(0,`rgba(255,255,255,${_})`),T.addColorStop(.5,`rgba(255,255,255,${_*.25})`),T.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=T,e.fillRect(0,z,r,O-z),e.restore(),e.restore()}const Vt=new Map,fn=new Set,qn=new Set;function ia(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 Od(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)&&ia(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 _d(e){for(const t of e)t&&ia(t).catch(()=>{})}const mn=new Map,Gt=new Set;function So(e,t,n){return`${e}|${t}|${n??""}`}function zd(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,y)=>{const v=()=>{mn.has(r)?p(mn.get(r)):Gt.has(r)?requestAnimationFrame(v):y(new Error(`Pattern render failed: ${r}`))};v()});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>`,g=new Blob([f],{type:"image/svg+xml;charset=utf-8"}),m=URL.createObjectURL(g);return new Promise((p,y)=>{const v=new Image;v.onload=()=>{mn.set(r,v),Gt.delete(r),URL.revokeObjectURL(m),p(v)},v.onerror=()=>{Gt.delete(r),URL.revokeObjectURL(m),y(new Error(`Failed to render pattern tile: ${e.name}`))},v.src=m})}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)||zd(t,n,r).catch(()=>{}),null)}const Bd=et.scoped("karaokeScoringConfig"),la={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}},Gd="karaoke.scoringPresets";function Wd(){try{const e=localStorage.getItem(Gd);return e?JSON.parse(e):null}catch(e){return Bd.warn("Failed to parse scoring presets overrides",e),null}}function wo(e){const t={...la},n=Wd();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=wo();const Ud=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=wo(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},Co=(e="normal")=>exports.ScoringPresets[e]||la.normal,wr={},Vd=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"&&(wr==null?void 0:wr.VITE_DEBUG_KARAOKE)==="true";function Fr(e,t,...n){(Vd||typeof window<"u"&&window.DEBUG_KARAOKE)&&console.log(`%c[KARAOKE-DEBUG]%c [${e}] ${t}`,"background:#6c3483;color:#fff;padding:1px 4px;border-radius:3px;font-weight:bold","color:#6c3483;font-weight:bold",...n)}let ft=null,qe=null,nt=null,St=null,it=null,Ae=null,Za="",Xa=0,Qa="";const Dr=(e,t,n,r,a,o,i,l,c,d,h,f,g,m,p,y,v,x,C,b,k,R,A,$)=>{e.clearRect(0,0,t,n);const W=$??null,w=(W==null?void 0:W.filledBar)??At,D=(W==null?void 0:W.emptyBar)??lr,_=(W==null?void 0:W.goldFilledBar)??dr,P=(W==null?void 0:W.goldEmptyBar)??cr,B=(W==null?void 0:W.font)??ur,z=dn(w.capStyleName),K=dn(D.capStyleName),Z=dn(_.capStyleName),O=dn(P.capStyleName),X=w.patternName?un(w.patternName):null,N=D.patternName?un(D.patternName):null,U=_.patternName?un(_.patternName):null,L=P.patternName?un(P.patternName):null,T=X?gn(e,X,w.patternColor??w.color??"#ffffff",w.patternColor):null,S=N?gn(e,N,D.patternColor??D.color??"#d1d5db",D.patternColor):null,I=U?gn(e,U,_.patternColor??"#FFD700",_.patternColor):null,M=L?gn(e,L,P.patternColor??"#FFD700",P.patternColor):null;Qa!==o&&(Qa=o,Fr("RENDER",`?? Renderer using settings for "${o}" � filled: cap=${w.capStyleName}, glass=${w.glass} | empty: cap=${D.capStyleName}, glass=${D.glass} | goldFilled: cap=${_.capStyleName}, pattern=${_.patternName??"none"} | goldEmpty: cap=${P.capStyleName}, pattern=${P.patternName??"none"} | hasSettings=${!!W}`,{filledBar:w,emptyBar:D,goldFilledBar:_,goldEmptyBar:P,filledOverlay:!!T,emptyOverlay:!!S,goldFilledOverlay:!!I,goldEmptyOverlay:!!M}));const F=w.textureUrl?pn(e,w.textureUrl,w.textureScale):null,j=D.textureUrl?pn(e,D.textureUrl,D.textureScale):null,E=_.textureUrl?pn(e,_.textureUrl,_.textureScale):null,H=P.textureUrl?pn(e,P.textureUrl,P.textureScale):null,Y=typeof document<"u"?Nr(l||"var(--accent-primary, #ffcc00)"):l||"var(--accent-primary, #ffcc00)",J=An(Y||"#ffcc00"),ne=ie=>Nr(ie),ae=B.fontFamily||"Arial",re=B.fontSize||18,G=ne(B.fontColor||"var(--btn-text, #fff)"),q=B.outlineColor?ne(B.outlineColor):null,ee=typeof B.outlineWidth=="number"?B.outlineWidth:0,oe=B.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=C?-C:0,fe=b||t;e.fillStyle=Y,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=G,oe){const ie=oe.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),q&&ee>0&&(e.lineWidth=ee,e.strokeStyle=q,e.strokeText(o,ce+20,22)),e.restore(),v){const ie=ne(x||"var(--text-secondary, #6b7280)");e.font=`bold 12px ${ae}`;const he=e.measureText(v).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=G,e.fillText(v,ve+Oe,ge+14),e.font=`bold ${re}px ${ae}`}const ye=120;if(e.fillStyle=Y,e.fillRect(ce+fe-ye-10,5,ye,25),e.fillStyle=G,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=ne(k.currentCombo>=20?"var(--success, #FFD700)":"var(--warning, #ff9800)"),e.globalAlpha=.9,wd(e,me,7,ve,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=ne(k.currentCombo>=20?"var(--text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(he,me+8,22),e.font=`bold 14px ${ae}`}if(R&&R.length>0){const ie=R[R.length-1];if(ie.label){const he=`${R.length}-${ie.label}`;he!==Za&&(Za=he,Xa=Date.now());const Oe=Date.now()-Xa;if(Oe<2500){const ve=Oe<2e3?1:1-(Oe-2e3)/500,me={Perfect:ne("var(--success, #00e676)"),Great:ne("var(--success, #66bb6a)"),Good:ne("var(--accent-primary, #ffeb3b)"),OK:ne("var(--warning, #ff9800)"),Bad:ne("var(--error, #ef5350)"),Awful:ne("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]||G,e.shadowColor="rgba(0,0,0,0.5)",e.shadowBlur=6,e.fillText(ge,$e,58),q&&ee>0&&(e.lineWidth=ee,e.strokeStyle=q,e.strokeText(ge,$e,58)),e.restore()}}}const je=a-2,Fe=a+5,Re=40;let Se=1/0,te=-1/0;if(r.forEach(ie=>{ie.forEach(he=>{he.pitch<Se&&(Se=he.pitch),he.pitch>te&&(te=he.pitch)})}),c&&Array.isArray(c)&&c.length>0){let ie=null;isFinite(Se)&&isFinite(te)&&(ie=Math.round((Se+te)/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=lo(me,ge);ke<he&&(he=ke),ke>Oe&&(Oe=ke)}),he!==1/0&&Oe!==-1/0&&(he<Se&&(Se=Math.floor(he-2)),Oe>te&&(te=Math.ceil(Oe+2)))}(!isFinite(Se)||!isFinite(te))&&(Se=40,te=80),Se===te&&(Se=Math.max(0,Se-6),te=te+6);const se=ie=>{const he=n-Re-10;return Re+he-(ie-Se)/(te-Se)*he},De=Co(g||"normal"),tt=(n-Re-10)/Math.max(1,te-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=se(ke);ie.strokeStyle=ne(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,te),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=se(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:Wa,Ie=p&&typeof p.glowBlur=="number"?p.glowBlur:Ga;ie.shadowColor=Ke,ie.shadowBlur=Math.max(4,Ie-12),ie.fillStyle=ne("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,P.color??ot,P.highlight,P.glow,P.glass,L,P.patternColor,P.patternOnly,H,M),ie.save(),$e(ie,Me,_e,Te,we,We),ie.clip(),ie.globalAlpha=.18,ie.fillStyle=ne("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,Z,_.color??"#FFD700",_.highlight,_.glow,_.glass,U,_.patternColor,_.patternOnly,E,I)}),ie.restore()),ze.length===0&&(ie.lineWidth=1,ie.strokeStyle=ne("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,K,D.color??Ke,D.highlight,D.glow,D.glass,N,D.patternColor,D.patternOnly,j,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,z,w.color??J,w.highlight,w.glow,w.glass,X,w.patternColor,w.patternOnly,F,T)}),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=se(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=se(ie.pitch),yt=!!ie.isGold):he?(Ge=se(he.pitch),yt=!!he.isGold):Ge=n*.5}const ut=Y||ne("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=se(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(!jd(A||"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(),m&&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)),m&&Ae&&nt)try{const me=An(ut),{h:ge,s:ke,l:$e}=xd(me),be=Sd(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:Wa,ve=p&&typeof p.glowBlur=="number"?p.glowBlur:Ga;e.save(),yt?(e.shadowColor=Oe,e.shadowBlur=ve,e.fillStyle=ne("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=ne("var(--shadow, rgba(0,0,0,0.35))"),e.stroke(),e.restore()}try{if(Array.isArray(y)&&y.length>0){const ie=Date.now(),he=p&&typeof p.lifeMs=="number"?p.lifeMs:pd,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)};y.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=se(me.notePitch),be=ve(me.seed||Math.floor(me.createdAt%1e5)),Me=p&&typeof p.count=="number"?p.count:md,Te=p&&typeof p.baseSpeed=="number"?p.baseSpeed:gd,_e=p&&typeof p.baseSize=="number"?p.baseSize:yd;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),Tl=Math.max(6,ht*2.6),yr=vd(Ea,Aa,60,Math.round(Tl),(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}},ko=({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:g="var(--karaoke-player-bg, #2196f3)",playerCount:m=2,gapDesaturation:p,goldSettings:y,difficultyLevel:v,algorithmLabel:x,algorithmColor:C,latencyMs:b=null,top:k,animationMode:R,karaokeSettings:A=null}=r,$=u.useRef(null),W=u.useRef(null),[w,D]=u.useState({width:600,height:150,top:250,visibleWidth:600}),[_,P]=u.useState(0),B=u.useRef(0),z=u.useRef(null),K=u.useRef(null),Z=u.useRef(null),O=u.useRef(t),X=u.useRef(performance.now()),N=u.useRef(e),U=u.useRef(w),L=u.useRef(a),T=u.useRef(d),S=u.useRef(0),I=u.useRef(!1),M=u.useRef(null),F=u.useRef(null),j=()=>{const E=(e==null?void 0:e.id)??null;if(E!==F.current||!M.current){F.current=E;const H=e.notes.map(G=>G.noteLine);M.current=ea(H,e.bpm??void 0);const Y=M.current.reduce((G,q)=>G+q.length,0),J=M.current.reduce((G,q)=>G+q.filter(ee=>ee.isGold).length,0),ne=M.current.flat().map(G=>G.pitch),ae=ne.length?Math.min(...ne):0,re=ne.length?Math.max(...ne):0;Fr("BARS",`?? Parsed notes for "${e.title}" — ${M.current.length} verses, ${Y} notes (including ${J} golden), pitch range: ${ae}–${re}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:H.length,verseCount:M.current.length,totalNotes:Y,goldCount:J,minPitch:ae,maxPitch:re})}return M.current};return u.useEffect(()=>{const E=(Y,J,ne)=>Y+(J-Y)*ne,H=Y=>{K.current===null&&(K.current=Y);const J=Math.min(.1,(Y-(K.current||Y))/1e3);K.current=Y;const ne=S.current,ae=B.current,re=1-Math.exp(-12*J),G=Math.abs(ae-ne)<.25?ae:E(ne,ae,re);Math.abs(G-ne)>1e-4&&(P(G),S.current=G,$.current&&($.current.style.transform=`translateX(${G}px)`)),z.current=requestAnimationFrame(H)};return z.current=requestAnimationFrame(H),()=>{z.current&&cancelAnimationFrame(z.current),z.current=null,K.current=null}},[]),u.useEffect(()=>{const E=()=>{if(!n.current)return;const H=n.current.getBoundingClientRect(),Y=2/Math.max(1,m),J=Math.round(H.width*Y),ne=Math.round(H.width),ae=J*(150/600);D({width:J,height:ae,top:30,visibleWidth:ne})};return E(),window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[n,m]),u.useEffect(()=>{var ne;if(d||!$.current)return;const E=$.current.getContext("2d");if(!E)return;const H=j(),Y=t-(e.gap??0)/1e3,J=Dr(E,w.width,w.height,H,Y,h,f,g,a,e.id,p??void 0,o,v??void 0,d,y??void 0,i,x,C,S.current,w.visibleWidth,l,c,R,A);if(J&&$.current){const ae=w.visibleWidth||(((ne=W.current)==null?void 0:ne.getBoundingClientRect().width)??w.width),re=w.width;let G=Math.round(ae/2-J.ballX);const q=ae-re;G=Math.max(q,Math.min(0,G)),B.current=G}},[t,e,w,a,d,o,i,R,A]),u.useEffect(()=>{O.current=t,X.current=performance.now()},[t]),u.useEffect(()=>{N.current=e},[e]),u.useEffect(()=>{U.current=w},[w]),u.useEffect(()=>{L.current=a},[a]),u.useEffect(()=>{T.current=d},[d]),u.useEffect(()=>{const E=()=>{var oe;const H=$.current,Y=N.current,J=U.current;if(!H||!Y||!J)return;const ne=H.getContext("2d");if(!ne)return;const ae=j(),re=Math.min(.5,(performance.now()-X.current)/1e3),q=(T.current?O.current+re:O.current)-(Y.gap??0)/1e3,ee=Dr(ne,J.width,J.height,ae,q,h,f,g,L.current,Y.id,p??void 0,o,v??void 0,T.current,y??void 0,i,x,C,S.current,J.visibleWidth,l,c,R,A);if(ee){const ce=J.visibleWidth||(((oe=W.current)==null?void 0:oe.getBoundingClientRect().width)??J.width),fe=J.width;let Q=Math.round(ce/2-ee.ballX);const ue=ce-fe;Q=Math.max(ue,Math.min(0,Q)),B.current=Q}};if(d){I.current||(I.current=!0,Fr("BARS",`? Drawing bars in RAF loop � canvas: ${U.current.width}�${U.current.height}px, player: ${h}`,{canvasSize:U.current}));const H=()=>{E(),Z.current=requestAnimationFrame(H)};return Z.current=requestAnimationFrame(H),()=>{Z.current&&cancelAnimationFrame(Z.current),Z.current=null}}I.current=!1},[d,h,f,g,p,o,v,y,i,R,A]),s.jsxs("div",{ref:W,style:{position:"absolute",left:"50%",top:`${k??w.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:w.visibleWidth,height:w.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 b<"u"&&b!==null?(()=>{const E=b,H=E<=120?"var(--latency-good, #10b981)":E<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",Y=`${E}ms`;return s.jsxs("div",{className:E>250?"av-latency-pulse":"",style:{background:H,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:Y})]})})():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:$,width:w.width,height:w.height,role:"img","aria-label":`Pitch timeline for ${h??"player"}. Score: ${f??0}`,style:{position:"absolute",left:0,top:0,transform:`translateX(${_}px)`,willChange:"transform"}})]})},Mo="/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:`${Mo}/${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:`${Mo}/${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,"🎨")],jo=ca.flatMap(e=>e.entries);function qd(e){return jo.find(t=>t.url===e)}const Ro=({fill:e,onChange:t,previewColor:n,accentColor:r="#0d6efd"})=>{const{t:a}=xe(),[o,i]=u.useState(null),l=(y,v)=>{t({...e,[y]:v})},c=u.useMemo(()=>{const y=e.color||n||"#2196f3";return(v,x,C)=>{const b=Cn.find(R=>R.name===v)||Cn[0],k=x?nr.find(R=>R.name===x)??null:null;return xo({width:80,height:22,capStyle:b,color:y,highlight:e.highlight,glow:e.glow,glass:e.glass,pattern:k,patternColor:e.patternColor,patternOnly:e.patternOnly,textureUrl:C??null,textureScale:e.textureScale})}},[e,n]),d=`2px solid ${r}`,h=r==="#d4a017"?"#fff8e1":"#e7f1ff",f=u.useRef(null),g=u.useRef(null),m=u.useCallback((y,v)=>{y.current&&y.current.scrollBy({left:v*180,behavior:"smooth"})},[]),p={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:a("playerForm.barColor","Color")}),s.jsx(Ve.Form.Check,{type:"checkbox",id:`bar-color-auto-${r}`,label:a("playerForm.auto","Auto"),checked:!e.color,onChange:y=>l("color",y.target.checked?null:n||"#2196f3"),className:"mb-0"}),e.color&&s.jsx("input",{type:"color",value:e.color,onChange:y=>l("color",y.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),s.jsx(Ve.Form.Label,{style:{fontSize:13,color:"#ccc"},children:a("playerForm.capShape","Cap shape")}),s.jsxs("div",{style:{position:"relative",marginBottom:10},children:[s.jsx("button",{type:"button",style:{...p,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>m(f,-1),children:"‹"}),s.jsx("button",{type:"button",style:{...p,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, rgba(30,30,30,0.9) 60%, transparent)"},onClick:()=>m(f,1),children:"›"}),s.jsx("div",{ref:f,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:Cn.map(y=>{const v=e.capStyleName===y.name;return s.jsx("div",{title:y.name,onClick:()=>l("capStyleName",y.name),style:{cursor:"pointer",flexShrink:0,border:v?d:"1px solid #555",borderRadius:6,padding:3,background:v?h:"#222"},dangerouslySetInnerHTML:{__html:c(y.name,null)}},y.name)})})]}),s.jsx(Ve.Form.Label,{style:{fontSize:13,color:"#ccc"},children:a("playerForm.pattern","Pattern")}),s.jsxs("div",{style:{position:"relative",marginBottom:10},children:[s.jsx("button",{type:"button",style:{...p,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>m(g,-1),children:"‹"}),s.jsx("button",{type:"button",style:{...p,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, rgba(30,30,30,0.9) 60%, transparent)"},onClick:()=>m(g,1),children:"›"}),s.jsxs("div",{ref:g,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:[s.jsx("div",{title:"None",onClick:()=>l("patternName",null),style:{cursor:"pointer",flexShrink:0,border:e.patternName?"1px solid #555":d,borderRadius:6,padding:"3px 8px",background:e.patternName?"#222":h,fontSize:12,lineHeight:"22px",color:"#ccc"},children:"—"}),nr.map(y=>{const v=e.patternName===y.name;return s.jsx("div",{title:y.name,onClick:()=>l("patternName",y.name),style:{cursor:"pointer",flexShrink:0,border:v?d:"1px solid #555",borderRadius:6,padding:3,background:v?h:"#222"},dangerouslySetInnerHTML:{__html:c(e.capStyleName,y.name)}},y.name)})]})]}),s.jsx(Ve.Form.Check,{type:"switch",id:`bar-pattern-only-${r}`,label:a("playerForm.patternOnly","Pattern only (flat, no 3D)"),checked:e.patternOnly,onChange:y=>l("patternOnly",y.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:a("playerForm.patternColor","Pattern color")}),s.jsx(Ve.Form.Check,{type:"checkbox",id:`bar-pattern-color-auto-${r}`,label:a("playerForm.auto","Auto"),checked:!e.patternColor,onChange:y=>l("patternColor",y.target.checked?null:n||"#ffffff"),className:"mb-0"}),e.patternColor&&s.jsx("input",{type:"color",value:e.patternColor,onChange:y=>l("patternColor",y.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:[a("playerForm.highlight","Highlight"),": ",e.highlight,"%"]}),s.jsx(Ve.Form.Range,{min:0,max:100,value:e.highlight,onChange:y=>l("highlight",parseInt(y.target.value)),className:"mb-2"}),s.jsxs(Ve.Form.Label,{style:{fontSize:13,color:"#ccc"},children:[a("playerForm.glow","Glow"),": ",e.glow,"%"]}),s.jsx(Ve.Form.Range,{min:0,max:100,value:e.glow,onChange:y=>l("glow",parseInt(y.target.value)),className:"mb-2"})]}),s.jsxs(Ve.Form.Label,{style:{fontSize:13,color:"#ccc"},children:[a("playerForm.glass","Transparency (glass)"),": ",e.glass,"%"]}),s.jsx(Ve.Form.Range,{min:0,max:100,value:e.glass,onChange:y=>l("glass",parseInt(y.target.value)),className:"mb-2"}),s.jsx(Ve.Form.Label,{style:{fontSize:13,fontWeight:600,marginTop:4,color:"#ccc"},children:a("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:()=>{l("textureUrl",null),i(null)},children:a("playerForm.texNone","None")}),ca.map(y=>s.jsx("button",{type:"button",className:`btn btn-sm ${(o==null?void 0:o.name)===y.name?"btn-primary":"btn-outline-secondary"}`,onClick:()=>i(v=>(v==null?void 0:v.name)===y.name?null:y),title:y.name,children:y.icon},y.name))]}),o&&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:o.entries.map(y=>{const v=e.textureUrl===y.url;return s.jsx("div",{title:y.label,onClick:()=>l("textureUrl",v?null:y.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:v?`3px solid ${r}`:"1px solid #bbb",backgroundImage:`url(${y.url})`,backgroundSize:"cover",boxShadow:v?`0 0 6px ${r}`:void 0}},y.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:[a("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:y=>l("textureScale",parseInt(y.target.value)/100),className:"mb-2"})]})]})},He=et.scoped("AudioPitchAnalyzer");function $o({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),[g,m]=u.useState({}),[p,y]=u.useState({}),[v,x]=u.useState([]),[C,b]=u.useState([]),[k,R]=u.useState(!1),[A,$]=u.useState(null),[W]=u.useState(null),[w]=u.useState(null),[D,_]=u.useState(null),P=u.useRef(null);function B(L){try{if(L instanceof Error){let S=`${L.message}
40
40
  ${L.stack??""}`;const I=L;if(I!=null&&I.attemptedUrls)try{S+=`
41
41
  Attempted URLs: ${Array.isArray(I.attemptedUrls)?I.attemptedUrls.join(", "):String(I.attemptedUrls)}`}catch{S+=`
42
42
  Attempted URLs: ${String(I.attemptedUrls)}`}return S}const T=L;return T!=null&&T.attemptedUrls?`Error: ${String(T.message??T)}
43
- Attempted URLs: ${Array.isArray(T.attemptedUrls)?T.attemptedUrls.join(", "):String(T.attemptedUrls)}`:String(L)}catch{return"Unknown error"}}function z(L){if(!L||L<=0)return null;const T=12*Math.log2(L/440)+69;return Math.round(T-12)}async function K(L){var S;const T=(S=L.target.files)==null?void 0:S[0];T&&await Z(T,h)}async function Z(L,T){$(null),b([]),R(!0);try{const S=await L.arrayBuffer(),I=window.AudioContext??window.webkitAudioContext,F=await new I().decodeAudioData(S),j=F.getChannelData(0);d(j);const E=F.sampleRate,H=Math.floor(E*.1),Y=H,J=()=>{const ee=[],oe=Er.PitchDetector.forFloat32Array(H);for(let ce=0;ce<j.length-H;ce+=Y){const fe=j.slice(ce,ce+H),[Q,ue]=oe.findPitch(fe,E),ye=z(Q);ye&&Q>50&&Q<2e3&&ue>.7&&ee.push({start:ce/E,duration:H/E,pitch:ye,freq:Q})}return ee},ne=()=>{const ee=[];for(let oe=0;oe<j.length-H;oe+=Y){const ce=j.slice(oe,oe+H),fe=X(ce,E),Q=z(fe);Q&&fe>50&&fe<2e3&&ee.push({start:oe/E,duration:H/E,pitch:Q,freq:fe})}return ee};if(T){R(!0),$(null);const ee={};try{const oe={};try{ee.pitchy=J(),oe.pitchy=null}catch(ce){ee.pitchy=[],oe.pitchy=B(ce),He.warn("pitchy failed",ce)}try{ee["ultrastar-wp"]=ne(),oe["ultrastar-wp"]=null}catch(ce){ee["ultrastar-wp"]=[],oe["ultrastar-wp"]=B(ce),He.warn("ultrastar-wp failed",ce)}ee.aubio=[],oe.aubio="disabled";try{if(!r)throw new Error("CREPE backend not configured");const fe=(await r(L)).track??[];ee.crepe=fe.map((Q,ue)=>{var ye;return{start:Q.t,duration:(ye=fe[ue+1])!=null&&ye.t?fe[ue+1].t-Q.t:.1,pitch:z(Q.hz)??0,freq:Q.hz}}),oe.crepe=null}catch(ce){ee.crepe=[],oe.crepe=B(ce),He.warn("crepe failed",ce)}try{if(!a)throw new Error("Librosa backend not configured");const fe=(await a(new File([L],L.name,{type:L.type}))).track??[];ee.librosa=fe.map((Q,ue)=>{var ye;return{start:Q.t,duration:(ye=fe[ue+1])!=null&&ye.t?fe[ue+1].t-Q.t:.1,pitch:z(Q.hz)??0,freq:Q.hz}}),oe.librosa=null}catch(ce){ee.librosa=[],oe.librosa=B(ce),He.warn("librosa failed",ce)}y(oe),m(ee),b(ee[i]??[])}catch(oe){He.error("compareAll overall failed",oe);const ce=oe instanceof Error?oe.message:String(oe);$(o("audioPitch.errorComparing")+ce)}finally{R(!1)}return}const ae=[],re=[];let G=0;if(i==="pitchy"){const ee=Er.PitchDetector.forFloat32Array(H);for(let oe=0;oe<j.length-H;oe+=Y){const ce=j.slice(oe,oe+H);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[Q,ue]=ee.findPitch(ce,E),ye=z(Q);ye&&Q>50&&Q<2e3&&ue>.7&&(ae.push({start:oe/E,duration:H/E,pitch:ye,freq:Q}),G++)}}else if(i==="crepe")try{if(!r)throw new Error("CREPE backend not configured");const ee=await r(L);if(!ee.track||ee.track.length===0)$(o("audioPitch.crepeNoNotes")),He.warn("Crepe: No notes detected in audio file.");else{const oe=ee.track.map((ce,fe)=>{const Q=z(ce.hz);return Q&&ce.hz>50&&ce.hz<2e3?{start:ce.t,duration:fe<ee.track.length-1?ee.track[fe+1].t-ce.t:.1,pitch:Q,freq:ce.hz}:null}).filter(ce=>ce!==null);if(b(oe),e)try{e(oe)}catch(ce){He.error("Error in onSegments:",ce)}v([]),d(null);return}}catch(ee){$(o("audioPitch.crepeBackendError")),_(B(ee)),He.error("Crepe: Error calling backend:",ee)}else if(i==="librosa")try{await O(L),v([]),d(null);return}catch(ee){$(o("audioPitch.librosaBackendError")),_(B(ee)),He.error("Librosa: Error calling backend:",ee)}else if(i==="ultrastar-wp")for(let ee=0;ee<j.length-H;ee+=Y){const oe=j.slice(ee,ee+H);let ce=0;for(let ue=0;ue<oe.length;ue++)ce+=oe[ue]*oe[ue];ce=Math.sqrt(ce/oe.length),re.push(ce);const fe=X(oe,E),Q=z(fe);Q&&fe>50&&fe<2e3&&(ae.push({start:ee/E,duration:H/E,pitch:Q,freq:fe}),G++)}v(re);const q=N(ae);if(b(q),e)try{e(q)}catch(ee){He.error("Error in onSegments:",ee)}q.length===0&&i!=="crepe"&&($(o("audioPitch.noNotesDetected")),He.warn("No notes detected in audio file."))}catch(S){$(o("audioPitch.errorAnalyzing")+(S instanceof Error?S.message:String(S))),_(B(S)),He.error("Error analyzing audio file:",S)}finally{R(!1)}}u.useEffect(()=>{n&&Z(n,!0)},[n]);async function O(L){try{if(!a)throw new Error("Librosa backend not configured");const T=new File([L],"capture.wav",{type:"audio/wav"}),I=((await a(T)).track??[]).map(M=>({t:M.t,hz:M.hz}));if(e){const M=I.map((F,j)=>{var Y;const E=((Y=I[j+1])==null?void 0:Y.t)??F.t+.1,H=z(F.hz)??0;return{start:F.t,duration:Math.max(.05,E-F.t),pitch:H,freq:F.hz}});e(M),b(M)}}catch(T){He.warn("Librosa analysis failed, falling back to local detectors",T);const I=(typeof T=="object"&&T!==null?T:{}).attemptedUrls;I&&He.error("Librosa attempted URLs:",I);const M=I?Array.isArray(I)?I.join(", "):String(I):null,F=T instanceof Error?T.message:String(T);$(o("audioPitch.librosaBackendError")+": "+F+(M?" (attempted: "+M+")":"")),_(B(T))}}function X(L,T){const M=Math.floor(T/50),F=Math.max(2,Math.floor(T/2e3));let j=0;for(let J=0;J<L.length;J++)j+=L[J]*L[J];if(j<=1e-8)return 0;let E=-1,H=0;const Y=1e-10;for(let J=F;J<=Math.min(M,L.length-2);J++){let ne=0;const ae=L.length-J;for(let G=0;G<ae;G++)ne+=L[G]*L[G+J];const re=ne/(ae+Y)/(j/L.length+Y);re>H&&(H=re,E=J)}return E>0&&H>.01?T/E:0}function N(L){if(L.length===0)return[];const T=[];let S=L[0];for(let I=1;I<L.length;I++){const M=L[I];M.pitch===S.pitch&&Math.abs(M.freq-S.freq)<1?S.duration+=M.duration:(T.push(S),S=M)}return T.push(S),T}function U(){try{const L=Object.keys(g).length>0?Object.keys(g):["pitchy","ultrastar-wp","aubio","crepe","librosa"],T=(()=>{let G=0;for(const q of L){const ee=g[q]??[];for(const oe of ee)G=Math.max(G,oe.start+(oe.duration||0))}return G||0})(),S=(G,q)=>!G||!q?1/0:1200*Math.log2(G/q),I=(G,q)=>{if(!G||!q)return!1;const ee=Math.round(Math.log2(q/G)),oe=G*Math.pow(2,ee),ce=Math.abs(S(oe,q));return Math.abs(ee)>=1&&ce<50},M=G=>{const q={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!G||G.length===0)return q;q.count=G.length,q.totalDur=G.reduce((fe,Q)=>fe+(Q.duration||0),0);const ee=G.map(fe=>fe.freq).filter(Boolean);if(ee.length===0)return q;const oe=ee.reduce((fe,Q)=>fe+Q,0)/ee.length,ce=ee.reduce((fe,Q)=>fe+(Q-oe)*(Q-oe),0)/ee.length;return q.meanFreq=oe,q.stdFreq=Math.sqrt(ce||0),q.meanDur=q.totalDur/q.count,q.voicedFraction=T>0?q.totalDur/T:null,q},F=(G,q)=>{let ee=0,oe=0;const ce=[];for(const Q of G){const ue=Q.start,ye=Q.start+(Q.duration||.05);let je=null,Fe=0;for(const Re of q){const Se=Re.start,te=Re.start+(Re.duration||.05),se=Math.max(0,Math.min(ye,te)-Math.max(ue,Se));se>Fe&&(Fe=se,je=Re)}if(je&&Fe>0){const Re=Math.abs(S(Q.freq,je.freq));ce.push(Re),Re<50&&ee++,I(Q.freq,je.freq)&&oe++}}const fe=ce.length?ce.reduce((Q,ue)=>Q+ue,0)/ce.length:null;return{matches:ee,compared:G.length,meanCents:fe,octaveErrors:oe}},j=[];j.push("# AudioPitchAnalyzer � Comparative Report"),j.push(`Generated: ${new Date().toISOString()}`),j.push(""),j.push("## Summary"),j.push(`- Selected algorithm in UI: **${i}**`),j.push(`- Total analyzed duration (approx): **${T.toFixed(3)} s**`),j.push(""),j.push("## Per-algorithm statistics"),j.push("| Algorithm | Segments | Total voiced (s) | Voiced fraction | Mean freq (Hz) | Std freq (Hz) | Mean dur (s) |"),j.push("|---|---:|---:|---:|---:|---:|---:|");const E={};for(const G of L){const q=g[G]??[],ee=M(q);E[G]=ee,j.push(`| ${G} | ${ee.count||0} | ${(ee.totalDur||0).toFixed(3)} | ${ee.voicedFraction!==null?(ee.voicedFraction*100).toFixed(1)+"%":"N/A"} | ${ee.meanFreq?ee.meanFreq.toFixed(1):"N/A"} | ${ee.stdFreq?ee.stdFreq.toFixed(1):"N/A"} | ${ee.meanDur?ee.meanDur.toFixed(3):"N/A"} |`)}j.push(""),j.push("## Pairwise agreement (reference -> test)");const H=L.includes("crepe")?"crepe":L.includes("librosa")?"librosa":L.includes("pitchy")?"pitchy":L[0];j.push(`Reference algorithm: **${H}**`),j.push(""),j.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),j.push("|---|---:|---:|---:|---:|---:|");for(const G of L){if(G===H)continue;const q=F(g[H]??[],g[G]??[]),ee=q.compared?(q.matches/q.compared*100).toFixed(1)+"%":"N/A";j.push(`| ${H} -> ${G} | ${q.matches} | ${q.compared} | ${ee} | ${q.meanCents!==null?q.meanCents.toFixed(1):"N/A"} | ${q.octaveErrors} |`)}j.push(""),j.push("## Observations and analysis"),j.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."),j.push("- Pairwise match rate shows how often algorithms agree on the same regions (within ~50 cents). Octave error counts highlight typical autocorrelation octave mistakes."),j.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."),j.push("");for(const G of L){j.push(`### ${G}`);const q=E[G];j.push(`- Segments: ${q.count||0}`),j.push(`- Total voiced (s): ${(q.totalDur||0).toFixed(3)}`),j.push(`- Voiced fraction: ${q.voicedFraction!==null?(q.voicedFraction*100).toFixed(1)+"%":"N/A"}`),j.push(`- Mean frequency: ${q.meanFreq?q.meanFreq.toFixed(2)+" Hz":"N/A"}`),j.push(`- Std frequency: ${q.stdFreq?q.stdFreq.toFixed(2)+" Hz":"N/A"}`),j.push("")}j.push("## Conclusions & recommendation");const Y=[];for(const G of L){if(G===H){Y.push({alg:G,score:100});continue}const q=F(g[H]??[],g[G]??[]),ee=q.compared?q.matches/q.compared:0,oe=q.compared?q.octaveErrors/q.compared:0,ce=ee-oe*.5;Y.push({alg:G,score:ce})}Y.sort((G,q)=>q.score-G.score),j.push(`- Based on this recording, recommended authoritative detector: **${Y[0].alg}** (best agreement with reference).`),j.push("- For live, low-latency feedback use Pitchy (YIN) with smoothing/hysteresis; use Crepe/Librosa for authoritative scoring or post-processing."),j.push("- If octave errors are frequent, consider octave-correction heuristics (prefer lower octave when ambiguity) or combine detectors via voting."),j.push(""),j.push("## Raw data (per-algorithm segments)");for(const G of L){const q=g[G]??[];j.push(`### ${G} � ${q.length} segments`);for(const oe of q)j.push(`- ${oe.start.toFixed(3)} .. ${(oe.start+(oe.duration||0)).toFixed(3)} : ${oe.freq.toFixed(2)} Hz (pitch ${oe.pitch})`);const ee=p[G];ee&&j.push(`- Error: ${ee}`),j.push("")}const J=j.join(`
43
+ Attempted URLs: ${Array.isArray(T.attemptedUrls)?T.attemptedUrls.join(", "):String(T.attemptedUrls)}`:String(L)}catch{return"Unknown error"}}function z(L){if(!L||L<=0)return null;const T=12*Math.log2(L/440)+69;return Math.round(T-12)}async function K(L){var S;const T=(S=L.target.files)==null?void 0:S[0];T&&await Z(T,h)}async function Z(L,T){$(null),b([]),R(!0);try{const S=await L.arrayBuffer(),I=window.AudioContext??window.webkitAudioContext,F=await new I().decodeAudioData(S),j=F.getChannelData(0);d(j);const E=F.sampleRate,H=Math.floor(E*.1),Y=H,J=()=>{const ee=[],oe=Er.PitchDetector.forFloat32Array(H);for(let ce=0;ce<j.length-H;ce+=Y){const fe=j.slice(ce,ce+H),[Q,ue]=oe.findPitch(fe,E),ye=z(Q);ye&&Q>50&&Q<2e3&&ue>.7&&ee.push({start:ce/E,duration:H/E,pitch:ye,freq:Q})}return ee},ne=()=>{const ee=[];for(let oe=0;oe<j.length-H;oe+=Y){const ce=j.slice(oe,oe+H),fe=X(ce,E),Q=z(fe);Q&&fe>50&&fe<2e3&&ee.push({start:oe/E,duration:H/E,pitch:Q,freq:fe})}return ee};if(T){R(!0),$(null);const ee={};try{const oe={};try{ee.pitchy=J(),oe.pitchy=null}catch(ce){ee.pitchy=[],oe.pitchy=B(ce),He.warn("pitchy failed",ce)}try{ee["ultrastar-wp"]=ne(),oe["ultrastar-wp"]=null}catch(ce){ee["ultrastar-wp"]=[],oe["ultrastar-wp"]=B(ce),He.warn("ultrastar-wp failed",ce)}ee.aubio=[],oe.aubio="disabled";try{if(!r)throw new Error("CREPE backend not configured");const fe=(await r(L)).track??[];ee.crepe=fe.map((Q,ue)=>{var ye;return{start:Q.t,duration:(ye=fe[ue+1])!=null&&ye.t?fe[ue+1].t-Q.t:.1,pitch:z(Q.hz)??0,freq:Q.hz}}),oe.crepe=null}catch(ce){ee.crepe=[],oe.crepe=B(ce),He.warn("crepe failed",ce)}try{if(!a)throw new Error("Librosa backend not configured");const fe=(await a(new File([L],L.name,{type:L.type}))).track??[];ee.librosa=fe.map((Q,ue)=>{var ye;return{start:Q.t,duration:(ye=fe[ue+1])!=null&&ye.t?fe[ue+1].t-Q.t:.1,pitch:z(Q.hz)??0,freq:Q.hz}}),oe.librosa=null}catch(ce){ee.librosa=[],oe.librosa=B(ce),He.warn("librosa failed",ce)}y(oe),m(ee),b(ee[i]??[])}catch(oe){He.error("compareAll overall failed",oe);const ce=oe instanceof Error?oe.message:String(oe);$(o("audioPitch.errorComparing")+ce)}finally{R(!1)}return}const ae=[],re=[];let G=0;if(i==="pitchy"){const ee=Er.PitchDetector.forFloat32Array(H);for(let oe=0;oe<j.length-H;oe+=Y){const ce=j.slice(oe,oe+H);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[Q,ue]=ee.findPitch(ce,E),ye=z(Q);ye&&Q>50&&Q<2e3&&ue>.7&&(ae.push({start:oe/E,duration:H/E,pitch:ye,freq:Q}),G++)}}else if(i==="crepe")try{if(!r)throw new Error("CREPE backend not configured");const ee=await r(L);if(!ee.track||ee.track.length===0)$(o("audioPitch.crepeNoNotes")),He.warn("Crepe: No notes detected in audio file.");else{const oe=ee.track.map((ce,fe)=>{const Q=z(ce.hz);return Q&&ce.hz>50&&ce.hz<2e3?{start:ce.t,duration:fe<ee.track.length-1?ee.track[fe+1].t-ce.t:.1,pitch:Q,freq:ce.hz}:null}).filter(ce=>ce!==null);if(b(oe),e)try{e(oe)}catch(ce){He.error("Error in onSegments:",ce)}x([]),d(null);return}}catch(ee){$(o("audioPitch.crepeBackendError")),_(B(ee)),He.error("Crepe: Error calling backend:",ee)}else if(i==="librosa")try{await O(L),x([]),d(null);return}catch(ee){$(o("audioPitch.librosaBackendError")),_(B(ee)),He.error("Librosa: Error calling backend:",ee)}else if(i==="ultrastar-wp")for(let ee=0;ee<j.length-H;ee+=Y){const oe=j.slice(ee,ee+H);let ce=0;for(let ue=0;ue<oe.length;ue++)ce+=oe[ue]*oe[ue];ce=Math.sqrt(ce/oe.length),re.push(ce);const fe=X(oe,E),Q=z(fe);Q&&fe>50&&fe<2e3&&(ae.push({start:ee/E,duration:H/E,pitch:Q,freq:fe}),G++)}x(re);const q=N(ae);if(b(q),e)try{e(q)}catch(ee){He.error("Error in onSegments:",ee)}q.length===0&&i!=="crepe"&&($(o("audioPitch.noNotesDetected")),He.warn("No notes detected in audio file."))}catch(S){$(o("audioPitch.errorAnalyzing")+(S instanceof Error?S.message:String(S))),_(B(S)),He.error("Error analyzing audio file:",S)}finally{R(!1)}}u.useEffect(()=>{n&&Z(n,!0)},[n]);async function O(L){try{if(!a)throw new Error("Librosa backend not configured");const T=new File([L],"capture.wav",{type:"audio/wav"}),I=((await a(T)).track??[]).map(M=>({t:M.t,hz:M.hz}));if(e){const M=I.map((F,j)=>{var Y;const E=((Y=I[j+1])==null?void 0:Y.t)??F.t+.1,H=z(F.hz)??0;return{start:F.t,duration:Math.max(.05,E-F.t),pitch:H,freq:F.hz}});e(M),b(M)}}catch(T){He.warn("Librosa analysis failed, falling back to local detectors",T);const I=(typeof T=="object"&&T!==null?T:{}).attemptedUrls;I&&He.error("Librosa attempted URLs:",I);const M=I?Array.isArray(I)?I.join(", "):String(I):null,F=T instanceof Error?T.message:String(T);$(o("audioPitch.librosaBackendError")+": "+F+(M?" (attempted: "+M+")":"")),_(B(T))}}function X(L,T){const M=Math.floor(T/50),F=Math.max(2,Math.floor(T/2e3));let j=0;for(let J=0;J<L.length;J++)j+=L[J]*L[J];if(j<=1e-8)return 0;let E=-1,H=0;const Y=1e-10;for(let J=F;J<=Math.min(M,L.length-2);J++){let ne=0;const ae=L.length-J;for(let G=0;G<ae;G++)ne+=L[G]*L[G+J];const re=ne/(ae+Y)/(j/L.length+Y);re>H&&(H=re,E=J)}return E>0&&H>.01?T/E:0}function N(L){if(L.length===0)return[];const T=[];let S=L[0];for(let I=1;I<L.length;I++){const M=L[I];M.pitch===S.pitch&&Math.abs(M.freq-S.freq)<1?S.duration+=M.duration:(T.push(S),S=M)}return T.push(S),T}function U(){try{const L=Object.keys(g).length>0?Object.keys(g):["pitchy","ultrastar-wp","aubio","crepe","librosa"],T=(()=>{let G=0;for(const q of L){const ee=g[q]??[];for(const oe of ee)G=Math.max(G,oe.start+(oe.duration||0))}return G||0})(),S=(G,q)=>!G||!q?1/0:1200*Math.log2(G/q),I=(G,q)=>{if(!G||!q)return!1;const ee=Math.round(Math.log2(q/G)),oe=G*Math.pow(2,ee),ce=Math.abs(S(oe,q));return Math.abs(ee)>=1&&ce<50},M=G=>{const q={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!G||G.length===0)return q;q.count=G.length,q.totalDur=G.reduce((fe,Q)=>fe+(Q.duration||0),0);const ee=G.map(fe=>fe.freq).filter(Boolean);if(ee.length===0)return q;const oe=ee.reduce((fe,Q)=>fe+Q,0)/ee.length,ce=ee.reduce((fe,Q)=>fe+(Q-oe)*(Q-oe),0)/ee.length;return q.meanFreq=oe,q.stdFreq=Math.sqrt(ce||0),q.meanDur=q.totalDur/q.count,q.voicedFraction=T>0?q.totalDur/T:null,q},F=(G,q)=>{let ee=0,oe=0;const ce=[];for(const Q of G){const ue=Q.start,ye=Q.start+(Q.duration||.05);let je=null,Fe=0;for(const Re of q){const Se=Re.start,te=Re.start+(Re.duration||.05),se=Math.max(0,Math.min(ye,te)-Math.max(ue,Se));se>Fe&&(Fe=se,je=Re)}if(je&&Fe>0){const Re=Math.abs(S(Q.freq,je.freq));ce.push(Re),Re<50&&ee++,I(Q.freq,je.freq)&&oe++}}const fe=ce.length?ce.reduce((Q,ue)=>Q+ue,0)/ce.length:null;return{matches:ee,compared:G.length,meanCents:fe,octaveErrors:oe}},j=[];j.push("# AudioPitchAnalyzer � Comparative Report"),j.push(`Generated: ${new Date().toISOString()}`),j.push(""),j.push("## Summary"),j.push(`- Selected algorithm in UI: **${i}**`),j.push(`- Total analyzed duration (approx): **${T.toFixed(3)} s**`),j.push(""),j.push("## Per-algorithm statistics"),j.push("| Algorithm | Segments | Total voiced (s) | Voiced fraction | Mean freq (Hz) | Std freq (Hz) | Mean dur (s) |"),j.push("|---|---:|---:|---:|---:|---:|---:|");const E={};for(const G of L){const q=g[G]??[],ee=M(q);E[G]=ee,j.push(`| ${G} | ${ee.count||0} | ${(ee.totalDur||0).toFixed(3)} | ${ee.voicedFraction!==null?(ee.voicedFraction*100).toFixed(1)+"%":"N/A"} | ${ee.meanFreq?ee.meanFreq.toFixed(1):"N/A"} | ${ee.stdFreq?ee.stdFreq.toFixed(1):"N/A"} | ${ee.meanDur?ee.meanDur.toFixed(3):"N/A"} |`)}j.push(""),j.push("## Pairwise agreement (reference -> test)");const H=L.includes("crepe")?"crepe":L.includes("librosa")?"librosa":L.includes("pitchy")?"pitchy":L[0];j.push(`Reference algorithm: **${H}**`),j.push(""),j.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),j.push("|---|---:|---:|---:|---:|---:|");for(const G of L){if(G===H)continue;const q=F(g[H]??[],g[G]??[]),ee=q.compared?(q.matches/q.compared*100).toFixed(1)+"%":"N/A";j.push(`| ${H} -> ${G} | ${q.matches} | ${q.compared} | ${ee} | ${q.meanCents!==null?q.meanCents.toFixed(1):"N/A"} | ${q.octaveErrors} |`)}j.push(""),j.push("## Observations and analysis"),j.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."),j.push("- Pairwise match rate shows how often algorithms agree on the same regions (within ~50 cents). Octave error counts highlight typical autocorrelation octave mistakes."),j.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."),j.push("");for(const G of L){j.push(`### ${G}`);const q=E[G];j.push(`- Segments: ${q.count||0}`),j.push(`- Total voiced (s): ${(q.totalDur||0).toFixed(3)}`),j.push(`- Voiced fraction: ${q.voicedFraction!==null?(q.voicedFraction*100).toFixed(1)+"%":"N/A"}`),j.push(`- Mean frequency: ${q.meanFreq?q.meanFreq.toFixed(2)+" Hz":"N/A"}`),j.push(`- Std frequency: ${q.stdFreq?q.stdFreq.toFixed(2)+" Hz":"N/A"}`),j.push("")}j.push("## Conclusions & recommendation");const Y=[];for(const G of L){if(G===H){Y.push({alg:G,score:100});continue}const q=F(g[H]??[],g[G]??[]),ee=q.compared?q.matches/q.compared:0,oe=q.compared?q.octaveErrors/q.compared:0,ce=ee-oe*.5;Y.push({alg:G,score:ce})}Y.sort((G,q)=>q.score-G.score),j.push(`- Based on this recording, recommended authoritative detector: **${Y[0].alg}** (best agreement with reference).`),j.push("- For live, low-latency feedback use Pitchy (YIN) with smoothing/hysteresis; use Crepe/Librosa for authoritative scoring or post-processing."),j.push("- If octave errors are frequent, consider octave-correction heuristics (prefer lower octave when ambiguity) or combine detectors via voting."),j.push(""),j.push("## Raw data (per-algorithm segments)");for(const G of L){const q=g[G]??[];j.push(`### ${G} � ${q.length} segments`);for(const oe of q)j.push(`- ${oe.start.toFixed(3)} .. ${(oe.start+(oe.duration||0)).toFixed(3)} : ${oe.freq.toFixed(2)} Hz (pitch ${oe.pitch})`);const ee=p[G];ee&&j.push(`- Error: ${ee}`),j.push("")}const J=j.join(`
44
44
  `),ne=new Blob([J],{type:"text/markdown;charset=utf-8"}),ae=URL.createObjectURL(ne),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(L){He.error("generateScientificReport error",L),He.warn(o("audioPitch.reportError")+String(L))}}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:L=>l(L.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:L=>f(L.target.checked)})," ",o("audioPitch.compareAll")]}),s.jsx("input",{type:"file",accept:"audio/*",ref:P,onChange:K,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]}),A&&s.jsxs("div",{style:{color:"red",marginTop:8},children:[s.jsxs("b",{children:[i,": "]}),s.jsx("div",{children:A}),D&&s.jsx("pre",{style:{background:"#111",color:"#f88",padding:8,borderRadius:4,whiteSpace:"pre-wrap",marginTop:8},children:D})]}),W&&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:W}),w&&s.jsxs("div",{style:{marginTop:8},children:[s.jsx("b",{children:"Probe:"})," ",w]})]}),(Object.keys(g).length>0||Object.keys(p).length>0)&&s.jsxs("div",{style:{marginTop:12},children:[s.jsx("button",{onClick:()=>U(),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(([L,T])=>T).map(([L,T])=>s.jsxs("div",{style:{marginTop:6},children:[s.jsxs("b",{children:[L,":"]}),s.jsx("pre",{style:{background:"#111",color:"#f88",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:T})]},L))]})]}),C.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:[C.map(L=>`: ${Math.round(L.start*10)} ${Math.round(L.duration*10)} ${L.pitch} [${L.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:L=>{if(!L)return;const T=L.getContext("2d");if(T){T.clearRect(0,0,600,100),T.strokeStyle="#0ff",T.beginPath();for(let S=0;S<c.length;S+=Math.ceil(c.length/600)){const I=S/c.length*600,M=50-c[S]*48;S===0?T.moveTo(I,M):T.lineTo(I,M)}if(T.stroke(),x.length>0){T.strokeStyle="#ff0",T.beginPath();for(let S=0;S<x.length;S++){const I=S/x.length*600,M=100-x[S]*90;S===0?T.moveTo(I,M):T.lineTo(I,M)}T.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&&C.length===0&&!A&&s.jsx("div",{style:{marginTop:16,color:"#aaa"},children:s.jsx("i",{children:o("audioPitch.noNotesDetected")})}),h&&Object.keys(g).length>0&&s.jsxs("div",{style:{marginTop:16},children:[s.jsx("h4",{children:o("audioPitch.algorithmComparison")}),Object.entries(g).map(([L,T])=>s.jsxs("div",{style:{marginBottom:12},children:[s.jsx("b",{children:L}),": ",o("audioPitch.detectedSegments")," ",T.length,s.jsx("pre",{style:{background:"#111",color:"#ddd",padding:8,borderRadius:4,marginTop:8},children:T.map(S=>`: ${Math.round(S.start*10)} ${Math.round(S.duration*10)} ${S.pitch} [${S.freq.toFixed(1)} Hz]`).join(`
47
- `)})]},L))]})]})}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}))],To=[{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 Ja=!1;function Po(){try{const e=localStorage.getItem(da);if(e){const t=JSON.parse(e);return{...Jt,...t}}}catch{}return{...Jt}}async function Kd(e){if(Ja||(Ja=!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 Eo(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=To.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}=Eo(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=Po();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)"],Ao={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 No(e,t){const n=Ao[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 Io(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 Lo(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:Io(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,g,m,p,y;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,v=o.indexOf(!0);if(o[x]){const C=Or(i.note.pitch);this.config.onPitch(C),a-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=a,(m=(g=this.config).onHitFeedback)==null||m.call(g,{type:"perfect",lane:x,time:a}))}else if(v>=0){const b=Math.abs(v-x)*3,k=Or(i.note.pitch+b);this.config.onPitch(k),a-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=a,(y=(p=this.config).onHitFeedback)==null||y.call(p,{type:"miss",lane:v,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=No(n,t.difficulty),this.events=Lo(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,lines:n,notes:r,currentIndex:a,animationConfig:o})=>{const i=n[e]??"",l=r.findIndex(v=>v.lineIndex===e),c=l>=0&&l===a,d=(o==null?void 0:o.enabled)??!0,h=(o==null?void 0:o.durationMs)??300,f=(o==null?void 0:o.translateX)??8,g=(o==null?void 0:o.scale)??1.01,m=(o==null?void 0:o.easing)??"cubic-bezier(.22,1,.36,1)",p=(o==null?void 0:o.opacityInactive)??.9,y=(o==null?void 0:o.boxShadow)??"0 6px 18px rgba(3,102,214,0.08)",x={transition:d?`transform ${h}ms ${m}, opacity ${h}ms ${m}`:"none",transform:c?`translateX(${f}px) scale(${g})`:"translateX(0px) scale(1)",opacity:c?1:p,boxShadow:c?y:"none"};return s.jsx("div",{style:{...t,padding:"4px 6px",borderRadius:4},"data-note-idx":l>=0?l:void 0,children:s.jsx("div",{style:{...x,background:c?"rgba(0,130,200,0.12)":"transparent",padding:"4px 6px",borderRadius:4},children:s.jsx("code",{style:{fontFamily:"monospace",whiteSpace:"pre-wrap"},children:i})})})},Fo=({ultrastarText:e,audioUrl:t,audioRef:n,animationConfig:r})=>{const{t:a}=ve(),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),g=u.useRef(0),m=u.useRef(0),[p,y]=u.useState(-1),x=u.useMemo(()=>(e||"").split(/\r?\n/),[e]),v=28,C=x.length*v,b=u.useMemo(()=>({lines:x,notes:d,currentIndex:p,animationConfig:r}),[x,d,p,r]);return u.useEffect(()=>{const k=i.current;k&&(l?k.play().catch(()=>c(!1)):k.pause())},[l,i]),u.useEffect(()=>{const k=i.current;if(!k)return;let R=-1;const A=r??null,$=A&&typeof A.scrollSmooth=="number"?A.scrollSmooth:.18;let W=performance.now();const w=()=>{var U,L,T,S;const D=performance.now(),_=Math.max(0,Math.min(.2,(D-W)/1e3));W=D;const P=k.currentTime||0;g.current=P;let B=-1;for(let I=0;I<d.length;I++){const M=d[I];if(P>=M.start&&P<M.start+Math.max(.001,M.duration)){B=I;break}}B!==R&&(R=B,y(B));let z=0;if(R>=0){const I=((U=d[R])==null?void 0:U.lineIndex)??0,M=((T=(L=h.current)==null?void 0:L.element)==null?void 0:T.clientHeight)??220;z=I*v-M/2+v/2;const F=Math.max(0,C-M);(isNaN(z)||!isFinite(z))&&(z=0),z=Math.max(0,Math.min(z,F))}const K=1-Math.pow(Math.max(0,1-$),Math.min(4,_*60)),N=(((r==null?void 0:r.scrollEasing)||"easeOutCubic")==="linear"?(I=>I):I=>1-Math.pow(1-I,3))(K);m.current=m.current+(z-m.current)*N;try{const I=(S=h.current)==null?void 0:S.element;I&&typeof I.scrollTop=="number"&&(I.scrollTop=Math.round(m.current))}catch{}f.current=requestAnimationFrame(w)};return f.current=requestAnimationFrame(w),()=>{f.current&&cancelAnimationFrame(f.current)}},[i,d,C,r,h]),s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[s.jsx("button",{onClick:()=>c(k=>!k),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.List,{defaultHeight:220,rowCount:x.length,rowHeight:v,listRef:h,rowComponent:Jd,rowProps:b,style:{width:"100%"}}):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 Do({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 g=c.current;g&&"rebuildTexts"in g&&typeof g.rebuildTexts=="function"&&g.rebuildTexts()},[e]),u.useEffect(()=>{let h=!0;return(async()=>{var A;if(!h||!a.current)return;const f=await import("phaser"),g="default"in f?f.default:f;if(!a.current||!h)return;const m=i,p=l,y=c,x=n,v=r,C=d;class b extends g.Scene{constructor(){super({key:"preview"}),this.texts=[],this.audioEl=null}create(){if(y.current=this,this.rebuildTexts(),v!=null&&v.current)this.audioEl=null;else if(x!=null&&x.current)this.audioEl=x.current;else{const W=document.querySelector("audio");W instanceof HTMLAudioElement?this.audioEl=W:C.current?(this.audioEl=document.createElement("audio"),this.audioEl.src=C.current,this.audioEl.preload="metadata",this.audioEl.style.display="none",document.body.appendChild(this.audioEl)):this.audioEl=null}}rebuildTexts(){for(const P of this.texts)P.destroy();this.texts=[];const W={font:"18px monospace",color:"#ffffff"},w=22;let D=20;const _=m.current;for(let P=0;P<_.length;P++){const B=this.add.text(10,D,_[P]||" ",W).setOrigin(0,0);this.texts.push(B),D+=w}}update(){let W=0;if(v!=null&&v.current&&typeof v.current.getCurrentTime=="function")try{W=v.current.getCurrentTime()||0}catch{W=0}else W=this.audioEl&&this.audioEl.currentTime||0;for(let D=0;D<this.texts.length;D++)this.texts[D].setStyle({backgroundColor:void 0,color:"#ffffff"});const w=p.current;for(const D of w)if(W>=D.start&&W<D.start+Math.max(.001,D.duration)){const _=this.texts[D.lineIndex];_&&_.setStyle({backgroundColor:"rgba(0,130,200,0.16)",color:"#00aaff"})}}}const k=((A=a.current)==null?void 0:A.clientWidth)??640,R={type:g.AUTO,parent:a.current,width:k,height:Math.round(k/2),backgroundColor:"#101010",scene:[b]};o.current=new g.Game(R)})(),()=>{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),Oo=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&&Oo(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],_o=({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:g=!1,onEnded:m,enableKeyboardShortcuts:p=!0,shuffle:y=!1,repeatMode:x="none",playbackSpeed:v=1,abLoop:C=null,onRepeatModeChange:b,onShuffleChange:k,onSpeedChange:R,sleepTimer:A=0,onSleepTimerExpired:$})=>{const{t:W}=ve(),[w,D]=u.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),_=e[w],P=u.useMemo(()=>au(_),[_]),[B,z]=u.useState(!1),[K,Z]=u.useState(0),[O,X]=u.useState(0),[N,U]=u.useState(.9),[L,T]=u.useState(null),[S,I]=u.useState(null),M=u.useRef(null),[F,j]=u.useState(y),[E,H]=u.useState(x),[Y,J]=u.useState(v),[ne,ae]=u.useState(C),[re,G]=u.useState([]),[q,ee]=u.useState(A>0?A*60:null),oe=u.useRef(null),[ce,fe]=u.useState(()=>Ns()),Q=u.useRef(null),ue=u.useRef(null),ye=u.useRef(null),je=u.useRef(null);u.useEffect(()=>{if(F&&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]]}G(le)}},[F,e.length]),u.useEffect(()=>(oe.current&&(window.clearInterval(oe.current),oe.current=null),A>0&&B&&(ee(A*60),oe.current=window.setInterval(()=>{ee(le=>!le||le<=1?(oe.current&&window.clearInterval(oe.current),oe.current=null,$==null||$(),null):le-1)},1e3)),()=>{oe.current&&window.clearInterval(oe.current)}),[A,B]);const Fe=u.useCallback(le=>{const de=Math.min(Math.max(0,le),Math.max(0,e.length-1));D(de),o==null||o(de)},[e.length,o]),Re=u.useCallback(()=>{if(F&&re.length>0){const de=re.indexOf(w)+1;return de<re.length?re[de]:E==="all"?re[0]:-1}return w<e.length-1?w+1:E==="all"?0:-1},[w,e.length,F,re,E]),Se=u.useCallback(()=>{if(F&&re.length>0){const le=re.indexOf(w);return le>0?re[le-1]:E==="all"?re[re.length-1]:-1}return w>0?w-1:E==="all"?e.length-1:-1},[w,e.length,F,re,E]),te=u.useCallback(()=>{const le=Re();le>=0&&Fe(le)},[Re,Fe]),se=u.useCallback(async()=>{var le,de;await Et(),fe(!0),(P==null?void 0:P.kind)==="youtube"?(le=Q.current)==null||le.playVideo():(de=ue.current)==null||de.play(),z(!0),i==null||i(!0)},[P,i]),Ne=u.useCallback(()=>{var le,de;(P==null?void 0:P.kind)==="youtube"?(le=Q.current)==null||le.pauseVideo():(de=ue.current)==null||de.pause(),z(!1),i==null||i(!1)},[P,i]),De=u.useCallback(()=>B?Ne():se(),[B,se,Ne]),Pe=u.useCallback(le=>{var ie;const de=(_==null?void 0:_.startOffset)??0,Ce=le+de;(P==null?void 0:P.kind)==="youtube"?(ie=Q.current)==null||ie.seekTo(Ce,!0):ue.current&&(ue.current.currentTime=Ce);const vt=Math.max(0,le);X(vt),l==null||l(vt)},[P,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;U(le),T(null),(P==null?void 0:P.kind)==="youtube"?(Ce=(de=Q.current)==null?void 0:de.setVolume)==null||Ce.call(de,Math.round(le*100)):ue.current&&(ue.current.volume=le)},[P]),dt=u.useCallback(()=>{L!==null?we(L):(T(N),we(0))},[N,L,we]),Rn=u.useCallback(le=>{var de,Ce;J(le),ue.current&&(ue.current.playbackRate=le),(P==null?void 0:P.kind)==="youtube"&&((Ce=(de=Q.current)==null?void 0:de.setPlaybackRate)==null||Ce.call(de,le)),R==null||R(le)},[P,R]),Xe=u.useCallback(()=>{const le=["none","all","one"],de=le[(le.indexOf(E)+1)%le.length];H(de),b==null||b(de)},[E,b]),Ge=u.useCallback(()=>{const le=!F;j(le),k==null||k(le)},[F,k]),It=u.useCallback(le=>{ae(le)},[]);u.useImperativeHandle(c,()=>({play:se,pause:Ne,toggle:De,seekTo:Pe,setVolume:we,setSpeed:Rn,setRepeatMode:le=>{H(le),b==null||b(le)},toggleShuffle:Ge,setABLoop:It,getUnderlyingPlayer:()=>(P==null?void 0:P.kind)==="youtube"?Q.current:(P==null?void 0:P.kind)==="hls"||(P==null?void 0:P.kind)==="audio"?ue.current:null}),[se,Ne,De,Pe,we,Rn,Ge,It,P==null?void 0:P.kind]),u.useEffect(()=>{const le=window.setInterval(()=>{let de=0,Ce=0;(P==null?void 0:P.kind)==="youtube"&&Q.current?(de=Q.current.getCurrentTime()||0,Ce=Q.current.getDuration()||0):ue.current&&(de=ue.current.currentTime||0,Ce=ue.current.duration||0);const vt=(_==null?void 0:_.startOffset)??0,ie=Math.max(0,de-vt);X(ie),Z(Ce),l==null||l(ie),ne&&ie>=ne.b&&Pe(ne.a)},250);return()=>window.clearInterval(le)},[P==null?void 0:P.kind,l,ne]),u.useEffect(()=>()=>{M.current&&(window.clearInterval(M.current),M.current=null)},[]),u.useEffect(()=>{if(ye.current){try{ye.current.destroy()}catch{}ye.current=null}if(ue.current&&(ue.current.volume=N,ue.current.crossOrigin=P!=null&&P.withCredentials?"use-credentials":"anonymous"),(P==null?void 0:P.kind)==="hls"&&Oo(P.url)){const le=ue.current;if(!le)return;const de=()=>{le.src=P.url,le.load();const Ce=(_==null?void 0:_.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(P!=null&&P.withCredentials&&(Oe.withCredentials=!0),P!=null&&P.headers)for(const[xe,me]of Object.entries(P.headers))try{Oe.setRequestHeader(xe,me)}catch{}}});ye.current=he,he.loadSource(P.url),he.attachMedia(le),he.on(ie.Events.MANIFEST_PARSED,()=>{n&&le.play().catch(()=>{})})}else de()}catch(vt){tu.debug("HLS.js setup failed, falling back to native playback",vt),de()}})()}else if((P==null?void 0:P.kind)==="audio"&&P.url&&ue.current){const le=ue.current;le.src=P.url,le.load();const de=(_==null?void 0:_.startOffset)??0;try{de&&!isNaN(de)&&(le.currentTime=de)}catch{}n&&le.play().catch(()=>{})}M.current&&(window.clearInterval(M.current),M.current=null),I(null),X(0),Z(0),n&&(P==null?void 0:P.kind)==="youtube"&&r>0?(I(r),M.current=window.setInterval(()=>{I(le=>{var de;if(!le)return null;if(le<=1){M.current&&(window.clearInterval(M.current),M.current=null);try{(de=Q.current)==null||de.playVideo()}catch{}return z(!0),i==null||i(!0),null}return le-1})},1e3)):z(!!n)},[P==null?void 0:P.url,P==null?void 0:P.kind,P==null?void 0:P.withCredentials,JSON.stringify(P==null?void 0:P.headers),n,N]);const yt=u.useCallback(()=>{if(E==="one"){Pe(0),se();return}const le=Re();le>=0?Fe(le):(z(!1),i==null||i(!1),Pe(0),m==null||m())},[E,Re,Fe,i,Pe,m,se]);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,K));break;case"ArrowLeft":de.preventDefault(),Pe(Math.max(0,O-5));break;case"ArrowUp":de.preventDefault(),we(Math.min(1,N+.05));break;case"ArrowDown":de.preventDefault(),we(Math.max(0,N-.05));break;case"m":case"M":dt();break;case"n":case"N":te();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,K,we,N,dt,te,tt,Xe,Ge]);const mr=(P==null?void 0:P.kind)==="youtube"||d==="full"||d==="nobuttons",ut=h>0?e.slice(w+1,w+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),se()},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:(P==null?void 0:P.kind)==="youtube"?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(P==null?void 0:P.kind)==="youtube"&&s.jsx(Yr,{videoId:P.videoId??uu(P.url),onReady:le=>{Q.current=le.target,we(N);const de=(_==null?void 0:_.startOffset)??0;try{de&&le.target.seekTo(de,!0)}catch{}if(d==="nobuttons"){try{le.target.playVideo()}catch{}z(!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:g?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"}}),((P==null?void 0:P.kind)==="audio"||(P==null?void 0:P.kind)==="hls")&&s.jsxs(s.Fragment,{children:[d==="full"&&s.jsx("div",{style:{textAlign:"center",color:"var(--text, #e2e8f0)"},children:_!=null&&_.coverUrl?s.jsx("img",{alt:"cover",src:_.coverUrl,style:{height:a-24,objectFit:"contain"}}):s.jsxs("div",{style:{opacity:.8},children:[s.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[_==null?void 0:_.artist," � ",_==null?void 0:_.title]}),s.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-dim, #94a3b8)"},children:(P==null?void 0:P.label)??`${(P==null?void 0:P.codec)??""} ${(P==null?void 0:P.quality)??""}`.trim()})]})}),s.jsx("audio",{ref:ue,onEnded:yt,onLoadedMetadata:()=>{const le=ue.current;le&&Z(le.duration||0)},crossOrigin:P!=null&&P.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:(_==null?void 0:_.title)??"�"}),s.jsx("div",{style:{color:"var(--text-dim, #64748b)",fontSize:13},children:(_==null?void 0:_.artist)??"�"})]})}),d==="full"&&s.jsxs(s.Fragment,{children:[s.jsx(zo,{currentTime:O,duration:K}),s.jsx(ou,{isPlaying:B,index:w,count:e.length,currentTime:O,duration:K,volume:N,onPrev:tt,onNext:te,onToggle:De,onSeek:Pe,onVolume:we}),s.jsx(du,{shuffleOn:F,repeatMode:E,speed:Y,abLoop:ne,currentTime:O,sleepRemaining:q,onToggleShuffle:Ge,onCycleRepeat:Xe,onSpeedChange:Rn,onSetABLoop:It,onMuteToggle:dt,isMuted:L!==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:K,onSeek:Pe})}),(d==="minimal"||d==="compact")&&s.jsx(lu,{isPlaying:B,canPrev:w>0,canNext:w<e.length-1,onPrev:tt,onNext:te,onToggle:De}),d==="compact"&&ut.length>0&&s.jsx(cu,{items:ut,onPick:le=>Fe(w+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===w?"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"},zo=({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}=ve();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:g=>d(parseFloat(g.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:g=>h(parseFloat(g.target.value)),"aria-label":"Volume"})]})]})},iu=({currentTime:e,duration:t,onSeek:n})=>s.jsxs(s.Fragment,{children:[s.jsx(zo,{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}=ve();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}=ve();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:g}=ve(),m={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:g("player.shuffle","Shuffle"),"aria-label":g("player.shuffle","Shuffle"),style:{...at,opacity:e?1:.4,fontWeight:e?700:400},children:"🔀"}),s.jsx("button",{onClick:l,title:`${g("player.repeat","Repeat")}: ${p[t]}`,"aria-label":`${g("player.repeat","Repeat")}: ${p[t]}`,style:{...at,opacity:t==="none"?.4:1},children:m[t]}),s.jsx("select",{value:n,onChange:y=>c(parseFloat(y.target.value)),title:g("player.speed","Speed"),"aria-label":g("player.speed","Speed"),style:{...at,minWidth:56,fontSize:12},children:su.map(y=>s.jsxs("option",{value:y,children:[y,"x"]},y))}),s.jsx("button",{onClick:h,title:g("player.mute","Mute"),"aria-label":g("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:g("player.clearLoop","Clear loop"),style:{...at,fontSize:11,padding:"2px 6px"},children:"✕"})]}):s.jsx("button",{onClick:()=>d({a,b:a+10}),title:g("player.abLoop","A-B Loop"),"aria-label":g("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),es=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")}`},Cr={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}=ve();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:[es(r)," / ",es(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:Cr,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:Cr,children:e?"⏸":"▶"}),s.jsx("button",{onClick:l,disabled:t>=n-1,title:f("playerControls.next","Next"),"aria-label":f("playerControls.nextTrack","Next track"),style:Cr,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:g=>d(parseFloat(g.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:g=>h(parseFloat(g.target.value))})]})]})]})},Bo=u.memo(fu);function pu(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 mu=({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 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(mu,{active:t===o,onClick:()=>n(o),title:`Tryb: ${o}`,children:o},o))})})},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:"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)})})},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 xu(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,g=n-h,m=c/o*240+a;e.fillStyle=`hsl(${m%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(f+1,g,l-2,h)}}function vu(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,g=n-h,m=c/48*240+a;e.fillStyle=`hsl(${m%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(f+1,g,l-2,h)}}function Su(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()}function wu(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,g=r[f]/255,m=(a+h/12*180+d/6*90)%360,p=70+g*25,y=25+g*35;e.fillStyle=`hsl(${m}, ${p}%, ${y}%)`,e.fillRect(h*l,d*c,Math.ceil(l),Math.ceil(c))}}function Cu(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 g=r[f*i]/255,m=f/96*Math.PI*2,p=d,y=d+g*(h-d),x=l+Math.cos(m)*p,v=c+Math.sin(m)*p,C=l+Math.cos(m)*y,b=c+Math.sin(m)*y;e.strokeStyle=`hsl(${f/96*360+a},85%,60%)`,e.lineWidth=3,e.beginPath(),e.moveTo(x,v),e.lineTo(C,b),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 ku(e,t,n,r,a,o){const i=t/2,l=n/2,c=Math.min(t,n)*.5,d=ts(r,0,Math.floor(r.length*.1))/255,h=ts(r,Math.floor(r.length*.6),r.length)/255;o.current+=.01+h*.03;const f=24;for(let g=0;g<f;g++){const m=o.current+g/f*Math.PI*2,p=(.35+d*.55)*c,y=i+Math.cos(m)*p,x=l+Math.sin(m)*p,v=e.createRadialGradient(i,l,0,i,l,p),C=g/f*360+a;v.addColorStop(0,`hsla(${C},85%,65%,0.0)`),v.addColorStop(1,`hsla(${C},85%,65%,0.9)`),e.strokeStyle=v,e.lineWidth=6+h*8,e.beginPath(),e.moveTo(i,l),e.lineTo(y,x),e.stroke()}e.fillStyle="rgba(2,6,23,0.25)",e.fillRect(0,0,t,n)}function ts(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 Mu(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,g=.5+Math.random()*(2.5+r*4);o.current.push({x:i,y:l,vx:Math.cos(f)*g,vy:Math.sin(f)*g,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 g=1-f.life/f.max;e.fillStyle=`hsla(${f.hue},85%,60%,${Math.max(0,g)})`,e.beginPath(),e.arc(f.x,f.y,2+g*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 ju(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),g=r[f]/255,m=d+h*d*.55+g*d*.5,p=(o+h*40)%360;e.lineWidth=3+g*6,e.strokeStyle=`hsla(${p},80%,60%,${.5+.5*a})`,e.beginPath(),e.arc(i,l,m,0,Math.PI*2),e.stroke()}}function Ru(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),g=r[f]/255,m=(a+h/14*210+d/8*90)%360,p=65+g*30,y=20+g*40,x=(1-g)*4;e.fillStyle=`hsl(${m}, ${p}%, ${y}%)`,e.fillRect(h*l+x,d*c+x,Math.max(1,l-2*x),Math.max(1,c-2*x))}}function $u(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 Tu(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 $u(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 Pu(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,g=1+r*2;for(const p of c.sprites){p.ang+=p.spin*g,p.z-=p.vz*(.8+r*2.4),p.z<40&&(p.z=f);const y=Math.min(t,n)*.32+Math.sin(p.ang*.8)*18;p.x=Math.cos(p.ang)*y,p.y=Math.sin(p.ang*1.1)*y*.6}const m=[...c.sprites].sort((p,y)=>y.z-p.z);for(const p of m){const y=f/(f-p.z)*.6*p.size,x=d+p.x*y,v=h+p.y*y,C=64*y,b=64*y;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,v,C*.7,b*.7,0,0,Math.PI*2),e.fill(),e.restore(),p.img&&p.img.width?e.drawImage(p.img,x-C/2,v-b/2,C,b):(e.save(),e.fillStyle=`hsl(${(a+180)%360}, 40%, 55%)`,e.fillRect(x-C/2,v-b/2,C,b),e.restore())}}function Eu(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}function Au(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 Nu(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,g=h.y/h.z*600,m=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(m,p),e.lineTo(f,g),e.stroke()}e.restore()}function Iu(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),g=f*d;e.strokeStyle=`hsla(${(a+h*30)%360}, 70%, 45%, 0.35)`,e.lineWidth=1,e.beginPath(),e.arc(i,l,g,0,Math.PI*2),e.stroke();const m=Math.floor(r.length*f|0),p=(r[m]??0)/255,y=6+h*2;for(let x=0;x<y;x++){const v=o.current*(1+h*.15)+x/y*Math.PI*2,C=g+Math.sin(v*2)*6*p,b=i+Math.cos(v)*C,k=l+Math.sin(v)*C;e.fillStyle=`hsla(${(a+h*30+x*6)%360}, 90%, ${55+p*30}%, ${.6+p*.3})`,e.beginPath(),e.arc(b,k,2+p*4,0,Math.PI*2),e.fill()}}}function Lu(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,g=h/c*Math.PI*2,m=f*(Math.min(t,n)*.22)+6,p=o+Math.cos(g)*l,y=i+Math.sin(g)*l,x=o+Math.cos(g)*(l+m),v=i+Math.sin(g)*(l+m);e.strokeStyle=`hsl(${(a+h*3)%360}, 90%, ${40+f*40}%)`,e.lineWidth=3,e.beginPath(),e.moveTo(p,y),e.lineTo(x,v),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 Fu(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 g=1;g<3;g++){const m=g*Math.PI*2/3;e.lineTo(Math.cos(m)*f,Math.sin(m)*f)}e.closePath(),e.shadowBlur=12,e.shadowColor=e.strokeStyle,e.stroke(),e.restore()}}function Du(e,t,n,r,a,o){if(!o.current){const f=[];for(let m=0;m<24;m++)f.push({ang:m/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 g=f.baseR+Math.sin(f.phase)*d,m=l+Math.cos(f.ang)*g,p=c+Math.sin(f.ang)*g;h.push([m,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[g,m]=h[f],[p,y]=h[(f+1)%h.length],x=(g+p)/2,v=(m+y)/2;f===0?e.moveTo(x,v):e.quadraticCurveTo(g,m,x,v)}e.closePath(),e.fill(),e.stroke()}function Ou(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 g=f/h*Math.PI*2+r*(.6+a*1.4),m=(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))),y=6;e.save(),e.translate(i,l),e.rotate(g+m),e.beginPath(),e.moveTo(0,0);for(let v=1;v<=y;v++){const C=p/y*v,b=(Math.sin(r*3+f*.8+v)*.6+Math.cos(r*2+f+v*.7))*(8+24*a),k=C,R=b;e.lineTo(R,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 sn(e,t){return e+Math.random()*(t-e)}function _u(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 Ot(e,t){return e+Math.random()*(t-e)}function zu(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 g=(f+.5)/d*t,m=(r[Math.floor((f+1)/(d+1)*r.length)]||0)/255,p=n*.18+(.25+a*.6+m*.7)*n*.55,y=e.createLinearGradient(g,n,g,n-p);y.addColorStop(0,`hsla(${(o+40)%360},100%,55%,.9)`),y.addColorStop(.5,`hsla(${(o+10)%360},100%,60%,.75)`),y.addColorStop(1,`hsla(${(o-20)%360},100%,80%,.05)`);const x=Math.sin(l.t*1.2+f*.8)*(15+a*30);e.fillStyle=y,e.beginPath(),e.moveTo(g-20,n),e.bezierCurveTo(g-35,n-p*.45,g-25+x,n-p*.75,g+x,n-p),e.bezierCurveTo(g+25+x*.3,n-p*.65,g+35,n-p*.35,g+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 g=l.embers[f];if(g.x+=g.vx,g.y+=g.vy,g.vy-=.01,g.life-=.015+a*.02,g.life<=0||g.y<-10){l.embers.splice(f,1);continue}const m=e.createRadialGradient(g.x,g.y,0,g.x,g.y,g.r*3);m.addColorStop(0,`hsla(${(o+25)%360},100%,65%,.9)`),m.addColorStop(1,`hsla(${(o+25)%360},100%,65%,0)`),e.fillStyle=m,e.beginPath(),e.arc(g.x,g.y,g.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 Bu(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 m=0;m<d;m++){const p=(r[m]-128)/128,y=Math.sin(o*1.5+m*.03)*.12,x=m*h,v=i-l-(p+y)*c;m===0?e.moveTo(x,v):e.lineTo(x,v)}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 m=0;m<d;m++){const p=(r[m]-128)/128,y=Math.cos(o*1.3+m*.035)*.12,x=m*h,v=i+l+(p+y)*c;m===0?e.moveTo(x,v):e.lineTo(x,v)}const g=e.createLinearGradient(0,i+l,0,n);g.addColorStop(0,"hsla(190,90%,65%,0.9)"),g.addColorStop(1,"hsla(160,85%,55%,0.4)"),e.strokeStyle=g,e.lineWidth=2,e.stroke(),e.globalCompositeOperation="lighter",e.strokeStyle="rgba(255,255,255,0.08)",e.lineWidth=6,e.beginPath(),e.moveTo(0,i-l),e.lineTo(t,i-l),e.stroke(),e.beginPath(),e.moveTo(0,i+l),e.lineTo(t,i+l),e.stroke(),e.globalCompositeOperation="source-over"}const 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:g=14})=>{const m=u.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette","radial","rays","particles","rings","grid","imageTornado","colorRipples","starfield","orbitals","eqcircle","triangles","blob","plasma","lavaLamp","cozyFire","rift"],[e,h]),p=u.useMemo(()=>{const U=m.includes(c)?c:m[0];try{const L=localStorage.getItem(d);if(!L)return U;const T=JSON.parse(L);return m.includes(T)?T:U}catch{return U}},[m,c,d]),[y,x]=pu(d,p),v=u.useRef(null),C=u.useRef(null),b=u.useRef(null),k=u.useRef(null),R=u.useRef(null),A=u.useRef(null),$=u.useRef(0),W=u.useRef(0),w=u.useRef([]),[D,_]=u.useState(0),P=u.useRef(null),B=u.useRef(null),z=u.useRef(null),K=u.useRef(null),Z=u.useRef(null),O=u.useRef(null),X=u.useRef(null),N=y!=="cover"&&y!=="video";return u.useEffect(()=>{var F;if(e==="youtube"||(C.current&&(cancelAnimationFrame(C.current),C.current=null),!N))return;Et();const U=tn(),L=t.current;if(!L)return;if(!b.current)try{b.current=U.createMediaElementSource(L)}catch{}if(!k.current){const j=U.createAnalyser();j.fftSize=2048,j.smoothingTimeConstant=.85,k.current=j;try{(F=b.current)==null||F.connect(j)}catch{}try{j.connect(U.destination)}catch{}}const T=k.current;R.current=new Uint8Array(T.frequencyBinCount),A.current=new Uint8Array(T.fftSize);const S=()=>{const j=v.current,E=Math.max(1,Math.floor(window.devicePixelRatio||1));j.width=Math.floor(j.clientWidth*E),j.height=Math.floor(j.clientHeight*E);const H=j.getContext("2d");H==null||H.setTransform(1,0,0,1,0,0),H==null||H.scale(E,E)};S();const I=()=>S();window.addEventListener("resize",I),Au(z,220,v.current.width,v.current.height);const M=async()=>{const j=v.current;if(!j)return;const E=j.getContext("2d");if(!E)return;const H=Math.max(1,Math.floor(window.devicePixelRatio||1)),Y=j.width/H,J=j.height/H,ne=performance.now()*.001,ae=y==="waveform"||y==="rift";ae?T.getByteTimeDomainData(A.current):T.getByteFrequencyData(R.current);let re=0;const G=ae?A.current:R.current;for(let q=0;q<G.length;q++){const ee=ae?(G[q]-128)/128:G[q]/255;re+=ee*ee}if(re=Math.sqrt(re/G.length),_(Math.min(1,re)),E.clearRect(0,0,Y,J),y==="spectrum")xu(E,Y,J,R.current,$.current);else if(y==="bars")vu(E,Y,J,R.current,$.current);else if(y==="waveform")Su(E,Y,J,A.current);else if(y==="palette"){const q=($.current+re*120)%360;wu(E,Y,J,R.current,q)}else if(y==="radial")Cu(E,Y,J,R.current,$.current);else if(y==="rays")ku(E,Y,J,R.current,$.current,W);else if(y==="particles")Mu(E,Y,J,re,$.current,w);else if(y==="rings")ju(E,Y,J,R.current,re,$.current);else if(y==="grid"){const q=($.current+re*160)%360;Ru(E,Y,J,R.current,q)}else if(y==="imageTornado"){const q=f!=null&&f.length?f:a?[a]:[];await Tu(P,q,g,Y,J);const ee=($.current+re*100)%360;Pu(E,Y,J,re,ee,P)}else if(y==="colorRipples"){const q=($.current+re*120)%360;Eu(E,Y,J,re,q,B)}else if(y==="starfield"){const q=($.current+60)%360;Nu(E,Y,J,re,q,z)}else if(y==="orbitals"){const q=($.current+re*180)%360;Iu(E,Y,J,R.current,q,W)}else if(y==="eqcircle"){const q=($.current+120)%360;Lu(E,Y,J,R.current,q)}else if(y==="triangles"){const q=($.current+40)%360;Fu(E,Y,J,re,q,K)}else if(y==="blob"){const q=($.current+90)%360;Du(E,Y,J,re,q,Z)}else if(y==="plasma"){const q=($.current+re*200)%360;Ou(E,Y,J,ne,re,q)}else if(y==="rift")Bu(E,Y,J,A.current,re,ne);else if(y==="lavaLamp"){const q=($.current+re*80)%360;_u(E,Y,J,re,q,O)}else if(y==="cozyFire"){const q=($.current+re*140)%360;zu(E,Y,J,R.current,re,q,X)}$.current=($.current+.4)%360,C.current=requestAnimationFrame(M)};return C.current=requestAnimationFrame(M),()=>{window.removeEventListener("resize",I),C.current&&cancelAnimationFrame(C.current)}},[N,e,t,y,f,g,a]),s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none",background:y==="cover"?"transparent":Gu},children:y==="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:v,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:m,active:y,setActive:x,rows:2}),s.jsx(gu,{vu:D,hide:e==="youtube"})]})]})},Go=({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 y=()=>{p.src=r.url,p.load(),t&&p.play().catch(()=>{})};if(p.canPlayType("application/vnd.apple.mpegurl")){y();return}(async()=>{const v=(await import("hls.js")).default;if(v.isSupported()){const C=new v({xhrSetup:b=>{if(r!=null&&r.withCredentials&&(b.withCredentials=!0),r!=null&&r.headers)for(const[k,R]of Object.entries(r.headers))b.setRequestHeader(k,String(R))}});i.current=C,C.loadSource(r.url),C.attachMedia(p),C.on(v.Events.MANIFEST_PARSED,()=>t&&p.play().catch(()=>{}))}else y()})()}(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",g=f?"video":"cover",m=`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:g,storageKey:m},`vis-${m}`)]})};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}),Wo=({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 g=u.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette"],[e,h]),m=u.useMemo(()=>{const P=g.includes(c)?c:g[0];try{const B=localStorage.getItem(d);if(!B)return P;const z=JSON.parse(B);return g.includes(z)?z:P}catch{return P}},[g,c,d]),[p,y]=Wu(d,m),x=u.useRef(null),[v,C]=u.useState(0),b=u.useRef(null),k=u.useRef(null),R=u.useRef(null),A=u.useRef(null),$=u.useRef(null),W=u.useRef(0),w=p==="spectrum"||p==="bars"||p==="waveform"||p==="palette";u.useEffect(()=>{var O;if(e==="youtube")return;if(!w){b.current&&cancelAnimationFrame(b.current);return}Et();const P=tn(),B=t.current;if(!B)return;if(!k.current)try{k.current=P.createMediaElementSource(B)}catch{}if(!R.current){const X=P.createAnalyser();X.fftSize=2048,X.smoothingTimeConstant=.85,R.current=X;try{(O=k.current)==null||O.connect(X)}catch{}try{X.connect(P.destination)}catch{}}const z=R.current;A.current=new Uint8Array(z.frequencyBinCount),$.current=new Uint8Array(z.fftSize);const K=()=>{if(!x.current)return;const X=x.current,N=X.getContext("2d");if(!N)return;const U=X.width,L=X.height;N.clearRect(0,0,U,L),p==="waveform"?z.getByteTimeDomainData($.current):z.getByteFrequencyData(A.current);let T=0;const S=p==="waveform"?$.current:A.current;for(let I=0;I<S.length;I++){const M=p==="waveform"?(S[I]-128)/128:S[I]/255;T+=M*M}if(T=Math.sqrt(T/S.length),C(Math.min(1,T)),p==="spectrum"||p==="bars"){const I=A.current,M=p==="bars"?48:Math.min(I.length,256),F=Math.floor(I.length/M),j=U/M;for(let E=0;E<M;E++){const H=I[E*F]/255,Y=H*(L-6),J=E*j,ne=L-Y,ae=E/M*240+W.current;N.fillStyle=`hsl(${ae%360}, 80%, ${Math.max(30,40+H*30)}%)`,N.fillRect(J+1,ne,j-2,Y)}}else if(p==="waveform"){const I=$.current;N.lineWidth=2,N.strokeStyle="#c7d2fe",N.beginPath();const M=U/I.length;for(let F=0;F<I.length;F++){const j=(I[F]-128)/128,E=F*M,H=L/2+j*(L*.45);F===0?N.moveTo(E,H):N.lineTo(E,H)}N.stroke()}else if(p==="palette"){const F=U/12,j=L/6,E=(W.current+T*120)%360;for(let H=0;H<6;H++)for(let Y=0;Y<12;Y++){const J=(H*12+Y)%A.current.length,ne=A.current[J]/255,ae=(E+Y/12*180+H/6*90)%360,re=70+ne*25,G=25+ne*35;N.fillStyle=`hsl(${ae}, ${re}%, ${G}%)`,N.fillRect(Y*F,H*j,Math.ceil(F),Math.ceil(j))}}N.strokeStyle=getComputedStyle(document.documentElement).getPropertyValue("--waveform-stroke")||"#c7d2fe",b.current=requestAnimationFrame(K)},Z=()=>{var U;const X=x.current,N=Math.max(1,Math.floor(window.devicePixelRatio||1));X.width=Math.floor(X.clientWidth*N),X.height=Math.floor(X.clientHeight*N),(U=X.getContext("2d"))==null||U.scale(N,N)};return Z(),window.addEventListener("resize",Z),b.current=requestAnimationFrame(K),()=>{window.removeEventListener("resize",Z),b.current&&cancelAnimationFrame(b.current)}},[w,e,t,p]);const D=()=>{if(e==="youtube")return null;const P=12,B=Math.round(v*P);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:P}).map((z,K)=>{const Z=120*(K/P);return s.jsx("div",{style:{width:6,height:18,borderRadius:2,background:K<B?`hsl(${Z}, 80%, 50%)`:"#1f2937"}},K)})})},_=()=>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:_()}):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:g.map(P=>s.jsx(Vu,{active:p===P,onClick:()=>y(P),title:`Tryb: ${P}`,children:P},P))}),s.jsx("div",{style:{position:"absolute",right:10,bottom:10,pointerEvents:"none",zIndex:9998},children:s.jsx(D,{})})]})]})},Uo=({artist:e,title:t,hideControls:n=!0,isPlaying:r,onTimeUpdate:a,searchYouTubeByArtistTitle:o})=>{const{t:i}=ve(),[l,c]=u.useState(e||""),[d,h]=u.useState(t||""),[f,g]=u.useState(null),[m,p]=u.useState(null),y=u.useRef(null),[x,v]=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(g)},[e,t,o]),u.useEffect(()=>{m&&(r?m.playVideo():m.pauseVideo())},[r,m]),u.useEffect(()=>{if(m&&a){const b=setInterval(()=>{const k=m.getCurrentTime();a(k)},100);return()=>clearInterval(b)}},[m,a]),u.useEffect(()=>{const b=()=>{if(y.current){const k=y.current.clientWidth,R=Math.round(k*(9/16));v({width:k,height:R})}};return b(),window.addEventListener("resize",b),()=>window.removeEventListener("resize",b)},[]);const C=async()=>{if(!o)return;const b=await o(l,d);g(b)};return s.jsxs("div",{ref:y,style:{width:"100%",maxWidth:"900px",margin:"0 auto"},children:[(!e||!t||!f)&&s.jsxs("div",{children:[s.jsx("input",{value:l,onChange:b=>c(b.target.value),placeholder:i("youtubePlayer.artist","Artist"),"aria-label":i("youtubePlayer.artist","Artist")}),s.jsx("input",{value:d,onChange:b=>h(b.target.value),placeholder:i("youtubePlayer.title","Title"),"aria-label":i("youtubePlayer.title","Title")}),s.jsx("button",{onClick:C,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:b=>p(b.target)}),!n&&s.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px"},children:[s.jsx("button",{onClick:()=>m==null?void 0:m.playVideo(),children:"? Play"}),s.jsx("button",{onClick:()=>m==null?void 0:m.pauseVideo(),children:"? Pause"})]})]})]})},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:g}=t,{onChange:m,onRemove:p,onMoveUp:y,onMoveDown:x,onChangeLp:v,onSelectSource:C}=n,{readOnly:b=!1,canMoveUp:k=!0,canMoveDown:R=!0,activeSource:A}=r,{t:$}=ve(),W=u.useRef(null);u.useEffect(()=>{!i&&W.current&&W.current.focus()},[i]);const w=B=>{if(!b&&B.key==="Enter"){const z=B.target.closest("div.gpi-row"),K=z==null?void 0:z.querySelectorAll("input[data-role='field']");if(!K||K.length===0)return;const Z=Array.from(K).indexOf(B.target),O=K[Z+1]??K[0];O==null||O.focus()}},D=B=>{const z=h.includes(B),K=A===B,Z={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid #e5e7eb",background:K?"var(--active-bg, #eef2ff)":"var(--bg, #fff)",opacity:z?1:.35,cursor:z&&C&&!b?"pointer":"default",transition:"transform .05s ease"},O=B==="youtube"?"#FF0000":B==="spotify"?"#1DB954":B==="tidal"?"#111827":B==="hls"?"#7C3AED":"#374151",X=B==="youtube"?Ia.faYoutube:B==="spotify"?Ia.faSpotify:B==="tidal"?xr.faGem:B==="hls"?xr.faWaveSquare:xr.faMusic,N=B==="youtube"?"YouTube":B==="spotify"?"Spotify":B==="tidal"?"TIDAL":B==="hls"?"HLS":"Audio",U=$("playlistItem.sourceLabel")+": "+N+(K?` ${$("playlistItem.sourceSelected")}`:""),L=()=>{!z||!C||b||C(B)};return s.jsx("button",{type:"button",title:N,onClick:L,disabled:!z||b,style:Z,"aria-pressed":K,"aria-label":U,children:s.jsx(Fl.FontAwesomeIcon,{icon:X,style:{color:O}})},B)},_=["youtube","tidal","spotify","hls","audio"],P=typeof d=="number"?d:o+1;return s.jsxs("div",{className:"gpi-row",role:"group","aria-label":$("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:P,onChange:B=>v==null?void 0:v(Number(B.target.value)),disabled:b||!v,"aria-label":"Lp",title:$("playlistItem.positionOnList"),style:qu}),s.jsx("input",{ref:W,"data-role":"field",type:"text",value:i,onChange:B=>m({artist:B.target.value}),placeholder:"Artist",onKeyDown:w,disabled:b,"aria-label":"Artist",className:"gpi-input",style:kr}),s.jsx("input",{"data-role":"field",type:"text",value:l,onChange:B=>m({title:B.target.value}),placeholder:"Title",onKeyDown:w,disabled:b,"aria-label":"Title",className:"gpi-input",style:kr}),f&&s.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:B=>m({version:B.target.value||void 0}),placeholder:$("playlistItem.versionOptional"),onKeyDown:w,disabled:b,"aria-label":"Version",className:"gpi-input",style:kr}),s.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":$("playlistItem.availableSources"),children:_.map(D)}),s.jsxs("div",{className:"gpi-actions",style:{display:"flex",gap:6,justifyContent:"flex-end"},children:[g&&s.jsx("button",{type:"button",...g,draggable:!0,"aria-label":$("playlistItem.dragReorder"),title:$("playlistItem.dragReorder"),style:Nn,children:"≡"}),s.jsx("button",{type:"button",onClick:y,disabled:!k||b,"aria-label":$("playlistItem.moveUp"),title:$("playlistItem.moveUp"),style:Nn,children:"↑"}),s.jsx("button",{type:"button",onClick:x,disabled:!R||b,"aria-label":$("playlistItem.moveDown"),title:$("playlistItem.moveDown"),style:Nn,children:"↓"}),s.jsx("button",{type:"button",onClick:p,disabled:b,"aria-label":$("common.delete"),title:$("common.delete"),style:{...Nn,color:"var(--danger, #b91c1c)"},children:"✕"})]})]})},qu={width:48,border:"1px solid #e5e7eb",borderRadius:6,padding:"8px 6px",fontSize:14,textAlign:"center"},kr={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})),Hu=e=>e.map(({id:t,...n})=>n),Ku=null,Yu=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}},Vo=({value:e,defaultValue:t,onChange:n,allowVersion:r=!0,maxItems:a,addButtonLabel:o,emptyState:i=Ku,readOnly:l=!1,autoFocusNewItem:c=!0,enableBulkPaste:d=!0})=>{const{t:h}=ve(),f=e!==void 0,[g,m]=u.useState(()=>In(e||t)),[p,y]=u.useState(""),x=u.useRef(null),[v,C]=u.useState(null);u.useEffect(()=>{f&&m(In(e))},[f,JSON.stringify(e)]);const b=u.useCallback(N=>{n==null||n(Hu(N))},[n]),k=u.useCallback(N=>{if(f){const U=N(In(e));b(U)}else m(U=>{const L=N(U);return b(L),L})},[b,f,e]),R=a?g.length<a:!0,A=u.useCallback(()=>{!R||l||k(N=>[...N,{id:_r(),artist:"",title:"",version:void 0}])},[R,l,k]),$=u.useCallback((N,U)=>{k(L=>L.map(T=>T.id===N?{...T,...U}:T))},[k]),W=u.useCallback(N=>{l||k(U=>U.filter(L=>L.id!==N))},[l,k]),w=u.useCallback((N,U)=>{k(L=>{const T=L.findIndex(F=>F.id===N);if(T<0)return L;const S=T+U;if(S<0||S>=L.length)return L;const I=[...L],[M]=I.splice(T,1);return I.splice(S,0,M),I})},[k]),D=u.useCallback((N,U)=>{k(L=>{const T=L.findIndex(F=>F.id===N);if(T<0)return L;const S=Math.max(0,Math.min(L.length-1,U-1));if(T===S)return L;const I=[...L],[M]=I.splice(T,1);return I.splice(S,0,M),I})},[k]),_=N=>U=>{l||(x.current=N,U.dataTransfer.effectAllowed="move",U.dataTransfer.setData("text/plain",N))},P=N=>U=>{l||(U.preventDefault(),U.dataTransfer.dropEffect="move",C(N))},B=N=>()=>C(U=>U===N?null:U),z=N=>U=>{if(l)return;U.preventDefault();const L=x.current??U.dataTransfer.getData("text/plain");C(null),x.current=null,!(!L||L===N)&&k(T=>{const S=T.findIndex(j=>j.id===L),I=T.findIndex(j=>j.id===N);if(S<0||I<0||S===I)return T;const M=[...T],[F]=M.splice(S,1);return M.splice(I,0,F),M})},K=()=>{x.current=null,C(null)},Z=u.useCallback(()=>{if(!d||l)return;const U=p.split(/\r?\n/).map(L=>L.trim()).filter(Boolean).map(Yu).filter(L=>!!L);U.length!==0&&(k(L=>{const T=(a??1/0)-L.length,S=U.slice(0,Math.max(0,T)).map(I=>({id:_r(),...I}));return[...L,...S]}),y(""))},[d,l,p,a,k]);u.useEffect(()=>{},[g.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.")}),X=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:A,disabled:!R||l,className:"gp-add",style:{padding:"6px 10px",borderRadius:6,border:"1px solid #d1d5db",background:"#f9fafb"},"aria-label":X,children:["+ ",X]})})]}),g.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:g.map((N,U)=>{const L=v===N.id;return s.jsx("li",{draggable:!l,onDragStart:_(N.id),onDragOver:P(N.id),onDragLeave:B(N.id),onDrop:z(N.id),onDragEnd:K,style:{border:L?"2px dashed #6366f1":"2px solid transparent",borderRadius:8,padding:L?4:0},children:s.jsx(pa,{data:{id:N.id,index:U,lp:U+1,artist:N.artist,title:N.title,version:r?N.version??void 0:void 0,sourcesAvailable:void 0},display:{allowVersion:r,dragHandleProps:{onDragStart:_(N.id)}},callbacks:{onChange:T=>$(N.id,T),onRemove:()=>W(N.id),onMoveUp:()=>w(N.id,-1),onMoveDown:()=>w(N.id,1),onChangeLp:T=>D(N.id,T)},state:{readOnly:l,canMoveUp:U>0,canMoveDown:U<g.length-1}})},N.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:N=>y(N.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:"#222",borderRadius:4,width:"100%",maxWidth:600,display:"block"},role:"img","aria-label":"Waveform and RMS visualization canvas",ref:L=>{if(!L)return;const T=L.getContext("2d");if(T){T.clearRect(0,0,600,100),T.strokeStyle="#0ff",T.beginPath();for(let S=0;S<c.length;S+=Math.ceil(c.length/600)){const I=S/c.length*600,M=50-c[S]*48;S===0?T.moveTo(I,M):T.lineTo(I,M)}if(T.stroke(),v.length>0){T.strokeStyle="#ff0",T.beginPath();for(let S=0;S<v.length;S++){const I=S/v.length*600,M=100-v[S]*90;S===0?T.moveTo(I,M):T.lineTo(I,M)}T.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&&C.length===0&&!A&&s.jsx("div",{style:{marginTop:16,color:"#aaa"},children:s.jsx("i",{children:o("audioPitch.noNotesDetected")})}),h&&Object.keys(g).length>0&&s.jsxs("div",{style:{marginTop:16},children:[s.jsx("h4",{children:o("audioPitch.algorithmComparison")}),Object.entries(g).map(([L,T])=>s.jsxs("div",{style:{marginBottom:12},children:[s.jsx("b",{children:L}),": ",o("audioPitch.detectedSegments")," ",T.length,s.jsx("pre",{style:{background:"#111",color:"#ddd",padding:8,borderRadius:4,marginTop:8},children:T.map(S=>`: ${Math.round(S.start*10)} ${Math.round(S.duration*10)} ${S.pitch} [${S.freq.toFixed(1)} Hz]`).join(`
47
+ `)})]},L))]})]})}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 Hd=[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",Kd=[{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"},...Hd.map(e=>({value:e.family,label:e.family}))],To=[{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 Ja=!1;function Po(){try{const e=localStorage.getItem(da);if(e){const t=JSON.parse(e);return{...Jt,...t}}}catch{}return{...Jt}}async function Yd(e){if(Ja||(Ja=!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 Zd(e){const t=JSON.stringify(e);localStorage.setItem(da,t),ua(e)}function Eo(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=To.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}=Eo(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 Xd(){const e=Po();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)"],Ao={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 No(e,t){const n=Ao[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 Io(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 Lo(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:Io(i.pitch,t),lineIndex:a,noteIndex:o})}return r.sort((a,o)=>a.note.startTime-o.note.startTime),r}class Qd{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,g,m,p,y;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 v=i.lane,x=o.indexOf(!0);if(o[v]){const C=Or(i.note.pitch);this.config.onPitch(C),a-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=a,(m=(g=this.config).onHitFeedback)==null||m.call(g,{type:"perfect",lane:v,time:a}))}else if(x>=0){const b=Math.abs(x-v)*3,k=Or(i.note.pitch+b);this.config.onPitch(k),a-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=a,(y=(p=this.config).onHitFeedback)==null||y.call(p,{type:"miss",lane:x,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=No(n,t.difficulty),this.events=Lo(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 Jd(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 eu=({index:e,style:t,lines:n,notes:r,currentIndex:a,animationConfig:o})=>{const i=n[e]??"",l=r.findIndex(x=>x.lineIndex===e),c=l>=0&&l===a,d=(o==null?void 0:o.enabled)??!0,h=(o==null?void 0:o.durationMs)??300,f=(o==null?void 0:o.translateX)??8,g=(o==null?void 0:o.scale)??1.01,m=(o==null?void 0:o.easing)??"cubic-bezier(.22,1,.36,1)",p=(o==null?void 0:o.opacityInactive)??.9,y=(o==null?void 0:o.boxShadow)??"0 6px 18px rgba(3,102,214,0.08)",v={transition:d?`transform ${h}ms ${m}, opacity ${h}ms ${m}`:"none",transform:c?`translateX(${f}px) scale(${g})`:"translateX(0px) scale(1)",opacity:c?1:p,boxShadow:c?y:"none"};return s.jsx("div",{style:{...t,padding:"4px 6px",borderRadius:4},"data-note-idx":l>=0?l:void 0,children:s.jsx("div",{style:{...v,background:c?"rgba(0,130,200,0.12)":"transparent",padding:"4px 6px",borderRadius:4},children:s.jsx("code",{style:{fontFamily:"monospace",whiteSpace:"pre-wrap"},children:i})})})},Fo=({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(()=>Jd(e),[e]),h=u.useRef(null),f=u.useRef(null),g=u.useRef(0),m=u.useRef(0),[p,y]=u.useState(-1),v=u.useMemo(()=>(e||"").split(/\r?\n/),[e]),x=28,C=v.length*x,b=u.useMemo(()=>({lines:v,notes:d,currentIndex:p,animationConfig:r}),[v,d,p,r]);return u.useEffect(()=>{const k=i.current;k&&(l?k.play().catch(()=>c(!1)):k.pause())},[l,i]),u.useEffect(()=>{const k=i.current;if(!k)return;let R=-1;const A=r??null,$=A&&typeof A.scrollSmooth=="number"?A.scrollSmooth:.18;let W=performance.now();const w=()=>{var U,L,T,S;const D=performance.now(),_=Math.max(0,Math.min(.2,(D-W)/1e3));W=D;const P=k.currentTime||0;g.current=P;let B=-1;for(let I=0;I<d.length;I++){const M=d[I];if(P>=M.start&&P<M.start+Math.max(.001,M.duration)){B=I;break}}B!==R&&(R=B,y(B));let z=0;if(R>=0){const I=((U=d[R])==null?void 0:U.lineIndex)??0,M=((T=(L=h.current)==null?void 0:L.element)==null?void 0:T.clientHeight)??220;z=I*x-M/2+x/2;const F=Math.max(0,C-M);(isNaN(z)||!isFinite(z))&&(z=0),z=Math.max(0,Math.min(z,F))}const K=1-Math.pow(Math.max(0,1-$),Math.min(4,_*60)),N=(((r==null?void 0:r.scrollEasing)||"easeOutCubic")==="linear"?(I=>I):I=>1-Math.pow(1-I,3))(K);m.current=m.current+(z-m.current)*N;try{const I=(S=h.current)==null?void 0:S.element;I&&typeof I.scrollTop=="number"&&(I.scrollTop=Math.round(m.current))}catch{}f.current=requestAnimationFrame(w)};return f.current=requestAnimationFrame(w),()=>{f.current&&cancelAnimationFrame(f.current)}},[i,d,C,r,h]),s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[s.jsx("button",{onClick:()=>c(k=>!k),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(Fl.List,{defaultHeight:220,rowCount:v.length,rowHeight:x,listRef:h,rowComponent:eu,rowProps:b,style:{width:"100%"}}):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 tu(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 Do({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}=tu(e);i.current=h,l.current=f;const g=c.current;g&&"rebuildTexts"in g&&typeof g.rebuildTexts=="function"&&g.rebuildTexts()},[e]),u.useEffect(()=>{let h=!0;return(async()=>{var A;if(!h||!a.current)return;const f=await import("phaser"),g="default"in f?f.default:f;if(!a.current||!h)return;const m=i,p=l,y=c,v=n,x=r,C=d;class b extends g.Scene{constructor(){super({key:"preview"}),this.texts=[],this.audioEl=null}create(){if(y.current=this,this.rebuildTexts(),x!=null&&x.current)this.audioEl=null;else if(v!=null&&v.current)this.audioEl=v.current;else{const W=document.querySelector("audio");W instanceof HTMLAudioElement?this.audioEl=W:C.current?(this.audioEl=document.createElement("audio"),this.audioEl.src=C.current,this.audioEl.preload="metadata",this.audioEl.style.display="none",document.body.appendChild(this.audioEl)):this.audioEl=null}}rebuildTexts(){for(const P of this.texts)P.destroy();this.texts=[];const W={font:"18px monospace",color:"#ffffff"},w=22;let D=20;const _=m.current;for(let P=0;P<_.length;P++){const B=this.add.text(10,D,_[P]||" ",W).setOrigin(0,0);this.texts.push(B),D+=w}}update(){let W=0;if(x!=null&&x.current&&typeof x.current.getCurrentTime=="function")try{W=x.current.getCurrentTime()||0}catch{W=0}else W=this.audioEl&&this.audioEl.currentTime||0;for(let D=0;D<this.texts.length;D++)this.texts[D].setStyle({backgroundColor:void 0,color:"#ffffff"});const w=p.current;for(const D of w)if(W>=D.start&&W<D.start+Math.max(.001,D.duration)){const _=this.texts[D.lineIndex];_&&_.setStyle({backgroundColor:"rgba(0,130,200,0.16)",color:"#00aaff"})}}}const k=((A=a.current)==null?void 0:A.clientWidth)??640,R={type:g.AUTO,parent:a.current,width:k,height:Math.round(k/2),backgroundColor:"#101010",scene:[b]};o.current=new g.Game(R)})(),()=>{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 nu=et.scoped("GenericPlayer"),ru=e=>/youtu(\.be|be\.com)/i.test(e),Oo=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),au=e=>!!e&&/\.(mp3|aac|m4a|flac|wav|ogg)(\?.*)?$/i.test(e),su=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&&ru(i.url)))??null;if(n)return n;const r=t("hls")||e.sources.find(i=>i.url&&Oo(i.url))||null;if(r)return r;const a=t("audio")||e.sources.find(i=>i.url&&au(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")}`},ou=[.25,.5,.75,1,1.25,1.5,1.75,2],_o=({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:g=!1,onEnded:m,enableKeyboardShortcuts:p=!0,shuffle:y=!1,repeatMode:v="none",playbackSpeed:x=1,abLoop:C=null,onRepeatModeChange:b,onShuffleChange:k,onSpeedChange:R,sleepTimer:A=0,onSleepTimerExpired:$})=>{const{t:W}=xe(),[w,D]=u.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),_=e[w],P=u.useMemo(()=>su(_),[_]),[B,z]=u.useState(!1),[K,Z]=u.useState(0),[O,X]=u.useState(0),[N,U]=u.useState(.9),[L,T]=u.useState(null),[S,I]=u.useState(null),M=u.useRef(null),[F,j]=u.useState(y),[E,H]=u.useState(v),[Y,J]=u.useState(x),[ne,ae]=u.useState(C),[re,G]=u.useState([]),[q,ee]=u.useState(A>0?A*60:null),oe=u.useRef(null),[ce,fe]=u.useState(()=>Ns()),Q=u.useRef(null),ue=u.useRef(null),ye=u.useRef(null),je=u.useRef(null);u.useEffect(()=>{if(F&&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]]}G(le)}},[F,e.length]),u.useEffect(()=>(oe.current&&(window.clearInterval(oe.current),oe.current=null),A>0&&B&&(ee(A*60),oe.current=window.setInterval(()=>{ee(le=>!le||le<=1?(oe.current&&window.clearInterval(oe.current),oe.current=null,$==null||$(),null):le-1)},1e3)),()=>{oe.current&&window.clearInterval(oe.current)}),[A,B]);const Fe=u.useCallback(le=>{const de=Math.min(Math.max(0,le),Math.max(0,e.length-1));D(de),o==null||o(de)},[e.length,o]),Re=u.useCallback(()=>{if(F&&re.length>0){const de=re.indexOf(w)+1;return de<re.length?re[de]:E==="all"?re[0]:-1}return w<e.length-1?w+1:E==="all"?0:-1},[w,e.length,F,re,E]),Se=u.useCallback(()=>{if(F&&re.length>0){const le=re.indexOf(w);return le>0?re[le-1]:E==="all"?re[re.length-1]:-1}return w>0?w-1:E==="all"?e.length-1:-1},[w,e.length,F,re,E]),te=u.useCallback(()=>{const le=Re();le>=0&&Fe(le)},[Re,Fe]),se=u.useCallback(async()=>{var le,de;await Et(),fe(!0),(P==null?void 0:P.kind)==="youtube"?(le=Q.current)==null||le.playVideo():(de=ue.current)==null||de.play(),z(!0),i==null||i(!0)},[P,i]),Ne=u.useCallback(()=>{var le,de;(P==null?void 0:P.kind)==="youtube"?(le=Q.current)==null||le.pauseVideo():(de=ue.current)==null||de.pause(),z(!1),i==null||i(!1)},[P,i]),De=u.useCallback(()=>B?Ne():se(),[B,se,Ne]),Pe=u.useCallback(le=>{var ie;const de=(_==null?void 0:_.startOffset)??0,Ce=le+de;(P==null?void 0:P.kind)==="youtube"?(ie=Q.current)==null||ie.seekTo(Ce,!0):ue.current&&(ue.current.currentTime=Ce);const xt=Math.max(0,le);X(xt),l==null||l(xt)},[P,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;U(le),T(null),(P==null?void 0:P.kind)==="youtube"?(Ce=(de=Q.current)==null?void 0:de.setVolume)==null||Ce.call(de,Math.round(le*100)):ue.current&&(ue.current.volume=le)},[P]),dt=u.useCallback(()=>{L!==null?we(L):(T(N),we(0))},[N,L,we]),Rn=u.useCallback(le=>{var de,Ce;J(le),ue.current&&(ue.current.playbackRate=le),(P==null?void 0:P.kind)==="youtube"&&((Ce=(de=Q.current)==null?void 0:de.setPlaybackRate)==null||Ce.call(de,le)),R==null||R(le)},[P,R]),Xe=u.useCallback(()=>{const le=["none","all","one"],de=le[(le.indexOf(E)+1)%le.length];H(de),b==null||b(de)},[E,b]),Ge=u.useCallback(()=>{const le=!F;j(le),k==null||k(le)},[F,k]),It=u.useCallback(le=>{ae(le)},[]);u.useImperativeHandle(c,()=>({play:se,pause:Ne,toggle:De,seekTo:Pe,setVolume:we,setSpeed:Rn,setRepeatMode:le=>{H(le),b==null||b(le)},toggleShuffle:Ge,setABLoop:It,getUnderlyingPlayer:()=>(P==null?void 0:P.kind)==="youtube"?Q.current:(P==null?void 0:P.kind)==="hls"||(P==null?void 0:P.kind)==="audio"?ue.current:null}),[se,Ne,De,Pe,we,Rn,Ge,It,P==null?void 0:P.kind]),u.useEffect(()=>{const le=window.setInterval(()=>{let de=0,Ce=0;(P==null?void 0:P.kind)==="youtube"&&Q.current?(de=Q.current.getCurrentTime()||0,Ce=Q.current.getDuration()||0):ue.current&&(de=ue.current.currentTime||0,Ce=ue.current.duration||0);const xt=(_==null?void 0:_.startOffset)??0,ie=Math.max(0,de-xt);X(ie),Z(Ce),l==null||l(ie),ne&&ie>=ne.b&&Pe(ne.a)},250);return()=>window.clearInterval(le)},[P==null?void 0:P.kind,l,ne]),u.useEffect(()=>()=>{M.current&&(window.clearInterval(M.current),M.current=null)},[]),u.useEffect(()=>{if(ye.current){try{ye.current.destroy()}catch{}ye.current=null}if(ue.current&&(ue.current.volume=N,ue.current.crossOrigin=P!=null&&P.withCredentials?"use-credentials":"anonymous"),(P==null?void 0:P.kind)==="hls"&&Oo(P.url)){const le=ue.current;if(!le)return;const de=()=>{le.src=P.url,le.load();const Ce=(_==null?void 0:_.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(P!=null&&P.withCredentials&&(Oe.withCredentials=!0),P!=null&&P.headers)for(const[ve,me]of Object.entries(P.headers))try{Oe.setRequestHeader(ve,me)}catch{}}});ye.current=he,he.loadSource(P.url),he.attachMedia(le),he.on(ie.Events.MANIFEST_PARSED,()=>{n&&le.play().catch(()=>{})})}else de()}catch(xt){nu.debug("HLS.js setup failed, falling back to native playback",xt),de()}})()}else if((P==null?void 0:P.kind)==="audio"&&P.url&&ue.current){const le=ue.current;le.src=P.url,le.load();const de=(_==null?void 0:_.startOffset)??0;try{de&&!isNaN(de)&&(le.currentTime=de)}catch{}n&&le.play().catch(()=>{})}M.current&&(window.clearInterval(M.current),M.current=null),I(null),X(0),Z(0),n&&(P==null?void 0:P.kind)==="youtube"&&r>0?(I(r),M.current=window.setInterval(()=>{I(le=>{var de;if(!le)return null;if(le<=1){M.current&&(window.clearInterval(M.current),M.current=null);try{(de=Q.current)==null||de.playVideo()}catch{}return z(!0),i==null||i(!0),null}return le-1})},1e3)):z(!!n)},[P==null?void 0:P.url,P==null?void 0:P.kind,P==null?void 0:P.withCredentials,JSON.stringify(P==null?void 0:P.headers),n,N]);const yt=u.useCallback(()=>{if(E==="one"){Pe(0),se();return}const le=Re();le>=0?Fe(le):(z(!1),i==null||i(!1),Pe(0),m==null||m())},[E,Re,Fe,i,Pe,m,se]);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,K));break;case"ArrowLeft":de.preventDefault(),Pe(Math.max(0,O-5));break;case"ArrowUp":de.preventDefault(),we(Math.min(1,N+.05));break;case"ArrowDown":de.preventDefault(),we(Math.max(0,N-.05));break;case"m":case"M":dt();break;case"n":case"N":te();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,K,we,N,dt,te,tt,Xe,Ge]);const mr=(P==null?void 0:P.kind)==="youtube"||d==="full"||d==="nobuttons",ut=h>0?e.slice(w+1,w+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),se()},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:(P==null?void 0:P.kind)==="youtube"?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(P==null?void 0:P.kind)==="youtube"&&s.jsx(Yr,{videoId:P.videoId??hu(P.url),onReady:le=>{Q.current=le.target,we(N);const de=(_==null?void 0:_.startOffset)??0;try{de&&le.target.seekTo(de,!0)}catch{}if(d==="nobuttons"){try{le.target.playVideo()}catch{}z(!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:g?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"}}),((P==null?void 0:P.kind)==="audio"||(P==null?void 0:P.kind)==="hls")&&s.jsxs(s.Fragment,{children:[d==="full"&&s.jsx("div",{style:{textAlign:"center",color:"var(--text, #e2e8f0)"},children:_!=null&&_.coverUrl?s.jsx("img",{alt:"cover",src:_.coverUrl,style:{height:a-24,objectFit:"contain"}}):s.jsxs("div",{style:{opacity:.8},children:[s.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[_==null?void 0:_.artist," � ",_==null?void 0:_.title]}),s.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-dim, #94a3b8)"},children:(P==null?void 0:P.label)??`${(P==null?void 0:P.codec)??""} ${(P==null?void 0:P.quality)??""}`.trim()})]})}),s.jsx("audio",{ref:ue,onEnded:yt,onLoadedMetadata:()=>{const le=ue.current;le&&Z(le.duration||0)},crossOrigin:P!=null&&P.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:(_==null?void 0:_.title)??"�"}),s.jsx("div",{style:{color:"var(--text-dim, #64748b)",fontSize:13},children:(_==null?void 0:_.artist)??"�"})]})}),d==="full"&&s.jsxs(s.Fragment,{children:[s.jsx(zo,{currentTime:O,duration:K}),s.jsx(iu,{isPlaying:B,index:w,count:e.length,currentTime:O,duration:K,volume:N,onPrev:tt,onNext:te,onToggle:De,onSeek:Pe,onVolume:we}),s.jsx(uu,{shuffleOn:F,repeatMode:E,speed:Y,abLoop:ne,currentTime:O,sleepRemaining:q,onToggleShuffle:Ge,onCycleRepeat:Xe,onSpeedChange:Rn,onSetABLoop:It,onMuteToggle:dt,isMuted:L!==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(lu,{currentTime:O,duration:K,onSeek:Pe})}),(d==="minimal"||d==="compact")&&s.jsx(cu,{isPlaying:B,canPrev:w>0,canNext:w<e.length-1,onPrev:tt,onNext:te,onToggle:De}),d==="compact"&&ut.length>0&&s.jsx(du,{items:ut,onPick:le=>Fe(w+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===w?"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"},zo=({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)]})]}),iu=({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:g=>d(parseFloat(g.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:g=>h(parseFloat(g.target.value)),"aria-label":"Volume"})]})]})},lu=({currentTime:e,duration:t,onSeek:n})=>s.jsxs(s.Fragment,{children:[s.jsx(zo,{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"})]}),cu=({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:"?"})]})},du=({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))})]})},uu=({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:g}=xe(),m={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:g("player.shuffle","Shuffle"),"aria-label":g("player.shuffle","Shuffle"),style:{...at,opacity:e?1:.4,fontWeight:e?700:400},children:"🔀"}),s.jsx("button",{onClick:l,title:`${g("player.repeat","Repeat")}: ${p[t]}`,"aria-label":`${g("player.repeat","Repeat")}: ${p[t]}`,style:{...at,opacity:t==="none"?.4:1},children:m[t]}),s.jsx("select",{value:n,onChange:y=>c(parseFloat(y.target.value)),title:g("player.speed","Speed"),"aria-label":g("player.speed","Speed"),style:{...at,minWidth:56,fontSize:12},children:ou.map(y=>s.jsxs("option",{value:y,children:[y,"x"]},y))}),s.jsx("button",{onClick:h,title:g("player.mute","Mute"),"aria-label":g("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:g("player.clearLoop","Clear loop"),style:{...at,fontSize:11,padding:"2px 6px"},children:"✕"})]}):s.jsx("button",{onClick:()=>d({a,b:a+10}),title:g("player.abLoop","A-B Loop"),"aria-label":g("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 hu(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 fu=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),es=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")}`},Cr={border:"1px solid #d1d5db",borderRadius:8,padding:"6px 10px",background:"#fff",cursor:"pointer"},pu=({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:[es(r)," / ",es(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:Cr,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:Cr,children:e?"⏸":"▶"}),s.jsx("button",{onClick:l,disabled:t>=n-1,title:f("playerControls.next","Next"),"aria-label":f("playerControls.nextTrack","Next track"),style:Cr,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:g=>d(parseFloat(g.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:g=>h(parseFloat(g.target.value))})]})]})]})},Bo=u.memo(pu);function mu(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=({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 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(gu,{active:t===o,onClick:()=>n(o),title:`Tryb: ${o}`,children:o},o))})})},yu=({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)})})},bu="#94a3b8",vu=({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:bu},children:a??r??"—"})]})});function xu(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,g=n-h,m=c/o*240+a;e.fillStyle=`hsl(${m%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(f+1,g,l-2,h)}}function Su(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,g=n-h,m=c/48*240+a;e.fillStyle=`hsl(${m%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(f+1,g,l-2,h)}}function wu(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()}function Cu(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,g=r[f]/255,m=(a+h/12*180+d/6*90)%360,p=70+g*25,y=25+g*35;e.fillStyle=`hsl(${m}, ${p}%, ${y}%)`,e.fillRect(h*l,d*c,Math.ceil(l),Math.ceil(c))}}function ku(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 g=r[f*i]/255,m=f/96*Math.PI*2,p=d,y=d+g*(h-d),v=l+Math.cos(m)*p,x=c+Math.sin(m)*p,C=l+Math.cos(m)*y,b=c+Math.sin(m)*y;e.strokeStyle=`hsl(${f/96*360+a},85%,60%)`,e.lineWidth=3,e.beginPath(),e.moveTo(v,x),e.lineTo(C,b),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 Mu(e,t,n,r,a,o){const i=t/2,l=n/2,c=Math.min(t,n)*.5,d=ts(r,0,Math.floor(r.length*.1))/255,h=ts(r,Math.floor(r.length*.6),r.length)/255;o.current+=.01+h*.03;const f=24;for(let g=0;g<f;g++){const m=o.current+g/f*Math.PI*2,p=(.35+d*.55)*c,y=i+Math.cos(m)*p,v=l+Math.sin(m)*p,x=e.createRadialGradient(i,l,0,i,l,p),C=g/f*360+a;x.addColorStop(0,`hsla(${C},85%,65%,0.0)`),x.addColorStop(1,`hsla(${C},85%,65%,0.9)`),e.strokeStyle=x,e.lineWidth=6+h*8,e.beginPath(),e.moveTo(i,l),e.lineTo(y,v),e.stroke()}e.fillStyle="rgba(2,6,23,0.25)",e.fillRect(0,0,t,n)}function ts(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 ju(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,g=.5+Math.random()*(2.5+r*4);o.current.push({x:i,y:l,vx:Math.cos(f)*g,vy:Math.sin(f)*g,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 g=1-f.life/f.max;e.fillStyle=`hsla(${f.hue},85%,60%,${Math.max(0,g)})`,e.beginPath(),e.arc(f.x,f.y,2+g*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 Ru(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),g=r[f]/255,m=d+h*d*.55+g*d*.5,p=(o+h*40)%360;e.lineWidth=3+g*6,e.strokeStyle=`hsla(${p},80%,60%,${.5+.5*a})`,e.beginPath(),e.arc(i,l,m,0,Math.PI*2),e.stroke()}}function $u(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),g=r[f]/255,m=(a+h/14*210+d/8*90)%360,p=65+g*30,y=20+g*40,v=(1-g)*4;e.fillStyle=`hsl(${m}, ${p}%, ${y}%)`,e.fillRect(h*l+v,d*c+v,Math.max(1,l-2*v),Math.max(1,c-2*v))}}function Tu(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 Pu(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 Tu(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 Eu(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,g=1+r*2;for(const p of c.sprites){p.ang+=p.spin*g,p.z-=p.vz*(.8+r*2.4),p.z<40&&(p.z=f);const y=Math.min(t,n)*.32+Math.sin(p.ang*.8)*18;p.x=Math.cos(p.ang)*y,p.y=Math.sin(p.ang*1.1)*y*.6}const m=[...c.sprites].sort((p,y)=>y.z-p.z);for(const p of m){const y=f/(f-p.z)*.6*p.size,v=d+p.x*y,x=h+p.y*y,C=64*y,b=64*y;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(v,x,C*.7,b*.7,0,0,Math.PI*2),e.fill(),e.restore(),p.img&&p.img.width?e.drawImage(p.img,v-C/2,x-b/2,C,b):(e.save(),e.fillStyle=`hsl(${(a+180)%360}, 40%, 55%)`,e.fillRect(v-C/2,x-b/2,C,b),e.restore())}}function Au(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}function Nu(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 Iu(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,g=h.y/h.z*600,m=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(m,p),e.lineTo(f,g),e.stroke()}e.restore()}function Lu(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),g=f*d;e.strokeStyle=`hsla(${(a+h*30)%360}, 70%, 45%, 0.35)`,e.lineWidth=1,e.beginPath(),e.arc(i,l,g,0,Math.PI*2),e.stroke();const m=Math.floor(r.length*f|0),p=(r[m]??0)/255,y=6+h*2;for(let v=0;v<y;v++){const x=o.current*(1+h*.15)+v/y*Math.PI*2,C=g+Math.sin(x*2)*6*p,b=i+Math.cos(x)*C,k=l+Math.sin(x)*C;e.fillStyle=`hsla(${(a+h*30+v*6)%360}, 90%, ${55+p*30}%, ${.6+p*.3})`,e.beginPath(),e.arc(b,k,2+p*4,0,Math.PI*2),e.fill()}}}function Fu(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,g=h/c*Math.PI*2,m=f*(Math.min(t,n)*.22)+6,p=o+Math.cos(g)*l,y=i+Math.sin(g)*l,v=o+Math.cos(g)*(l+m),x=i+Math.sin(g)*(l+m);e.strokeStyle=`hsl(${(a+h*3)%360}, 90%, ${40+f*40}%)`,e.lineWidth=3,e.beginPath(),e.moveTo(p,y),e.lineTo(v,x),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 Du(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 g=1;g<3;g++){const m=g*Math.PI*2/3;e.lineTo(Math.cos(m)*f,Math.sin(m)*f)}e.closePath(),e.shadowBlur=12,e.shadowColor=e.strokeStyle,e.stroke(),e.restore()}}function Ou(e,t,n,r,a,o){if(!o.current){const f=[];for(let m=0;m<24;m++)f.push({ang:m/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 g=f.baseR+Math.sin(f.phase)*d,m=l+Math.cos(f.ang)*g,p=c+Math.sin(f.ang)*g;h.push([m,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[g,m]=h[f],[p,y]=h[(f+1)%h.length],v=(g+p)/2,x=(m+y)/2;f===0?e.moveTo(v,x):e.quadraticCurveTo(g,m,v,x)}e.closePath(),e.fill(),e.stroke()}function _u(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 g=f/h*Math.PI*2+r*(.6+a*1.4),m=(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))),y=6;e.save(),e.translate(i,l),e.rotate(g+m),e.beginPath(),e.moveTo(0,0);for(let x=1;x<=y;x++){const C=p/y*x,b=(Math.sin(r*3+f*.8+x)*.6+Math.cos(r*2+f+x*.7))*(8+24*a),k=C,R=b;e.lineTo(R,k)}e.globalCompositeOperation="lighter";const v=(o+f*(240/h))%360;e.strokeStyle=`hsla(${v}, 90%, ${60+a*20}%, ${.35+a*.4})`,e.lineWidth=2+a*2,e.stroke(),e.restore()}e.beginPath(),e.arc(i,l,c*(.98+.02*Math.sin(r*2)),0,Math.PI*2),e.strokeStyle=`hsla(${(o+40)%360},90%,70%,${.25+a*.25})`,e.lineWidth=1.5,e.stroke(),e.globalCompositeOperation="source-over"}function sn(e,t){return e+Math.random()*(t-e)}function zu(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 Ot(e,t){return e+Math.random()*(t-e)}function Bu(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 g=(f+.5)/d*t,m=(r[Math.floor((f+1)/(d+1)*r.length)]||0)/255,p=n*.18+(.25+a*.6+m*.7)*n*.55,y=e.createLinearGradient(g,n,g,n-p);y.addColorStop(0,`hsla(${(o+40)%360},100%,55%,.9)`),y.addColorStop(.5,`hsla(${(o+10)%360},100%,60%,.75)`),y.addColorStop(1,`hsla(${(o-20)%360},100%,80%,.05)`);const v=Math.sin(l.t*1.2+f*.8)*(15+a*30);e.fillStyle=y,e.beginPath(),e.moveTo(g-20,n),e.bezierCurveTo(g-35,n-p*.45,g-25+v,n-p*.75,g+v,n-p),e.bezierCurveTo(g+25+v*.3,n-p*.65,g+35,n-p*.35,g+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 g=l.embers[f];if(g.x+=g.vx,g.y+=g.vy,g.vy-=.01,g.life-=.015+a*.02,g.life<=0||g.y<-10){l.embers.splice(f,1);continue}const m=e.createRadialGradient(g.x,g.y,0,g.x,g.y,g.r*3);m.addColorStop(0,`hsla(${(o+25)%360},100%,65%,.9)`),m.addColorStop(1,`hsla(${(o+25)%360},100%,65%,0)`),e.fillStyle=m,e.beginPath(),e.arc(g.x,g.y,g.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 Gu(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 m=0;m<d;m++){const p=(r[m]-128)/128,y=Math.sin(o*1.5+m*.03)*.12,v=m*h,x=i-l-(p+y)*c;m===0?e.moveTo(v,x):e.lineTo(v,x)}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 m=0;m<d;m++){const p=(r[m]-128)/128,y=Math.cos(o*1.3+m*.035)*.12,v=m*h,x=i+l+(p+y)*c;m===0?e.moveTo(v,x):e.lineTo(v,x)}const g=e.createLinearGradient(0,i+l,0,n);g.addColorStop(0,"hsla(190,90%,65%,0.9)"),g.addColorStop(1,"hsla(160,85%,55%,0.4)"),e.strokeStyle=g,e.lineWidth=2,e.stroke(),e.globalCompositeOperation="lighter",e.strokeStyle="rgba(255,255,255,0.08)",e.lineWidth=6,e.beginPath(),e.moveTo(0,i-l),e.lineTo(t,i-l),e.stroke(),e.beginPath(),e.moveTo(0,i+l),e.lineTo(t,i+l),e.stroke(),e.globalCompositeOperation="source-over"}const Wu="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:g=14})=>{const m=u.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette","radial","rays","particles","rings","grid","imageTornado","colorRipples","starfield","orbitals","eqcircle","triangles","blob","plasma","lavaLamp","cozyFire","rift"],[e,h]),p=u.useMemo(()=>{const U=m.includes(c)?c:m[0];try{const L=localStorage.getItem(d);if(!L)return U;const T=JSON.parse(L);return m.includes(T)?T:U}catch{return U}},[m,c,d]),[y,v]=mu(d,p),x=u.useRef(null),C=u.useRef(null),b=u.useRef(null),k=u.useRef(null),R=u.useRef(null),A=u.useRef(null),$=u.useRef(0),W=u.useRef(0),w=u.useRef([]),[D,_]=u.useState(0),P=u.useRef(null),B=u.useRef(null),z=u.useRef(null),K=u.useRef(null),Z=u.useRef(null),O=u.useRef(null),X=u.useRef(null),N=y!=="cover"&&y!=="video";return u.useEffect(()=>{var F;if(e==="youtube"||(C.current&&(cancelAnimationFrame(C.current),C.current=null),!N))return;Et();const U=tn(),L=t.current;if(!L)return;if(!b.current)try{b.current=U.createMediaElementSource(L)}catch{}if(!k.current){const j=U.createAnalyser();j.fftSize=2048,j.smoothingTimeConstant=.85,k.current=j;try{(F=b.current)==null||F.connect(j)}catch{}try{j.connect(U.destination)}catch{}}const T=k.current;R.current=new Uint8Array(T.frequencyBinCount),A.current=new Uint8Array(T.fftSize);const S=()=>{const j=x.current,E=Math.max(1,Math.floor(window.devicePixelRatio||1));j.width=Math.floor(j.clientWidth*E),j.height=Math.floor(j.clientHeight*E);const H=j.getContext("2d");H==null||H.setTransform(1,0,0,1,0,0),H==null||H.scale(E,E)};S();const I=()=>S();window.addEventListener("resize",I),Nu(z,220,x.current.width,x.current.height);const M=async()=>{const j=x.current;if(!j)return;const E=j.getContext("2d");if(!E)return;const H=Math.max(1,Math.floor(window.devicePixelRatio||1)),Y=j.width/H,J=j.height/H,ne=performance.now()*.001,ae=y==="waveform"||y==="rift";ae?T.getByteTimeDomainData(A.current):T.getByteFrequencyData(R.current);let re=0;const G=ae?A.current:R.current;for(let q=0;q<G.length;q++){const ee=ae?(G[q]-128)/128:G[q]/255;re+=ee*ee}if(re=Math.sqrt(re/G.length),_(Math.min(1,re)),E.clearRect(0,0,Y,J),y==="spectrum")xu(E,Y,J,R.current,$.current);else if(y==="bars")Su(E,Y,J,R.current,$.current);else if(y==="waveform")wu(E,Y,J,A.current);else if(y==="palette"){const q=($.current+re*120)%360;Cu(E,Y,J,R.current,q)}else if(y==="radial")ku(E,Y,J,R.current,$.current);else if(y==="rays")Mu(E,Y,J,R.current,$.current,W);else if(y==="particles")ju(E,Y,J,re,$.current,w);else if(y==="rings")Ru(E,Y,J,R.current,re,$.current);else if(y==="grid"){const q=($.current+re*160)%360;$u(E,Y,J,R.current,q)}else if(y==="imageTornado"){const q=f!=null&&f.length?f:a?[a]:[];await Pu(P,q,g,Y,J);const ee=($.current+re*100)%360;Eu(E,Y,J,re,ee,P)}else if(y==="colorRipples"){const q=($.current+re*120)%360;Au(E,Y,J,re,q,B)}else if(y==="starfield"){const q=($.current+60)%360;Iu(E,Y,J,re,q,z)}else if(y==="orbitals"){const q=($.current+re*180)%360;Lu(E,Y,J,R.current,q,W)}else if(y==="eqcircle"){const q=($.current+120)%360;Fu(E,Y,J,R.current,q)}else if(y==="triangles"){const q=($.current+40)%360;Du(E,Y,J,re,q,K)}else if(y==="blob"){const q=($.current+90)%360;Ou(E,Y,J,re,q,Z)}else if(y==="plasma"){const q=($.current+re*200)%360;_u(E,Y,J,ne,re,q)}else if(y==="rift")Gu(E,Y,J,A.current,re,ne);else if(y==="lavaLamp"){const q=($.current+re*80)%360;zu(E,Y,J,re,q,O)}else if(y==="cozyFire"){const q=($.current+re*140)%360;Bu(E,Y,J,R.current,re,q,X)}$.current=($.current+.4)%360,C.current=requestAnimationFrame(M)};return C.current=requestAnimationFrame(M),()=>{window.removeEventListener("resize",I),C.current&&cancelAnimationFrame(C.current)}},[N,e,t,y,f,g,a]),s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none",background:y==="cover"?"transparent":Wu},children:y==="cover"?s.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:s.jsx(vu,{height:r,coverUrl:a,title:o,subtitle:i,label:l})}):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(ha,{modes:m,active:y,setActive:v,rows:2}),s.jsx(yu,{vu:D,hide:e==="youtube"})]})]})},Go=({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"&&fu(r.url)){const y=()=>{p.src=r.url,p.load(),t&&p.play().catch(()=>{})};if(p.canPlayType("application/vnd.apple.mpegurl")){y();return}(async()=>{const x=(await import("hls.js")).default;if(x.isSupported()){const C=new x({xhrSetup:b=>{if(r!=null&&r.withCredentials&&(b.withCredentials=!0),r!=null&&r.headers)for(const[k,R]of Object.entries(r.headers))b.setRequestHeader(k,String(R))}});i.current=C,C.loadSource(r.url),C.attachMedia(p),C.on(x.Events.MANIFEST_PARSED,()=>t&&p.play().catch(()=>{}))}else y()})()}(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",g=f?"video":"cover",m=`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:g,storageKey:m},`vis-${m}`)]})};function Uu(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 Vu="var(--text-dim, #94a3b8)",qu=({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}),Wo=({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 g=u.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette"],[e,h]),m=u.useMemo(()=>{const P=g.includes(c)?c:g[0];try{const B=localStorage.getItem(d);if(!B)return P;const z=JSON.parse(B);return g.includes(z)?z:P}catch{return P}},[g,c,d]),[p,y]=Uu(d,m),v=u.useRef(null),[x,C]=u.useState(0),b=u.useRef(null),k=u.useRef(null),R=u.useRef(null),A=u.useRef(null),$=u.useRef(null),W=u.useRef(0),w=p==="spectrum"||p==="bars"||p==="waveform"||p==="palette";u.useEffect(()=>{var O;if(e==="youtube")return;if(!w){b.current&&cancelAnimationFrame(b.current);return}Et();const P=tn(),B=t.current;if(!B)return;if(!k.current)try{k.current=P.createMediaElementSource(B)}catch{}if(!R.current){const X=P.createAnalyser();X.fftSize=2048,X.smoothingTimeConstant=.85,R.current=X;try{(O=k.current)==null||O.connect(X)}catch{}try{X.connect(P.destination)}catch{}}const z=R.current;A.current=new Uint8Array(z.frequencyBinCount),$.current=new Uint8Array(z.fftSize);const K=()=>{if(!v.current)return;const X=v.current,N=X.getContext("2d");if(!N)return;const U=X.width,L=X.height;N.clearRect(0,0,U,L),p==="waveform"?z.getByteTimeDomainData($.current):z.getByteFrequencyData(A.current);let T=0;const S=p==="waveform"?$.current:A.current;for(let I=0;I<S.length;I++){const M=p==="waveform"?(S[I]-128)/128:S[I]/255;T+=M*M}if(T=Math.sqrt(T/S.length),C(Math.min(1,T)),p==="spectrum"||p==="bars"){const I=A.current,M=p==="bars"?48:Math.min(I.length,256),F=Math.floor(I.length/M),j=U/M;for(let E=0;E<M;E++){const H=I[E*F]/255,Y=H*(L-6),J=E*j,ne=L-Y,ae=E/M*240+W.current;N.fillStyle=`hsl(${ae%360}, 80%, ${Math.max(30,40+H*30)}%)`,N.fillRect(J+1,ne,j-2,Y)}}else if(p==="waveform"){const I=$.current;N.lineWidth=2,N.strokeStyle="#c7d2fe",N.beginPath();const M=U/I.length;for(let F=0;F<I.length;F++){const j=(I[F]-128)/128,E=F*M,H=L/2+j*(L*.45);F===0?N.moveTo(E,H):N.lineTo(E,H)}N.stroke()}else if(p==="palette"){const F=U/12,j=L/6,E=(W.current+T*120)%360;for(let H=0;H<6;H++)for(let Y=0;Y<12;Y++){const J=(H*12+Y)%A.current.length,ne=A.current[J]/255,ae=(E+Y/12*180+H/6*90)%360,re=70+ne*25,G=25+ne*35;N.fillStyle=`hsl(${ae}, ${re}%, ${G}%)`,N.fillRect(Y*F,H*j,Math.ceil(F),Math.ceil(j))}}N.strokeStyle=getComputedStyle(document.documentElement).getPropertyValue("--waveform-stroke")||"#c7d2fe",b.current=requestAnimationFrame(K)},Z=()=>{var U;const X=v.current,N=Math.max(1,Math.floor(window.devicePixelRatio||1));X.width=Math.floor(X.clientWidth*N),X.height=Math.floor(X.clientHeight*N),(U=X.getContext("2d"))==null||U.scale(N,N)};return Z(),window.addEventListener("resize",Z),b.current=requestAnimationFrame(K),()=>{window.removeEventListener("resize",Z),b.current&&cancelAnimationFrame(b.current)}},[w,e,t,p]);const D=()=>{if(e==="youtube")return null;const P=12,B=Math.round(x*P);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:P}).map((z,K)=>{const Z=120*(K/P);return s.jsx("div",{style:{width:6,height:18,borderRadius:2,background:K<B?`hsl(${Z}, 80%, 50%)`:"#1f2937"}},K)})})},_=()=>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:Vu},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:_()}):s.jsx("canvas",{ref:v,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:g.map(P=>s.jsx(qu,{active:p===P,onClick:()=>y(P),title:`Tryb: ${P}`,children:P},P))}),s.jsx("div",{style:{position:"absolute",right:10,bottom:10,pointerEvents:"none",zIndex:9998},children:s.jsx(D,{})})]})]})},Uo=({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,g]=u.useState(null),[m,p]=u.useState(null),y=u.useRef(null),[v,x]=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(g)},[e,t,o]),u.useEffect(()=>{m&&(r?m.playVideo():m.pauseVideo())},[r,m]),u.useEffect(()=>{if(m&&a){const b=setInterval(()=>{const k=m.getCurrentTime();a(k)},100);return()=>clearInterval(b)}},[m,a]),u.useEffect(()=>{const b=()=>{if(y.current){const k=y.current.clientWidth,R=Math.round(k*(9/16));x({width:k,height:R})}};return b(),window.addEventListener("resize",b),()=>window.removeEventListener("resize",b)},[]);const C=async()=>{if(!o)return;const b=await o(l,d);g(b)};return s.jsxs("div",{ref:y,style:{width:"100%",maxWidth:"900px",margin:"0 auto"},children:[(!e||!t||!f)&&s.jsxs("div",{children:[s.jsx("input",{value:l,onChange:b=>c(b.target.value),placeholder:i("youtubePlayer.artist","Artist"),"aria-label":i("youtubePlayer.artist","Artist")}),s.jsx("input",{value:d,onChange:b=>h(b.target.value),placeholder:i("youtubePlayer.title","Title"),"aria-label":i("youtubePlayer.title","Title")}),s.jsx("button",{onClick:C,children:i("youtubePlayer.search","Search")})]}),f&&s.jsxs("div",{children:[s.jsx(Yr,{videoId:f,opts:{width:v.width.toString(),height:v.height.toString(),playerVars:{autoplay:1,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,annotations:0}},onReady:b=>p(b.target)}),!n&&s.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px"},children:[s.jsx("button",{onClick:()=>m==null?void 0:m.playVideo(),children:"? Play"}),s.jsx("button",{onClick:()=>m==null?void 0:m.pauseVideo(),children:"? Pause"})]})]})]})},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:g}=t,{onChange:m,onRemove:p,onMoveUp:y,onMoveDown:v,onChangeLp:x,onSelectSource:C}=n,{readOnly:b=!1,canMoveUp:k=!0,canMoveDown:R=!0,activeSource:A}=r,{t:$}=xe(),W=u.useRef(null);u.useEffect(()=>{!i&&W.current&&W.current.focus()},[i]);const w=B=>{if(!b&&B.key==="Enter"){const z=B.target.closest("div.gpi-row"),K=z==null?void 0:z.querySelectorAll("input[data-role='field']");if(!K||K.length===0)return;const Z=Array.from(K).indexOf(B.target),O=K[Z+1]??K[0];O==null||O.focus()}},D=B=>{const z=h.includes(B),K=A===B,Z={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid #e5e7eb",background:K?"var(--active-bg, #eef2ff)":"var(--bg, #fff)",opacity:z?1:.35,cursor:z&&C&&!b?"pointer":"default",transition:"transform .05s ease"},O=B==="youtube"?"#FF0000":B==="spotify"?"#1DB954":B==="tidal"?"#111827":B==="hls"?"#7C3AED":"#374151",X=B==="youtube"?Ia.faYoutube:B==="spotify"?Ia.faSpotify:B==="tidal"?vr.faGem:B==="hls"?vr.faWaveSquare:vr.faMusic,N=B==="youtube"?"YouTube":B==="spotify"?"Spotify":B==="tidal"?"TIDAL":B==="hls"?"HLS":"Audio",U=$("playlistItem.sourceLabel")+": "+N+(K?` ${$("playlistItem.sourceSelected")}`:""),L=()=>{!z||!C||b||C(B)};return s.jsx("button",{type:"button",title:N,onClick:L,disabled:!z||b,style:Z,"aria-pressed":K,"aria-label":U,children:s.jsx(Dl.FontAwesomeIcon,{icon:X,style:{color:O}})},B)},_=["youtube","tidal","spotify","hls","audio"],P=typeof d=="number"?d:o+1;return s.jsxs("div",{className:"gpi-row",role:"group","aria-label":$("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:P,onChange:B=>x==null?void 0:x(Number(B.target.value)),disabled:b||!x,"aria-label":"Lp",title:$("playlistItem.positionOnList"),style:Hu}),s.jsx("input",{ref:W,"data-role":"field",type:"text",value:i,onChange:B=>m({artist:B.target.value}),placeholder:"Artist",onKeyDown:w,disabled:b,"aria-label":"Artist",className:"gpi-input",style:kr}),s.jsx("input",{"data-role":"field",type:"text",value:l,onChange:B=>m({title:B.target.value}),placeholder:"Title",onKeyDown:w,disabled:b,"aria-label":"Title",className:"gpi-input",style:kr}),f&&s.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:B=>m({version:B.target.value||void 0}),placeholder:$("playlistItem.versionOptional"),onKeyDown:w,disabled:b,"aria-label":"Version",className:"gpi-input",style:kr}),s.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":$("playlistItem.availableSources"),children:_.map(D)}),s.jsxs("div",{className:"gpi-actions",style:{display:"flex",gap:6,justifyContent:"flex-end"},children:[g&&s.jsx("button",{type:"button",...g,draggable:!0,"aria-label":$("playlistItem.dragReorder"),title:$("playlistItem.dragReorder"),style:Nn,children:"≡"}),s.jsx("button",{type:"button",onClick:y,disabled:!k||b,"aria-label":$("playlistItem.moveUp"),title:$("playlistItem.moveUp"),style:Nn,children:"↑"}),s.jsx("button",{type:"button",onClick:v,disabled:!R||b,"aria-label":$("playlistItem.moveDown"),title:$("playlistItem.moveDown"),style:Nn,children:"↓"}),s.jsx("button",{type:"button",onClick:p,disabled:b,"aria-label":$("common.delete"),title:$("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"},kr={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}},Vo=({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,[g,m]=u.useState(()=>In(e||t)),[p,y]=u.useState(""),v=u.useRef(null),[x,C]=u.useState(null);u.useEffect(()=>{f&&m(In(e))},[f,JSON.stringify(e)]);const b=u.useCallback(N=>{n==null||n(Ku(N))},[n]),k=u.useCallback(N=>{if(f){const U=N(In(e));b(U)}else m(U=>{const L=N(U);return b(L),L})},[b,f,e]),R=a?g.length<a:!0,A=u.useCallback(()=>{!R||l||k(N=>[...N,{id:_r(),artist:"",title:"",version:void 0}])},[R,l,k]),$=u.useCallback((N,U)=>{k(L=>L.map(T=>T.id===N?{...T,...U}:T))},[k]),W=u.useCallback(N=>{l||k(U=>U.filter(L=>L.id!==N))},[l,k]),w=u.useCallback((N,U)=>{k(L=>{const T=L.findIndex(F=>F.id===N);if(T<0)return L;const S=T+U;if(S<0||S>=L.length)return L;const I=[...L],[M]=I.splice(T,1);return I.splice(S,0,M),I})},[k]),D=u.useCallback((N,U)=>{k(L=>{const T=L.findIndex(F=>F.id===N);if(T<0)return L;const S=Math.max(0,Math.min(L.length-1,U-1));if(T===S)return L;const I=[...L],[M]=I.splice(T,1);return I.splice(S,0,M),I})},[k]),_=N=>U=>{l||(v.current=N,U.dataTransfer.effectAllowed="move",U.dataTransfer.setData("text/plain",N))},P=N=>U=>{l||(U.preventDefault(),U.dataTransfer.dropEffect="move",C(N))},B=N=>()=>C(U=>U===N?null:U),z=N=>U=>{if(l)return;U.preventDefault();const L=v.current??U.dataTransfer.getData("text/plain");C(null),v.current=null,!(!L||L===N)&&k(T=>{const S=T.findIndex(j=>j.id===L),I=T.findIndex(j=>j.id===N);if(S<0||I<0||S===I)return T;const M=[...T],[F]=M.splice(S,1);return M.splice(I,0,F),M})},K=()=>{v.current=null,C(null)},Z=u.useCallback(()=>{if(!d||l)return;const U=p.split(/\r?\n/).map(L=>L.trim()).filter(Boolean).map(Zu).filter(L=>!!L);U.length!==0&&(k(L=>{const T=(a??1/0)-L.length,S=U.slice(0,Math.max(0,T)).map(I=>({id:_r(),...I}));return[...L,...S]}),y(""))},[d,l,p,a,k]);u.useEffect(()=>{},[g.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.")}),X=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:A,disabled:!R||l,className:"gp-add",style:{padding:"6px 10px",borderRadius:6,border:"1px solid #d1d5db",background:"#f9fafb"},"aria-label":X,children:["+ ",X]})})]}),g.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:g.map((N,U)=>{const L=x===N.id;return s.jsx("li",{draggable:!l,onDragStart:_(N.id),onDragOver:P(N.id),onDragLeave:B(N.id),onDrop:z(N.id),onDragEnd:K,style:{border:L?"2px dashed #6366f1":"2px solid transparent",borderRadius:8,padding:L?4:0},children:s.jsx(pa,{data:{id:N.id,index:U,lp:U+1,artist:N.artist,title:N.title,version:r?N.version??void 0:void 0,sourcesAvailable:void 0},display:{allowVersion:r,dragHandleProps:{onDragStart:_(N.id)}},callbacks:{onChange:T=>$(N.id,T),onRemove:()=>W(N.id),onMoveUp:()=>w(N.id,-1),onMoveDown:()=>w(N.id,1),onChangeLp:T=>D(N.id,T)},state:{readOnly:l,canMoveUp:U>0,canMoveDown:U<g.length-1}})},N.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:N=>y(N.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:Z,disabled:!p.trim(),style:{padding:"6px 10px",borderRadius:6,border:"1px solid #d1d5db",background:"#f9fafb"},children:h("genericPlaylist.addFromList","Add from list")})]})]})]})})]})},ns=["#ef4444","#f97316","#f59e0b","#eab308","#84cc16","#22c55e","#14b8a6","#06b6d4","#3b82f6","#6366f1","#8b5cf6","#a855f7","#d946ef","#ec4899","#f43f5e","#78716c","#64748b","#000000"],Ln=["🎵","🎸","🎹","🎤","🎧","🥁","🎷","🎺","❤️","⭐","🔥","💎","🌙","☀️","🌊","🎯"],qo=({tags:e,onCreateTag:t,onUpdateTag:n,onDeleteTag:r,selectedTracks:a,onAssignTag:o,onUnassignTag:i})=>{const{t:l}=ve(),[c,d]=u.useState(null),[h,f]=u.useState(""),[g,m]=u.useState(ns[8]),[p,y]=u.useState(Ln[0]),[x,v]=u.useState(!1),[C,b]=u.useState(null),[k,R]=u.useState(""),[A,$]=u.useState(""),[W,w]=u.useState(""),D=u.useCallback(O=>{d(O.id),R(O.name),$(O.color),w(O.icon||Ln[0])},[]),_=u.useCallback(()=>{c&&k.trim()&&(n(c,k.trim(),A,W),d(null))},[c,k,A,W,n]),P=u.useCallback(()=>{h.trim()&&(t(h.trim(),g,p),f(""),v(!1))},[h,g,p,t]),B=u.useCallback(O=>{C===O?(r(O),b(null)):(b(O),setTimeout(()=>b(null),3e3))},[C,r]),z=a&&a.length>0,K=O=>!a||a.length===0?!1:a.every(X=>X.tags.includes(O)),Z=O=>!a||a.length===0?!1:a.some(X=>X.tags.includes(O))&&!K(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:()=>v(!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"&&P()}),s.jsx("button",{onClick:P,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:ns.map(O=>s.jsx("div",{onClick:()=>m(O),style:{width:20,height:20,borderRadius:"50%",background:O,cursor:"pointer",border:g===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:()=>y(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))})]})]}),z&&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:W,onChange:X=>w(X.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:Ln.map(X=>s.jsx("option",{value:X,children:X},X))}),s.jsx("input",{type:"color",value:A,onChange:X=>$(X.target.value),style:{width:24,height:24,border:"none",cursor:"pointer",padding:0}}),s.jsx("input",{type:"text",value:k,onChange:X=>R(X.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:X=>X.key==="Enter"&&_()}),s.jsx("button",{onClick:_,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]}),z&&o&&i&&s.jsx("input",{type:"checkbox",checked:K(O.id),ref:X=>{X&&(X.indeterminate=Z(O.id))},onChange:()=>{const X=a.map(N=>N.id);K(O.id)?i(X,O.id):o(X,O.id)},style:{cursor:"pointer"}}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:()=>D(O),style:Fn("var(--text-secondary, #9ca3af)"),title:l("playlistManager.editTag"),children:"✏"}),s.jsx("button",{onClick:()=>B(O.id),style:Fn(C===O.id?"var(--error, #ef4444)":"var(--text-secondary, #9ca3af)"),title:C===O.id?l("playlistManager.confirmDelete"):l("playlistManager.deleteTag"),children:C===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||{}),Ho=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(Ho||{}),Ko=(e=>(e.Left="left",e.Right="right",e))(Ko||{}),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||{}),Yo=(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))(Yo||{}),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 Zu=[{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"}],Xu=[{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 Qu(e){return"logic"in e&&"rules"in e}function zr(){return{id:crypto.randomUUID(),field:Ye.Artist,operator:Ze.Contains,value:""}}function Zo(){return{id:crypto.randomUUID(),logic:"and",rules:[zr()]}}const Ju=({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:Zu.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:Xu.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:"✕"})]}),Xo=({group:e,onChange:t,onRemove:n,depth:r=0})=>{const{t:a}=ve(),o=u.useCallback((f,g)=>{const m=[...e.rules];m[f]=g,t({...e,rules:m})},[e,t]),i=u.useCallback(f=>{const g=e.rules.filter((m,p)=>p!==f);t({...e,rules:g.length>0?g:[zr()]})},[e,t]),l=u.useCallback(()=>{t({...e,rules:[...e.rules,zr()]})},[e,t]),c=u.useCallback(()=>{t({...e,rules:[...e.rules,Zo()]})},[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,g)=>Qu(f)?s.jsx(Xo,{group:f,onChange:m=>o(g,m),onRemove:()=>i(g),depth:r+1},f.id):s.jsx(Ju,{rule:f,onChange:m=>o(g,m),onRemove:()=>i(g)},f.id))]})},Qo=({rules:e,onChange:t,limit:n,onLimitChange:r})=>{const{t:a}=ve(),o=e??Zo();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(Xo,{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)")})]})]})},rs=e=>{if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`},eh={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:g,onFilterChange:m,compact:p=!1,draggable:y=!1,onDragStart:x,dropTarget:v=!1,onDrop:C})=>{const{t:b}=ve(),[k,R]=u.useState(null),[A,$]=u.useState(null),W=u.useRef(null),w=u.useMemo(()=>{let S=e??[];if(g.trim()){const I=g.toLowerCase();S=S.filter(M=>{var F,j;return M.title.toLowerCase().includes(I)||M.artist.toLowerCase().includes(I)||((F=M.album)==null?void 0:F.toLowerCase().includes(I))||((j=M.genre)==null?void 0:j.toLowerCase().includes(I))})}return[...S].sort((I,M)=>{const F=h==="asc"?1:-1;switch(d){case"title":return F*I.title.localeCompare(M.title);case"artist":return F*I.artist.localeCompare(M.artist);case"album":return F*(I.album??"").localeCompare(M.album??"");case"duration":return F*((I.duration??0)-(M.duration??0));case"year":return F*((I.year??0)-(M.year??0));case"rating":return F*((I.rating??0)-(M.rating??0));case"addedDate":return F*(I.addedAt??"").localeCompare(M.addedAt??"");case"custom":return F*((I.customOrder??0)-(M.customOrder??0));default:return 0}})},[e,g,d,h]),D=u.useCallback((S,I)=>{const M=w[S];if(M){if(I.ctrlKey||I.metaKey){const F=new Set(n);F.has(M.id)?F.delete(M.id):F.add(M.id),r(F)}else if(I.shiftKey&&W.current!==null){const F=Math.min(W.current,S),j=Math.max(W.current,S),E=new Set(n);for(let H=F;H<=j;H++)E.add(w[H].id);r(E)}else r(new Set([M.id]));W.current=S}},[w,n,r]),_=u.useCallback(()=>{n.size===w.length?r(new Set):r(new Set(w.map(S=>S.id)))},[w,n,r]),P=({field:S,label:I,width:M})=>{const F=d===S;return s.jsxs("div",{style:{width:M,flex:M?void 0:1,cursor:"pointer",userSelect:"none",fontWeight:F?700:500,fontSize:"0.72rem",textTransform:"uppercase",letterSpacing:"0.04em",opacity:F?1:.6,display:"flex",alignItems:"center",gap:4},onClick:()=>{F?f(S,h===qt.Asc?qt.Desc:qt.Asc):f(S,qt.Asc)},children:[I,F&&s.jsx("span",{children:h==="asc"?"↑":"↓"})]})},B=u.useCallback((S,I)=>{const M=n.has(S.id)?Array.from(n):[S.id];I.dataTransfer.setData("trackIds",JSON.stringify(M)),I.dataTransfer.effectAllowed="move",x==null||x(M,I)},[n,x]),z=u.useCallback((S,I)=>{I.preventDefault(),I.dataTransfer.dropEffect="move",R(S)},[]),K=u.useCallback((S,I)=>{I.preventDefault(),R(null);try{const M=I.dataTransfer.getData("trackIds");if(M&&i){const F=JSON.parse(M),j=w.filter(Y=>!F.includes(Y.id)),E=w.filter(Y=>F.includes(Y.id)),H=Math.min(S,j.length);j.splice(H,0,...E),i(j.map(Y=>Y.id))}}catch{}},[w,i]),Z=u.useCallback(S=>{S.preventDefault(),R(null),C==null||C(S)},[C]),O=u.useMemo(()=>new Map(t.map(S=>[S.id,S])),[t]),X=S=>S.replace(/[^a-z0-9_-]/gi,"-"),N=p?36:48,U={display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)",color:"var(--text-secondary, #6b7280)"},L=(S,I)=>({display:"flex",alignItems:"center",gap:8,padding:p?"4px 12px":"6px 12px",height:N,cursor:"pointer",background:I?"var(--accent-light, #dbeafe)":S?"var(--selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--border-subtle, #f3f4f6)",transition:"background 0.1s"}),T=w.length>0&&n.size===w.length;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:v?S=>{S.preventDefault(),S.dataTransfer.dropEffect="copy"}:void 0,onDrop:v?Z: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:g,onChange:S=>m(S.target.value),placeholder:"🔍 "+b("playlistManager.filterTracks"),style:{flex:1,fontSize:"0.82rem",padding:"6px 10px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #f9fafb)",color:"var(--text-primary, #1f2937)"}}),s.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[w.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:U,children:[s.jsx("div",{style:{width:28},children:s.jsx("input",{type:"checkbox",checked:T,onChange:_,style:{cursor:"pointer"}})}),s.jsx("div",{style:{width:20},children:"#"}),!p&&s.jsx("div",{style:{width:44}}),s.jsx(P,{field:"title",label:b("playlistManager.colTitle")}),s.jsx(P,{field:"artist",label:b("playlistManager.colArtist")}),!p&&s.jsx(P,{field:"album",label:b("playlistManager.colAlbum")}),s.jsx(P,{field:"duration",label:b("playlistManager.colDuration"),width:60}),!p&&s.jsx(P,{field:"year",label:b("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:[w.length===0&&s.jsx("div",{style:{padding:24,textAlign:"center",opacity:.4,fontSize:"0.85rem"},children:e.length===0?b("playlistManager.emptyPlaylist"):b("playlistManager.noMatchingTracks")}),w.map((S,I)=>{const M=n.has(S.id),F=k===I;return s.jsxs("div",{style:L(M,F),onClick:j=>D(I,j),onDoubleClick:()=>a==null?void 0:a(S),draggable:y,onDragStart:j=>B(S,j),onDragOver:j=>z(I,j),onDrop:j=>K(I,j),onDragLeave:()=>R(null),children:[s.jsx("div",{style:{width:28},children:s.jsx("input",{type:"checkbox",checked:M,onChange:()=>{const j=new Set(n);M?j.delete(S.id):j.add(S.id),r(j)},onClick:j=>j.stopPropagation(),style:{cursor:"pointer"}})}),s.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:I+1}),!p&&s.jsx("div",{style:{width:44,height:36,flexShrink:0},children:S.coverUrl?s.jsx("img",{src:S.coverUrl,alt:S.title||b("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:rs(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:eh[S.source]??"?"}),!p&&s.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[S.tags.slice(0,2).map(j=>{const E=O.get(j);if(!E)return null;const H=`--tag-${X(j)}`;return s.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${H}-bg, ${E.color}22)`,color:`var(${H}, ${E.color})`,whiteSpace:"nowrap"},children:E.name},j)}),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:j=>{j.stopPropagation(),$(A===S.id?null:S.id)},title:b("playlistManager.morActions"),children:"⋮"}),A===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:b("playlistManager.assignTag")}),t.map(j=>{const E=S.tags.includes(j.id);return s.jsxs("div",{style:{padding:"4px 8px",borderRadius:4,cursor:"pointer",fontSize:"0.78rem",display:"flex",alignItems:"center",gap:6,background:E?`var(--tag-${X(j.id)}-bg, ${j.color}22)`:"transparent"},onClick:H=>{H.stopPropagation();const Y=n.size>0?Array.from(n):[S.id];E||l==null||l(Y,[j.id]),$(null)},children:[s.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:`var(--tag-${X(j.id)}, ${j.color})`,flexShrink:0}}),s.jsx("span",{children:j.name}),E&&s.jsx("span",{style:{marginLeft:"auto"},children:"✓"})]},j.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:[w.length," ",b("playlistManager.tracks")]}),s.jsx("span",{children:rs(w.reduce((S,I)=>S+(I.duration??0),0))}),n.size>0&&s.jsxs("span",{children:[n.size," ",b("playlistManager.selected")]})]})]})},as=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),Jo=({playlists:e,tags:t,onCopyTracks:n,onMoveTracks:r,onRemoveTracks:a,onReorderTracks:o,onPlay:i,onTagTracks:l,initialLeftId:c,initialRightId:d})=>{const{t:h}=ve(),[f,g]=u.useState(()=>as(c??null)),[m,p]=u.useState(()=>as(d??null)),[y,x]=u.useState("left"),[v,C]=u.useState(null),[b,k]=u.useState(50),[R,A]=u.useState(!1),$=u.useMemo(()=>e.find(T=>T.id===f.playlistId),[e,f.playlistId]),W=u.useMemo(()=>e.find(T=>T.id===m.playlistId),[e,m.playlistId]),w=u.useCallback((T,S)=>{T==="left"?g(I=>({...I,...S})):p(I=>({...I,...S}))},[]),D=u.useCallback(T=>T==="left"?f:m,[f,m]),_=T=>T==="left"?"right":"left",P=u.useCallback(T=>{const S=D(T),I=D(_(T));!S.playlistId||!I.playlistId||S.selectedTrackIds.size===0||(n(S.playlistId,I.playlistId,Array.from(S.selectedTrackIds)),w(T,{selectedTrackIds:new Set}))},[D,n,w]),B=u.useCallback(T=>{const S=D(T),I=D(_(T));!S.playlistId||!I.playlistId||S.selectedTrackIds.size===0||(r(S.playlistId,I.playlistId,Array.from(S.selectedTrackIds)),w(T,{selectedTrackIds:new Set}))},[D,r,w]),z=u.useCallback(T=>{const S=D(T);!S.playlistId||S.selectedTrackIds.size===0||C({operation:"copy",sourcePlaylistId:S.playlistId,trackIds:Array.from(S.selectedTrackIds)})},[D]),K=u.useCallback(T=>{const S=D(T);!S.playlistId||S.selectedTrackIds.size===0||C({operation:"cut",sourcePlaylistId:S.playlistId,trackIds:Array.from(S.selectedTrackIds)})},[D]),Z=u.useCallback(T=>{const S=D(T);!v||!S.playlistId||(v.operation==="copy"?n(v.sourcePlaylistId,S.playlistId,v.trackIds):r(v.sourcePlaylistId,S.playlistId,v.trackIds),C(null))},[v,D,n,r]),O=u.useCallback(T=>{T.key==="Tab"&&!T.shiftKey&&(T.preventDefault(),x(S=>_(S))),(T.ctrlKey||T.metaKey)&&T.key==="c"&&z(y),(T.ctrlKey||T.metaKey)&&T.key==="x"&&K(y),(T.ctrlKey||T.metaKey)&&T.key==="v"&&Z(y)},[y,z,K,Z]),X=u.useCallback(()=>A(!0),[]),N=u.useCallback(T=>{if(!R)return;const S=T.currentTarget.getBoundingClientRect(),I=(T.clientX-S.left)/S.width*100;k(Math.max(20,Math.min(80,I)))},[R]),U=u.useCallback(()=>A(!1),[]),L=T=>{const S=D(T),I=T==="left"?$:W,M=y===T,j=!!D(_(T)).playlistId;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",border:M?"2px solid var(--accent, #3b82f6)":"2px solid transparent",borderRadius:8,overflow:"hidden",background:"var(--card-bg, #fff)"},onClick:()=>x(T),children:[s.jsx("div",{style:{padding:"8px 12px",background:M?"var(--accent, #3b82f6)":"var(--surface-bg, #f3f4f6)",color:M?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:s.jsxs("select",{value:S.playlistId??"",onChange:E=>w(T,{playlistId:E.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:M?"var(--accent-overlay, #ffffff30)":"var(--input-bg, #fff)",color:M?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)"},children:[s.jsx("option",{value:"",children:h("playlistManager.selectPlaylist")}),e.map(E=>s.jsxs("option",{value:E.id,children:[E.name," (",E.trackCount,")"]},E.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:Mr(!1),onClick:()=>P(T),disabled:!S.playlistId||!j||S.selectedTrackIds.size===0,title:h("playlistManager.copyToOther"),children:[T==="left"?"📋→":"←📋"," ",h("playlistManager.copy")]}),s.jsxs("button",{style:Mr(!1),onClick:()=>B(T),disabled:!S.playlistId||!j||S.selectedTrackIds.size===0,title:h("playlistManager.moveToOther"),children:[T==="left"?"✂→":"←✂"," ",h("playlistManager.move")]}),s.jsx("div",{style:{flex:1}}),v&&s.jsxs("button",{style:Mr(!0),onClick:()=>Z(T),disabled:!S.playlistId,children:["📌 ",h("playlistManager.paste")," (",v.trackIds.length,")"]})]}),I?s.jsx(ga,{tracks:I.tracks,tags:t,selectedTrackIds:S.selectedTrackIds,onSelectionChange:E=>w(T,{selectedTrackIds:E}),onPlay:i,onRemove:E=>a(I.id,E),onReorder:E=>o(I.id,E),onTagTracks:l,sortField:S.sortField,sortDir:S.sortDir,onSortChange:(E,H)=>w(T,{sortField:E,sortDir:H}),filterText:S.filterText,onFilterChange:E=>w(T,{filterText:E}),compact:!0,draggable:!0}):s.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",opacity:.3,fontSize:"0.85rem"},children:h("playlistManager.selectPlaylistPrompt")})]})};return s.jsxs("div",{style:{display:"flex",height:"100%",userSelect:R?"none":"auto"},onKeyDown:O,onMouseMove:N,onMouseUp:U,tabIndex:0,children:[s.jsx("div",{style:{width:`${b}%`,minWidth:200},children:L("left")}),s.jsx("div",{style:{width:6,cursor:"col-resize",background:R?"var(--accent, #3b82f6)":"var(--border-color, #e5e7eb)",transition:R?"none":"background 0.15s",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseDown:X,children:s.jsx("div",{style:{width:2,height:40,borderRadius:1,background:R?"var(--btn-text, #fff)":"var(--text-secondary, #9ca3af)"}})}),s.jsx("div",{style:{flex:1,minWidth:200},children:L("right")})]})},Mr=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"}),ei="av:local-playlists";function th(){try{const e=localStorage.getItem(ei);return e?JSON.parse(e):[]}catch{return[]}}function nh(e){const t=JSON.stringify(e);try{localStorage.setItem(ei,t)}catch{}}function ya(){const[e,t]=u.useState(()=>th()),n=u.useRef(!1);return u.useEffect(()=>{n.current=!0},[]),u.useEffect(()=>{nh(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 rh=et.scoped("PlaylistList"),ah={border:"1px solid #e5e7eb",borderRadius:8,background:"#fff"},sh={...ah,padding:"8px 10px",cursor:"pointer"},ti={border:"1px solid var(--border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--bg, #fff)",cursor:"pointer"},oh={...ti,background:"var(--primary, #4f46e5)",borderColor:"var(--primary, #4f46e5)",color:"var(--bg, #fff)"},ba=({selectedId:e,onSelect:t,onCreateRemote:n})=>{const{t:r}=ve(),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()?oh:{...ti,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){rh.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:{...sh,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 ↑")})]})]})},ih=et.scoped("PlaylistBrowser"),ss={display:"grid",gap:12},os=e=>({artist:(e.artists??[]).join(", "),title:e.title}),ni=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:n})=>{var g;const{t:r}=ve(),a=ya(),[o,i]=u.useState(null),[l,c]=u.useState(""),[,d]=u.useState([]),h=o==null?void 0:o.id,f=(m,p)=>{if("addItems"in a){a.addItems(m.id,p);const x=a.list().find(v=>v.id===m.id)||m;i(x);return}const y=a;if("update"in a&&typeof y.update=="function"){const x=Array.from([...m.items||[],...p]);y.update({...m,items:x});const v=a.list().find(C=>C.id===m.id)||{...m,items:x};i(v);return}ih.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:ss,children:[s.jsx("h3",{style:{margin:0},children:r("playlistBrowser.playlists")}),s.jsx(ba,{selectedId:h,onSelect:i}),o&&s.jsxs("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:[r("playlistBrowser.selected","Selected"),": ",s.jsx("strong",{children:o.name})," � ",((g=o.items)==null?void 0:g.length)??0," ",r("playlistBrowser.tracks","tracks")]})]}),s.jsxs("div",{style:ss,children:[s.jsx("h3",{style:{margin:0},children:r("playlistBrowser.library")}),s.jsxs("div",{children:[e==null?void 0:e({placeholder:r("playlistBrowser.searchAndAdd","Search and add to playlist..."),onPick:m=>{o&&f(o,[os(m)])}}),s.jsx("input",{placeholder:r("playlistBrowser.fullSearch","Full search (Enter does not add, full list below)"),value:l,onChange:m=>c(m.target.value),style:{width:"100%",border:"1px solid #d1d5db",borderRadius:8,padding:"6px 10px",marginTop:10}})]}),t==null?void 0:t({query:l,onPick:m=>{o&&f(o,[os(m)])}}),n==null?void 0:n({onPlayNow:m=>d(m),onAddToQueue:m=>d(p=>[...p,...m]),onAddDescriptors:m=>o&&f(o,m)})]})]})};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 ri=(e,t=null)=>e.filter(n=>n.parentId===t).sort((n,r)=>n.sortOrder-r.sortOrder).map(n=>({...n,children:ri(e,n.id)})),lh={[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)"}},ai=({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:g,onDisconnectService:m,onDragPlaylistToFolder:p,collapsed:y=!1,onToggleCollapse:x})=>{const{t:v}=ve(),[C,b]=u.useState(new Set),[k,R]=u.useState(!1),[A,$]=u.useState(""),[W,w]=u.useState(null),[D,_]=u.useState(!1),[P,B]=u.useState(""),[z,K]=u.useState("static"),[Z,O]=u.useState(null),[X,N]=u.useState(""),[U,L]=u.useState(null),[T,S]=u.useState(!1),I=u.useMemo(()=>ri(e),[e]),M=u.useCallback(Q=>{b(ue=>{const ye=new Set(ue);return ye.has(Q)?ye.delete(Q):ye.add(Q),ye})},[]),F=u.useCallback(()=>{A.trim()&&(c(A.trim(),W),$(""),R(!1))},[A,W,c]),j=u.useCallback(()=>{P.trim()&&(f(P.trim(),z,a),B(""),_(!1))},[P,z,a,f]),E=u.useCallback(Q=>{X.trim()&&(d(Q,X.trim()),O(null),N(""))},[X,d]),H=u.useCallback((Q,ue)=>{Q.preventDefault(),Q.dataTransfer.dropEffect="move",L(ue)},[]),Y=u.useCallback((Q,ue)=>{Q.preventDefault();const ye=Q.dataTransfer.getData("playlistId");ye&&p&&p(ye,ue),L(null)},[p]),J=u.useCallback(()=>L(null),[]),ne=u.useCallback(Q=>t.filter(ue=>(ue.folderId??null)===Q),[t]),ae={width:y?48:280,minWidth:y?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)"},G=(Q,ue=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:ue?"var(--accent-light, #dbeafe)":Q?"var(--accent, #3b82f6)":"transparent",color:Q?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",transition:"background 0.15s",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),q={background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:"2px 6px",borderRadius:4,color:"var(--text-secondary, #6b7280)"},ee={fontSize:"0.8rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)",width:"100%"},oe=(Q,ue)=>{var Se,te;const ye=C.has(Q.id),je=a===Q.id,Fe=U===Q.id,Re=ne(Q.id);return s.jsxs("div",{children:[s.jsxs("div",{style:{...G(je,Fe),paddingLeft:12+ue*16},onClick:()=>{i(Q.id),Q.children&&Q.children.length>0&&M(Q.id)},onDragOver:se=>H(se,Q.id),onDrop:se=>Y(se,Q.id),onDragLeave:J,children:[s.jsx("span",{style:{width:14,textAlign:"center",flexShrink:0,fontSize:"0.7rem"},children:(((Se=Q.children)==null?void 0:Se.length)||0)>0||Re.length>0?ye?"▼":"▶":"·"}),Z===Q.id?s.jsx("input",{value:X,onChange:se=>N(se.target.value),onKeyDown:se=>{se.key==="Enter"&&E(Q.id),se.key==="Escape"&&O(null)},onBlur:()=>E(Q.id),autoFocus:!0,style:{...ee,flex:1},onClick:se=>se.stopPropagation()}):s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Q.icon??"📁"}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:Q.name}),s.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:Re.length}),s.jsx("button",{style:q,onClick:se=>{se.stopPropagation(),O(Q.id),N(Q.name)},title:v("common.rename"),children:"✏"}),s.jsx("button",{style:{...q,color:"var(--error, #ef4444)"},onClick:se=>{se.stopPropagation(),h(Q.id)},title:v("common.delete"),children:"✕"})]})]}),ye&&s.jsxs(s.Fragment,{children:[Re.map(se=>ce(se,ue+1)),(te=Q.children)==null?void 0:te.map(se=>oe(se,ue+1))]})]},Q.id)},ce=(Q,ue)=>{const ye=o===Q.id;return s.jsxs("div",{style:{...G(ye),paddingLeft:12+ue*16+22},onClick:()=>l(Q.id),draggable:!0,onDragStart:je=>{je.dataTransfer.setData("playlistId",Q.id),je.dataTransfer.effectAllowed="move"},children:[s.jsx("span",{style:{fontSize:"0.7rem"},children:Q.type==="dynamic"?"⚡":"🎵"}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:Q.name}),s.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:Q.trackCount})]},Q.id)};if(y)return s.jsx("div",{style:ae,children:s.jsx("button",{style:{...q,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:x,title:v("playlistManager.expandSidebar"),children:"▶"})});const fe=ne(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:["🎶 ",v("playlistManager.title")]}),s.jsx("button",{style:q,onClick:x,title:v("playlistManager.collapseSidebar"),children:"◀"})]}),s.jsxs("div",{style:{...re,display:"flex",gap:4,flexWrap:"wrap"},children:[s.jsxs("button",{style:{...q,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:6,padding:"4px 10px"},onClick:()=>_(!0),children:["+ ",v("playlistManager.newPlaylist")]}),s.jsxs("button",{style:{...q,border:"1px solid var(--border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{R(!0),w(a)},children:["📁 ",v("playlistManager.newFolder")]})]}),D&&s.jsxs("div",{style:{...re,display:"flex",flexDirection:"column",gap:6},children:[s.jsx("input",{value:P,onChange:Q=>B(Q.target.value),placeholder:v("playlistManager.playlistName"),style:ee,autoFocus:!0,onKeyDown:Q=>{Q.key==="Enter"&&j(),Q.key==="Escape"&&_(!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:z==="static",onChange:()=>K("static")}),v("playlistManager.static")]}),s.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[s.jsx("input",{type:"radio",checked:z==="dynamic",onChange:()=>K("dynamic")}),"⚡ ",v("playlistManager.dynamic")]}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{style:{...q,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:j,"aria-label":"Confirm create playlist",children:"✓"}),s.jsx("button",{style:q,onClick:()=>_(!1),"aria-label":"Cancel create playlist",children:"✕"})]})]}),k&&s.jsxs("div",{style:{...re,display:"flex",gap:6},children:[s.jsx("input",{value:A,onChange:Q=>$(Q.target.value),placeholder:v("playlistManager.folderName"),style:{...ee,flex:1},autoFocus:!0,onKeyDown:Q=>{Q.key==="Enter"&&F(),Q.key==="Escape"&&R(!1)}}),s.jsx("button",{style:{...q,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:F,"aria-label":"Confirm create folder",children:"✓"}),s.jsx("button",{style:q,onClick:()=>R(!1),"aria-label":"Cancel create folder",children:"✕"})]}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsxs("div",{style:G(a===null&&o===null,U==="__root__"),onClick:()=>i(null),onDragOver:Q=>H(Q,null),onDrop:Q=>Y(Q,null),onDragLeave:J,children:[s.jsx("span",{children:"🏠"}),s.jsx("span",{style:{flex:1},children:v("playlistManager.allPlaylists")}),s.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:t.length})]}),fe.map(Q=>ce(Q,0)),I.map(Q=>oe(Q,0))]}),n.length>0&&s.jsxs("div",{style:re,children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:v("playlistManager.tags")}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:n.map(Q=>s.jsxs("span",{style:{fontSize:"0.7rem",padding:"2px 8px",borderRadius:12,background:Q.color+"22",color:Q.color,border:`1px solid ${Q.color}44`,cursor:"pointer"},children:[Q.icon&&`${Q.icon} `,Q.name]},Q.id))})]}),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(!T),children:[s.jsxs("span",{children:["🔗 ",v("playlistManager.services")]}),s.jsx("span",{children:T?"▲":"▼"})]}),T&&s.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[Tt.Spotify,Tt.Tidal,Tt.YouTube].map(Q=>{const ue=lh[Q],ye=r.find(je=>je.platform===Q);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??v("playlistManager.connected")}),s.jsx("button",{style:{...q,color:"#ef4444"},onClick:()=>m(Q),children:"✕"})]}):s.jsx("button",{style:{...q,background:ue.color,color:"#fff",borderRadius:4,padding:"2px 8px"},onClick:()=>g(Q),children:v("playlistManager.connect")})]},Q)})})]})]})},ch=({playlist:e,tags:t,onPlay:n,selectedTrackIds:r,onSelectionChange:a})=>{const{t:o}=ve(),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)})})},si=u.memo(ch),is=e=>e.replace(/[^a-z0-9_-]/gi,"-"),ls={background:"none",border:"none",cursor:"pointer",fontSize:"0.78rem",padding:"2px 4px",opacity:.4},dh=({playlists:e,folders:t,tags:n,activeFolderId:r,onSelectPlaylist:a,onDeletePlaylist:o,onDuplicatePlaylist:i})=>{const{t:l}=ve(),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(g=>g.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:g=>{g.currentTarget.style.boxShadow="0 4px 12px rgba(0,0,0,0.08)",g.currentTarget.style.transform="translateY(-1px)"},onMouseLeave:g=>{g.currentTarget.style.boxShadow="none",g.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(g=>{const m=n.find(p=>p.id===g);return m?s.jsx("span",{style:{padding:"1px 8px",borderRadius:12,background:`var(--tag-${is(g)}-bg, ${m.color}18)`,color:`var(--tag-${is(g)}, ${m.color})`,fontSize:"0.65rem",fontWeight:500},children:m.name},g):null})}),s.jsxs("div",{style:{display:"flex",gap:4,marginTop:8},children:[s.jsx("button",{onClick:g=>{g.stopPropagation(),i(d.id)},style:ls,title:l("playlistManager.duplicate"),children:"📋"}),s.jsx("button",{onClick:g=>{g.stopPropagation(),o(d.id)},style:ls,title:l("playlistManager.delete"),children:"🗑"})]})]},d.id)})})},oi=u.memo(dh),cs=[{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)"}],ii=({onSearch:e,results:t,isSearching:n,onAddToPlaylist:r,onPlayPreview:a})=>{const{t:o}=ve(),[i,l]=u.useState(""),[c,d]=u.useState(new Set([lt.Library,lt.Spotify,lt.Tidal,lt.YouTube])),[h,f]=u.useState(new Set),[g,m]=u.useState(!1),p=u.useRef(null),y=u.useCallback($=>{d(W=>{const w=new Set(W);return w.has($)?w.delete($):w.add($),w})},[]),x=u.useCallback($=>{l($),p.current&&clearTimeout(p.current),$.trim().length>=2&&(p.current=setTimeout(()=>{e($.trim(),Array.from(c))},350))},[c,e]),v=u.useCallback($=>{$.preventDefault(),i.trim().length>=2&&e(i.trim(),Array.from(c))},[i,c,e]),C=u.useCallback($=>{f(W=>{const w=new Set(W);return w.has($)?w.delete($):w.add($),w})},[]),b=u.useCallback(()=>{h.size===t.length?f(new Set):f(new Set(t.map($=>$.id)))},[h,t]),k=u.useCallback(()=>{const $=t.filter(W=>h.has(W.id));$.length>0&&(r($),f(new Set))},[t,h,r]),R=$=>{if(!$)return"--:--";const W=Math.floor($/60),w=$%60;return`${W}:${w.toString().padStart(2,"0")}`},A=$=>{const W=cs.find(w=>w.value===$);return W?W.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:()=>m(!g),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:g?"▲":"▼"})]}),g&&s.jsxs("div",{style:{padding:"0 12px 12px"},children:[s.jsx("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap"},children:cs.map($=>{const W=c.has($.value);return s.jsxs("button",{onClick:()=>y($.value),style:{padding:"4px 10px",borderRadius:20,border:W?`2px solid ${$.css}`:"1px solid var(--border-color, #d1d5db)",background:W?$.cssBg:"transparent",color:W?$.css:"var(--text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:W?600:400,transition:"all 0.15s"},children:[$.icon," ",$.label]},$.value)})}),s.jsxs("form",{onSubmit:v,style:{display:"flex",gap:6,marginBottom:8},children:[s.jsx("input",{type:"text",value:i,onChange:$=>x($.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:b}),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($=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:"1px solid var(--border-color, #f3f4f6)",background:h.has($.id)?"var(--accent-bg, #eff6ff)":"transparent",cursor:"pointer",fontSize:"0.78rem"},onClick:()=>C($.id),children:[s.jsx("input",{type:"checkbox",checked:h.has($.id),readOnly:!0}),s.jsx("span",{children:A($.source)}),$.imageUrl&&s.jsx("img",{src:$.imageUrl,alt:$.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:$.title}),s.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[$.artist,$.album?` — ${$.album}`:""]})]}),s.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:R($.duration)}),a&&s.jsx("button",{onClick:W=>{W.stopPropagation(),a($)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem"},title:o("playlistManager.preview"),children:"▶"})]},$.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")})]})]})},uh=[{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)"}],hh={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},fh={display:"flex",justifyContent:"space-between",alignItems:"center"},ph={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)"},ds={padding:12,borderRadius:8,border:"1px solid var(--border, #e2e8f0)",cursor:"pointer",transition:"border-color 0.15s"},li=["connect","browse","tracks","options","importing","done"];function mh(e){return li.indexOf(e)}function gh(e){if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const ci=({connections:e,onConnect:t,onDisconnect:n,onFetchPlaylists:r,onFetchTracks:a,onImport:o,onClose:i,targetFolders:l})=>{const{t:c}=ve(),[d,h]=u.useState("connect"),[f,g]=u.useState(null),[m,p]=u.useState([]),[y,x]=u.useState(null),[v,C]=u.useState([]),[b,k]=u.useState(new Set),[R,A]=u.useState(!1),[$,W]=u.useState(null),[w,D]=u.useState(null),[_,P]=u.useState(null),[B,z]=u.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[K,Z]=u.useState(""),O=u.useMemo(()=>new Set(e.filter(G=>G.connected).map(G=>G.platform)),[e]),X=u.useCallback(G=>e.find(q=>q.platform===G),[e]),N=u.useCallback(G=>{if(g(G),G===99){h("tracks"),Z(""),C([]),A(!1);return}O.has(G)?(h("browse"),A(!0),P(null),r(G).then(q=>{p(q),A(!1)}).catch(q=>{P(String(q)),A(!1)})):t(G)},[O,t,r]),U=u.useCallback(G=>{x(G),h("tracks"),A(!0),P(null),a(G).then(q=>{C(q),k(new Set(q.map(ee=>ee.externalId))),A(!1)}).catch(q=>{P(String(q)),A(!1)})},[a]),L=u.useCallback(G=>{k(q=>{const ee=new Set(q);return ee.has(G)?ee.delete(G):ee.add(G),ee})},[]),T=u.useCallback(()=>{k(G=>G.size===v.length?new Set:new Set(v.map(q=>q.externalId)))},[v]),S=u.useCallback(async()=>{if(!y)return;const G=v.filter(q=>b.has(q.externalId));if(G.length!==0){h("importing"),W({total:G.length,imported:0,skipped:0,failed:0}),P(null);try{const q=await o(y,G,B);D(q),h("done")}catch(q){P(String(q)),h("options")}}},[y,v,b,B,o]),I=d!=="connect"&&d!=="importing"&&d!=="done",M=u.useCallback(()=>{switch(d){case"browse":h("connect");break;case"tracks":h("browse");break;case"options":h("tracks");break}},[d]),F=()=>s.jsx("div",{style:ph,children:li.map((G,q)=>s.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:q<=mh(d)?"var(--accent, #6366f1)":"var(--border, #e2e8f0)",transition:"background 0.2s"}},G))}),j=()=>s.jsxs("div",{style:{display:"grid",gap:12},children:[s.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:c("importWizard.selectPlatform","Select a music platform to import from")}),uh.map(G=>{const q=X(G.value),ee=O.has(G.value);return s.jsxs("div",{style:{...ds,display:"flex",alignItems:"center",gap:12,borderColor:ee?G.color:void 0},onClick:()=>N(G.value),role:"button",tabIndex:0,onKeyDown:oe=>oe.key==="Enter"&&N(G.value),children:[s.jsx("span",{style:{fontSize:24},children:G.icon}),s.jsxs("div",{style:{flex:1},children:[s.jsx("strong",{children:G.label}),(q==null?void 0:q.username)&&s.jsx("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:q.username})]}),ee?s.jsxs("span",{style:{color:G.color,fontSize:12,fontWeight:600},children:[c("importWizard.connected","Connected")," ✓"]}):s.jsx("span",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:c("importWizard.clickToConnect","Click to connect")})]},G.value)})]}),E=()=>s.jsxs("div",{style:{display:"grid",gap:12},children:[s.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:c("importWizard.selectPlaylist","Select a playlist to import")}),R?s.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--text-dim, #64748b)"},children:c("importWizard.loading","Loading playlists…")}):s.jsxs("div",{style:{display:"grid",gap:8,maxHeight:320,overflowY:"auto"},children:[m.map(G=>s.jsxs("div",{style:{...ds,display:"flex",alignItems:"center",gap:12},onClick:()=>U(G),role:"button",tabIndex:0,onKeyDown:q=>q.key==="Enter"&&U(G),children:[G.coverUrl&&s.jsx("img",{src:G.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:G.name}),G.description&&s.jsx("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:G.description})]}),s.jsxs("span",{style:{fontSize:12,color:"var(--text-dim, #64748b)",whiteSpace:"nowrap"},children:[G.trackCount," ",c("importWizard.tracks","tracks")]})]},G.id)),m.length===0&&s.jsx("div",{style:{textAlign:"center",padding:24,color:"var(--text-dim, #64748b)"},children:c("importWizard.noPlaylists","No playlists found")})]})]}),H=u.useCallback(G=>{const ee=G.split(`
51
- `).map(oe=>oe.trim()).filter(Boolean).map((oe,ce)=>{const fe=oe.match(/^(.+?)\s*[-–—]\s*(.+)$/);return fe?{externalId:`paste-${ce}`,title:fe[2].trim(),artist:fe[1].trim(),album:void 0,duration:0}:{externalId:`paste-${ce}`,title:oe,artist:"",album:void 0,duration:0}});C(ee),k(new Set(ee.map(oe=>oe.externalId)))},[]),Y=()=>s.jsxs("div",{style:{display:"grid",gap:12},children:[f===99&&v.length===0&&s.jsxs("div",{style:{display:"grid",gap:8},children:[s.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:c("importWizard.pasteInstructions",'Paste your track list below (one track per line). Use "Artist - Title" format for best results.')}),s.jsx("textarea",{value:K,onChange:G=>Z(G.target.value),placeholder:`Daft Punk - Get Lucky
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:Z,disabled:!p.trim(),style:{padding:"6px 10px",borderRadius:6,border:"1px solid #d1d5db",background:"#f9fafb"},children:h("genericPlaylist.addFromList","Add from list")})]})]})]})})]})},ns=["#ef4444","#f97316","#f59e0b","#eab308","#84cc16","#22c55e","#14b8a6","#06b6d4","#3b82f6","#6366f1","#8b5cf6","#a855f7","#d946ef","#ec4899","#f43f5e","#78716c","#64748b","#000000"],Ln=["🎵","🎸","🎹","🎤","🎧","🥁","🎷","🎺","❤️","⭐","🔥","💎","🌙","☀️","🌊","🎯"],qo=({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(""),[g,m]=u.useState(ns[8]),[p,y]=u.useState(Ln[0]),[v,x]=u.useState(!1),[C,b]=u.useState(null),[k,R]=u.useState(""),[A,$]=u.useState(""),[W,w]=u.useState(""),D=u.useCallback(O=>{d(O.id),R(O.name),$(O.color),w(O.icon||Ln[0])},[]),_=u.useCallback(()=>{c&&k.trim()&&(n(c,k.trim(),A,W),d(null))},[c,k,A,W,n]),P=u.useCallback(()=>{h.trim()&&(t(h.trim(),g,p),f(""),x(!1))},[h,g,p,t]),B=u.useCallback(O=>{C===O?(r(O),b(null)):(b(O),setTimeout(()=>b(null),3e3))},[C,r]),z=a&&a.length>0,K=O=>!a||a.length===0?!1:a.every(X=>X.tags.includes(O)),Z=O=>!a||a.length===0?!1:a.some(X=>X.tags.includes(O))&&!K(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:()=>x(!v),style:{background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"4px 10px",fontSize:"0.72rem",cursor:"pointer"},children:["+ ",l("playlistManager.newTag")]})]}),s.jsxs("div",{style:{padding:12},children:[v&&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"&&P()}),s.jsx("button",{onClick:P,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:ns.map(O=>s.jsx("div",{onClick:()=>m(O),style:{width:20,height:20,borderRadius:"50%",background:O,cursor:"pointer",border:g===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:()=>y(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))})]})]}),z&&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:W,onChange:X=>w(X.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:Ln.map(X=>s.jsx("option",{value:X,children:X},X))}),s.jsx("input",{type:"color",value:A,onChange:X=>$(X.target.value),style:{width:24,height:24,border:"none",cursor:"pointer",padding:0}}),s.jsx("input",{type:"text",value:k,onChange:X=>R(X.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:X=>X.key==="Enter"&&_()}),s.jsx("button",{onClick:_,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]}),z&&o&&i&&s.jsx("input",{type:"checkbox",checked:K(O.id),ref:X=>{X&&(X.indeterminate=Z(O.id))},onChange:()=>{const X=a.map(N=>N.id);K(O.id)?i(X,O.id):o(X,O.id)},style:{cursor:"pointer"}}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:()=>D(O),style:Fn("var(--text-secondary, #9ca3af)"),title:l("playlistManager.editTag"),children:"✏"}),s.jsx("button",{onClick:()=>B(O.id),style:Fn(C===O.id?"var(--error, #ef4444)":"var(--text-secondary, #9ca3af)"),title:C===O.id?l("playlistManager.confirmDelete"):l("playlistManager.deleteTag"),children:C===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||{}),Ho=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(Ho||{}),Ko=(e=>(e.Left="left",e.Right="right",e))(Ko||{}),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||{}),Yo=(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))(Yo||{}),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 Zo(){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:"✕"})]}),Xo=({group:e,onChange:t,onRemove:n,depth:r=0})=>{const{t:a}=xe(),o=u.useCallback((f,g)=>{const m=[...e.rules];m[f]=g,t({...e,rules:m})},[e,t]),i=u.useCallback(f=>{const g=e.rules.filter((m,p)=>p!==f);t({...e,rules:g.length>0?g:[zr()]})},[e,t]),l=u.useCallback(()=>{t({...e,rules:[...e.rules,zr()]})},[e,t]),c=u.useCallback(()=>{t({...e,rules:[...e.rules,Zo()]})},[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,g)=>Ju(f)?s.jsx(Xo,{group:f,onChange:m=>o(g,m),onRemove:()=>i(g),depth:r+1},f.id):s.jsx(eh,{rule:f,onChange:m=>o(g,m),onRemove:()=>i(g)},f.id))]})},Qo=({rules:e,onChange:t,limit:n,onLimitChange:r})=>{const{t:a}=xe(),o=e??Zo();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(Xo,{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)")})]})]})},rs=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:g,onFilterChange:m,compact:p=!1,draggable:y=!1,onDragStart:v,dropTarget:x=!1,onDrop:C})=>{const{t:b}=xe(),[k,R]=u.useState(null),[A,$]=u.useState(null),W=u.useRef(null),w=u.useMemo(()=>{let S=e??[];if(g.trim()){const I=g.toLowerCase();S=S.filter(M=>{var F,j;return M.title.toLowerCase().includes(I)||M.artist.toLowerCase().includes(I)||((F=M.album)==null?void 0:F.toLowerCase().includes(I))||((j=M.genre)==null?void 0:j.toLowerCase().includes(I))})}return[...S].sort((I,M)=>{const F=h==="asc"?1:-1;switch(d){case"title":return F*I.title.localeCompare(M.title);case"artist":return F*I.artist.localeCompare(M.artist);case"album":return F*(I.album??"").localeCompare(M.album??"");case"duration":return F*((I.duration??0)-(M.duration??0));case"year":return F*((I.year??0)-(M.year??0));case"rating":return F*((I.rating??0)-(M.rating??0));case"addedDate":return F*(I.addedAt??"").localeCompare(M.addedAt??"");case"custom":return F*((I.customOrder??0)-(M.customOrder??0));default:return 0}})},[e,g,d,h]),D=u.useCallback((S,I)=>{const M=w[S];if(M){if(I.ctrlKey||I.metaKey){const F=new Set(n);F.has(M.id)?F.delete(M.id):F.add(M.id),r(F)}else if(I.shiftKey&&W.current!==null){const F=Math.min(W.current,S),j=Math.max(W.current,S),E=new Set(n);for(let H=F;H<=j;H++)E.add(w[H].id);r(E)}else r(new Set([M.id]));W.current=S}},[w,n,r]),_=u.useCallback(()=>{n.size===w.length?r(new Set):r(new Set(w.map(S=>S.id)))},[w,n,r]),P=({field:S,label:I,width:M})=>{const F=d===S;return s.jsxs("div",{style:{width:M,flex:M?void 0:1,cursor:"pointer",userSelect:"none",fontWeight:F?700:500,fontSize:"0.72rem",textTransform:"uppercase",letterSpacing:"0.04em",opacity:F?1:.6,display:"flex",alignItems:"center",gap:4},onClick:()=>{F?f(S,h===qt.Asc?qt.Desc:qt.Asc):f(S,qt.Asc)},children:[I,F&&s.jsx("span",{children:h==="asc"?"↑":"↓"})]})},B=u.useCallback((S,I)=>{const M=n.has(S.id)?Array.from(n):[S.id];I.dataTransfer.setData("trackIds",JSON.stringify(M)),I.dataTransfer.effectAllowed="move",v==null||v(M,I)},[n,v]),z=u.useCallback((S,I)=>{I.preventDefault(),I.dataTransfer.dropEffect="move",R(S)},[]),K=u.useCallback((S,I)=>{I.preventDefault(),R(null);try{const M=I.dataTransfer.getData("trackIds");if(M&&i){const F=JSON.parse(M),j=w.filter(Y=>!F.includes(Y.id)),E=w.filter(Y=>F.includes(Y.id)),H=Math.min(S,j.length);j.splice(H,0,...E),i(j.map(Y=>Y.id))}}catch{}},[w,i]),Z=u.useCallback(S=>{S.preventDefault(),R(null),C==null||C(S)},[C]),O=u.useMemo(()=>new Map(t.map(S=>[S.id,S])),[t]),X=S=>S.replace(/[^a-z0-9_-]/gi,"-"),N=p?36:48,U={display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)",color:"var(--text-secondary, #6b7280)"},L=(S,I)=>({display:"flex",alignItems:"center",gap:8,padding:p?"4px 12px":"6px 12px",height:N,cursor:"pointer",background:I?"var(--accent-light, #dbeafe)":S?"var(--selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--border-subtle, #f3f4f6)",transition:"background 0.1s"}),T=w.length>0&&n.size===w.length;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:x?S=>{S.preventDefault(),S.dataTransfer.dropEffect="copy"}:void 0,onDrop:x?Z: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:g,onChange:S=>m(S.target.value),placeholder:"🔍 "+b("playlistManager.filterTracks"),style:{flex:1,fontSize:"0.82rem",padding:"6px 10px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #f9fafb)",color:"var(--text-primary, #1f2937)"}}),s.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[w.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:U,children:[s.jsx("div",{style:{width:28},children:s.jsx("input",{type:"checkbox",checked:T,onChange:_,style:{cursor:"pointer"}})}),s.jsx("div",{style:{width:20},children:"#"}),!p&&s.jsx("div",{style:{width:44}}),s.jsx(P,{field:"title",label:b("playlistManager.colTitle")}),s.jsx(P,{field:"artist",label:b("playlistManager.colArtist")}),!p&&s.jsx(P,{field:"album",label:b("playlistManager.colAlbum")}),s.jsx(P,{field:"duration",label:b("playlistManager.colDuration"),width:60}),!p&&s.jsx(P,{field:"year",label:b("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:[w.length===0&&s.jsx("div",{style:{padding:24,textAlign:"center",opacity:.4,fontSize:"0.85rem"},children:e.length===0?b("playlistManager.emptyPlaylist"):b("playlistManager.noMatchingTracks")}),w.map((S,I)=>{const M=n.has(S.id),F=k===I;return s.jsxs("div",{style:L(M,F),onClick:j=>D(I,j),onDoubleClick:()=>a==null?void 0:a(S),draggable:y,onDragStart:j=>B(S,j),onDragOver:j=>z(I,j),onDrop:j=>K(I,j),onDragLeave:()=>R(null),children:[s.jsx("div",{style:{width:28},children:s.jsx("input",{type:"checkbox",checked:M,onChange:()=>{const j=new Set(n);M?j.delete(S.id):j.add(S.id),r(j)},onClick:j=>j.stopPropagation(),style:{cursor:"pointer"}})}),s.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:I+1}),!p&&s.jsx("div",{style:{width:44,height:36,flexShrink:0},children:S.coverUrl?s.jsx("img",{src:S.coverUrl,alt:S.title||b("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:rs(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(j=>{const E=O.get(j);if(!E)return null;const H=`--tag-${X(j)}`;return s.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${H}-bg, ${E.color}22)`,color:`var(${H}, ${E.color})`,whiteSpace:"nowrap"},children:E.name},j)}),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:j=>{j.stopPropagation(),$(A===S.id?null:S.id)},title:b("playlistManager.morActions"),children:"⋮"}),A===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:b("playlistManager.assignTag")}),t.map(j=>{const E=S.tags.includes(j.id);return s.jsxs("div",{style:{padding:"4px 8px",borderRadius:4,cursor:"pointer",fontSize:"0.78rem",display:"flex",alignItems:"center",gap:6,background:E?`var(--tag-${X(j.id)}-bg, ${j.color}22)`:"transparent"},onClick:H=>{H.stopPropagation();const Y=n.size>0?Array.from(n):[S.id];E||l==null||l(Y,[j.id]),$(null)},children:[s.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:`var(--tag-${X(j.id)}, ${j.color})`,flexShrink:0}}),s.jsx("span",{children:j.name}),E&&s.jsx("span",{style:{marginLeft:"auto"},children:"✓"})]},j.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:[w.length," ",b("playlistManager.tracks")]}),s.jsx("span",{children:rs(w.reduce((S,I)=>S+(I.duration??0),0))}),n.size>0&&s.jsxs("span",{children:[n.size," ",b("playlistManager.selected")]})]})]})},as=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),Jo=({playlists:e,tags:t,onCopyTracks:n,onMoveTracks:r,onRemoveTracks:a,onReorderTracks:o,onPlay:i,onTagTracks:l,initialLeftId:c,initialRightId:d})=>{const{t:h}=xe(),[f,g]=u.useState(()=>as(c??null)),[m,p]=u.useState(()=>as(d??null)),[y,v]=u.useState("left"),[x,C]=u.useState(null),[b,k]=u.useState(50),[R,A]=u.useState(!1),$=u.useMemo(()=>e.find(T=>T.id===f.playlistId),[e,f.playlistId]),W=u.useMemo(()=>e.find(T=>T.id===m.playlistId),[e,m.playlistId]),w=u.useCallback((T,S)=>{T==="left"?g(I=>({...I,...S})):p(I=>({...I,...S}))},[]),D=u.useCallback(T=>T==="left"?f:m,[f,m]),_=T=>T==="left"?"right":"left",P=u.useCallback(T=>{const S=D(T),I=D(_(T));!S.playlistId||!I.playlistId||S.selectedTrackIds.size===0||(n(S.playlistId,I.playlistId,Array.from(S.selectedTrackIds)),w(T,{selectedTrackIds:new Set}))},[D,n,w]),B=u.useCallback(T=>{const S=D(T),I=D(_(T));!S.playlistId||!I.playlistId||S.selectedTrackIds.size===0||(r(S.playlistId,I.playlistId,Array.from(S.selectedTrackIds)),w(T,{selectedTrackIds:new Set}))},[D,r,w]),z=u.useCallback(T=>{const S=D(T);!S.playlistId||S.selectedTrackIds.size===0||C({operation:"copy",sourcePlaylistId:S.playlistId,trackIds:Array.from(S.selectedTrackIds)})},[D]),K=u.useCallback(T=>{const S=D(T);!S.playlistId||S.selectedTrackIds.size===0||C({operation:"cut",sourcePlaylistId:S.playlistId,trackIds:Array.from(S.selectedTrackIds)})},[D]),Z=u.useCallback(T=>{const S=D(T);!x||!S.playlistId||(x.operation==="copy"?n(x.sourcePlaylistId,S.playlistId,x.trackIds):r(x.sourcePlaylistId,S.playlistId,x.trackIds),C(null))},[x,D,n,r]),O=u.useCallback(T=>{T.key==="Tab"&&!T.shiftKey&&(T.preventDefault(),v(S=>_(S))),(T.ctrlKey||T.metaKey)&&T.key==="c"&&z(y),(T.ctrlKey||T.metaKey)&&T.key==="x"&&K(y),(T.ctrlKey||T.metaKey)&&T.key==="v"&&Z(y)},[y,z,K,Z]),X=u.useCallback(()=>A(!0),[]),N=u.useCallback(T=>{if(!R)return;const S=T.currentTarget.getBoundingClientRect(),I=(T.clientX-S.left)/S.width*100;k(Math.max(20,Math.min(80,I)))},[R]),U=u.useCallback(()=>A(!1),[]),L=T=>{const S=D(T),I=T==="left"?$:W,M=y===T,j=!!D(_(T)).playlistId;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",border:M?"2px solid var(--accent, #3b82f6)":"2px solid transparent",borderRadius:8,overflow:"hidden",background:"var(--card-bg, #fff)"},onClick:()=>v(T),children:[s.jsx("div",{style:{padding:"8px 12px",background:M?"var(--accent, #3b82f6)":"var(--surface-bg, #f3f4f6)",color:M?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:s.jsxs("select",{value:S.playlistId??"",onChange:E=>w(T,{playlistId:E.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:M?"var(--accent-overlay, #ffffff30)":"var(--input-bg, #fff)",color:M?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)"},children:[s.jsx("option",{value:"",children:h("playlistManager.selectPlaylist")}),e.map(E=>s.jsxs("option",{value:E.id,children:[E.name," (",E.trackCount,")"]},E.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:Mr(!1),onClick:()=>P(T),disabled:!S.playlistId||!j||S.selectedTrackIds.size===0,title:h("playlistManager.copyToOther"),children:[T==="left"?"📋→":"←📋"," ",h("playlistManager.copy")]}),s.jsxs("button",{style:Mr(!1),onClick:()=>B(T),disabled:!S.playlistId||!j||S.selectedTrackIds.size===0,title:h("playlistManager.moveToOther"),children:[T==="left"?"✂→":"←✂"," ",h("playlistManager.move")]}),s.jsx("div",{style:{flex:1}}),x&&s.jsxs("button",{style:Mr(!0),onClick:()=>Z(T),disabled:!S.playlistId,children:["📌 ",h("playlistManager.paste")," (",x.trackIds.length,")"]})]}),I?s.jsx(ga,{tracks:I.tracks,tags:t,selectedTrackIds:S.selectedTrackIds,onSelectionChange:E=>w(T,{selectedTrackIds:E}),onPlay:i,onRemove:E=>a(I.id,E),onReorder:E=>o(I.id,E),onTagTracks:l,sortField:S.sortField,sortDir:S.sortDir,onSortChange:(E,H)=>w(T,{sortField:E,sortDir:H}),filterText:S.filterText,onFilterChange:E=>w(T,{filterText:E}),compact:!0,draggable:!0}):s.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",opacity:.3,fontSize:"0.85rem"},children:h("playlistManager.selectPlaylistPrompt")})]})};return s.jsxs("div",{style:{display:"flex",height:"100%",userSelect:R?"none":"auto"},onKeyDown:O,onMouseMove:N,onMouseUp:U,tabIndex:0,children:[s.jsx("div",{style:{width:`${b}%`,minWidth:200},children:L("left")}),s.jsx("div",{style:{width:6,cursor:"col-resize",background:R?"var(--accent, #3b82f6)":"var(--border-color, #e5e7eb)",transition:R?"none":"background 0.15s",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseDown:X,children:s.jsx("div",{style:{width:2,height:40,borderRadius:1,background:R?"var(--btn-text, #fff)":"var(--text-secondary, #9ca3af)"}})}),s.jsx("div",{style:{flex:1,minWidth:200},children:L("right")})]})},Mr=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"}),ei="av:local-playlists";function nh(){try{const e=localStorage.getItem(ei);return e?JSON.parse(e):[]}catch{return[]}}function rh(e){const t=JSON.stringify(e);try{localStorage.setItem(ei,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"},ti={border:"1px solid var(--border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--bg, #fff)",cursor:"pointer"},ih={...ti,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:{...ti,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"),ss={display:"grid",gap:12},os=e=>({artist:(e.artists??[]).join(", "),title:e.title}),ni=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:n})=>{var g;const{t:r}=xe(),a=ya(),[o,i]=u.useState(null),[l,c]=u.useState(""),[,d]=u.useState([]),h=o==null?void 0:o.id,f=(m,p)=>{if("addItems"in a){a.addItems(m.id,p);const v=a.list().find(x=>x.id===m.id)||m;i(v);return}const y=a;if("update"in a&&typeof y.update=="function"){const v=Array.from([...m.items||[],...p]);y.update({...m,items:v});const x=a.list().find(C=>C.id===m.id)||{...m,items:v};i(x);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:ss,children:[s.jsx("h3",{style:{margin:0},children:r("playlistBrowser.playlists")}),s.jsx(ba,{selectedId:h,onSelect:i}),o&&s.jsxs("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:[r("playlistBrowser.selected","Selected"),": ",s.jsx("strong",{children:o.name})," � ",((g=o.items)==null?void 0:g.length)??0," ",r("playlistBrowser.tracks","tracks")]})]}),s.jsxs("div",{style:ss,children:[s.jsx("h3",{style:{margin:0},children:r("playlistBrowser.library")}),s.jsxs("div",{children:[e==null?void 0:e({placeholder:r("playlistBrowser.searchAndAdd","Search and add to playlist..."),onPick:m=>{o&&f(o,[os(m)])}}),s.jsx("input",{placeholder:r("playlistBrowser.fullSearch","Full search (Enter does not add, full list below)"),value:l,onChange:m=>c(m.target.value),style:{width:"100%",border:"1px solid #d1d5db",borderRadius:8,padding:"6px 10px",marginTop:10}})]}),t==null?void 0:t({query:l,onPick:m=>{o&&f(o,[os(m)])}}),n==null?void 0:n({onPlayNow:m=>d(m),onAddToQueue:m=>d(p=>[...p,...m]),onAddDescriptors:m=>o&&f(o,m)})]})]})};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 ri=(e,t=null)=>e.filter(n=>n.parentId===t).sort((n,r)=>n.sortOrder-r.sortOrder).map(n=>({...n,children:ri(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)"}},ai=({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:g,onDisconnectService:m,onDragPlaylistToFolder:p,collapsed:y=!1,onToggleCollapse:v})=>{const{t:x}=xe(),[C,b]=u.useState(new Set),[k,R]=u.useState(!1),[A,$]=u.useState(""),[W,w]=u.useState(null),[D,_]=u.useState(!1),[P,B]=u.useState(""),[z,K]=u.useState("static"),[Z,O]=u.useState(null),[X,N]=u.useState(""),[U,L]=u.useState(null),[T,S]=u.useState(!1),I=u.useMemo(()=>ri(e),[e]),M=u.useCallback(Q=>{b(ue=>{const ye=new Set(ue);return ye.has(Q)?ye.delete(Q):ye.add(Q),ye})},[]),F=u.useCallback(()=>{A.trim()&&(c(A.trim(),W),$(""),R(!1))},[A,W,c]),j=u.useCallback(()=>{P.trim()&&(f(P.trim(),z,a),B(""),_(!1))},[P,z,a,f]),E=u.useCallback(Q=>{X.trim()&&(d(Q,X.trim()),O(null),N(""))},[X,d]),H=u.useCallback((Q,ue)=>{Q.preventDefault(),Q.dataTransfer.dropEffect="move",L(ue)},[]),Y=u.useCallback((Q,ue)=>{Q.preventDefault();const ye=Q.dataTransfer.getData("playlistId");ye&&p&&p(ye,ue),L(null)},[p]),J=u.useCallback(()=>L(null),[]),ne=u.useCallback(Q=>t.filter(ue=>(ue.folderId??null)===Q),[t]),ae={width:y?48:280,minWidth:y?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)"},G=(Q,ue=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:ue?"var(--accent-light, #dbeafe)":Q?"var(--accent, #3b82f6)":"transparent",color:Q?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",transition:"background 0.15s",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),q={background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:"2px 6px",borderRadius:4,color:"var(--text-secondary, #6b7280)"},ee={fontSize:"0.8rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)",width:"100%"},oe=(Q,ue)=>{var Se,te;const ye=C.has(Q.id),je=a===Q.id,Fe=U===Q.id,Re=ne(Q.id);return s.jsxs("div",{children:[s.jsxs("div",{style:{...G(je,Fe),paddingLeft:12+ue*16},onClick:()=>{i(Q.id),Q.children&&Q.children.length>0&&M(Q.id)},onDragOver:se=>H(se,Q.id),onDrop:se=>Y(se,Q.id),onDragLeave:J,children:[s.jsx("span",{style:{width:14,textAlign:"center",flexShrink:0,fontSize:"0.7rem"},children:(((Se=Q.children)==null?void 0:Se.length)||0)>0||Re.length>0?ye?"▼":"▶":"·"}),Z===Q.id?s.jsx("input",{value:X,onChange:se=>N(se.target.value),onKeyDown:se=>{se.key==="Enter"&&E(Q.id),se.key==="Escape"&&O(null)},onBlur:()=>E(Q.id),autoFocus:!0,style:{...ee,flex:1},onClick:se=>se.stopPropagation()}):s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Q.icon??"📁"}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:Q.name}),s.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:Re.length}),s.jsx("button",{style:q,onClick:se=>{se.stopPropagation(),O(Q.id),N(Q.name)},title:x("common.rename"),children:"✏"}),s.jsx("button",{style:{...q,color:"var(--error, #ef4444)"},onClick:se=>{se.stopPropagation(),h(Q.id)},title:x("common.delete"),children:"✕"})]})]}),ye&&s.jsxs(s.Fragment,{children:[Re.map(se=>ce(se,ue+1)),(te=Q.children)==null?void 0:te.map(se=>oe(se,ue+1))]})]},Q.id)},ce=(Q,ue)=>{const ye=o===Q.id;return s.jsxs("div",{style:{...G(ye),paddingLeft:12+ue*16+22},onClick:()=>l(Q.id),draggable:!0,onDragStart:je=>{je.dataTransfer.setData("playlistId",Q.id),je.dataTransfer.effectAllowed="move"},children:[s.jsx("span",{style:{fontSize:"0.7rem"},children:Q.type==="dynamic"?"⚡":"🎵"}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:Q.name}),s.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:Q.trackCount})]},Q.id)};if(y)return s.jsx("div",{style:ae,children:s.jsx("button",{style:{...q,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:v,title:x("playlistManager.expandSidebar"),children:"▶"})});const fe=ne(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:["🎶 ",x("playlistManager.title")]}),s.jsx("button",{style:q,onClick:v,title:x("playlistManager.collapseSidebar"),children:"◀"})]}),s.jsxs("div",{style:{...re,display:"flex",gap:4,flexWrap:"wrap"},children:[s.jsxs("button",{style:{...q,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:6,padding:"4px 10px"},onClick:()=>_(!0),children:["+ ",x("playlistManager.newPlaylist")]}),s.jsxs("button",{style:{...q,border:"1px solid var(--border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{R(!0),w(a)},children:["📁 ",x("playlistManager.newFolder")]})]}),D&&s.jsxs("div",{style:{...re,display:"flex",flexDirection:"column",gap:6},children:[s.jsx("input",{value:P,onChange:Q=>B(Q.target.value),placeholder:x("playlistManager.playlistName"),style:ee,autoFocus:!0,onKeyDown:Q=>{Q.key==="Enter"&&j(),Q.key==="Escape"&&_(!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:z==="static",onChange:()=>K("static")}),x("playlistManager.static")]}),s.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[s.jsx("input",{type:"radio",checked:z==="dynamic",onChange:()=>K("dynamic")}),"⚡ ",x("playlistManager.dynamic")]}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{style:{...q,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:j,"aria-label":"Confirm create playlist",children:"✓"}),s.jsx("button",{style:q,onClick:()=>_(!1),"aria-label":"Cancel create playlist",children:"✕"})]})]}),k&&s.jsxs("div",{style:{...re,display:"flex",gap:6},children:[s.jsx("input",{value:A,onChange:Q=>$(Q.target.value),placeholder:x("playlistManager.folderName"),style:{...ee,flex:1},autoFocus:!0,onKeyDown:Q=>{Q.key==="Enter"&&F(),Q.key==="Escape"&&R(!1)}}),s.jsx("button",{style:{...q,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:F,"aria-label":"Confirm create folder",children:"✓"}),s.jsx("button",{style:q,onClick:()=>R(!1),"aria-label":"Cancel create folder",children:"✕"})]}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsxs("div",{style:G(a===null&&o===null,U==="__root__"),onClick:()=>i(null),onDragOver:Q=>H(Q,null),onDrop:Q=>Y(Q,null),onDragLeave:J,children:[s.jsx("span",{children:"🏠"}),s.jsx("span",{style:{flex:1},children:x("playlistManager.allPlaylists")}),s.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:t.length})]}),fe.map(Q=>ce(Q,0)),I.map(Q=>oe(Q,0))]}),n.length>0&&s.jsxs("div",{style:re,children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:x("playlistManager.tags")}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:n.map(Q=>s.jsxs("span",{style:{fontSize:"0.7rem",padding:"2px 8px",borderRadius:12,background:Q.color+"22",color:Q.color,border:`1px solid ${Q.color}44`,cursor:"pointer"},children:[Q.icon&&`${Q.icon} `,Q.name]},Q.id))})]}),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(!T),children:[s.jsxs("span",{children:["🔗 ",x("playlistManager.services")]}),s.jsx("span",{children:T?"▲":"▼"})]}),T&&s.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[Tt.Spotify,Tt.Tidal,Tt.YouTube].map(Q=>{const ue=ch[Q],ye=r.find(je=>je.platform===Q);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??x("playlistManager.connected")}),s.jsx("button",{style:{...q,color:"#ef4444"},onClick:()=>m(Q),children:"✕"})]}):s.jsx("button",{style:{...q,background:ue.color,color:"#fff",borderRadius:4,padding:"2px 8px"},onClick:()=>g(Q),children:x("playlistManager.connect")})]},Q)})})]})]})},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)})})},si=u.memo(dh),is=e=>e.replace(/[^a-z0-9_-]/gi,"-"),ls={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(g=>g.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:g=>{g.currentTarget.style.boxShadow="0 4px 12px rgba(0,0,0,0.08)",g.currentTarget.style.transform="translateY(-1px)"},onMouseLeave:g=>{g.currentTarget.style.boxShadow="none",g.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(g=>{const m=n.find(p=>p.id===g);return m?s.jsx("span",{style:{padding:"1px 8px",borderRadius:12,background:`var(--tag-${is(g)}-bg, ${m.color}18)`,color:`var(--tag-${is(g)}, ${m.color})`,fontSize:"0.65rem",fontWeight:500},children:m.name},g):null})}),s.jsxs("div",{style:{display:"flex",gap:4,marginTop:8},children:[s.jsx("button",{onClick:g=>{g.stopPropagation(),i(d.id)},style:ls,title:l("playlistManager.duplicate"),children:"📋"}),s.jsx("button",{onClick:g=>{g.stopPropagation(),o(d.id)},style:ls,title:l("playlistManager.delete"),children:"🗑"})]})]},d.id)})})},oi=u.memo(uh),cs=[{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)"}],ii=({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),[g,m]=u.useState(!1),p=u.useRef(null),y=u.useCallback($=>{d(W=>{const w=new Set(W);return w.has($)?w.delete($):w.add($),w})},[]),v=u.useCallback($=>{l($),p.current&&clearTimeout(p.current),$.trim().length>=2&&(p.current=setTimeout(()=>{e($.trim(),Array.from(c))},350))},[c,e]),x=u.useCallback($=>{$.preventDefault(),i.trim().length>=2&&e(i.trim(),Array.from(c))},[i,c,e]),C=u.useCallback($=>{f(W=>{const w=new Set(W);return w.has($)?w.delete($):w.add($),w})},[]),b=u.useCallback(()=>{h.size===t.length?f(new Set):f(new Set(t.map($=>$.id)))},[h,t]),k=u.useCallback(()=>{const $=t.filter(W=>h.has(W.id));$.length>0&&(r($),f(new Set))},[t,h,r]),R=$=>{if(!$)return"--:--";const W=Math.floor($/60),w=$%60;return`${W}:${w.toString().padStart(2,"0")}`},A=$=>{const W=cs.find(w=>w.value===$);return W?W.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:()=>m(!g),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:g?"▲":"▼"})]}),g&&s.jsxs("div",{style:{padding:"0 12px 12px"},children:[s.jsx("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap"},children:cs.map($=>{const W=c.has($.value);return s.jsxs("button",{onClick:()=>y($.value),style:{padding:"4px 10px",borderRadius:20,border:W?`2px solid ${$.css}`:"1px solid var(--border-color, #d1d5db)",background:W?$.cssBg:"transparent",color:W?$.css:"var(--text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:W?600:400,transition:"all 0.15s"},children:[$.icon," ",$.label]},$.value)})}),s.jsxs("form",{onSubmit:x,style:{display:"flex",gap:6,marginBottom:8},children:[s.jsx("input",{type:"text",value:i,onChange:$=>v($.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:b}),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($=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:"1px solid var(--border-color, #f3f4f6)",background:h.has($.id)?"var(--accent-bg, #eff6ff)":"transparent",cursor:"pointer",fontSize:"0.78rem"},onClick:()=>C($.id),children:[s.jsx("input",{type:"checkbox",checked:h.has($.id),readOnly:!0}),s.jsx("span",{children:A($.source)}),$.imageUrl&&s.jsx("img",{src:$.imageUrl,alt:$.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:$.title}),s.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[$.artist,$.album?` — ${$.album}`:""]})]}),s.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:R($.duration)}),a&&s.jsx("button",{onClick:W=>{W.stopPropagation(),a($)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem"},title:o("playlistManager.preview"),children:"▶"})]},$.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)"},ds={padding:12,borderRadius:8,border:"1px solid var(--border, #e2e8f0)",cursor:"pointer",transition:"border-color 0.15s"},li=["connect","browse","tracks","options","importing","done"];function gh(e){return li.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 ci=({connections:e,onConnect:t,onDisconnect:n,onFetchPlaylists:r,onFetchTracks:a,onImport:o,onClose:i,targetFolders:l})=>{const{t:c}=xe(),[d,h]=u.useState("connect"),[f,g]=u.useState(null),[m,p]=u.useState([]),[y,v]=u.useState(null),[x,C]=u.useState([]),[b,k]=u.useState(new Set),[R,A]=u.useState(!1),[$,W]=u.useState(null),[w,D]=u.useState(null),[_,P]=u.useState(null),[B,z]=u.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[K,Z]=u.useState(""),O=u.useMemo(()=>new Set(e.filter(G=>G.connected).map(G=>G.platform)),[e]),X=u.useCallback(G=>e.find(q=>q.platform===G),[e]),N=u.useCallback(G=>{if(g(G),G===99){h("tracks"),Z(""),C([]),A(!1);return}O.has(G)?(h("browse"),A(!0),P(null),r(G).then(q=>{p(q),A(!1)}).catch(q=>{P(String(q)),A(!1)})):t(G)},[O,t,r]),U=u.useCallback(G=>{v(G),h("tracks"),A(!0),P(null),a(G).then(q=>{C(q),k(new Set(q.map(ee=>ee.externalId))),A(!1)}).catch(q=>{P(String(q)),A(!1)})},[a]),L=u.useCallback(G=>{k(q=>{const ee=new Set(q);return ee.has(G)?ee.delete(G):ee.add(G),ee})},[]),T=u.useCallback(()=>{k(G=>G.size===x.length?new Set:new Set(x.map(q=>q.externalId)))},[x]),S=u.useCallback(async()=>{if(!y)return;const G=x.filter(q=>b.has(q.externalId));if(G.length!==0){h("importing"),W({total:G.length,imported:0,skipped:0,failed:0}),P(null);try{const q=await o(y,G,B);D(q),h("done")}catch(q){P(String(q)),h("options")}}},[y,x,b,B,o]),I=d!=="connect"&&d!=="importing"&&d!=="done",M=u.useCallback(()=>{switch(d){case"browse":h("connect");break;case"tracks":h("browse");break;case"options":h("tracks");break}},[d]),F=()=>s.jsx("div",{style:mh,children:li.map((G,q)=>s.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:q<=gh(d)?"var(--accent, #6366f1)":"var(--border, #e2e8f0)",transition:"background 0.2s"}},G))}),j=()=>s.jsxs("div",{style:{display:"grid",gap:12},children:[s.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:c("importWizard.selectPlatform","Select a music platform to import from")}),hh.map(G=>{const q=X(G.value),ee=O.has(G.value);return s.jsxs("div",{style:{...ds,display:"flex",alignItems:"center",gap:12,borderColor:ee?G.color:void 0},onClick:()=>N(G.value),role:"button",tabIndex:0,onKeyDown:oe=>oe.key==="Enter"&&N(G.value),children:[s.jsx("span",{style:{fontSize:24},children:G.icon}),s.jsxs("div",{style:{flex:1},children:[s.jsx("strong",{children:G.label}),(q==null?void 0:q.username)&&s.jsx("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:q.username})]}),ee?s.jsxs("span",{style:{color:G.color,fontSize:12,fontWeight:600},children:[c("importWizard.connected","Connected")," ✓"]}):s.jsx("span",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:c("importWizard.clickToConnect","Click to connect")})]},G.value)})]}),E=()=>s.jsxs("div",{style:{display:"grid",gap:12},children:[s.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:c("importWizard.selectPlaylist","Select a playlist to import")}),R?s.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--text-dim, #64748b)"},children:c("importWizard.loading","Loading playlists…")}):s.jsxs("div",{style:{display:"grid",gap:8,maxHeight:320,overflowY:"auto"},children:[m.map(G=>s.jsxs("div",{style:{...ds,display:"flex",alignItems:"center",gap:12},onClick:()=>U(G),role:"button",tabIndex:0,onKeyDown:q=>q.key==="Enter"&&U(G),children:[G.coverUrl&&s.jsx("img",{src:G.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:G.name}),G.description&&s.jsx("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:G.description})]}),s.jsxs("span",{style:{fontSize:12,color:"var(--text-dim, #64748b)",whiteSpace:"nowrap"},children:[G.trackCount," ",c("importWizard.tracks","tracks")]})]},G.id)),m.length===0&&s.jsx("div",{style:{textAlign:"center",padding:24,color:"var(--text-dim, #64748b)"},children:c("importWizard.noPlaylists","No playlists found")})]})]}),H=u.useCallback(G=>{const ee=G.split(`
51
+ `).map(oe=>oe.trim()).filter(Boolean).map((oe,ce)=>{const fe=oe.match(/^(.+?)\s*[-–—]\s*(.+)$/);return fe?{externalId:`paste-${ce}`,title:fe[2].trim(),artist:fe[1].trim(),album:void 0,duration:0}:{externalId:`paste-${ce}`,title:oe,artist:"",album:void 0,duration:0}});C(ee),k(new Set(ee.map(oe=>oe.externalId)))},[]),Y=()=>s.jsxs("div",{style:{display:"grid",gap:12},children:[f===99&&x.length===0&&s.jsxs("div",{style:{display:"grid",gap:8},children:[s.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:c("importWizard.pasteInstructions",'Paste your track list below (one track per line). Use "Artist - Title" format for best results.')}),s.jsx("textarea",{value:K,onChange:G=>Z(G.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:K.trim().length===0?.5:1},disabled:K.trim().length===0,onClick:()=>H(K),type:"button",children:c("importWizard.parseTracks","Parse Tracks")})]}),(f!==99||v.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:[y==null?void 0:y.name," — ",b.size,"/",v.length," ",c("importWizard.selected","selected")]}),s.jsx("button",{style:Dn,onClick:T,type:"button",children:b.size===v.length?c("importWizard.deselectAll","Deselect All"):c("importWizard.selectAll","Select All")})]}),R?s.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--text-dim, #64748b)"},children:c("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:c("importWizard.title","Title")}),s.jsx("th",{style:{padding:"4px 8px"},children:c("importWizard.artist","Artist")}),s.jsx("th",{style:{padding:"4px 8px"},children:c("importWizard.album","Album")}),s.jsx("th",{style:{padding:"4px 8px",textAlign:"right"},children:c("importWizard.duration","Duration")})]})}),s.jsx("tbody",{children:v.map(G=>{const q=b.has(G.externalId);return s.jsxs("tr",{style:{borderBottom:"1px solid var(--border, #e2e8f0)",opacity:q?1:.5,cursor:"pointer"},onClick:()=>L(G.externalId),children:[s.jsx("td",{style:{padding:"6px 8px"},children:s.jsx("input",{type:"checkbox",checked:q,readOnly:!0})}),s.jsx("td",{style:{padding:"6px 8px",fontWeight:500},children:G.title}),s.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:G.artist}),s.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:G.album??"—"}),s.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--text-dim, #64748b)"},children:gh(G.duration)})]},G.externalId)})})]})}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsxs("button",{style:{...bn,opacity:b.size===0?.5:1},disabled:b.size===0,onClick:()=>h("options"),type:"button",children:[c("importWizard.next","Next")," →"]})})]})]}),J=()=>s.jsxs("div",{style:{display:"grid",gap:16},children:[s.jsx("p",{style:{margin:0,fontWeight:600},children:c("importWizard.importOptions","Import options")}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:B.mergeTags,onChange:G=>z(q=>({...q,mergeTags:G.target.checked}))}),c("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:B.mergeFolders,onChange:G=>z(q=>({...q,mergeFolders:G.target.checked}))}),c("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:B.overwriteExisting,onChange:G=>z(q=>({...q,overwriteExisting:G.target.checked}))}),c("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:c("importWizard.targetFolder","Target folder")}),s.jsxs("select",{style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border, #e2e8f0)"},value:B.targetFolderId??"",onChange:G=>z(q=>({...q,targetFolderId:G.target.value||void 0})),children:[s.jsx("option",{value:"",children:c("importWizard.root","— Root —")}),l.map(G=>s.jsx("option",{value:G.id,children:G.name},G.id))]})]}),s.jsx("div",{style:{marginTop:8,padding:12,borderRadius:8,background:"var(--info-bg, #eff6ff)",fontSize:13},children:c("importWizard.summary",`Ready to import ${b.size} tracks from "${(y==null?void 0:y.name)??""}"`)}),s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[s.jsx("button",{style:Dn,onClick:M,type:"button",children:c("importWizard.back","← Back")}),s.jsx("button",{style:bn,onClick:S,type:"button",children:c("importWizard.startImport","Start Import")})]})]}),ne=()=>{const G=$?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:c("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:`${G}%`,background:"var(--accent, #6366f1)",borderRadius:4,transition:"width 0.3s"}})}),$&&s.jsxs("div",{style:{fontSize:13,color:"var(--text-dim, #64748b)"},children:[$.imported," / ",$.total," ",c("importWizard.tracks","tracks"),$.currentTrack&&s.jsxs("div",{style:{marginTop:4},children:["🎵 ",$.currentTrack]})]})]})},ae=()=>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:c("importWizard.complete","Import Complete")}),w&&s.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[s.jsxs("div",{children:[s.jsx("strong",{children:w.imported})," ",c("importWizard.imported","imported")]}),w.skipped>0&&s.jsxs("div",{style:{color:"var(--warning, #f59e0b)"},children:[w.skipped," ",c("importWizard.skipped","skipped (duplicates)")]}),w.failed>0&&s.jsxs("div",{style:{color:"var(--error, #ef4444)"},children:[w.failed," ",c("importWizard.failed","failed")]}),w.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:c("importWizard.showFailed","Show failed tracks")}),s.jsx("ul",{style:{marginTop:4,paddingLeft:20},children:w.failedTracks.map((G,q)=>s.jsx("li",{children:G},q))})]})]}),s.jsx("button",{style:bn,onClick:i,type:"button",children:c("importWizard.close","Done")})]}),re={connect:c("importWizard.stepConnect","Connect"),browse:c("importWizard.stepBrowse","Browse"),tracks:c("importWizard.stepTracks","Select Tracks"),options:c("importWizard.stepOptions","Options"),importing:c("importWizard.stepImporting","Importing"),done:c("importWizard.stepDone","Done")};return s.jsxs("div",{style:hh,children:[F(),s.jsxs("div",{style:fh,children:[s.jsxs("h2",{style:{margin:0,fontSize:18},children:[c("importWizard.title","Import Playlist")," — ",re[d]]}),I&&s.jsxs("button",{style:Dn,onClick:M,type:"button",children:["← ",c("importWizard.back","Back")]}),d==="connect"&&s.jsx("button",{style:Dn,onClick:i,type:"button",children:"✕"})]}),_&&s.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--error-bg, #fef2f2)",color:"var(--error, #ef4444)",fontSize:13},children:_}),d==="connect"&&j(),d==="browse"&&E(),d==="tracks"&&Y(),d==="options"&&J(),d==="importing"&&ne(),d==="done"&&ae()]})};function us(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function di(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 jr(e,t){const n=di(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function yh(e){const t=di(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function ui(){const e=us("--text-primary")||"rgba(255,255,255,0.95)",t=us("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",a=yh(e)<.45;return{base:jr(e,.92),staffLine:jr(e,.22),outline:a?"rgba(255,255,255,0.75)":"rgba(0,0,0,0.55)",accents:[jr(t,.95)],isDark:n,notesDark:a}}const 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}],xh="concert-harp",xa=Object.fromEntries(bh.map(e=>[e.id,e])),vh="nice2dev-note-sound-set";function hi(){try{const e=localStorage.getItem(vh);if(e&&xa[e])return e}catch{}return xh}const hr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),fi=46,ct=5,Hn=4,Sh=(fi-(ct-1)*Hn)/2,wh=6,Ch=18,kh=110,Mh=50,fr=hr?Mh:kh,jh=hr?4:2,Rh=hr?2:4,hs=hr?1:0,$h=180,fs=2.8,ps=40,Th=14,ms=1.2,Ph=16,Rr=[64,67,71,74,77],Wt=64,xn=77;function Eh(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(Rr[n]+(Rr[r]-Rr[n])*a)}function Ah(e){return(Math.max(Wt-1*(xn-Wt)/(ct-1),Math.min(xn+1*(xn-Wt)/(ct-1),e))-Wt)/(xn-Wt)*(ct-1)}const gs=2.5,ys=.72,Nh=.55,vn=new Map;let Kn=null;async function Ih(e){const t=e??hi(),n=xa[t];if(!n||!n.dir){vn.clear(),Kn=t;return}if(Kn===t&&vn.size>0)return;vn.clear(),Kn=t;const r=tn(),a=[];for(let o=Wt;o<=xn;o++)a.push(fetch(`/assets/soundfonts/notes/${n.dir}/note-${o}.mp3`).then(i=>i.arrayBuffer()).then(i=>r.decodeAudioData(i)).then(i=>{vn.set(o,i)}).catch(()=>{}));await Promise.all(a)}function bs(e){const t=vn.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 xs=["𝅘𝅥","𝅘𝅥𝅮","𝅘𝅥𝅯","𝅘𝅥𝅰","𝅘𝅥𝅱","♪","♫","♬"];function Lh(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 Fh(e){const t=Lh(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:xs[Math.floor(t()*xs.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:o})}return n.sort((r,a)=>r.x-a.x),n}const Je=Fh(fr),on=new Float32Array(fr),On=new Float32Array(fr),Sn=new Float32Array(fr);let Br=!1;const Dh=(ct-1)/2;function Oh(){if(!Br){Br=!0;for(let e=0;e<Je.length;e++)Sn[e]=Je[e].lineIdx}}let Gr=[],vs="";function _h(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function zh(e){const t=_h(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 pi({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((y,x,v)=>{const C=Sh+y*Hn,b=x/v*Math.PI*2;return C+Math.sin(b)*wh},[]),g=u.useCallback(y=>{const x=t.current;if(!x)return;if(l.current++,hs>0&&l.current%(hs+1)!==0){a.current=y,n.current=requestAnimationFrame(g);return}const v=x.getContext("2d");if(!v)return;const C=Math.min(window.devicePixelRatio||1,Rh),b=x.getBoundingClientRect(),k=b.width,R=b.height;(x.width!==Math.round(k*C)||x.height!==Math.round(R*C))&&(x.width=Math.round(k*C),x.height=Math.round(R*C),v.setTransform(C,0,0,C,0,0));const A=a.current?(y-a.current)/1e3:0;a.current=y,r.current=(r.current+Ch*A)%k,v.clearRect(0,0,k,R),i.current++,(!o.current||i.current%60===0)&&(o.current=ui());const $=o.current;zh($),v.strokeStyle=$.staffLine,v.lineWidth=.7;for(let _=0;_<ct;_++){v.beginPath();for(let P=0;P<=k;P+=jh){const B=f(_,P,k);P===0?v.moveTo(P,B):v.lineTo(P,B)}v.stroke()}const W=r.current,w=(e==null?void 0:e.current)??null;if(w!==null){Oh();const _=Ah(w),P=gs*A;for(let B=0;B<Je.length;B++){const K=(Je[B].lineIdx-Dh)*Nh,O=_*ys+(_+K)*(1-ys)-Sn[B];Sn[B]+=O>0?Math.min(P,O):Math.max(-P,O)}}else if(Br){const _=gs*.4*A;for(let P=0;P<Je.length;P++){const z=Je[P].lineIdx-Sn[P];Sn[P]+=z>0?Math.min(_,z):Math.max(-_,z)}}const D=c.current;D&&(D.timer-=A,D.timer<=0&&(c.current=null));for(let _=0;_<Je.length;_++){const P=Je[_];if(On[_]>0){On[_]-=A;const K=Math.max(0,On[_]/fs);on[_]+=$h*K*A,on[_]>k&&(on[_]-=k)}const B=Gr[_];if(!B)continue;const z=P.lineIdx;for(let K=0;K<2;K++){let O=((P.x*k-W-on[_]+K*k)%k+k)%k;const X=f(Math.max(0,Math.min(ct-1,Math.round(z))),O,k),N=(z-Math.round(z))*Hn;let U=X+N;if(D&&D.timer>0){const L=O-D.x,T=U-D.y,S=Math.sqrt(L*L+T*T);if(S<ps&&S>.1){const I=D.timer/ms,M=Th*(1-S/ps)*I;O+=L/S*M,U+=T/S*M}}v.drawImage(B.canvas,O-B.ox,U-B.oy)}}n.current=requestAnimationFrame(g)},[f]),m=u.useCallback(y=>{const x=t.current;if(!x)return;const v=x.getBoundingClientRect(),C=y.clientX-v.left,b=y.clientY-v.top,k=v.width,R=r.current;let A=1/0,$=-1;for(let W=0;W<Je.length;W++){const w=Je[W],_=((w.x*k-R-on[W])%k+k)%k,P=f(Math.max(0,Math.min(ct-1,Math.round(w.lineIdx))),_,k),B=(w.lineIdx-Math.round(w.lineIdx))*Hn,z=P+B,K=_-C,Z=z-b,O=K*K+Z*Z;O<A&&(A=O,$=W)}if($>=0&&Math.sqrt(A)<Ph){On[$]=fs;const W=Je[$],w=Eh(W.lineIdx);try{Et();const D=hi(),_=xa[D];_!=null&&_.dir&&(Kn!==D||!h.current?(h.current=!0,Ih(D).then(()=>bs(w))):bs(w))}catch{}}c.current={x:C,y:b,timer:ms}},[f]),p=u.useCallback(y=>{const x=t.current;if(!x)return;const v=x.getBoundingClientRect(),C=y.clientX-v.left,b=y.clientY-v.top;d.current={x:C,y:b},c.current&&c.current.timer>0&&(c.current.x=C,c.current.y=b)},[]);return u.useEffect(()=>(n.current=requestAnimationFrame(g),()=>cancelAnimationFrame(n.current)),[g]),s.jsx("canvas",{ref:t,"aria-hidden":"true",role:"img","aria-label":"Note river animation canvas",onClick:m,onMouseMove:p,style:{display:"block",width:"100%",height:fi,marginBottom:5,cursor:"pointer",background:"transparent"}})}const Bh=14,Gh=.9,Wh=320,Uh=160,Vh=6,Ss=8,qh=14,ws=["♪","♫","♬","𝅘𝅥𝅮","𝅘𝅥𝅯"];function mi(){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 g=Math.random()*Math.PI*2,m=Uh*(.4+Math.random()*.6),p=Gh*(.6+Math.random()*.4),y=Math.random()<.15?0:-1;t.current.push({x:d,y:h,vx:Math.cos(g)*m,vy:Math.sin(g)*m-60,rot:Math.random()*Math.PI*2,vr:(Math.random()-.5)*Vh*2,size:Ss+Math.random()*(qh-Ss),char:ws[Math.floor(Math.random()*ws.length)],life:p,maxLife:p,colorIdx:y})}},[]),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 g=window.devicePixelRatio||1,m=window.innerWidth,p=window.innerHeight;(h.width!==Math.round(m*g)||h.height!==Math.round(p*g))&&(h.width=Math.round(m*g),h.height=Math.round(p*g),h.style.width=`${m}px`,h.style.height=`${p}px`,f.setTransform(g,0,0,g,0,0));const y=r.current?Math.min((d-r.current)/1e3,.05):0;r.current=d,f.clearRect(0,0,m,p),i.current++,(!o.current||i.current%60===0)&&(o.current=ui());const x=o.current;if(navigator.getGamepads){const C=navigator.getGamepads();for(let b=0;b<C.length;b++){const k=C[b];if(k)for(let R=0;R<k.buttons.length;R++){const A=b*100+R,$=k.buttons[R].pressed;$&&!a.current[A]&&l(m/2,p/2),a.current[A]=$}}}const v=[];f.textAlign="center",f.textBaseline="middle";for(const C of t.current){if(C.life-=y,C.life<=0)continue;C.vy+=Wh*y,C.x+=C.vx*y,C.y+=C.vy*y,C.rot+=C.vr*y;const b=Math.max(0,C.life/C.maxLife),k=.5+.5*b;f.save(),f.globalAlpha=b,f.translate(C.x,C.y),f.rotate(C.rot),f.font=`${C.size*k}px serif`,f.lineWidth=1.4,f.strokeStyle=x.notesDark?`rgba(255,255,255,${b*.8})`:`rgba(0,0,0,${b*.55})`,f.strokeText(C.char,0,0);const R=C.colorIdx<0?x.base:x.accents[C.colorIdx%x.accents.length];f.fillStyle=R.replace(/[\d.]+\)$/,`${b})`),f.fillText(C.char,0,0),f.restore(),v.push(C)}t.current=v,n.current=requestAnimationFrame(c)},[l]);return u.useEffect(()=>{const d=f=>{l(f.clientX,f.clientY)},h=f=>{if(f.key!=="Enter")return;const g=document.activeElement;if(g){const m=g.getBoundingClientRect();l(m.left+m.width/2,m.top+m.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 gi{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 Cs=et.scoped("AudioPlaybackEngine");class Hh{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){Cs.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 Cs.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 gi(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 g=f;i.connect(g.input),i=g.output,"dry"in f&&a.connect(g.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,g=o.handleType||"linear",m=Math.max(2,Math.ceil((d-c)*20));for(let p=0;p<=m;++p){const y=p/m;let x=h;if(g==="linear")x=h+(f-h)*y;else if(g==="step")x=y<1?h:f;else if(g==="exp"){const k=Math.max(h/127,.001),R=Math.max(f/127,.001);x=k*Math.pow(R/k,y)*127}const v=c+(d-c)*y,C=this.audioContext.currentTime+(v-this.currentTime);C>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(l.cc,x,C)}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 Kh=[{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([]),g=u.useRef(null),m=u.useCallback((p,y)=>{const x=p.data??new Uint8Array(0),v=x[0]??0,C=x[1]??0,b=x[2]??0,k=p.timeStamp,R=v&240,A=v&15,$=y.id,W=y.name??"MIDI Input",w=t===void 0||t===A;if((R===144||R===128)&&w){const D=R===144&&b>0;return{type:D?"noteon":"noteoff",note:C,velocity:D?b:0,channel:A,ts:k,deviceId:$,deviceName:W}}return R===176&&w?{type:"cc",controller:C,value:b,channel:A,ts:k,deviceId:$,deviceName:W}:R===208&&w?{type:"aftertouch",pressure:C,channel:A,ts:k,deviceId:$,deviceName:W}:R===224&&w?{type:"pitchbend",value:(C|b<<7)-8192,channel:A,ts:k,deviceId:$,deviceName:W}:R===192&&w?{type:"program",program:C,channel:A,ts:k,deviceId:$,deviceName:W}:{type:"unknown",status:v,data1:C,data2:b,channel:A,ts:k,deviceId:$,deviceName:W}},[t]);return u.useEffect(()=>{if(!("requestMIDIAccess"in navigator)){l(!1);return}l(!0);let p=!1;return navigator.requestMIDIAccess({sysex:n}).then(y=>{if(p)return;g.current=y,d(!0);const x=()=>{const v=Array.from(y.inputs.values()),C=a?v.filter(b=>(b.name||"").toUpperCase().includes(a.toUpperCase())):v;f(C),o==null||o(C),v.forEach(b=>b.onmidimessage=null),C.forEach(b=>{b.onmidimessage=k=>r==null?void 0:r(m(k,b))})};x(),y.onstatechange=()=>x()}),()=>{p=!0;const y=g.current;y&&(y.inputs.forEach(x=>x.onmidimessage=null),y.onstatechange=null)}},[a,r,o,m,n]),{supported:i,granted:c,inputs:h}}const va="nice2dev.midiLearn";function Yh(){try{const e=localStorage.getItem(va);return e?JSON.parse(e):{}}catch{return{}}}function ks(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(va,JSON.stringify(t))}function Zh(e){const{parameters:t,onParameterChange:n}=e,[r,a]=u.useState(()=>{const b=Yh();return t.map(k=>{const R=b[k.id];return{id:k.id,paramName:k.name,type:(R==null?void 0:R.type)??"cc",number:R==null?void 0:R.number,channel:R==null?void 0:R.channel,min:(R==null?void 0:R.min)??k.min??0,max:(R==null?void 0:R.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 g=u.useCallback(b=>{var R;c(b);const k=f.current;if(k.learning&&k.targetId){if(!d.current.find(W=>W.id===k.targetId))return;let $={};switch(b.type){case"cc":$={type:"cc",number:b.controller,channel:b.channel};break;case"noteon":$={type:"note",number:b.note,channel:b.channel};break;case"pitchbend":$={type:"pitchbend",channel:b.channel};break;case"aftertouch":$={type:"aftertouch",channel:b.channel};break;default:return}a(W=>{const w=W.map(D=>D.id===k.targetId?{...D,...$}:D);return ks(w),w}),i({learning:!1,targetId:null});return}for(const A of d.current){if(A.number===void 0&&A.type!=="pitchbend"&&A.type!=="aftertouch"||A.channel!==void 0&&b.channel!==A.channel)continue;let $=null,W=127;if(A.type==="cc"&&b.type==="cc"&&b.controller===A.number?$=b.value:A.type==="note"&&b.type==="noteon"&&b.note===A.number?$=b.velocity:A.type==="pitchbend"&&b.type==="pitchbend"?($=b.value+8192,W=16383):A.type==="aftertouch"&&b.type==="aftertouch"&&($=b.pressure),$!==null){const w=$/W,D=A.min+w*(A.max-A.min);a(_=>_.map(P=>P.id===A.id?{...P,value:w}:P)),(R=h.current)==null||R.call(h,A.id,D,w)}}},[]),{supported:m,granted:p}=pr({onEvent:g}),y=u.useCallback(b=>{i({learning:!0,targetId:b})},[]),x=u.useCallback(()=>{i({learning:!1,targetId:null})},[]),v=u.useCallback(b=>{a(k=>{const R=k.map(A=>A.id===b?{...A,type:"cc",number:void 0,channel:void 0}:A);return ks(R),R})},[]),C=u.useCallback(()=>{a(b=>{const k=b.map(R=>({...R,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(va),k})},[]);return{bindings:r,startLearn:y,cancelLearn:x,removeBinding:v,clearAll:C,learnState:o,midiSupported:m,midiGranted:p,lastEvent:l}}const Xh={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function Qh(e={}){const{lowerZone:t=Xh,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 g=u.useCallback(y=>{var v,C,b,k,R;if(!f.current.has(y.channel??-1))return;const x=`${y.channel}`;switch(y.type){case"noteon":{const A={note:y.note,channel:y.channel,velocity:y.velocity,pitchBend:0,pressure:0,slide:0,lastUpdate:y.ts};l.current.set(x,A),i(Array.from(l.current.values())),(v=d.current)==null||v.call(d,A);break}case"noteoff":{l.current.delete(x),i(Array.from(l.current.values())),(C=h.current)==null||C.call(h,y.channel,y.note);break}case"pitchbend":{const A=l.current.get(x);A&&(A.pitchBend=y.value,A.lastUpdate=y.ts,(b=c.current)==null||b.call(c,A),i(Array.from(l.current.values())));break}case"aftertouch":{const A=l.current.get(x);A&&(A.pressure=y.pressure,A.lastUpdate=y.ts,(k=c.current)==null||k.call(c,A),i(Array.from(l.current.values())));break}case"cc":{if(y.controller===74){const A=l.current.get(x);A&&(A.slide=y.value,A.lastUpdate=y.ts,(R=c.current)==null||R.call(c,A),i(Array.from(l.current.values())))}break}}},[]),{supported:m,granted:p}=pr({onEvent:g,sysex:!1});return{activeNotes:o,midiSupported:m,midiGranted:p}}const Jh={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 ef(e={},t=Jh){const[n,r]=u.useState(()=>{const m=localStorage.getItem("oxygen25.layout");return m?JSON.parse(m):t}),[a,o]=u.useState([]),i=u.useRef({mode:"idle"}),l=u.useCallback(m=>{r(p=>{const y={...p,...m};return localStorage.setItem("oxygen25.layout",JSON.stringify(y)),y})},[]),c=u.useCallback(m=>{var x,v,C,b,k,R,A,$,W;const p=m.deviceName||"MIDI";o(w=>w.includes(p)?w:[...w,p]);const y=i.current;if(y.mode!=="idle"){if(y.mode==="knob"&&m.type==="cc"){const w=y.index;l({knobs:n.knobs.map(D=>D.index===w?{...D,cc:m.controller}:D)}),i.current={mode:"idle"};return}if(y.mode==="fader"&&m.type==="cc"){l({fader:{cc:m.controller,label:"Fader"}}),i.current={mode:"idle"};return}if(y.mode==="pad"&&m.type==="noteon"){const w=n.pads.slice();w[y.padIdx]={...w[y.padIdx],note:m.note},l({pads:w}),i.current={mode:"idle"};return}if(y.mode==="transport"&&m.type==="cc"){const w={...n.transport};w[y.action]=m.controller,l({transport:w}),i.current={mode:"idle"};return}}switch(m.type){case"noteon":{n.pads.findIndex(D=>D.note===m.note)>=0?(x=e.onPad)==null||x.call(e,{note:m.note,velocity:m.velocity,ts:m.ts,device:p}):(v=e.onKey)==null||v.call(e,{note:m.note,velocity:m.velocity,ts:m.ts,device:p});break}case"cc":{if(n.fader&&m.controller===n.fader.cc){(C=e.onFader)==null||C.call(e,{cc:m.controller,value:m.value,ts:m.ts,device:p});break}const w=n.knobs.find(_=>_.cc===m.controller);if(w){(b=e.onKnob)==null||b.call(e,{index:w.index,cc:m.controller,value:m.value,ts:m.ts,device:p});break}const D=Object.keys(n.transport).find(_=>n.transport[_]===m.controller);if(D){(k=e.onTransport)==null||k.call(e,{action:D,value:m.value,ts:m.ts,device:p});break}(R=e.onUnknown)==null||R.call(e,m);break}case"pitchbend":(A=e.onPitchBend)==null||A.call(e,{value:m.value,ts:m.ts,device:p});break;case"aftertouch":($=e.onAftertouch)==null||$.call(e,{pressure:m.pressure,ts:m.ts,device:p});break;default:(W=e.onUnknown)==null||W.call(e,m)}},[l,e,n]),{supported:d,granted:h,inputs:f}=pr({inputNameIncludes:void 0,onEvent:c,sysex:!1,channelFilter:void 0,onInputsChanged:m=>o(m.map(p=>p.name||"MIDI"))}),g=u.useMemo(()=>({knob:m=>i.current={mode:"knob",index:m},fader:()=>i.current={mode:"fader"},pad:m=>i.current={mode:"pad",padIdx:m},transport:m=>i.current={mode:"transport",action:m},cancel:()=>i.current={mode:"idle"},state:()=>i.current}),[]);return{supported:d,granted:h,inputs:f,layout:n,setLayout:l,learn:g,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]},tf=["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,nf=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:nf,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}]},yi={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function rf(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 bi=1;const _n=()=>bi++,xi=e=>60/e,af=e=>xi(e)/4;function $r(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 sf(e=yi){bi=1;const t=e.seed>0?rf(e.seed):Math.random,n=Wr[e.scale]??Wr.pentatonic,r=Ur[e.progression]??Ur.pop,a=Vr[e.drumPattern]??Vr.basic,o=xi(e.tempo),i=af(e.tempo),l=Math.max(1,e.bars),c=16,d=[],h=[],f=[],g=[];let m=0;for(let p=0;p<l;p++){const y=p*4*o,x=p%r.length,v=r[x];for(const b of v)f.push({id:_n(),pitch:$r(e.root,n,b,e.octave-1),start:y,duration:4*o-.01,velocity:70+Math.floor(t()*20)});const C=v[0];for(let b=0;b<4;b++){const k=b===2?C+(t()>.5?2:0):C;h.push({id:_n(),pitch:$r(e.root,n,k,e.octave-2),start:y+b*o,duration:o*.9,velocity:80+Math.floor(t()*30)})}for(let b=0;b<c;b++){if(t()>e.density)continue;const k=y+b*i,R=t()>.8?t()>.5?2:-2:t()>.5?1:-1;m=Math.max(-3,Math.min(n.length+3,m+R));const A=1+Math.floor(t()*3);d.push({id:_n(),pitch:$r(e.root,n,m,e.octave),start:k,duration:A*i*.95,velocity:85+Math.floor(t()*30)})}for(const b of a)g.push({id:_n(),pitch:b.pitch,start:y+b.step*i,duration:i*.8,velocity:b.vel+Math.floor(t()*10-5)})}return{melody:d,bass:h,chords:f,drums:g,config:e}}const of=Object.keys(Wr),lf=Object.keys(Ur),cf=Object.keys(Vr);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")]},Si={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")]},wi={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")]},Ci={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")]},ki=[vi,Si,wi,Ci,Sa];class df{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=ki.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 Mi(e){return{past:[],present:e,future:[]}}function ji(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function Ri(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 $i(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 Ti(e){return e.past.length>0}function Pi(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 Ei(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 Ai(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 Ni(e,t){return e.filter(n=>n.time<t.start||n.time>t.end)}function uf(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>n.id)}function Ii(e,t,n,r){const a={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:r};return[...e,a]}function Li(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 Fi(e){return JSON.stringify(e,null,2)}function Di(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 hf(e,t){switch(t.type){case"UNDO":return Ri(e);case"REDO":return $i(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=Ei(r,t.clipboard,t.targetTime);n=mt(n,t.layerId,a);break}case"CUT":{const r=rt(n,t.layerId),{remaining:a}=Ai(r,t.range);n=mt(n,t.layerId,a);break}case"DELETE_RANGE":{const r=rt(n,t.layerId),a=Ni(r,t.range);n=mt(n,t.layerId,a);break}case"RECORD":{const r=rt(n,t.layerId),a=Ii(r,t.cc,t.value,t.time);n=mt(n,t.layerId,a);break}case"THIN":{const r=rt(n,t.layerId),a=Li(r,t.keepEveryN);n=mt(n,t.layerId,a);break}case"IMPORT":{const r=Di(t.json);r.length>0&&(n=mt(n,t.layerId,r));break}}return ji(e,n)}}}function ff(e=[]){const[t,n]=u.useReducer(hf,Mi(e)),r=u.useRef([]),a=u.useCallback(b=>rt(t.present,b),[t.present]),o=u.useCallback((b,k)=>n({type:"ADD_EVENT",layerId:b,event:k}),[]),i=u.useCallback((b,k,R,A,$)=>n({type:"UPDATE_EVENT",layerId:b,id:k,value:R,time:A,handleType:$}),[]),l=u.useCallback((b,k)=>n({type:"REMOVE_EVENT",layerId:b,id:k}),[]),c=u.useCallback((b,k)=>n({type:"SET_EVENTS",layerId:b,events:k}),[]),d=u.useCallback(()=>n({type:"UNDO"}),[]),h=u.useCallback(()=>n({type:"REDO"}),[]),f=u.useCallback((b,k)=>{r.current=qr(rt(t.present,b),k)},[t.present]),g=u.useCallback((b,k)=>{r.current=qr(rt(t.present,b),k),n({type:"CUT",layerId:b,range:k})},[t.present]),m=u.useCallback((b,k)=>{r.current.length>0&&n({type:"PASTE",layerId:b,clipboard:r.current,targetTime:k})},[]),p=u.useCallback((b,k)=>n({type:"DELETE_RANGE",layerId:b,range:k}),[]),y=u.useCallback((b,k,R,A)=>n({type:"RECORD",layerId:b,cc:k,value:R,time:A}),[]),x=u.useCallback((b,k)=>n({type:"THIN",layerId:b,keepEveryN:k}),[]),v=u.useCallback(b=>Fi(rt(t.present,b)),[t.present]),C=u.useCallback((b,k)=>n({type:"IMPORT",layerId:b,json:k}),[]);return{snapshots:t.present,getEvents:a,addEvent:o,updateEvent:i,removeEvent:l,setEvents:c,undo:d,redo:h,canUndo:Ti(t),canRedo:Pi(t),copy:f,cut:g,paste:m,clipboard:r.current,deleteRange:p,record:y,thin:x,exportLane:v,importLane:C}}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 Oi(e,t){const n=e.steps.map((r,a)=>a===t?{...r,active:!r.active}:r);return{...e,steps:n}}function _i(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 zi(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 Bi(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 Wi(e,t){const n=e.steps.map((r,a)=>a===t?{...r,slide:!r.slide}:r);return{...e,steps:n}}function Ui(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 Vi(e){return{...e,steps:[...e.steps].reverse()}}function qi(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 Hi(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 Ki(e){return{...e,steps:e.steps.map(()=>wa(e.rootNote))}}function Ca(e,t=4){return 60/e/t}function Yi(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 Zi(e){return e.active&&Math.random()<e.probability}function pf(){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 mf(){const e=Nt("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function gf(){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 yf(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 bf(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 vf(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function Sf(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([]),g=u.useRef(a);g.current=a;const m=u.useRef(h);m.current=h;const p=u.useRef(c);p.current=c;const y=u.useRef(t);y.current=t;const x=u.useRef(n);x.current=n;const v=u.useRef(null),C=u.useRef(0),b=u.useRef(0),k=u.useCallback(()=>{var J,ne;if(!p.current)return;const M=g.current,F=C.current%M.length,j=M.steps[F];if(Zi(j)){const ae=Yi(C.current,M.bpm,M.swing);(J=y.current)==null||J.call(y,j,F,ae)}const E=(Date.now()-b.current)/1e3;for(let ae=0;ae<m.current.length;ae++){const re=m.current[ae];if(re.enabled&&re.targetCC!==void 0){const G=Xr(re,E,M.bpm);(ne=x.current)==null||ne.call(x,ae,re.targetCC,G)}}l(F),C.current++;const H=Ca(M.bpm)*1e3,Y=F%2===0?0:H*M.swing*.5;v.current=setTimeout(k,H+Y)},[]),R=u.useCallback(()=>{p.current||(C.current=0,b.current=Date.now(),d(!0),p.current=!0,k())},[k]),A=u.useCallback(()=>{d(!1),p.current=!1,l(-1),v.current&&(clearTimeout(v.current),v.current=null)},[]),$=u.useCallback(()=>{p.current?A():R()},[R,A]);u.useEffect(()=>()=>{v.current&&clearTimeout(v.current)},[]);const W=u.useCallback(M=>o(F=>Oi(F,M)),[]),w=u.useCallback((M,F)=>o(j=>_i(j,M,F)),[]),D=u.useCallback((M,F)=>o(j=>zi(j,M,F)),[]),_=u.useCallback((M,F)=>o(j=>Bi(j,M,F)),[]),P=u.useCallback((M,F)=>o(j=>Gi(j,M,F)),[]),B=u.useCallback(M=>o(F=>Wi(F,M)),[]),z=u.useCallback(M=>o(F=>Ui(F,M)),[]),K=u.useCallback(()=>o(M=>Vi(M)),[]),Z=u.useCallback(M=>o(F=>qi(F,M)),[]),O=u.useCallback((M,F)=>o(j=>Hi(j,M,F)),[]),X=u.useCallback(()=>o(M=>Ki(M)),[]),N=u.useCallback(M=>o(F=>({...F,bpm:Math.max(20,Math.min(300,M))})),[]),U=u.useCallback(M=>o(F=>({...F,swing:Math.max(0,Math.min(1,M))})),[]),L=u.useCallback(M=>{o(F=>{if(F.length===M)return F;const j=Array.from({length:M},(E,H)=>H<F.steps.length?F.steps[H]:{active:!1,note:F.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...F,length:M,steps:j}})},[]),T=u.useCallback(M=>{f(F=>[...F,M??ir()])},[]),S=u.useCallback(M=>{f(F=>F.filter((j,E)=>E!==M))},[]),I=u.useCallback((M,F)=>{f(j=>j.map((E,H)=>H===M?{...E,...F}:E))},[]);return{pattern:a,currentStep:i,playing:c,lfos:h,play:R,stop:A,togglePlayback:$,toggle:W,setNote:w,setVelocity:D,setGate:_,setProbability:P,toggleSlide:B,transpose:z,reverse:K,shift:Z,randomizeVel:O,clear:X,setPattern:o,setBpm:N,setSwing:U,setLength:L,addLFO:T,removeLFO:S,updateLFO:I}}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 wf(){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 Cf(){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 kf={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function Xi(){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:K.trim().length===0?.5:1},disabled:K.trim().length===0,onClick:()=>H(K),type:"button",children:c("importWizard.parseTracks","Parse Tracks")})]}),(f!==99||x.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:[y==null?void 0:y.name," — ",b.size,"/",x.length," ",c("importWizard.selected","selected")]}),s.jsx("button",{style:Dn,onClick:T,type:"button",children:b.size===x.length?c("importWizard.deselectAll","Deselect All"):c("importWizard.selectAll","Select All")})]}),R?s.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--text-dim, #64748b)"},children:c("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:c("importWizard.title","Title")}),s.jsx("th",{style:{padding:"4px 8px"},children:c("importWizard.artist","Artist")}),s.jsx("th",{style:{padding:"4px 8px"},children:c("importWizard.album","Album")}),s.jsx("th",{style:{padding:"4px 8px",textAlign:"right"},children:c("importWizard.duration","Duration")})]})}),s.jsx("tbody",{children:x.map(G=>{const q=b.has(G.externalId);return s.jsxs("tr",{style:{borderBottom:"1px solid var(--border, #e2e8f0)",opacity:q?1:.5,cursor:"pointer"},onClick:()=>L(G.externalId),children:[s.jsx("td",{style:{padding:"6px 8px"},children:s.jsx("input",{type:"checkbox",checked:q,readOnly:!0})}),s.jsx("td",{style:{padding:"6px 8px",fontWeight:500},children:G.title}),s.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:G.artist}),s.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:G.album??"—"}),s.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--text-dim, #64748b)"},children:yh(G.duration)})]},G.externalId)})})]})}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsxs("button",{style:{...bn,opacity:b.size===0?.5:1},disabled:b.size===0,onClick:()=>h("options"),type:"button",children:[c("importWizard.next","Next")," →"]})})]})]}),J=()=>s.jsxs("div",{style:{display:"grid",gap:16},children:[s.jsx("p",{style:{margin:0,fontWeight:600},children:c("importWizard.importOptions","Import options")}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:B.mergeTags,onChange:G=>z(q=>({...q,mergeTags:G.target.checked}))}),c("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:B.mergeFolders,onChange:G=>z(q=>({...q,mergeFolders:G.target.checked}))}),c("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:B.overwriteExisting,onChange:G=>z(q=>({...q,overwriteExisting:G.target.checked}))}),c("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:c("importWizard.targetFolder","Target folder")}),s.jsxs("select",{style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border, #e2e8f0)"},value:B.targetFolderId??"",onChange:G=>z(q=>({...q,targetFolderId:G.target.value||void 0})),children:[s.jsx("option",{value:"",children:c("importWizard.root","— Root —")}),l.map(G=>s.jsx("option",{value:G.id,children:G.name},G.id))]})]}),s.jsx("div",{style:{marginTop:8,padding:12,borderRadius:8,background:"var(--info-bg, #eff6ff)",fontSize:13},children:c("importWizard.summary",`Ready to import ${b.size} tracks from "${(y==null?void 0:y.name)??""}"`)}),s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[s.jsx("button",{style:Dn,onClick:M,type:"button",children:c("importWizard.back","← Back")}),s.jsx("button",{style:bn,onClick:S,type:"button",children:c("importWizard.startImport","Start Import")})]})]}),ne=()=>{const G=$?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:c("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:`${G}%`,background:"var(--accent, #6366f1)",borderRadius:4,transition:"width 0.3s"}})}),$&&s.jsxs("div",{style:{fontSize:13,color:"var(--text-dim, #64748b)"},children:[$.imported," / ",$.total," ",c("importWizard.tracks","tracks"),$.currentTrack&&s.jsxs("div",{style:{marginTop:4},children:["🎵 ",$.currentTrack]})]})]})},ae=()=>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:c("importWizard.complete","Import Complete")}),w&&s.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[s.jsxs("div",{children:[s.jsx("strong",{children:w.imported})," ",c("importWizard.imported","imported")]}),w.skipped>0&&s.jsxs("div",{style:{color:"var(--warning, #f59e0b)"},children:[w.skipped," ",c("importWizard.skipped","skipped (duplicates)")]}),w.failed>0&&s.jsxs("div",{style:{color:"var(--error, #ef4444)"},children:[w.failed," ",c("importWizard.failed","failed")]}),w.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:c("importWizard.showFailed","Show failed tracks")}),s.jsx("ul",{style:{marginTop:4,paddingLeft:20},children:w.failedTracks.map((G,q)=>s.jsx("li",{children:G},q))})]})]}),s.jsx("button",{style:bn,onClick:i,type:"button",children:c("importWizard.close","Done")})]}),re={connect:c("importWizard.stepConnect","Connect"),browse:c("importWizard.stepBrowse","Browse"),tracks:c("importWizard.stepTracks","Select Tracks"),options:c("importWizard.stepOptions","Options"),importing:c("importWizard.stepImporting","Importing"),done:c("importWizard.stepDone","Done")};return s.jsxs("div",{style:fh,children:[F(),s.jsxs("div",{style:ph,children:[s.jsxs("h2",{style:{margin:0,fontSize:18},children:[c("importWizard.title","Import Playlist")," — ",re[d]]}),I&&s.jsxs("button",{style:Dn,onClick:M,type:"button",children:["← ",c("importWizard.back","Back")]}),d==="connect"&&s.jsx("button",{style:Dn,onClick:i,type:"button",children:"✕"})]}),_&&s.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--error-bg, #fef2f2)",color:"var(--error, #ef4444)",fontSize:13},children:_}),d==="connect"&&j(),d==="browse"&&E(),d==="tracks"&&Y(),d==="options"&&J(),d==="importing"&&ne(),d==="done"&&ae()]})};function us(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function di(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 jr(e,t){const n=di(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function bh(e){const t=di(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function ui(){const e=us("--text-primary")||"rgba(255,255,255,0.95)",t=us("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",a=bh(e)<.45;return{base:jr(e,.92),staffLine:jr(e,.22),outline:a?"rgba(255,255,255,0.75)":"rgba(0,0,0,0.55)",accents:[jr(t,.95)],isDark:n,notesDark:a}}const vh=[{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}],xh="concert-harp",va=Object.fromEntries(vh.map(e=>[e.id,e])),Sh="nice2dev-note-sound-set";function hi(){try{const e=localStorage.getItem(Sh);if(e&&va[e])return e}catch{}return xh}const hr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),fi=46,ct=5,Hn=4,wh=(fi-(ct-1)*Hn)/2,Ch=6,kh=18,Mh=110,jh=50,fr=hr?jh:Mh,Rh=hr?4:2,$h=hr?2:4,hs=hr?1:0,Th=180,fs=2.8,ps=40,Ph=14,ms=1.2,Eh=16,Rr=[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(Rr[n]+(Rr[r]-Rr[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 gs=2.5,ys=.72,Ih=.55,xn=new Map;let Kn=null;async function Lh(e){const t=e??hi(),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 bs(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 vs=["𝅘𝅥","𝅘𝅥𝅮","𝅘𝅥𝅯","𝅘𝅥𝅰","𝅘𝅥𝅱","♪","♫","♬"];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:vs[Math.floor(t()*vs.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=[],xs="";function zh(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function Bh(e){const t=zh(e);t===xs&&Gr.length===Je.length||(xs=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 pi({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((y,v,x)=>{const C=wh+y*Hn,b=v/x*Math.PI*2;return C+Math.sin(b)*Ch},[]),g=u.useCallback(y=>{const v=t.current;if(!v)return;if(l.current++,hs>0&&l.current%(hs+1)!==0){a.current=y,n.current=requestAnimationFrame(g);return}const x=v.getContext("2d");if(!x)return;const C=Math.min(window.devicePixelRatio||1,$h),b=v.getBoundingClientRect(),k=b.width,R=b.height;(v.width!==Math.round(k*C)||v.height!==Math.round(R*C))&&(v.width=Math.round(k*C),v.height=Math.round(R*C),x.setTransform(C,0,0,C,0,0));const A=a.current?(y-a.current)/1e3:0;a.current=y,r.current=(r.current+kh*A)%k,x.clearRect(0,0,k,R),i.current++,(!o.current||i.current%60===0)&&(o.current=ui());const $=o.current;Bh($),x.strokeStyle=$.staffLine,x.lineWidth=.7;for(let _=0;_<ct;_++){x.beginPath();for(let P=0;P<=k;P+=Rh){const B=f(_,P,k);P===0?x.moveTo(P,B):x.lineTo(P,B)}x.stroke()}const W=r.current,w=(e==null?void 0:e.current)??null;if(w!==null){_h();const _=Nh(w),P=gs*A;for(let B=0;B<Je.length;B++){const K=(Je[B].lineIdx-Oh)*Ih,O=_*ys+(_+K)*(1-ys)-Sn[B];Sn[B]+=O>0?Math.min(P,O):Math.max(-P,O)}}else if(Br){const _=gs*.4*A;for(let P=0;P<Je.length;P++){const z=Je[P].lineIdx-Sn[P];Sn[P]+=z>0?Math.min(_,z):Math.max(-_,z)}}const D=c.current;D&&(D.timer-=A,D.timer<=0&&(c.current=null));for(let _=0;_<Je.length;_++){const P=Je[_];if(On[_]>0){On[_]-=A;const K=Math.max(0,On[_]/fs);on[_]+=Th*K*A,on[_]>k&&(on[_]-=k)}const B=Gr[_];if(!B)continue;const z=P.lineIdx;for(let K=0;K<2;K++){let O=((P.x*k-W-on[_]+K*k)%k+k)%k;const X=f(Math.max(0,Math.min(ct-1,Math.round(z))),O,k),N=(z-Math.round(z))*Hn;let U=X+N;if(D&&D.timer>0){const L=O-D.x,T=U-D.y,S=Math.sqrt(L*L+T*T);if(S<ps&&S>.1){const I=D.timer/ms,M=Ph*(1-S/ps)*I;O+=L/S*M,U+=T/S*M}}x.drawImage(B.canvas,O-B.ox,U-B.oy)}}n.current=requestAnimationFrame(g)},[f]),m=u.useCallback(y=>{const v=t.current;if(!v)return;const x=v.getBoundingClientRect(),C=y.clientX-x.left,b=y.clientY-x.top,k=x.width,R=r.current;let A=1/0,$=-1;for(let W=0;W<Je.length;W++){const w=Je[W],_=((w.x*k-R-on[W])%k+k)%k,P=f(Math.max(0,Math.min(ct-1,Math.round(w.lineIdx))),_,k),B=(w.lineIdx-Math.round(w.lineIdx))*Hn,z=P+B,K=_-C,Z=z-b,O=K*K+Z*Z;O<A&&(A=O,$=W)}if($>=0&&Math.sqrt(A)<Eh){On[$]=fs;const W=Je[$],w=Ah(W.lineIdx);try{Et();const D=hi(),_=va[D];_!=null&&_.dir&&(Kn!==D||!h.current?(h.current=!0,Lh(D).then(()=>bs(w))):bs(w))}catch{}}c.current={x:C,y:b,timer:ms}},[f]),p=u.useCallback(y=>{const v=t.current;if(!v)return;const x=v.getBoundingClientRect(),C=y.clientX-x.left,b=y.clientY-x.top;d.current={x:C,y:b},c.current&&c.current.timer>0&&(c.current.x=C,c.current.y=b)},[]);return u.useEffect(()=>(n.current=requestAnimationFrame(g),()=>cancelAnimationFrame(n.current)),[g]),s.jsx("canvas",{ref:t,"aria-hidden":"true",role:"img","aria-label":"Note river animation canvas",onClick:m,onMouseMove:p,style:{display:"block",width:"100%",height:fi,marginBottom:5,cursor:"pointer",background:"transparent"}})}const Gh=14,Wh=.9,Uh=320,Vh=160,qh=6,Ss=8,Hh=14,ws=["♪","♫","♬","𝅘𝅥𝅮","𝅘𝅥𝅯"];function mi(){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 g=Math.random()*Math.PI*2,m=Vh*(.4+Math.random()*.6),p=Wh*(.6+Math.random()*.4),y=Math.random()<.15?0:-1;t.current.push({x:d,y:h,vx:Math.cos(g)*m,vy:Math.sin(g)*m-60,rot:Math.random()*Math.PI*2,vr:(Math.random()-.5)*qh*2,size:Ss+Math.random()*(Hh-Ss),char:ws[Math.floor(Math.random()*ws.length)],life:p,maxLife:p,colorIdx:y})}},[]),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 g=window.devicePixelRatio||1,m=window.innerWidth,p=window.innerHeight;(h.width!==Math.round(m*g)||h.height!==Math.round(p*g))&&(h.width=Math.round(m*g),h.height=Math.round(p*g),h.style.width=`${m}px`,h.style.height=`${p}px`,f.setTransform(g,0,0,g,0,0));const y=r.current?Math.min((d-r.current)/1e3,.05):0;r.current=d,f.clearRect(0,0,m,p),i.current++,(!o.current||i.current%60===0)&&(o.current=ui());const v=o.current;if(navigator.getGamepads){const C=navigator.getGamepads();for(let b=0;b<C.length;b++){const k=C[b];if(k)for(let R=0;R<k.buttons.length;R++){const A=b*100+R,$=k.buttons[R].pressed;$&&!a.current[A]&&l(m/2,p/2),a.current[A]=$}}}const x=[];f.textAlign="center",f.textBaseline="middle";for(const C of t.current){if(C.life-=y,C.life<=0)continue;C.vy+=Uh*y,C.x+=C.vx*y,C.y+=C.vy*y,C.rot+=C.vr*y;const b=Math.max(0,C.life/C.maxLife),k=.5+.5*b;f.save(),f.globalAlpha=b,f.translate(C.x,C.y),f.rotate(C.rot),f.font=`${C.size*k}px serif`,f.lineWidth=1.4,f.strokeStyle=v.notesDark?`rgba(255,255,255,${b*.8})`:`rgba(0,0,0,${b*.55})`,f.strokeText(C.char,0,0);const R=C.colorIdx<0?v.base:v.accents[C.colorIdx%v.accents.length];f.fillStyle=R.replace(/[\d.]+\)$/,`${b})`),f.fillText(C.char,0,0),f.restore(),x.push(C)}t.current=x,n.current=requestAnimationFrame(c)},[l]);return u.useEffect(()=>{const d=f=>{l(f.clientX,f.clientY)},h=f=>{if(f.key!=="Enter")return;const g=document.activeElement;if(g){const m=g.getBoundingClientRect();l(m.left+m.width/2,m.top+m.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 gi{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 Cs=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){Cs.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 Cs.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 gi(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 g=f;i.connect(g.input),i=g.output,"dry"in f&&a.connect(g.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,g=o.handleType||"linear",m=Math.max(2,Math.ceil((d-c)*20));for(let p=0;p<=m;++p){const y=p/m;let v=h;if(g==="linear")v=h+(f-h)*y;else if(g==="step")v=y<1?h:f;else if(g==="exp"){const k=Math.max(h/127,.001),R=Math.max(f/127,.001);v=k*Math.pow(R/k,y)*127}const x=c+(d-c)*y,C=this.audioContext.currentTime+(x-this.currentTime);C>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(l.cc,v,C)}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([]),g=u.useRef(null),m=u.useCallback((p,y)=>{const v=p.data??new Uint8Array(0),x=v[0]??0,C=v[1]??0,b=v[2]??0,k=p.timeStamp,R=x&240,A=x&15,$=y.id,W=y.name??"MIDI Input",w=t===void 0||t===A;if((R===144||R===128)&&w){const D=R===144&&b>0;return{type:D?"noteon":"noteoff",note:C,velocity:D?b:0,channel:A,ts:k,deviceId:$,deviceName:W}}return R===176&&w?{type:"cc",controller:C,value:b,channel:A,ts:k,deviceId:$,deviceName:W}:R===208&&w?{type:"aftertouch",pressure:C,channel:A,ts:k,deviceId:$,deviceName:W}:R===224&&w?{type:"pitchbend",value:(C|b<<7)-8192,channel:A,ts:k,deviceId:$,deviceName:W}:R===192&&w?{type:"program",program:C,channel:A,ts:k,deviceId:$,deviceName:W}:{type:"unknown",status:x,data1:C,data2:b,channel:A,ts:k,deviceId:$,deviceName:W}},[t]);return u.useEffect(()=>{if(!("requestMIDIAccess"in navigator)){l(!1);return}l(!0);let p=!1;return navigator.requestMIDIAccess({sysex:n}).then(y=>{if(p)return;g.current=y,d(!0);const v=()=>{const x=Array.from(y.inputs.values()),C=a?x.filter(b=>(b.name||"").toUpperCase().includes(a.toUpperCase())):x;f(C),o==null||o(C),x.forEach(b=>b.onmidimessage=null),C.forEach(b=>{b.onmidimessage=k=>r==null?void 0:r(m(k,b))})};v(),y.onstatechange=()=>v()}),()=>{p=!0;const y=g.current;y&&(y.inputs.forEach(v=>v.onmidimessage=null),y.onstatechange=null)}},[a,r,o,m,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 ks(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 b=Zh();return t.map(k=>{const R=b[k.id];return{id:k.id,paramName:k.name,type:(R==null?void 0:R.type)??"cc",number:R==null?void 0:R.number,channel:R==null?void 0:R.channel,min:(R==null?void 0:R.min)??k.min??0,max:(R==null?void 0:R.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 g=u.useCallback(b=>{var R;c(b);const k=f.current;if(k.learning&&k.targetId){if(!d.current.find(W=>W.id===k.targetId))return;let $={};switch(b.type){case"cc":$={type:"cc",number:b.controller,channel:b.channel};break;case"noteon":$={type:"note",number:b.note,channel:b.channel};break;case"pitchbend":$={type:"pitchbend",channel:b.channel};break;case"aftertouch":$={type:"aftertouch",channel:b.channel};break;default:return}a(W=>{const w=W.map(D=>D.id===k.targetId?{...D,...$}:D);return ks(w),w}),i({learning:!1,targetId:null});return}for(const A of d.current){if(A.number===void 0&&A.type!=="pitchbend"&&A.type!=="aftertouch"||A.channel!==void 0&&b.channel!==A.channel)continue;let $=null,W=127;if(A.type==="cc"&&b.type==="cc"&&b.controller===A.number?$=b.value:A.type==="note"&&b.type==="noteon"&&b.note===A.number?$=b.velocity:A.type==="pitchbend"&&b.type==="pitchbend"?($=b.value+8192,W=16383):A.type==="aftertouch"&&b.type==="aftertouch"&&($=b.pressure),$!==null){const w=$/W,D=A.min+w*(A.max-A.min);a(_=>_.map(P=>P.id===A.id?{...P,value:w}:P)),(R=h.current)==null||R.call(h,A.id,D,w)}}},[]),{supported:m,granted:p}=pr({onEvent:g}),y=u.useCallback(b=>{i({learning:!0,targetId:b})},[]),v=u.useCallback(()=>{i({learning:!1,targetId:null})},[]),x=u.useCallback(b=>{a(k=>{const R=k.map(A=>A.id===b?{...A,type:"cc",number:void 0,channel:void 0}:A);return ks(R),R})},[]),C=u.useCallback(()=>{a(b=>{const k=b.map(R=>({...R,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(xa),k})},[]);return{bindings:r,startLearn:y,cancelLearn:v,removeBinding:x,clearAll:C,learnState:o,midiSupported:m,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 g=u.useCallback(y=>{var x,C,b,k,R;if(!f.current.has(y.channel??-1))return;const v=`${y.channel}`;switch(y.type){case"noteon":{const A={note:y.note,channel:y.channel,velocity:y.velocity,pitchBend:0,pressure:0,slide:0,lastUpdate:y.ts};l.current.set(v,A),i(Array.from(l.current.values())),(x=d.current)==null||x.call(d,A);break}case"noteoff":{l.current.delete(v),i(Array.from(l.current.values())),(C=h.current)==null||C.call(h,y.channel,y.note);break}case"pitchbend":{const A=l.current.get(v);A&&(A.pitchBend=y.value,A.lastUpdate=y.ts,(b=c.current)==null||b.call(c,A),i(Array.from(l.current.values())));break}case"aftertouch":{const A=l.current.get(v);A&&(A.pressure=y.pressure,A.lastUpdate=y.ts,(k=c.current)==null||k.call(c,A),i(Array.from(l.current.values())));break}case"cc":{if(y.controller===74){const A=l.current.get(v);A&&(A.slide=y.value,A.lastUpdate=y.ts,(R=c.current)==null||R.call(c,A),i(Array.from(l.current.values())))}break}}},[]),{supported:m,granted:p}=pr({onEvent:g,sysex:!1});return{activeNotes:o,midiSupported:m,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 m=localStorage.getItem("oxygen25.layout");return m?JSON.parse(m):t}),[a,o]=u.useState([]),i=u.useRef({mode:"idle"}),l=u.useCallback(m=>{r(p=>{const y={...p,...m};return localStorage.setItem("oxygen25.layout",JSON.stringify(y)),y})},[]),c=u.useCallback(m=>{var v,x,C,b,k,R,A,$,W;const p=m.deviceName||"MIDI";o(w=>w.includes(p)?w:[...w,p]);const y=i.current;if(y.mode!=="idle"){if(y.mode==="knob"&&m.type==="cc"){const w=y.index;l({knobs:n.knobs.map(D=>D.index===w?{...D,cc:m.controller}:D)}),i.current={mode:"idle"};return}if(y.mode==="fader"&&m.type==="cc"){l({fader:{cc:m.controller,label:"Fader"}}),i.current={mode:"idle"};return}if(y.mode==="pad"&&m.type==="noteon"){const w=n.pads.slice();w[y.padIdx]={...w[y.padIdx],note:m.note},l({pads:w}),i.current={mode:"idle"};return}if(y.mode==="transport"&&m.type==="cc"){const w={...n.transport};w[y.action]=m.controller,l({transport:w}),i.current={mode:"idle"};return}}switch(m.type){case"noteon":{n.pads.findIndex(D=>D.note===m.note)>=0?(v=e.onPad)==null||v.call(e,{note:m.note,velocity:m.velocity,ts:m.ts,device:p}):(x=e.onKey)==null||x.call(e,{note:m.note,velocity:m.velocity,ts:m.ts,device:p});break}case"cc":{if(n.fader&&m.controller===n.fader.cc){(C=e.onFader)==null||C.call(e,{cc:m.controller,value:m.value,ts:m.ts,device:p});break}const w=n.knobs.find(_=>_.cc===m.controller);if(w){(b=e.onKnob)==null||b.call(e,{index:w.index,cc:m.controller,value:m.value,ts:m.ts,device:p});break}const D=Object.keys(n.transport).find(_=>n.transport[_]===m.controller);if(D){(k=e.onTransport)==null||k.call(e,{action:D,value:m.value,ts:m.ts,device:p});break}(R=e.onUnknown)==null||R.call(e,m);break}case"pitchbend":(A=e.onPitchBend)==null||A.call(e,{value:m.value,ts:m.ts,device:p});break;case"aftertouch":($=e.onAftertouch)==null||$.call(e,{pressure:m.pressure,ts:m.ts,device:p});break;default:(W=e.onUnknown)==null||W.call(e,m)}},[l,e,n]),{supported:d,granted:h,inputs:f}=pr({inputNameIncludes:void 0,onEvent:c,sysex:!1,channelFilter:void 0,onInputsChanged:m=>o(m.map(p=>p.name||"MIDI"))}),g=u.useMemo(()=>({knob:m=>i.current={mode:"knob",index:m},fader:()=>i.current={mode:"fader"},pad:m=>i.current={mode:"pad",padIdx:m},transport:m=>i.current={mode:"transport",action:m},cancel:()=>i.current={mode:"idle"},state:()=>i.current}),[]);return{supported:d,granted:h,inputs:f,layout:n,setLayout:l,learn:g,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}]},yi={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 bi=1;const _n=()=>bi++,vi=e=>60/e,sf=e=>vi(e)/4;function $r(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 of(e=yi){bi=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=vi(e.tempo),i=sf(e.tempo),l=Math.max(1,e.bars),c=16,d=[],h=[],f=[],g=[];let m=0;for(let p=0;p<l;p++){const y=p*4*o,v=p%r.length,x=r[v];for(const b of x)f.push({id:_n(),pitch:$r(e.root,n,b,e.octave-1),start:y,duration:4*o-.01,velocity:70+Math.floor(t()*20)});const C=x[0];for(let b=0;b<4;b++){const k=b===2?C+(t()>.5?2:0):C;h.push({id:_n(),pitch:$r(e.root,n,k,e.octave-2),start:y+b*o,duration:o*.9,velocity:80+Math.floor(t()*30)})}for(let b=0;b<c;b++){if(t()>e.density)continue;const k=y+b*i,R=t()>.8?t()>.5?2:-2:t()>.5?1:-1;m=Math.max(-3,Math.min(n.length+3,m+R));const A=1+Math.floor(t()*3);d.push({id:_n(),pitch:$r(e.root,n,m,e.octave),start:k,duration:A*i*.95,velocity:85+Math.floor(t()*30)})}for(const b of a)g.push({id:_n(),pitch:b.pitch,start:y+b.step*i,duration:i*.8,velocity:b.vel+Math.floor(t()*10-5)})}return{melody:d,bass:h,chords:f,drums:g,config:e}}const lf=Object.keys(Wr),cf=Object.keys(Ur),df=Object.keys(Vr);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 xi={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")]},Si={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")]},wi={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")]},Ci={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")]},ki=[xi,Si,wi,Ci,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=ki.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 Mi(e){return{past:[],present:e,future:[]}}function ji(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function Ri(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 $i(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 Ti(e){return e.past.length>0}function Pi(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 Ei(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 Ai(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 Ni(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 Ii(e,t,n,r){const a={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:r};return[...e,a]}function Li(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 Fi(e){return JSON.stringify(e,null,2)}function Di(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 Ri(e);case"REDO":return $i(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=Ei(r,t.clipboard,t.targetTime);n=mt(n,t.layerId,a);break}case"CUT":{const r=rt(n,t.layerId),{remaining:a}=Ai(r,t.range);n=mt(n,t.layerId,a);break}case"DELETE_RANGE":{const r=rt(n,t.layerId),a=Ni(r,t.range);n=mt(n,t.layerId,a);break}case"RECORD":{const r=rt(n,t.layerId),a=Ii(r,t.cc,t.value,t.time);n=mt(n,t.layerId,a);break}case"THIN":{const r=rt(n,t.layerId),a=Li(r,t.keepEveryN);n=mt(n,t.layerId,a);break}case"IMPORT":{const r=Di(t.json);r.length>0&&(n=mt(n,t.layerId,r));break}}return ji(e,n)}}}function pf(e=[]){const[t,n]=u.useReducer(ff,Mi(e)),r=u.useRef([]),a=u.useCallback(b=>rt(t.present,b),[t.present]),o=u.useCallback((b,k)=>n({type:"ADD_EVENT",layerId:b,event:k}),[]),i=u.useCallback((b,k,R,A,$)=>n({type:"UPDATE_EVENT",layerId:b,id:k,value:R,time:A,handleType:$}),[]),l=u.useCallback((b,k)=>n({type:"REMOVE_EVENT",layerId:b,id:k}),[]),c=u.useCallback((b,k)=>n({type:"SET_EVENTS",layerId:b,events:k}),[]),d=u.useCallback(()=>n({type:"UNDO"}),[]),h=u.useCallback(()=>n({type:"REDO"}),[]),f=u.useCallback((b,k)=>{r.current=qr(rt(t.present,b),k)},[t.present]),g=u.useCallback((b,k)=>{r.current=qr(rt(t.present,b),k),n({type:"CUT",layerId:b,range:k})},[t.present]),m=u.useCallback((b,k)=>{r.current.length>0&&n({type:"PASTE",layerId:b,clipboard:r.current,targetTime:k})},[]),p=u.useCallback((b,k)=>n({type:"DELETE_RANGE",layerId:b,range:k}),[]),y=u.useCallback((b,k,R,A)=>n({type:"RECORD",layerId:b,cc:k,value:R,time:A}),[]),v=u.useCallback((b,k)=>n({type:"THIN",layerId:b,keepEveryN:k}),[]),x=u.useCallback(b=>Fi(rt(t.present,b)),[t.present]),C=u.useCallback((b,k)=>n({type:"IMPORT",layerId:b,json:k}),[]);return{snapshots:t.present,getEvents:a,addEvent:o,updateEvent:i,removeEvent:l,setEvents:c,undo:d,redo:h,canUndo:Ti(t),canRedo:Pi(t),copy:f,cut:g,paste:m,clipboard:r.current,deleteRange:p,record:y,thin:v,exportLane:x,importLane:C}}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 Oi(e,t){const n=e.steps.map((r,a)=>a===t?{...r,active:!r.active}:r);return{...e,steps:n}}function _i(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 zi(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 Bi(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 Wi(e,t){const n=e.steps.map((r,a)=>a===t?{...r,slide:!r.slide}:r);return{...e,steps:n}}function Ui(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 Vi(e){return{...e,steps:[...e.steps].reverse()}}function qi(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 Hi(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 Ki(e){return{...e,steps:e.steps.map(()=>wa(e.rootNote))}}function Ca(e,t=4){return 60/e/t}function Yi(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 Zi(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([]),g=u.useRef(a);g.current=a;const m=u.useRef(h);m.current=h;const p=u.useRef(c);p.current=c;const y=u.useRef(t);y.current=t;const v=u.useRef(n);v.current=n;const x=u.useRef(null),C=u.useRef(0),b=u.useRef(0),k=u.useCallback(()=>{var J,ne;if(!p.current)return;const M=g.current,F=C.current%M.length,j=M.steps[F];if(Zi(j)){const ae=Yi(C.current,M.bpm,M.swing);(J=y.current)==null||J.call(y,j,F,ae)}const E=(Date.now()-b.current)/1e3;for(let ae=0;ae<m.current.length;ae++){const re=m.current[ae];if(re.enabled&&re.targetCC!==void 0){const G=Xr(re,E,M.bpm);(ne=v.current)==null||ne.call(v,ae,re.targetCC,G)}}l(F),C.current++;const H=Ca(M.bpm)*1e3,Y=F%2===0?0:H*M.swing*.5;x.current=setTimeout(k,H+Y)},[]),R=u.useCallback(()=>{p.current||(C.current=0,b.current=Date.now(),d(!0),p.current=!0,k())},[k]),A=u.useCallback(()=>{d(!1),p.current=!1,l(-1),x.current&&(clearTimeout(x.current),x.current=null)},[]),$=u.useCallback(()=>{p.current?A():R()},[R,A]);u.useEffect(()=>()=>{x.current&&clearTimeout(x.current)},[]);const W=u.useCallback(M=>o(F=>Oi(F,M)),[]),w=u.useCallback((M,F)=>o(j=>_i(j,M,F)),[]),D=u.useCallback((M,F)=>o(j=>zi(j,M,F)),[]),_=u.useCallback((M,F)=>o(j=>Bi(j,M,F)),[]),P=u.useCallback((M,F)=>o(j=>Gi(j,M,F)),[]),B=u.useCallback(M=>o(F=>Wi(F,M)),[]),z=u.useCallback(M=>o(F=>Ui(F,M)),[]),K=u.useCallback(()=>o(M=>Vi(M)),[]),Z=u.useCallback(M=>o(F=>qi(F,M)),[]),O=u.useCallback((M,F)=>o(j=>Hi(j,M,F)),[]),X=u.useCallback(()=>o(M=>Ki(M)),[]),N=u.useCallback(M=>o(F=>({...F,bpm:Math.max(20,Math.min(300,M))})),[]),U=u.useCallback(M=>o(F=>({...F,swing:Math.max(0,Math.min(1,M))})),[]),L=u.useCallback(M=>{o(F=>{if(F.length===M)return F;const j=Array.from({length:M},(E,H)=>H<F.steps.length?F.steps[H]:{active:!1,note:F.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...F,length:M,steps:j}})},[]),T=u.useCallback(M=>{f(F=>[...F,M??ir()])},[]),S=u.useCallback(M=>{f(F=>F.filter((j,E)=>E!==M))},[]),I=u.useCallback((M,F)=>{f(j=>j.map((E,H)=>H===M?{...E,...F}:E))},[]);return{pattern:a,currentStep:i,playing:c,lfos:h,play:R,stop:A,togglePlayback:$,toggle:W,setNote:w,setVelocity:D,setGate:_,setProbability:P,toggleSlide:B,transpose:z,reverse:K,shift:Z,randomizeVel:O,clear:X,setPattern:o,setBpm:N,setSwing:U,setLength:L,addLFO:T,removeLFO:S,updateLFO:I}}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 Xi(){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 Ms=!1,zn=null;async function Qi(e){if(!Ms)return zn||(zn=(async()=>{const t=Xi(),n=new Blob([t],{type:"application/javascript"}),r=URL.createObjectURL(n);try{await e.audioWorklet.addModule(r),Ms=!0}finally{URL.revokeObjectURL(r)}})(),zn)}function Ji(e,t,n){const r=new AudioWorkletNode(e,"nice-audio-processor",{processorOptions:{...kf,...t}});return n&&(r.port.onmessage=a=>{a.data.type==="analysis"&&n(a.data.payload)}),r}function el(e,t=1){const n=new AudioWorkletNode(e,"nice-gain-processor");return n.parameters.get("gain").value=t,n}function tl(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 nl(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 Mf(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),[g,m]=u.useState(null),[p,y]=u.useState(null),x=u.useRef(null),v=u.useRef(null),C=u.useRef(null),b=u.useRef(null),k=u.useRef(null),R=u.useRef(null),A=u.useRef(null),$=u.useRef(null);u.useEffect(()=>{let z=!0;return(async()=>{try{const Z=new AudioContext;if(x.current=Z,await Qi(Z),!z){Z.close();return}const O=[];if(t){const X=Ji(Z,n,N=>{z&&(y(N),d==null||d(N))});v.current=X,O.push(X)}if(r){const X=el(Z,a);C.current=X,O.push(X)}if(o){const X=tl(Z,i);b.current=X,O.push(X)}if(l){const X=nl(Z,c);k.current=X,O.push(X)}if(O.length>0){A.current=O[0],$.current=O[O.length-1];for(let X=0;X<O.length-1;X++)O[X].connect(O[X+1])}f(!0)}catch(Z){z&&m(Z)}})(),()=>{var Z,O,X,N,U;z=!1,(Z=v.current)==null||Z.disconnect(),(O=C.current)==null||O.disconnect(),(X=b.current)==null||X.disconnect(),(N=k.current)==null||N.disconnect(),(U=x.current)==null||U.close()}},[t,r,o,l]);const W=u.useCallback(z=>{R.current&&R.current.disconnect(),R.current=z,A.current&&z.connect(A.current)},[]),w=u.useCallback(()=>{R.current&&(R.current.disconnect(),R.current=null)},[]),D=u.useCallback(()=>$.current,[]),_=u.useCallback(z=>{var Z;const K=(Z=C.current)==null?void 0:Z.parameters.get("gain");K&&(K.value=Math.max(0,Math.min(2,z)))},[]),P=u.useCallback((z,K)=>{var O;const Z=(O=b.current)==null?void 0:O.parameters.get(z);Z&&(Z.value=K)},[]),B=u.useCallback((z,K)=>{var O;const Z=(O=k.current)==null?void 0:O.parameters.get(z);Z&&(Z.value=K)},[]);return{isReady:h,error:g,analysis:p,connectSource:W,disconnectSource:w,getOutputNode:D,setGain:_,setCompressorParam:P,setVocoderParam:B,audioContext:x.current}}function rl(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function al(e){return e>=50?3:e>=30?2.5:e>=20?2:e>=10?1.5:1}function jf(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,g=0,m=0;const p=[];let y=0,x=0,v=0;const C=new Map;e.forEach((w,D)=>{const _=w.startTime,P=w.startTime+w.duration,B=_-a,z=P+o,K=t.filter(S=>S.t>=B&&S.t<=z&&S.hz>0);if(!K||K.length===0)return;const Z=Math.max(1,Math.ceil((w.duration||.25)/i)),O=Math.max(10,Math.round(100*(w.duration||1))),X=Math.max(1,Math.round(O/Z));let N=0;const U=[];for(let S=0;S<Z;S++){const I=_+S*(w.duration/Z),M=_+(S+1)*(w.duration/Z),F=Math.min(.06,w.duration/Z*.2),j=I-F,E=M+F,H=t.filter(G=>G.t>=j&&G.t<=E&&G.hz>0);if(!H||H.length===0)continue;let Y=0;H.forEach(G=>{let ee=((12*Math.log2(G.hz/440)+69)%12+12)%12;for(;ee-w.pitch>6;)ee-=12;for(;ee-w.pitch<-6;)ee+=12;const oe=Math.abs(ee-w.pitch);Y+=oe});const J=Y/H.length;let ne=0;if(r<=0)ne=J===0?1:0;else{const G=r*2;ne=Math.max(0,1-Math.min(J/G,1))}if(ne<=0)continue;const ae=!h&&w.isGold?2:1,re=Math.round(X*ae*ne);re>0&&(f+=re,N+=re,U.push({segIndex:S,frac:ne,add:re,segStart:j,segEnd:E,visualStart:I,visualEnd:M}))}const L=w.line??0;C.has(L)||C.set(L,{total:0,hit:0,comboBonus:0});const T=C.get(L);if(T.total++,N>0){y++,y>x&&(x=y),T.hit++;const S=al(y),I=S>1?Math.round(N*(S-1)):0;v+=I,T.comboBonus+=I;const M=Math.max(1,Math.ceil((w.duration||.25)/i)),j=U.length>=M,E=j?Math.round(Math.max(10,Math.round(100*(w.duration||1)))*l*(!h&&w.isGold?1.5:1)*d):0,H=j&&!h&&w.isGold?Math.round(Math.max(10,Math.round(100*(w.duration||1)))*c*d):0;g+=E,m+=H,p.push({noteKey:`${w.line??0}-${w.idx??0}`,segments:U,totalAdded:N,completed:j,completionBonus:E,goldFullBonus:H})}else y=0});const b=[];for(const[w,D]of C.entries()){const _=D.total>0?D.hit/D.total:0;b.push({verseIndex:w,hitFraction:_,label:rl(_),comboBonus:D.comboBonus})}const k={maxCombo:x,currentCombo:0,totalComboBonus:v},R=v+g+m,A=p.length,$=p.filter(w=>w.completed).length,W={hits:A,misses:e.length-A,good:A-$,perfect:$,maxCombo:x};return{classicScore:f,bonusScore:R,totalScore:f+R,total:f,perNote:p,combo:k,verseRatings:b,noteStats:W}}function sl(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 ol(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function Rf(e,t,n){const r=sl(t,n);if(r<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0,total:0};const a=ol(e.classicScore,r),o=Math.round(e.bonusScore/r*1e4);return{...e,classicScore:a,bonusScore:o,totalScore:a+o,total:a}}function il(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 $f(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 Tf(e,t="/backgrounds"){return e.backgroundImage?`${t}/${e.backgroundImage}`:""}function Pf(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 Ef(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 Af(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 Nf(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 If(e,t,n){const a=Date.parse(e)-n;return Math.max(0,Math.round(t-a))}const ll={crepe:"#a78bfa",librosa:"#34d399",pitchy:"#60a5fa",autocorr:"#555555"};function Lf(e){return e==="autocorr"?"Ultrastar":e.charAt(0).toUpperCase()+e.slice(1)}function Ff(e){return ll[e]??"#555555"}function Df(e){const t=ll[e]??"#555555";return`var(--algo-${e}, ${t})`}function Of(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=il(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 _f(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 zf(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 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.map(i=>i.id===n?{...i,bypass:!i.bypass}:i))||[]}}})}function Wf(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 Uf(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 Vf(e,t,n,r){e(a=>({...a,[n]:(a[n]||[]).filter(o=>o.id!==r)})),t(null)}function qf(e,t,n){e(r=>({...r,[n]:[]})),t(null)}function Hf(e,t,n){e(r=>({...r,[t]:n}))}function Kf(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 Yf(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 Zf(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 Xf(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 Qf(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 Jf(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),g=f.getChannelData(0),m=f.sampleRate,p=Math.floor(m*.1),y=p,x=[];if(t==="pitchy"){const v=Er.PitchDetector.forFloat32Array(p),C=Math.max(1,Math.floor((g.length-p)/y));let b=0;for(let k=0;k<g.length-p;k+=y){if(r!=null&&r.aborted)throw new Error("aborted");const R=g.slice(k,k+p);if(i)for(let _=0;_<R.length;_++)R[_]*=.5*(1-Math.cos(2*Math.PI*_/(R.length-1)));const[A,$]=v.findPitch(R,m),W=Bn(A);let w=0;for(let _=0;_<R.length;_++)w+=R[_]*R[_];w=Math.sqrt(w/R.length);const D=typeof o=="number"?o:.01;W&&A>50&&A<2e3&&$>.7&&w>D&&x.push({start:k/m,duration:p/m,pitch:W,freq:A}),b++,a&&a(b/C)}}else if(t==="crepe"){if(a&&a(.05),!l)throw new Error("CREPE backend callback (postPitch) is required for crepe algorithm");const v=await l(e);if(r!=null&&r.aborted)throw new Error("aborted");const C=Array.isArray(v.track)?v.track:[];C.length>0&&C.forEach((b,k)=>{var A;const R=Bn(b.hz);if(R&&b.hz>50&&b.hz<2e3){const $=((A=C[k+1])==null?void 0:A.t)??b.t+.1;x.push({start:b.t,duration:k<C.length-1?$-b.t:.1,pitch:R,freq:b.hz})}}),a&&a(1)}else if(t==="ultrastar-wp"){const v=Math.max(1,Math.floor((g.length-p)/y));let C=0;for(let b=0;b<g.length-p;b+=y){if(r!=null&&r.aborted)throw new Error("aborted");const k=g.slice(b,b+p);if(i)for(let W=0;W<k.length;W++)k[W]*=.5*(1-Math.cos(2*Math.PI*W/(k.length-1)));const A=Qf(k,m,typeof o=="number"?o:.01),$=Bn(A);$&&A>50&&A<2e3&&x.push({start:b/m,duration:p/m,pitch:$,freq:A}),C++,a&&a(C/v)}}if(t==="librosa"){if(a&&a(.05),!c)throw new Error("Librosa backend callback (postLibrosaPitchTrack) is required for librosa algorithm");const v=await c(e);if(r!=null&&r.aborted)throw new Error("aborted");const C=Array.isArray(v.track)?v.track:[];C.length>0&&C.forEach((b,k)=>{var A;const R=Bn(b.hz);if(R&&b.hz>50&&b.hz<2e3){const $=((A=C[k+1])==null?void 0:A.t)??b.t+.1;x.push({start:b.t,duration:k<C.length-1?$-b.t:.1,pitch:R,freq:b.hz})}}),a&&a(1)}return Xf(x)}function ep(e){switch(e){case"pitchy":return`#TITLE:Analyzed Song
389
+ `}let Ms=!1,zn=null;async function Qi(e){if(!Ms)return zn||(zn=(async()=>{const t=Xi(),n=new Blob([t],{type:"application/javascript"}),r=URL.createObjectURL(n);try{await e.audioWorklet.addModule(r),Ms=!0}finally{URL.revokeObjectURL(r)}})(),zn)}function Ji(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 el(e,t=1){const n=new AudioWorkletNode(e,"nice-gain-processor");return n.parameters.get("gain").value=t,n}function tl(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 nl(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),[g,m]=u.useState(null),[p,y]=u.useState(null),v=u.useRef(null),x=u.useRef(null),C=u.useRef(null),b=u.useRef(null),k=u.useRef(null),R=u.useRef(null),A=u.useRef(null),$=u.useRef(null);u.useEffect(()=>{let z=!0;return(async()=>{try{const Z=new AudioContext;if(v.current=Z,await Qi(Z),!z){Z.close();return}const O=[];if(t){const X=Ji(Z,n,N=>{z&&(y(N),d==null||d(N))});x.current=X,O.push(X)}if(r){const X=el(Z,a);C.current=X,O.push(X)}if(o){const X=tl(Z,i);b.current=X,O.push(X)}if(l){const X=nl(Z,c);k.current=X,O.push(X)}if(O.length>0){A.current=O[0],$.current=O[O.length-1];for(let X=0;X<O.length-1;X++)O[X].connect(O[X+1])}f(!0)}catch(Z){z&&m(Z)}})(),()=>{var Z,O,X,N,U;z=!1,(Z=x.current)==null||Z.disconnect(),(O=C.current)==null||O.disconnect(),(X=b.current)==null||X.disconnect(),(N=k.current)==null||N.disconnect(),(U=v.current)==null||U.close()}},[t,r,o,l]);const W=u.useCallback(z=>{R.current&&R.current.disconnect(),R.current=z,A.current&&z.connect(A.current)},[]),w=u.useCallback(()=>{R.current&&(R.current.disconnect(),R.current=null)},[]),D=u.useCallback(()=>$.current,[]),_=u.useCallback(z=>{var Z;const K=(Z=C.current)==null?void 0:Z.parameters.get("gain");K&&(K.value=Math.max(0,Math.min(2,z)))},[]),P=u.useCallback((z,K)=>{var O;const Z=(O=b.current)==null?void 0:O.parameters.get(z);Z&&(Z.value=K)},[]),B=u.useCallback((z,K)=>{var O;const Z=(O=k.current)==null?void 0:O.parameters.get(z);Z&&(Z.value=K)},[]);return{isReady:h,error:g,analysis:p,connectSource:W,disconnectSource:w,getOutputNode:D,setGain:_,setCompressorParam:P,setVocoderParam:B,audioContext:v.current}}function rl(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function al(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,g=0,m=0;const p=[];let y=0,v=0,x=0;const C=new Map;e.forEach((w,D)=>{const _=w.startTime,P=w.startTime+w.duration,B=_-a,z=P+o,K=t.filter(S=>S.t>=B&&S.t<=z&&S.hz>0);if(!K||K.length===0)return;const Z=Math.max(1,Math.ceil((w.duration||.25)/i)),O=Math.max(10,Math.round(100*(w.duration||1))),X=Math.max(1,Math.round(O/Z));let N=0;const U=[];for(let S=0;S<Z;S++){const I=_+S*(w.duration/Z),M=_+(S+1)*(w.duration/Z),F=Math.min(.06,w.duration/Z*.2),j=I-F,E=M+F,H=t.filter(G=>G.t>=j&&G.t<=E&&G.hz>0);if(!H||H.length===0)continue;let Y=0;H.forEach(G=>{let ee=((12*Math.log2(G.hz/440)+69)%12+12)%12;for(;ee-w.pitch>6;)ee-=12;for(;ee-w.pitch<-6;)ee+=12;const oe=Math.abs(ee-w.pitch);Y+=oe});const J=Y/H.length;let ne=0;if(r<=0)ne=J===0?1:0;else{const G=r*2;ne=Math.max(0,1-Math.min(J/G,1))}if(ne<=0)continue;const ae=!h&&w.isGold?2:1,re=Math.round(X*ae*ne);re>0&&(f+=re,N+=re,U.push({segIndex:S,frac:ne,add:re,segStart:j,segEnd:E,visualStart:I,visualEnd:M}))}const L=w.line??0;C.has(L)||C.set(L,{total:0,hit:0,comboBonus:0});const T=C.get(L);if(T.total++,N>0){y++,y>v&&(v=y),T.hit++;const S=al(y),I=S>1?Math.round(N*(S-1)):0;x+=I,T.comboBonus+=I;const M=Math.max(1,Math.ceil((w.duration||.25)/i)),j=U.length>=M,E=j?Math.round(Math.max(10,Math.round(100*(w.duration||1)))*l*(!h&&w.isGold?1.5:1)*d):0,H=j&&!h&&w.isGold?Math.round(Math.max(10,Math.round(100*(w.duration||1)))*c*d):0;g+=E,m+=H,p.push({noteKey:`${w.line??0}-${w.idx??0}`,segments:U,totalAdded:N,completed:j,completionBonus:E,goldFullBonus:H})}else y=0});const b=[];for(const[w,D]of C.entries()){const _=D.total>0?D.hit/D.total:0;b.push({verseIndex:w,hitFraction:_,label:rl(_),comboBonus:D.comboBonus})}const k={maxCombo:v,currentCombo:0,totalComboBonus:x},R=x+g+m,A=p.length,$=p.filter(w=>w.completed).length,W={hits:A,misses:e.length-A,good:A-$,perfect:$,maxCombo:v};return{classicScore:f,bonusScore:R,totalScore:f+R,total:f,perNote:p,combo:k,verseRatings:b,noteStats:W}}function sl(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 ol(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function $f(e,t,n){const r=sl(t,n);if(r<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0,total:0};const a=ol(e.classicScore,r),o=Math.round(e.bonusScore/r*1e4);return{...e,classicScore:a,bonusScore:o,totalScore:a+o,total:a}}function il(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 ll={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 ll[e]??"#555555"}function Of(e){const t=ll[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=il(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),g=f.getChannelData(0),m=f.sampleRate,p=Math.floor(m*.1),y=p,v=[];if(t==="pitchy"){const x=Er.PitchDetector.forFloat32Array(p),C=Math.max(1,Math.floor((g.length-p)/y));let b=0;for(let k=0;k<g.length-p;k+=y){if(r!=null&&r.aborted)throw new Error("aborted");const R=g.slice(k,k+p);if(i)for(let _=0;_<R.length;_++)R[_]*=.5*(1-Math.cos(2*Math.PI*_/(R.length-1)));const[A,$]=x.findPitch(R,m),W=Bn(A);let w=0;for(let _=0;_<R.length;_++)w+=R[_]*R[_];w=Math.sqrt(w/R.length);const D=typeof o=="number"?o:.01;W&&A>50&&A<2e3&&$>.7&&w>D&&v.push({start:k/m,duration:p/m,pitch:W,freq:A}),b++,a&&a(b/C)}}else if(t==="crepe"){if(a&&a(.05),!l)throw new Error("CREPE backend callback (postPitch) is required for crepe algorithm");const x=await l(e);if(r!=null&&r.aborted)throw new Error("aborted");const C=Array.isArray(x.track)?x.track:[];C.length>0&&C.forEach((b,k)=>{var A;const R=Bn(b.hz);if(R&&b.hz>50&&b.hz<2e3){const $=((A=C[k+1])==null?void 0:A.t)??b.t+.1;v.push({start:b.t,duration:k<C.length-1?$-b.t:.1,pitch:R,freq:b.hz})}}),a&&a(1)}else if(t==="ultrastar-wp"){const x=Math.max(1,Math.floor((g.length-p)/y));let C=0;for(let b=0;b<g.length-p;b+=y){if(r!=null&&r.aborted)throw new Error("aborted");const k=g.slice(b,b+p);if(i)for(let W=0;W<k.length;W++)k[W]*=.5*(1-Math.cos(2*Math.PI*W/(k.length-1)));const A=Jf(k,m,typeof o=="number"?o:.01),$=Bn(A);$&&A>50&&A<2e3&&v.push({start:b/m,duration:p/m,pitch:$,freq:A}),C++,a&&a(C/x)}}if(t==="librosa"){if(a&&a(.05),!c)throw new Error("Librosa backend callback (postLibrosaPitchTrack) is required for librosa algorithm");const x=await c(e);if(r!=null&&r.aborted)throw new Error("aborted");const C=Array.isArray(x.track)?x.track:[];C.length>0&&C.forEach((b,k)=>{var A;const R=Bn(b.hz);if(R&&b.hz>50&&b.hz<2e3){const $=((A=C[k+1])==null?void 0:A.t)??b.t+.1;v.push({start:b.t,duration:k<C.length-1?$-b.t:.1,pitch:R,freq:b.hz})}}),a&&a(1)}return Qf(v)}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 tp(e,t){return`${e}:${t}`}function np(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 rp(e){return e.length===0?[]:e.flat()}function ap(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 sp(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function cl(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 dl(e,t){const n=t.seed!=null?sp(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 ul(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 op(e,t){let n=[...e.map(r=>({...r}))];return t.template&&t.grooveStrength>0&&(n=ul(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=cl(n,t.swing)),t.humanize&&(n=dl(n,t.humanize)),n}function ip(e){return Ma.find(t=>t.id===e)}function lp(){return Ma.map(({id:e,name:t})=>({id:e,name:t}))}const cp=[{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 js(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 dp{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(),g=t.createGain(),m=t.createGain(),p=n-1,y=Math.abs(p)*5+2,x=Math.abs(p)*.015;h.type="sawtooth",h.frequency.value=y,g.gain.value=x,h.connect(g),g.connect(c.delayTime),c.delayTime.value=.02,f.type="sawtooth",f.frequency.value=y,m.gain.value=x,f.connect(m),m.connect(d.delayTime),d.delayTime.value=.02+x;const v=t.createGain();v.gain.value=.5;const C=t.createGain();return C.gain.value=.5,a.connect(c),a.connect(d),c.connect(v),d.connect(C),v.connect(i),C.connect(i),a.connect(l),i.connect(o),l.connect(o),h.start(),f.start(),{type:"chipmunk",nodes:[a,c,d,h,f,g,m,v,C,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=js(t,2+n*3,3);const g=t.createGain();g.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(g),i.connect(g),l.connect(g),r.connect(f),f.connect(g);const m=t.createGain();return m.gain.value=.7,r.connect(m),m.connect(a),g.connect(a),{type:"cave",nodes:[r,o,i,l,c,d,h,f,g,m,a],input:r,output:a}}buildReverb(t,n,r,a){const o=t.createGain(),i=t.createGain(),l=t.createConvolver();l.buffer=js(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 g=t.createGain();g.gain.value=.3+n*.2,r.connect(d),d.connect(g),g.connect(a),h.start(),i.push(d,h,f,g)}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 m of d){const p=t.createBiquadFilter();p.type="peaking",p.frequency.value=m,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 g=t.createGain();return g.gain.value=.5+n*.3,r.connect(o),o.connect(g),h.connect(g),r.connect(f),g.connect(a),f.connect(a),i.start(),{type:"autotune",nodes:[r,o,i,l,...c,h,g,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 g=200*Math.pow(2,f*.5),m=t.createBiquadFilter();m.type="bandpass",m.frequency.value=g,m.Q.value=4;const p=t.createBiquadFilter();p.type="bandpass",p.frequency.value=g,p.Q.value=4;const y=t.createGain();y.gain.value=0,r.connect(m),m.connect(y.gain),o.connect(p),p.connect(y),y.connect(d),c.push(m,p,y)}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 hl=["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=hl[Math.round(e)%12],n=Math.floor(Math.round(e)/12)-1;return`${t}${n}`}function Tr(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 up(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:g,totalScore:m,micSettings:p}=e,y=l.filter(te=>te.hz>0),x=y.map(te=>Ut(te.hz)),v=[],C=[],b=[],k=[...c].sort((te,se)=>te.startTime-se.startTime);function R(te){let se=0,Ne=k.length-1;for(;se<=Ne;){const De=se+Ne>>>1,Pe=k[De];if(te<Pe.startTime)Ne=De-1;else if(te>Pe.startTime+Pe.duration)se=De+1;else return Pe.pitch}return 0}for(const te of l){const se=te.hz>0?Ut(te.hz):0,Ne=R(te.t);if(C.push({t:te.t,sung:se,expected:Ne}),se>0&&Ne>0){const De=(se-Ne)*100;v.push(De)}}let A=0;for(const te of k){const se=te.startTime-.3,Ne=te.startTime+te.duration;for(;A<y.length&&y[A].t<se;)A++;A<y.length&&y[A].t<=Ne&&b.push((y[A].t-te.startTime)*1e3)}const $=v.map(Math.abs),W=[...$].sort((te,se)=>te-se),w=$.length>0?$.reduce((te,se)=>te+se,0)/$.length:0,D=Tr(W,50),_=$.length>1?Math.sqrt($.reduce((te,se)=>te+(se-w)**2,0)/($.length-1)):0,P=$.filter(te=>te<=50).length,B=$.filter(te=>te<=15).length,z=$.length>0?P/$.length*100:0,K=$.length>0?B/$.length*100:0,Z=["< −100","−100 to −50","−50 to −25","−25 to −15","−15 to 0","0 to +15","+15 to +25","+25 to +50","+50 to +100","> +100"],O=new Array(10).fill(0);for(const te of v){const se=te<-100?0:te<-50?1:te<-25?2:te<-15?3:te<0?4:te<15?5:te<25?6:te<50?7:te<100?8:9;O[se]++}const X=Z.map((te,se)=>({centRange:te,count:O[se],pct:v.length>0?O[se]/v.length*100:0})),N=y.map(te=>te.hz).sort((te,se)=>te-se),U=N.length>0?N[0]:0,L=N.length>0?N[N.length-1]:0,T=U>0?Ut(U):0,S=L>0?Ut(L):0,I=S-T,M=[...x].sort((te,se)=>te-se),F=Tr(M,10),j=Tr(M,90),E=new Array(12).fill(0);for(const te of x){const se=Math.round(te)%12;se>=0&&se<12&&E[se]++}const H=E.reduce((te,se)=>te+se,0),Y=hl.map((te,se)=>({note:te,count:E[se],pct:H>0?E[se]/H*100:0})),J=hp(y),ne=b.length>0?b.reduce((te,se)=>te+se,0)/b.length:0,ae=b.length>1?Math.sqrt(b.reduce((te,se)=>te+(se-ne)**2,0)/(b.length-1)):0,re=ae>0?Math.max(0,Math.min(100,100-ae/2)):100;let G=0,q=0;for(let te=1;te<x.length;te++){const se=Math.abs(x[te]-x[te-1]);G+=se,q++}const ee=q>0?G/q*100/12:0,oe=l.filter(te=>te.hz<=0).length,ce=l.length>0?(1-oe/l.length)*100:0,fe=new Map;for(const te of c){const se=te.line??0;fe.has(se)||fe.set(se,[]),fe.get(se).push(te)}const Q=new Map;for(const te of y){const se=R(te.t);if(se<=0)continue;let Ne=0,De=k.length-1,Pe=-1;for(;Ne<=De;){const we=Ne+De>>>1,dt=k[we];if(te.t<dt.startTime)De=we-1;else if(te.t>dt.startTime+dt.duration)Ne=we+1;else{Pe=dt.line??0;break}}if(Pe<0)continue;const tt=Math.abs((Ut(te.hz)-se)*100);Q.has(Pe)||Q.set(Pe,[]),Q.get(Pe).push(tt)}const ue=d.map(te=>{const se=fe.get(te.verseIndex)??[],Ne=Q.get(te.verseIndex)??[],De=Ne.length>0?Ne.reduce((Pe,tt)=>Pe+tt,0)/Ne.length:0;return{verseIndex:te.verseIndex,label:te.label,hitFraction:te.hitFraction,avgCentDeviation:Math.round(De*10)/10,noteCount:se.length,notesHit:Math.round(te.hitFraction*se.length),comboBonus:te.comboBonus}}),ye=2,je=.5,Fe=l.length>0?l[l.length-1].t:0,Re=[],Se=C.filter(te=>te.sung>0&&te.expected>0);if(Se.length>0){let te=0,se=0,Ne=0;for(let De=0;De<=Fe;De+=je){const Pe=De-ye/2,tt=De+ye/2;for(;se<Se.length&&Se[se].t<tt;)Math.abs(Se[se].sung-Se[se].expected)<=.5&&Ne++,se++;for(;te<se&&Se[te].t<Pe;)Math.abs(Se[te].sung-Se[te].expected)<=.5&&Ne--,te++;const we=se-te;Re.push({t:De,accuracy:we>0?Ne/we*100:0})}}else for(let te=0;te<=Fe;te+=je)Re.push({t:te,accuracy:0});return{playerName:t,playerColor:n,songTitle:r,songArtist:a,songBpm:o,difficulty:i,timestamp:new Date().toISOString(),classicScore:f,bonusScore:g,totalScore:m,maxCombo:(h==null?void 0:h.maxCombo)??0,totalComboBonus:(h==null?void 0:h.totalComboBonus)??0,totalPitchPoints:l.length,avgCentDeviation:Math.round(w*10)/10,medianCentDeviation:Math.round(D*10)/10,stdDevCents:Math.round(_*10)/10,intonationAccuracyPct:Math.round(z*10)/10,perfectHitPct:Math.round(K*10)/10,pitchDeviationHistogram:X,lowestHz:Math.round(U*10)/10,highestHz:Math.round(L*10)/10,lowestNote:T>0?Wn(T):"—",highestNote:S>0?Wn(S):"—",rangeInSemitones:Math.round(I*10)/10,tessituraLow:F>0?Wn(F):"—",tessituraHigh:j>0?Wn(j):"—",pitchClassDistribution:Y,vibrato:J,avgOnsetDeviationMs:Math.round(ne*10)/10,rhythmStabilityPct:Math.round(re*10)/10,jitterPct:Math.round(ee*100)/100,shimmerProxy:Math.round(ce*10)/10,verseMetrics:ue,micSettings:p,pitchOverTime:C,accuracyOverTime:Re}}function hp(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(m=>Ut(m.hz)),n=e.map(m=>m.t),r=.5,a=[],o=[];let i=0,l=0,c=0;for(let m=0;m<e.length;m++){for(l+=t[m],c++;i<m&&n[m]-n[i]>=r;)l-=t[i],c--,i++;if(c<6||(m-i)%10!==0)continue;const p=l/c;let y=0,x=t[i]-p,v=Math.abs(x);for(let k=i+1;k<=m;k++){const R=t[k]-p;R*x<0&&y++,x=R;const A=Math.abs(R);A>v&&(v=A)}const C=n[m]-n[i];if(C<=0)continue;const b=y/2/C;b>=3&&b<=12&&(a.push(b),o.push(v*100))}if(a.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const d=a.reduce((m,p)=>m+p,0)/a.length,h=o.reduce((m,p)=>m+p,0)/o.length,f=Math.sqrt(a.reduce((m,p)=>m+(p-d)**2,0)/a.length),g=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(g)}}function fl(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 Rs(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 fp(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 g=0;g<n;g++){const m=g+i+Math.floor((r-n)/2);if(m<0||m>=r)continue;const p=e[g],y=t[m];l+=p*y,c+=p*p,d+=y*y}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 pp(e,t,n=50,r=30){try{const a=Math.max(300,Math.round(e.length/t*1e3)),o=fl(a,t,n,r),i=Rs(e,t,1e3),l=Rs(o,t,1e3),d=fp(l.env,i.env)*1e3/1e3;return Math.round(d)}catch{return null}}function pl(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 pl(e)*60/t}function Hr(e,t,n){const r=ja(t,n);return Math.round(e/r)*r}function mp(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 gp(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function yp(e,t={}){const{timingRange:n=.02,velocityRange:r=10,seed:a}=t,o=a!=null?gp(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 bp(){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 vp(e,t,n){return{start:Hr(e.start,t,n),end:Hr(e.end,t,n),enabled:e.enabled}}function Sp(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function wp(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 Cp(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 ml{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)&&Cp(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 kp(e={}){const t=new ml,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 Mp(e){return Yn(e)}const jp=["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"],Rp=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],$p=500*1024*1024,Tp=20;function jt(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function Pp(e,t){return!!(e.type&&t.some(n=>e.type.startsWith(n.replace("*","")))||e.type.startsWith("audio/"))}function Ep(e,t){const n=jt(e.name);return n!==""&&t.includes(n)}function Ra(e,t={}){const n=t.maxSize??$p,r=t.allowedTypes??jp,a=t.allowedExtensions??Rp,o=t.maxFiles??Tp,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(!Pp(d,r)&&!Ep(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 gl(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 Ap(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 gl(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 Np(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 yl=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(yl||{}),kt=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(kt||{}),bl=(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))(bl||{}),xl=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(xl||{});const Ip=["#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 Lp(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 Fp(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"],Dp=e=>e.segments.some(t=>t.isOff||or.some(n=>t.name.toLowerCase().includes(n))),Op=e=>e.segments.find(t=>t.isOff||or.some(n=>t.name.toLowerCase().includes(n))),vl=e=>Math.floor((e.valueFrom+e.valueTo)/2),_p=e=>{const t=Op(e);return t?vl(t):0},zp=(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(()=>zp(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}})}),Dp(e)&&s.jsx("button",{type:"button",onClick:()=>c(_p(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})}},Pr=e=>Math.max(0,Math.min(255,Math.round(e)));function Sl({service:e,pollInterval:t=500,className:n,style:r}){const[a,o]=u.useState([]),[i,l]=u.useState(null),[c,d]=u.useState(()=>Array(513).fill(0)),[h,f]=u.useState(30),[g,m]=u.useState(0),[p,y]=u.useState(!1),x=u.useRef(null);u.useEffect(()=>{let w=!1;return e.getDevices().then(D=>{w||(o(D),D.length>0&&l(D[0]))}).catch(()=>{}),()=>{w=!0}},[e]),u.useEffect(()=>{if(x.current&&window.clearInterval(x.current),!(t<=0))return x.current=window.setInterval(async()=>{try{const w=await e.getState();Array.isArray(w.frontSnapshot)&&w.frontSnapshot.length>=513&&d(w.frontSnapshot.slice(0,513)),typeof w.fps=="number"&&f(w.fps),typeof w.startCode=="number"&&m(w.startCode)}catch{}},t),()=>{x.current&&window.clearInterval(x.current)}},[e,t]);const v=async()=>{i&&(await e.openPort(i.serialNumber||i.description),y(!0))},C=async()=>{await e.closePort(),y(!1)},b=async()=>{await e.blackout(),d(w=>{const D=[...w];for(let _=1;_<D.length;_++)D[_]=0;return D})},k=()=>e.configure(h,g),R=(w,D)=>{const _=Pr(D);d(P=>{const B=[...P];return B[w]=_,B})},A=(w,D)=>e.setChannel(w,Pr(D)),$=(i==null?void 0:i.deviceInfo)??null,W=u.useMemo(()=>{var w;return(w=$==null?void 0:$.channels)!=null&&w.length?$.channels:Array.from({length:16},(D,_)=>({channel:_+1,name:`Channel ${_+1}`,type:kt.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[$]);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:(i==null?void 0:i.serialNumber)||"",onChange:w=>l(a.find(D=>D.serialNumber===w.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid #d1d5db"},children:a.map(w=>{var D,_;return s.jsxs("option",{value:w.serialNumber,children:[((D=w.deviceInfo)==null?void 0:D.manufacturer)??""," ",((_=w.deviceInfo)==null?void 0:_.model)??w.description," (",w.serialNumber||w.description,")"]},w.serialNumber||w.description)})}),$&&s.jsxs("div",{style:{marginTop:6,fontSize:12,color:"#6b7280"},children:["Mode: ",s.jsx("b",{children:$.modeName}),", footprint: ",s.jsx("b",{children:$.footprint})]})]}),s.jsx("button",{onClick:v,disabled:!i||p,style:{padding:"10px 14px",borderRadius:8,border:"1px solid #10b981",background:"#ecfdf5",cursor:"pointer"},children:"Open port"}),s.jsx("button",{onClick:C,disabled:!p,style:{padding:"10px 14px",borderRadius:8,border:"1px solid #ef4444",background:"#fef2f2",cursor:"pointer"},children:"Close port"}),s.jsx("button",{onClick:b,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:h,onChange:w=>f(Number(w.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:g,onChange:w=>m(Pr(Number(w.target.value))),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid #d1d5db"}})]}),s.jsx("div",{children:s.jsx("button",{onClick:k,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(w=>s.jsx(Ta,{channel:w,value:c[w.channel]??0,onChange:D=>R(w.channel,D),onCommit:D=>A(w.channel,D)},w.channel))})]})]})}const wl=[{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 Cl{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,wl.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 g=f;switch(a){case"ease-in":g=f*f;break;case"ease-out":g=1-(1-f)*(1-f);break;case"ease-in-out":g=f<.5?2*f*f:1-Math.pow(-2*f+2,2)/2;break}const m=l.map((p,y)=>{const x=n[y]??p;return Math.round(p+(x-p)*g)});this.setFixtureValues(t,m),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,Gp=new Uint8Array([65,114,116,45,78,101,116,0]);function Wp(e,t){const n=new Uint8Array(18+t.length);return n.set(Gp,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 Up=5568;function Vp(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 g=new TextEncoder().encode(a.slice(0,63));l.set(g,44),l[108]=r,c.setUint16(109,0,!1),l[111]=n&255,l[112]=0,c.setUint16(113,e,!1);const m=o+11;return c.setUint16(115,28672|m&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 qp(e){const t=e>>8&255,n=e&255;return`239.255.${t}.${n}`}class Hp{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 Kp=({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:g,onPause:m,onStop:p,className:y=""})=>{const[x,v]=u.useState(1),[C,b]=u.useState(0),[k,R]=u.useState(!1),[A,$]=u.useState(null),[W,w]=u.useState(null),[D,_]=u.useState(!0),[P,B]=u.useState(1e3),z=u.useRef(null),K=u.useRef(null),Z=u.useRef(0),O=u.useMemo(()=>.1*x,[x]),X=u.useCallback(j=>j*O,[O]),N=u.useCallback(j=>j/O,[O]),U=u.useCallback(j=>{if(!D)return j;const E=6e4/o;return Math.round(j/E)*E},[D,o]);u.useEffect(()=>{if(k){const j=performance.now(),E=a,H=()=>{const Y=performance.now()-j,J=E+Y;if(J>=r){R(!1),i==null||i(0),p==null||p();return}L(J),i==null||i(J),K.current=requestAnimationFrame(H)};K.current=requestAnimationFrame(H),g==null||g()}else K.current!==null&&(cancelAnimationFrame(K.current),K.current=null),m==null||m();return()=>{K.current!==null&&cancelAnimationFrame(K.current)}},[k,a,r,i,g,m,p]);const L=u.useCallback(j=>{t.forEach(E=>{E.muted||E.cues.forEach(H=>{const Y=H.startTime,J=Y+H.duration;if(j>=Y&&j<J&&Z.current<Y){const ne=n.find(ae=>ae.id===H.sceneId);ne&&ne.fixtures.forEach(ae=>{H.fadeIn&&H.fadeIn>0?e.fadeFixture(ae.fixtureId,ae.values,H.fadeIn):e.setFixtureValues(ae.fixtureId,ae.values)})}if(Z.current<J&&j>=J){const ne=n.find(ae=>ae.id===H.sceneId);ne&&ne.fixtures.forEach(ae=>{if(e.getFixture(ae.fixtureId)&&H.fadeOut&&H.fadeOut>0){const G=new Array(ae.values.length).fill(0);e.fadeFixture(ae.fixtureId,G,H.fadeOut)}})}})}),Z.current=j},[t,n,e]),T=j=>{const E=Math.floor(j/1e3),H=Math.floor(E/60),Y=E%60,J=Math.floor(j%1e3/(1e3/30));return`${H}:${Y.toString().padStart(2,"0")}:${J.toString().padStart(2,"0")}`},S=u.useCallback(j=>{if(!z.current)return;const E=z.current.getBoundingClientRect(),H=j.clientX-E.left+C,Y=U(N(H));i==null||i(Math.max(0,Math.min(r,Y)))},[C,N,U,r,i]),I=u.useCallback((j,E,H)=>{const Y=t.find(ae=>ae.id===E),J=Y==null?void 0:Y.cues.find(ae=>ae.id===j);if(!J)return;const ne=U(Math.max(0,J.startTime+N(H)));c==null||c({...J,startTime:ne})},[t,N,U,c]),M=()=>{const j=6e4/o,E=Math.ceil(r/j),H=[];for(let Y=0;Y<=E;Y++){const J=Y*j,ne=X(J),ae=Y%4===0;H.push(s.jsx("div",{className:`nice-dmx-timeline__beat ${ae?"nice-dmx-timeline__beat--measure":""}`,style:{left:ne},children:ae&&s.jsx("span",{className:"nice-dmx-timeline__beat-label",children:Y/4+1})},Y))}return H},F=(j,E)=>{const H=X(j.startTime),Y=X(j.duration),J=n.find(ne=>ne.id===j.sceneId);return s.jsxs("div",{className:`nice-dmx-timeline__cue ${A===j.id?"nice-dmx-timeline__cue--selected":""}`,style:{left:H,width:Y,backgroundColor:(J==null?void 0:J.color)||E.color||"#8b5cf6"},onClick:ne=>{ne.stopPropagation(),$(j.id)},draggable:!E.locked,onDragEnd:ne=>{var re;const ae=(re=ne.target.parentElement)==null?void 0:re.getBoundingClientRect();ae&&I(j.id,E.id,ne.clientX-ae.left-H)},children:[s.jsx("span",{className:"nice-dmx-timeline__cue-name",children:j.name||(J==null?void 0:J.name)}),j.fadeIn&&j.fadeIn>0&&s.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--in",style:{width:X(j.fadeIn)}}),j.fadeOut&&j.fadeOut>0&&s.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--out",style:{width:X(j.fadeOut)}})]},j.id)};return s.jsxs("div",{className:`nice-dmx-timeline ${y}`,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:()=>R(!k),title:k?"Pause":"Play",children:k?"⏸":"▶"}),s.jsx("button",{type:"button",onClick:()=>{R(!1),i==null||i(0),e.blackout(),p==null||p()},title:"Stop",children:"⏹"})]}),s.jsx("div",{className:"nice-dmx-timeline__time",children:T(a)}),s.jsxs("div",{className:"nice-dmx-timeline__tools",children:[s.jsx("button",{type:"button",className:D?"active":"",onClick:()=>_(!D),title:"Snap to grid",children:"⊞"}),s.jsx("button",{type:"button",onClick:()=>v(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:()=>v(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(j=>s.jsxs("div",{className:`nice-dmx-timeline__header ${W===j.id?"nice-dmx-timeline__header--selected":""}`,onClick:()=>w(j.id),children:[s.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:j.color||"#8b5cf6"}}),s.jsx("span",{className:"nice-dmx-timeline__track-name",children:j.name}),s.jsxs("div",{className:"nice-dmx-timeline__track-controls",children:[s.jsx("button",{type:"button",className:j.muted?"active":"",onClick:E=>{E.stopPropagation(),f==null||f({...j,muted:!j.muted})},title:"Mute",children:"M"}),s.jsx("button",{type:"button",className:j.locked?"active":"",onClick:E=>{E.stopPropagation(),f==null||f({...j,locked:!j.locked})},title:"Lock",children:"🔒"})]})]},j.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:z,onClick:S,onScroll:j=>b(j.currentTarget.scrollLeft),children:[s.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:X(r)},children:M()}),t.map(j=>s.jsx("div",{className:`nice-dmx-timeline__track ${j.muted?"nice-dmx-timeline__track--muted":""}`,style:{width:X(r)},children:j.cues.map(E=>F(E,j))},j.id)),s.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:X(a)}})]})]})]})};function Yp(){const[e]=u.useState(()=>new Cl);return u.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function Zp(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 Xp=[{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 kl(){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),g=u.useRef(null),m=u.useRef(null),p=u.useRef(null),y=u.useRef(null),x=u.useRef([]),v=u.useRef(null),C=u.useRef(null),b=u.useCallback(()=>{if(m.current)return;const z=new AudioContext;m.current=z;const K=z.createGain();K.gain.value=n,y.current=K;const Z=z.createAnalyser();Z.fftSize=256,v.current=Z,K.connect(Z).connect(z.destination)},[]),k=u.useCallback(()=>{const z=g.current,K=m.current,Z=y.current;if(!z||!K||!Z||p.current)return;const O=K.createMediaElementSource(z);p.current=O,x.current.length>0?(O.connect(x.current[0]),x.current[x.current.length-1].connect(Z)):O.connect(Z)},[]),R=u.useCallback(()=>{var K;const z=g.current;!z||!C.current||(Et(),b(),k(),((K=m.current)==null?void 0:K.state)==="suspended"&&m.current.resume(),z.play().catch(Z=>d(String(Z))))},[b,k]),A=u.useCallback(()=>{var z;(z=g.current)==null||z.pause()},[]),$=u.useCallback(()=>{e?A():R()},[e,R,A]),W=u.useCallback(z=>{const K=Math.max(0,Math.min(1,z));r(K),y.current&&(y.current.gain.value=K),g.current&&(g.current.volume=K)},[]),w=u.useCallback(z=>{C.current=z,d(null),l(null),o(!0),p.current&&(p.current.disconnect(),p.current=null),g.current||(g.current=new Audio,g.current.crossOrigin="anonymous",g.current.addEventListener("playing",()=>{t(!0),o(!1)}),g.current.addEventListener("pause",()=>t(!1)),g.current.addEventListener("waiting",()=>o(!0)),g.current.addEventListener("canplay",()=>o(!1)),g.current.addEventListener("error",()=>d("Failed to load stream"))),g.current.src=z.streamUrl,g.current.load(),l({genre:z.genre,bitrate:z.bitrate})},[]),D=u.useCallback(z=>{m.current||b();const Z=m.current;x.current.forEach(X=>X.disconnect());const O=z.bands.map(X=>{const N=Z.createBiquadFilter();return N.type="peaking",N.frequency.value=X.frequency,N.gain.value=X.gain,N.Q.value=X.Q??1.4,N});for(let X=0;X<O.length-1;X++)O[X].connect(O[X+1]);x.current=O,p.current&&y.current&&(p.current.disconnect(),p.current.connect(O[0]),O[O.length-1].connect(y.current)),f(z.name)},[b]),_=u.useCallback(()=>{x.current.forEach(z=>z.disconnect()),x.current=[],p.current&&y.current&&(p.current.disconnect(),p.current.connect(y.current)),f(null)},[]);return u.useEffect(()=>()=>{var z,K,Z;(z=g.current)==null||z.pause(),g.current=null,x.current.forEach(O=>O.disconnect()),(K=p.current)==null||K.disconnect(),(Z=m.current)==null||Z.close()},[]),[{isPlaying:e,volume:n,isBuffering:a,metadata:i,error:c,activePreset:h},{play:R,pause:A,toggle:$,setVolume:W,setStation:w,applyEQPreset:D,clearEQ:_}]}function Ml({stations:e,activeStationId:t,onSelect:n,onToggleFavorite:r,className:a}){const{t:o}=ve(),[i,l]=u.useState(""),[c,d]=u.useState(null),[h,f]=u.useState(!1),g=u.useMemo(()=>[...new Set(e.map(p=>p.genre).filter(Boolean))],[e]),m=u.useMemo(()=>e.filter(p=>{var y,x;if(h&&!p.isFavorite||c&&p.genre!==c)return!1;if(i){const v=i.toLowerCase();return p.name.toLowerCase().includes(v)||(((y=p.genre)==null?void 0:y.toLowerCase().includes(v))??!1)||(((x=p.country)==null?void 0:x.toLowerCase().includes(v))??!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"}),g.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:[m.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:y=>{(y.key==="Enter"||y.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:y=>{y.stopPropagation(),r(p.id)},children:p.isFavorite?"★":"☆"})]},p.id)),m.length===0&&s.jsx("div",{className:"nice-station-browser__empty",children:(o==null?void 0:o("no_stations_found"))??"No stations found"})]})]})}function Qp({stations:e,initialStationId:t,autoPlay:n=!1,eqPresets:r=Xp,onStationChange:a,onPlayingChange:o,onMetadata:i,onToggleFavorite:l,onRecordingStart:c,onRecordingStop:d,showBrowser:h=!0,showEqualizer:f=!1,showVisualizer:g=!1,showMetadataHistory:m=!1,showRecording:p=!1,showSleepTimer:y=!1,className:x,style:v}){var F,j;const{t:C}=ve(),[b,k]=kl(),[R,A]=u.useState(()=>t?e.find(E=>E.id===t)??null:null),[$,W]=u.useState(f),w=u.useRef(null),D=u.useRef(0),[_,P]=u.useState([]),[B,z]=u.useState(!1),K=u.useRef(null),Z=u.useRef([]),[O,X]=u.useState(0),N=u.useRef(null),[U,L]=u.useState(0),[T,S]=u.useState(null),I=u.useRef(null);u.useEffect(()=>{o==null||o(b.isPlaying)},[b.isPlaying,o]),u.useEffect(()=>{b.metadata&&(i==null||i(b.metadata),(b.metadata.title||b.metadata.artist)&&P(E=>[{time:new Date,meta:b.metadata},...E.slice(0,49)]))},[b.metadata,i]);const M=u.useCallback(E=>{A(E),k.setStation(E),a==null||a(E),n&&setTimeout(()=>k.play(),100)},[k,a,n]);return u.useEffect(()=>{if(t&&!R){const E=e.find(H=>H.id===t);E&&M(E)}},[t,e]),u.useEffect(()=>{if(!g||!w.current)return;const E=w.current,H=E.getContext("2d");if(!H)return;const Y=()=>{D.current=requestAnimationFrame(Y),H.clearRect(0,0,E.width,E.height);const J=H.createLinearGradient(0,E.height,0,0);if(J.addColorStop(0,"rgba(99,102,241,0.8)"),J.addColorStop(.5,"rgba(168,85,247,0.6)"),J.addColorStop(1,"rgba(236,72,153,0.4)"),!b.isPlaying){const G=E.width/32;for(let q=0;q<32;q++){const ee=4+Math.sin(Date.now()/1e3+q*.3)*3;H.fillStyle=J,H.fillRect(q*G+1,E.height-ee,G-2,ee)}return}const ne=32,ae=E.width/ne;for(let re=0;re<ne;re++){const G=re/ne,ee=(Math.sin(Date.now()/200+re*.5)*.3+.5)*E.height*(1-G*.5)*(.5+Math.random()*.5);H.fillStyle=J,H.fillRect(re*ae+1,E.height-ee,ae-2,ee)}};return Y(),()=>cancelAnimationFrame(D.current)},[g,b.isPlaying]),u.useCallback(()=>{if(b.isPlaying)try{const H=new AudioContext().createMediaStreamDestination();Z.current=[];const Y=new MediaRecorder(H.stream,{mimeType:"audio/webm"});Y.ondataavailable=J=>{J.data.size>0&&Z.current.push(J.data)},Y.onstop=()=>{const J=new Blob(Z.current,{type:"audio/webm"});d==null||d(J),X(0),N.current&&window.clearInterval(N.current)},Y.start(1e3),K.current=Y,z(!0),X(0),N.current=window.setInterval(()=>{X(J=>J+1)},1e3),c==null||c()}catch{}},[b.isPlaying,c,d]),u.useCallback(()=>{K.current&&B&&(K.current.stop(),z(!1),N.current&&window.clearInterval(N.current))},[B]),u.useCallback(E=>{I.current&&window.clearInterval(I.current),L(E),S(E*60),I.current=window.setInterval(()=>{S(H=>!H||H<=1?(I.current&&window.clearInterval(I.current),I.current=null,k.pause(),null):H-1)},1e3)},[k]),u.useCallback(()=>{I.current&&window.clearInterval(I.current),I.current=null,S(null),L(0)},[]),u.useEffect(()=>()=>{N.current&&window.clearInterval(N.current),I.current&&window.clearInterval(I.current),cancelAnimationFrame(D.current)},[]),s.jsxs("div",{className:`nice-radio-player${x?` ${x}`:""}`,style:v,children:[s.jsx("div",{className:"nice-radio-player__now-playing",children:R?s.jsxs(s.Fragment,{children:[R.logoUrl&&s.jsx("img",{className:"nice-radio-player__cover",src:R.logoUrl,alt:R.name}),s.jsxs("div",{className:"nice-radio-player__info",children:[s.jsx("span",{className:"nice-radio-player__station-name",children:R.name}),((F=b.metadata)==null?void 0:F.title)&&s.jsx("span",{className:"nice-radio-player__track",children:b.metadata.artist?`${b.metadata.artist} — ${b.metadata.title}`:b.metadata.title}),((j=b.metadata)==null?void 0:j.genre)&&s.jsx("span",{className:"nice-radio-player__genre",children:b.metadata.genre}),b.isBuffering&&s.jsx("span",{className:"nice-radio-player__buffering",children:(C==null?void 0:C("buffering"))??"Buffering..."})]})]}):s.jsx("div",{className:"nice-radio-player__placeholder",children:(C==null?void 0:C("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:!R,"aria-label":b.isPlaying?"Pause":"Play",children:b.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:b.volume,onChange:E=>k.setVolume(parseFloat(E.target.value)),className:"nice-radio-player__volume-slider","aria-label":"Volume"})]}),s.jsx("button",{className:`nice-radio-player__eq-btn${$?" nice-radio-player__eq-btn--active":""}`,onClick:()=>W(!$),title:"Equalizer",children:"EQ"})]}),b.error&&s.jsx("div",{className:"nice-radio-player__error",children:b.error}),$&&s.jsx("div",{className:"nice-radio-player__equalizer",children:s.jsxs("div",{className:"nice-radio-player__eq-presets",children:[r.map(E=>s.jsx("button",{className:`nice-radio-player__eq-preset${b.activePreset===E.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>k.applyEQPreset(E),children:E.name},E.name)),b.activePreset&&s.jsx("button",{className:"nice-radio-player__eq-preset",onClick:k.clearEQ,children:(C==null?void 0:C("clear"))??"Clear"})]})}),h&&s.jsx(Ml,{stations:e,activeStationId:R==null?void 0:R.id,onSelect:M})]})}const Jp=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],e0={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class jl{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??Jp,audioConstraints:{...e0,echoCancellation:n.echoCancellation??!0,noiseSuppression:n.noiseSuppression??!0,autoGainControl:n.autoGainControl??!0}}}async initialize(){return this.localStream?this.localStream:(this.localStream=await navigator.mediaDevices.getUserMedia({audio:this.config.audioConstraints,video:!1}),this.localStream)}getLocalStream(){return this.localStream}getPeerIds(){return Array.from(this.peers.keys())}getPeerState(t){var n;return((n=this.peers.get(t))==null?void 0:n.state)??null}async createOffer(t){if(!this.localStream)throw new Error("WebRTCAudioManager not initialized. Call initialize() first.");const n=this.createPeerConnection(t),r=await n.createOffer();await n.setLocalDescription(r),this.sendSignalingMessage({type:"offer",from:this.localUserId,to:t,payload:r})}async handleSignalingMessage(t){if(t.to===this.localUserId)switch(t.type){case"offer":await this.handleOffer(t.from,t.payload);break;case"answer":await this.handleAnswer(t.from,t.payload);break;case"ice-candidate":await this.handleIceCandidate(t.from,t.payload);break;case"leave":this.removePeer(t.from);break}}removePeer(t){const n=this.peers.get(t);n&&(n.pc.close(),this.peers.delete(t))}disconnect(){for(const t of this.peers.keys())this.sendSignalingMessage({type:"leave",from:this.localUserId,to:t,payload:null});for(const t of this.peers.values())t.pc.close();this.peers.clear(),this.localStream&&(this.localStream.getTracks().forEach(t=>t.stop()),this.localStream=null)}setMuted(t){this.localStream&&this.localStream.getAudioTracks().forEach(n=>{n.enabled=!t})}isMuted(){if(!this.localStream)return!0;const t=this.localStream.getAudioTracks()[0];return t?!t.enabled:!0}createPeerConnection(t){const n=new RTCPeerConnection({iceServers:this.config.iceServers}),r={id:t,pc:n,remoteStream:null,state:n.connectionState};return this.peers.set(t,r),this.localStream&&this.localStream.getTracks().forEach(a=>{n.addTrack(a,this.localStream)}),n.onicecandidate=a=>{a.candidate&&this.sendSignalingMessage({type:"ice-candidate",from:this.localUserId,to:t,payload:a.candidate.toJSON()})},n.ontrack=a=>{var i;const[o]=a.streams;o&&(r.remoteStream=o,(i=this.onRemoteStream)==null||i.call(this,t,o))},n.onconnectionstatechange=()=>{var a;r.state=n.connectionState,(a=this.onPeerStateChange)==null||a.call(this,t,n.connectionState),(n.connectionState==="failed"||n.connectionState==="disconnected")&&this.removePeer(t)},n}async handleOffer(t,n){this.localStream||await this.initialize();const r=this.createPeerConnection(t);await r.setRemoteDescription(new RTCSessionDescription(n));const a=await r.createAnswer();await r.setLocalDescription(a),this.sendSignalingMessage({type:"answer",from:this.localUserId,to:t,payload:a})}async handleAnswer(t,n){const r=this.peers.get(t);r&&await r.pc.setRemoteDescription(new RTCSessionDescription(n))}async handleIceCandidate(t,n){const r=this.peers.get(t);r&&n&&await r.pc.addIceCandidate(new RTCIceCandidate(n))}sendSignalingMessage(t){var n;(n=this.onSignalingMessage)==null||n.call(this,t)}}function t0(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function n0(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function r0(){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:g=-10,deviceId:m,autoStart:p=!1,onStart:y,onStop:x,onAudioLevel:v,onError:C,className:b,style:k,barBorderRadius:R=2,barGap:A=2,lineWidth:$=2}=t,W=u.useRef(null),w=u.useRef(null),D=u.useRef(null),_=u.useRef(null),P=u.useRef(0),B=u.useRef(null),z=u.useRef(0),[K,Z]=u.useState(!1),O=u.useCallback((M,F,j=!0)=>{const E=j?M.createLinearGradient(0,o,0,0):M.createLinearGradient(0,0,a,0);return F.forEach((H,Y)=>{E.addColorStop(Y/(F.length-1),H)}),E},[a,o]),X=u.useCallback((M,F)=>{const E=(a-(i-1)*A)/i,H=Math.floor(F.length/i),Y=Array.isArray(l)?l:[l],J=Y.length>1?O(M,Y):Y[0];M.fillStyle=J;for(let ne=0;ne<i;ne++){const re=F[ne*H]/255*o,G=ne*(E+A),q=o-re;R>0?(M.beginPath(),M.roundRect(G,q,E,re,R),M.fill()):M.fillRect(G,q,E,re)}},[i,l,A,R,a,o,O]),N=u.useCallback((M,F)=>{const j=o/2,H=(a-(i-1)*A)/i,Y=Math.floor(F.length/i),J=Array.isArray(l)?l:[l],ne=J.length>1?O(M,J):J[0];M.fillStyle=ne;for(let ae=0;ae<i;ae++){const G=F[ae*Y]/255*j,q=ae*(H+A);R>0?(M.beginPath(),M.roundRect(q,j-G,H,G,R),M.fill(),M.beginPath(),M.roundRect(q,j,H,G,R),M.fill()):(M.fillRect(q,j-G,H,G),M.fillRect(q,j,H,G))}},[i,l,A,R,a,o,O]),U=u.useCallback((M,F)=>{const j=Array.isArray(l)?l:[l];M.strokeStyle=j.length>1?O(M,j,!1):j[0],M.lineWidth=$,M.lineCap="round",M.lineJoin="round",M.beginPath();const E=a/F.length;let H=0;for(let Y=0;Y<F.length;Y++){const ne=F[Y]/128*o/2;Y===0?M.moveTo(H,ne):M.lineTo(H,ne),H+=E}M.stroke()},[l,$,a,o,O]),L=u.useCallback((M,F)=>{const j=a/2,E=o/2,H=Math.min(a,o)/3,Y=Array.isArray(l)?l:[l];M.strokeStyle=Y.length>1?O(M,Y):Y[0],M.lineWidth=$;const J=Math.floor(F.length/64),ne=Math.PI*2/64;M.beginPath();for(let ae=0;ae<64;ae++){const re=F[ae*J]/255,G=H+re*H*.5,q=ae*ne-Math.PI/2,ee=j+Math.cos(q)*G,oe=E+Math.sin(q)*G;ae===0?M.moveTo(ee,oe):M.lineTo(ee,oe)}M.closePath(),M.stroke()},[l,$,a,o,O]),T=u.useCallback(()=>{const M=W.current,F=D.current,j=B.current;if(!M||!F||!j)return;const E=M.getContext("2d");if(!E)return;r==="waveform"?F.getByteTimeDomainData(j):F.getByteFrequencyData(j);let H=0;for(let Y=0;Y<j.length;Y++)H+=j[Y];switch(z.current=H/(j.length*255),v==null||v(z.current),E.clearRect(0,0,a,o),c!=="transparent"&&(E.fillStyle=c,E.fillRect(0,0,a,o)),r){case"bars":X(E,j);break;case"mirror-bars":N(E,j);break;case"waveform":U(E,j);break;case"circle":L(E,j);break}P.current=requestAnimationFrame(T)},[r,a,o,c,X,N,U,L,v]),S=u.useCallback(async()=>{try{if(K)return;const M=await navigator.mediaDevices.getUserMedia({audio:m?{deviceId:{exact:m}}:!0,video:!1});_.current=M;const F=new AudioContext;w.current=F;const j=F.createMediaStreamSource(M),E=F.createAnalyser();E.fftSize=d,E.smoothingTimeConstant=h,E.minDecibels=f,E.maxDecibels=g,j.connect(E),D.current=E,B.current=new Uint8Array(E.frequencyBinCount),Z(!0),y==null||y(),T()}catch(M){C==null||C(M instanceof Error?M:new Error(String(M)))}},[K,m,d,h,f,g,y,C,T]),I=u.useCallback(()=>{cancelAnimationFrame(P.current),_.current&&(_.current.getTracks().forEach(F=>F.stop()),_.current=null),w.current&&(w.current.close(),w.current=null),D.current=null,B.current=null,z.current=0,Z(!1),x==null||x();const M=W.current;if(M){const F=M.getContext("2d");F&&(F.clearRect(0,0,a,o),c!=="transparent"&&(F.fillStyle=c,F.fillRect(0,0,a,o)))}},[a,o,c,x]);return u.useImperativeHandle(n,()=>({start:S,stop:I,isCapturing:()=>K,getAudioLevel:()=>z.current}),[S,I,K]),u.useEffect(()=>(p&&S(),()=>{I()}),[p]),s.jsx("canvas",{ref:W,width:a,height:o,className:b,style:{display:"block",...k},"aria-label":"Audio visualizer"})}),$s=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}}},a0={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"},s0={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)"},o0={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)"},Rl=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:g,onSpeakingChange:m,speakingThreshold:p=.1,theme:y="auto",className:x,style:v,zIndex:C=1e3}=t,b=u.useRef(null),k=u.useRef(null),R=u.useRef(new Map);u.useRef(new Map);const[A,$]=u.useState(!1),[W,w]=u.useState(!1),[D,_]=u.useState(!1),[P,B]=u.useState(d),K=u.useMemo(()=>y==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":y,[y])==="dark"?o0:s0;u.useEffect(()=>{const T=new jl(r,l);return T.onRemoteStream=(S,I)=>{let M=R.current.get(S);M||(M=new Audio,M.autoplay=!0,R.current.set(S,M)),M.srcObject=I},T.onSignalingMessage=S=>{h==null||h(S)},T.onPeerStateChange=(S,I)=>{I==="connected"&&w(!0)},b.current=T,T.initialize().then(()=>{var S;(S=k.current)==null||S.start()}),()=>{T.disconnect(),R.current.forEach(S=>{S.srcObject=null}),R.current.clear()}},[r,l,h]);const Z=u.useCallback(()=>{var S;const T=!A;$(T),(S=b.current)==null||S.setMuted(T),f==null||f(T)},[A,f]),O=u.useCallback(()=>{var T,S;(T=b.current)==null||T.disconnect(),(S=k.current)==null||S.stop(),w(!1),g==null||g()},[g]),X=u.useCallback(T=>{const S=T>p;S!==D&&(_(S),m==null||m(r,S))},[p,D,r,m]),N=u.useCallback(async T=>{var S;await((S=b.current)==null?void 0:S.createOffer(T))},[]),U=u.useCallback(async T=>{var S;await((S=b.current)==null?void 0:S.handleSignalingMessage(T))},[]);u.useImperativeHandle(n,()=>({connectToPeer:N,handleSignalingMessage:U,toggleMute:Z,isMuted:()=>A,leave:O,getManager:()=>b.current}),[N,U,Z,A,O]);const L=({participant:T,isLocal:S,isSpeaking:I})=>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:K.hoverBg,border:`2px solid ${I?K.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:K.text,transition:"border-color 0.15s ease"},children:T.avatarUrl?s.jsx("img",{src:T.avatarUrl,alt:T.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):T.name.charAt(0).toUpperCase()}),s.jsx("div",{style:{flex:1,minWidth:0},children:s.jsxs("div",{style:{color:K.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[T.name,S&&s.jsx("span",{style:{color:K.textSecondary,fontWeight:400},children:" (You)"})]})}),T.isMuted&&s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:K.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 P?s.jsxs("div",{className:x,style:{...a0,...$s(c),backgroundColor:K.background,border:`1px solid ${K.border}`,zIndex:C,...v},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${K.border}`},children:[s.jsx("span",{style:{color:K.text,fontWeight:600},children:"Voice Chat"}),s.jsx("button",{onClick:()=>B(!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:K.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(L,{participant:{id:r,name:a,avatarUrl:o,isMuted:A},isLocal:!0,isSpeaking:D&&!A}),i.map(T=>s.jsx(L,{participant:T,isSpeaking:T.isSpeaking},T.id))]}),s.jsx(Pa,{ref:k,mode:"bars",width:256,height:32,barCount:24,barColor:A?"#9ca3af":["#3b82f6","#8b5cf6"],barGap:3,barBorderRadius:2,autoStart:!1,onAudioLevel:X,style:{borderRadius:4,opacity:A?.5:1}}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{onClick:Z,style:{flex:1,padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:A?K.mutedBg:K.activeBg,color:A?K.mutedIcon:K.activeIcon,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":A?"Unmute":"Mute",children:A?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",...$s(c),zIndex:C,...v},children:s.jsxs("button",{onClick:()=>B(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:K.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:K.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:K.speakingRing,color:"#fff",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:i.length+1})]})})});exports.ALL_CAP_STYLES=Cn;exports.ALL_EFFECTS=cp;exports.ALL_TEXTURES=jo;exports.ARTNET_PORT=Bp;exports.ASYMMETRIC_CAPS=po;exports.ArpeggiatorPanel=Hs;exports.AudioEffectType=bl;exports.AudioPitchAnalyzer=$o;exports.AudioPlaybackEngine=Hh;exports.AudioRecorder=to;exports.AudioTimeline=Fs;exports.AutoSavePanel=Zs;exports.BarFillEditor=Ro;exports.CCAutomationLaneEditor=Bs;exports.CCLane=As;exports.CONTROLLER_PROFILES=ki;exports.ChaseRunner=Hp;exports.CollaboratorPermission=xl;exports.DEFAULT_ARP_CONFIG=Ws;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=yi;exports.DMXEngine=Cl;exports.DRUM_PATTERN_NAMES=cf;exports.DefaultScoringPresets=la;exports.DmxChannelControl=Ta;exports.DmxChannelType=kt;exports.DmxEditor=Sl;exports.DmxOptionsControl=$a;exports.DmxSliderControl=kn;exports.DynamicRuleEditor=Qo;exports.DynamicRuleField=Ye;exports.DynamicRuleOperator=Ze;exports.EditorTrackProvider=Qr;exports.EditorUndoManager=td;exports.FIXTURE_PROFILES=wl;exports.GENERIC_PROFILE=Sa;exports.GRADIENT_PRESETS=To;exports.GROOVE_TEMPLATES=Ma;exports.GenericPlayer=_o;exports.GenericPlayerControls=Bo;exports.GenericPlayerStage=Go;exports.GenericPlayerStageVisualizer=Wo;exports.GenericPlaylist=Vo;exports.GenericPlaylistItem=pa;exports.KARAOKE_FONT_OPTIONS=Hd;exports.KEY_MAPS=Ao;exports.KaraokeEditorManager=Fo;exports.KaraokeFormat=yl;exports.KaraokeLyrics=oo;exports.KaraokePhaserRenderer=Do;exports.KaraokeTimeline=ko;exports.LANE_COLORS=yn;exports.LAUNCH_CONTROL_PROFILE=Ci;exports.LAYER_COLORS=Ip;exports.LFOPanel=Ks;exports.MINILAB_PROFILE=wi;exports.MPK_MINI_PROFILE=Si;exports.MasterFXPanel=Js;exports.MidiCCMapper=df;exports.ModeSwitcher=ha;exports.NOTE_NAMES=tf;exports.NiceArpeggiatorPanel=Hs;exports.NiceAudioErrorBoundary=_l;exports.NiceAudioPitchAnalyzer=$o;exports.NiceAudioTimeline=Fs;exports.NiceAutoSavePanel=Zs;exports.NiceBarFillEditor=Ro;exports.NiceCCAutomationLaneEditor=Bs;exports.NiceCCLane=As;exports.NiceDMXTimeline=Kp;exports.NiceDmxChannelControl=Ta;exports.NiceDmxEditor=Sl;exports.NiceDmxOptionsControl=$a;exports.NiceDmxSliderControl=kn;exports.NiceDynamicRuleEditor=Qo;exports.NiceEditorTrackProvider=Qr;exports.NiceGenericPlayer=_o;exports.NiceGenericPlayerControls=Bo;exports.NiceGenericPlayerStage=Go;exports.NiceGenericPlayerStageVisualizer=Wo;exports.NiceGenericPlaylist=Vo;exports.NiceGenericPlaylistItem=pa;exports.NiceI18nProvider=Ol;exports.NiceKaraokeEditorManager=Fo;exports.NiceKaraokeLyrics=oo;exports.NiceKaraokePhaserRenderer=Do;exports.NiceKaraokeTimeline=ko;exports.NiceLFOPanel=Ks;exports.NiceMasterFXPanel=Js;exports.NiceModeSwitcher=ha;exports.NiceNoteParticles=mi;exports.NiceNoteRiver=pi;exports.NicePianoRoll=Es;exports.NicePlaylistBrowser=ni;exports.NicePlaylistDualPane=Jo;exports.NicePlaylistGridView=si;exports.NicePlaylistImportWizard=ci;exports.NicePlaylistList=ba;exports.NicePlaylistOverview=oi;exports.NicePlaylistSearchBar=ii;exports.NicePlaylistSidebar=ai;exports.NicePlaylistTagEditor=qo;exports.NicePlaylistTrackList=ga;exports.NiceRadioPlayer=Qp;exports.NiceRecordingOptionsPanel=eo;exports.NiceStageVisualizer=fa;exports.NiceStationBrowser=Ml;exports.NiceStepSequencerPanel=Ys;exports.NiceStreamingVisualizer=Pa;exports.NiceUndoRedoPanel=Xs;exports.NiceVoiceChatOverlay=Rl;exports.NiceWaveform=Ps;exports.NiceYouTubePlayer=Uo;exports.NiceZoomSnapControls=Qs;exports.NoteParticles=mi;exports.NoteRiver=pi;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=Ko;exports.PianoRoll=Es;exports.PlaylistBrowser=ni;exports.PlaylistDualPane=Jo;exports.PlaylistGridView=si;exports.PlaylistImportWizard=ci;exports.PlaylistList=ba;exports.PlaylistOverview=oi;exports.PlaylistSearchBar=ii;exports.PlaylistSidebar=ai;exports.PlaylistTagEditor=qo;exports.PlaylistTrackList=ga;exports.PlaylistType=ma;exports.RecordingOptionsPanel=eo;exports.SACN_PORT=Up;exports.SCALE_NAMES=of;exports.SKEW_CAPS=mo;exports.SYMMETRIC_CAPS=oa;exports.ShortcutManager=ml;exports.SimpleSynth=gi;exports.SortDirection=qt;exports.SortField=Yo;exports.StageVisualizer=fa;exports.StepSequencerPanel=Ys;exports.StreamingVisualizer=Pa;exports.TEXTURE_CATEGORIES=ca;exports.TrackSource=lt;exports.UndoRedoPanel=Xs;exports.ViewMode=Ho;exports.VocalEffectsEngine=dp;exports.VoiceChatOverlay=Rl;exports.Waveform=Ps;exports.WebRTCAudioManager=jl;exports.YouTubePlayer=Uo;exports.ZoomSnapControls=Qs;exports.addEffectToLayer=zf;exports.addMidiNote=Uf;exports.analyzeAudioFileWithAlgorithm=Jf;exports.applyGroove=op;exports.applyGrooveTemplate=ul;exports.applyHumanize=dl;exports.applyKaraokeDisplayVars=ua;exports.applySwing=cl;exports.arrow_L=Mt;exports.arrow_R=gt;exports.autoCorrelate=Pf;exports.bracket_L=na;exports.bracket_R=ho;exports.buildArpSequence=Us;exports.buildLanes=No;exports.buildNoteDescriptors=Ef;exports.buildPadNoteEvents=Lo;exports.buildSegmentScores=Af;exports.canRedo=Pi;exports.canUndo=Ti;exports.chamfer_L=Qn;exports.chamfer_R=Zt;exports.clearMidiNotes=qf;exports.clearPattern=Ki;exports.computeTheoreticalMax=sl;exports.computeVocalPerformanceReport=up;exports.convertBrowserSongToKaraokeSongFile=_f;exports.copyCCEvents=qr;exports.createAnalyserNode=Ji;exports.createArpPattern=yf;exports.createArtNetPacket=Wp;exports.createBasslinePattern=bf;exports.createCCHistory=Mi;exports.createCompressorNode=tl;exports.createDefaultLFO=ir;exports.createDefaultShortcuts=kp;exports.createDropZoneHandlers=Ap;exports.createEmptyPattern=Nt;exports.createEmptyStep=wa;exports.createGainNode=el;exports.createHiHatPattern=gf;exports.createKickPattern=pf;exports.createLoopRegion=bp;exports.createSACNPacket=Vp;exports.createSnarePattern=mf;exports.createVocoderNode=nl;exports.createVoiceChatAudioContext=r0;exports.cutCCEvents=Ai;exports.deleteCCEventsInRange=Ni;exports.deserializeLFO=uc;exports.deserializePattern=vf;exports.downsampleAndQuantizePitchPoints=Nf;exports.drawGlossyBarOnCanvas=hn;exports.drawTimeline=Dr;exports.estimateLatencyMs=If;exports.estimateLatencyMsFromRecording=pp;exports.evaluateLFO=Zr;exports.evaluateLFOAsCC=Xr;exports.exportCCLane=Fi;exports.extractBpmFromNotes=io;exports.findTextureByUrl=Vd;exports.formatShortcut=Mp;exports.generateArpEvents=pc;exports.generatePlaceholderWaveform=ap;exports.generateSeed=sf;exports.generateUltrastarText=ep;exports.getActiveGradient=Eo;exports.getActiveLyrics=id;exports.getActiveWords=ld;exports.getAlgorithmColor=Ff;exports.getAlgorithmCssVar=Df;exports.getAlgorithmLabel=Lf;exports.getArpModes=Vs;exports.getArpRates=qs;exports.getAudioContext=tn;exports.getAudioInputDevices=n0;exports.getAudioWorkletProcessorCode=Xi;exports.getBackgroundUrl=Tf;exports.getCachedImage=Dd;exports.getCapStyleByName=dn;exports.getComboMultiplier=al;exports.getCoverUrl=$f;exports.getGrooveTemplate=ip;exports.getGrooveTemplateNames=lp;exports.getLaneForPitch=Io;exports.getNextPlayerColor=Lp;exports.getNextPlayerColorCss=Fp;exports.getOverlayCanvasPattern=gn;exports.getPatternByName=un;exports.getSACNMulticastAddress=qp;exports.getScoringPreset=Co;exports.getTexturePattern=pn;exports.getVerseRatingLabel=rl;exports.handleAddCCEvent=Kf;exports.handleRedo=ed;exports.handleRemoveCCEvent=Zf;exports.handleSelectCCLane=Hf;exports.handleUndo=Jc;exports.handleUpdateCCEvent=Yf;exports.hexToHsl=rr;exports.humanizeMidiNotes=yp;exports.hydrateKaraokeDisplayFromBackend=Kd;exports.hydratePlayerKaraokeSettingsFromBackend=$d;exports.hzToUltrastarPitch=lo;exports.importCCLane=Di;exports.initKaraokeDisplaySettings=Zd;exports.instrumentPresets=Kh;exports.isAudioContextRunning=Ns;exports.isInLoopRegion=Sp;exports.isWebRTCSupported=t0;exports.loadAllKaraokeSettings=Td;exports.loadAudioWorkletModule=Qi;exports.loadKaraokeDisplaySettings=Po;exports.loadKaraokeSettings=bo;exports.loadPlayerBarStyle=xo;exports.loadPlayerBarStyles=Ed;exports.loadRemoteScoringPresets=Wd;exports.makeClickReference=fl;exports.makeClipSelectionId=tp;exports.mergeWaveforms=rp;exports.midiToHz=Or;exports.normalizeHex=ar;exports.openAudioFilePicker=Np;exports.ornate_L=aa;exports.ornate_R=tr;exports.parseLyrics=sd;exports.parseNotes=ea;exports.parseVersesWithSyllables=so;exports.parseVersesWithWords=od;exports.parseVideoMetadata=il;exports.pasteCCEvents=Ei;exports.pill_L=$t;exports.pill_R=Ct;exports.preloadTexture=ia;exports.preloadTextures=Od;exports.probeAudioFile=gl;exports.pushCCState=ji;exports.quantizeMidiNotes=mp;exports.quantizeStepInBeats=pl;exports.quantizeStepInSeconds=ja;exports.randomizeVelocity=Hi;exports.recordCCEvent=Ii;exports.redoCC=$i;exports.removeEffectFromLayer=Bf;exports.removeMidiNote=Vf;exports.renderGlossyBarSvg=vo;exports.resumeAudioContext=Et;exports.reversePattern=Vi;exports.sampleLFOForDisplay=zs;exports.sampleLFOToCCEvents=_s;exports.saveKaraokeDisplaySettings=Yd;exports.saveKaraokeSettings=Rd;exports.savePlayerBarStyle=Pd;exports.scaleResult=Rf;exports.scaleTo10k=ol;exports.scoreNotesWithPitchPoints=jf;exports.selectCCEventsInRange=uf;exports.serializeLFO=dc;exports.serializePattern=xf;exports.setLoopFromSelection=xp;exports.setProjectWithUndo=ro;exports.setStepGate=Bi;exports.setStepNote=_i;exports.setStepProbability=Gi;exports.setStepVelocity=zi;exports.sharp_L=Kt;exports.sharp_R=Yt;exports.shield_L=Jn;exports.shield_R=uo;exports.shiftPattern=qi;exports.shouldTrigger=Zi;exports.skewTL_L=Un;exports.skewTL_R=Lr;exports.skewTR_L=Ir;exports.skewTR_R=Vn;exports.snapLoopToGrid=vp;exports.snapTimeToQuantize=Hr;exports.snapToGrid=np;exports.soft_L=ta;exports.soft_R=co;exports.stepDuration=Ca;exports.stepTimeOffset=Yi;exports.syncDivisionToHz=Ds;exports.tab_L=ra;exports.tab_R=fo;exports.thinCCEvents=Li;exports.toTrack=Of;exports.toggleEffectBypass=Gf;exports.toggleStep=Oi;exports.toggleStepSlide=Wi;exports.transposePattern=Ui;exports.undoCC=Ri;exports.updateEffectParams=Wf;exports.useAudioWorklet=Mf;exports.useAutoSave=Yc;exports.useCCAutomation=ff;exports.useDMXAudioSync=Zp;exports.useDMXEngine=Yp;exports.useEditorTrack=ad;exports.useLocalPlaylists=ya;exports.useMPE=Qh;exports.useMidiLearn=Zh;exports.useNiceTranslation=ve;exports.useOxygen25=ef;exports.usePitchWorker=wf;exports.usePlaybackEngine=Zc;exports.useProjectCRUD=rd;exports.useRadioStream=kl;exports.useRecording=Xc;exports.useScoringWorker=Cf;exports.useStepSequencer=Sf;exports.useWebMidi=pr;exports.useWorker=ka;exports.validateAudioFiles=Ra;exports.wave_L=er;exports.wave_R=sa;exports.waveformValue=Os;exports.wrapTimeInLoop=wp;
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 cl(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 dl(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 ul(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=ul(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=cl(n,t.swing)),t.humanize&&(n=dl(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 js(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(),g=t.createGain(),m=t.createGain(),p=n-1,y=Math.abs(p)*5+2,v=Math.abs(p)*.015;h.type="sawtooth",h.frequency.value=y,g.gain.value=v,h.connect(g),g.connect(c.delayTime),c.delayTime.value=.02,f.type="sawtooth",f.frequency.value=y,m.gain.value=v,f.connect(m),m.connect(d.delayTime),d.delayTime.value=.02+v;const x=t.createGain();x.gain.value=.5;const C=t.createGain();return C.gain.value=.5,a.connect(c),a.connect(d),c.connect(x),d.connect(C),x.connect(i),C.connect(i),a.connect(l),i.connect(o),l.connect(o),h.start(),f.start(),{type:"chipmunk",nodes:[a,c,d,h,f,g,m,x,C,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=js(t,2+n*3,3);const g=t.createGain();g.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(g),i.connect(g),l.connect(g),r.connect(f),f.connect(g);const m=t.createGain();return m.gain.value=.7,r.connect(m),m.connect(a),g.connect(a),{type:"cave",nodes:[r,o,i,l,c,d,h,f,g,m,a],input:r,output:a}}buildReverb(t,n,r,a){const o=t.createGain(),i=t.createGain(),l=t.createConvolver();l.buffer=js(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 g=t.createGain();g.gain.value=.3+n*.2,r.connect(d),d.connect(g),g.connect(a),h.start(),i.push(d,h,f,g)}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 m of d){const p=t.createBiquadFilter();p.type="peaking",p.frequency.value=m,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 g=t.createGain();return g.gain.value=.5+n*.3,r.connect(o),o.connect(g),h.connect(g),r.connect(f),g.connect(a),f.connect(a),i.start(),{type:"autotune",nodes:[r,o,i,l,...c,h,g,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 g=200*Math.pow(2,f*.5),m=t.createBiquadFilter();m.type="bandpass",m.frequency.value=g,m.Q.value=4;const p=t.createBiquadFilter();p.type="bandpass",p.frequency.value=g,p.Q.value=4;const y=t.createGain();y.gain.value=0,r.connect(m),m.connect(y.gain),o.connect(p),p.connect(y),y.connect(d),c.push(m,p,y)}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 hl=["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=hl[Math.round(e)%12],n=Math.floor(Math.round(e)/12)-1;return`${t}${n}`}function Tr(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:g,totalScore:m,micSettings:p}=e,y=l.filter(te=>te.hz>0),v=y.map(te=>Ut(te.hz)),x=[],C=[],b=[],k=[...c].sort((te,se)=>te.startTime-se.startTime);function R(te){let se=0,Ne=k.length-1;for(;se<=Ne;){const De=se+Ne>>>1,Pe=k[De];if(te<Pe.startTime)Ne=De-1;else if(te>Pe.startTime+Pe.duration)se=De+1;else return Pe.pitch}return 0}for(const te of l){const se=te.hz>0?Ut(te.hz):0,Ne=R(te.t);if(C.push({t:te.t,sung:se,expected:Ne}),se>0&&Ne>0){const De=(se-Ne)*100;x.push(De)}}let A=0;for(const te of k){const se=te.startTime-.3,Ne=te.startTime+te.duration;for(;A<y.length&&y[A].t<se;)A++;A<y.length&&y[A].t<=Ne&&b.push((y[A].t-te.startTime)*1e3)}const $=x.map(Math.abs),W=[...$].sort((te,se)=>te-se),w=$.length>0?$.reduce((te,se)=>te+se,0)/$.length:0,D=Tr(W,50),_=$.length>1?Math.sqrt($.reduce((te,se)=>te+(se-w)**2,0)/($.length-1)):0,P=$.filter(te=>te<=50).length,B=$.filter(te=>te<=15).length,z=$.length>0?P/$.length*100:0,K=$.length>0?B/$.length*100:0,Z=["< −100","−100 to −50","−50 to −25","−25 to −15","−15 to 0","0 to +15","+15 to +25","+25 to +50","+50 to +100","> +100"],O=new Array(10).fill(0);for(const te of x){const se=te<-100?0:te<-50?1:te<-25?2:te<-15?3:te<0?4:te<15?5:te<25?6:te<50?7:te<100?8:9;O[se]++}const X=Z.map((te,se)=>({centRange:te,count:O[se],pct:x.length>0?O[se]/x.length*100:0})),N=y.map(te=>te.hz).sort((te,se)=>te-se),U=N.length>0?N[0]:0,L=N.length>0?N[N.length-1]:0,T=U>0?Ut(U):0,S=L>0?Ut(L):0,I=S-T,M=[...v].sort((te,se)=>te-se),F=Tr(M,10),j=Tr(M,90),E=new Array(12).fill(0);for(const te of v){const se=Math.round(te)%12;se>=0&&se<12&&E[se]++}const H=E.reduce((te,se)=>te+se,0),Y=hl.map((te,se)=>({note:te,count:E[se],pct:H>0?E[se]/H*100:0})),J=fp(y),ne=b.length>0?b.reduce((te,se)=>te+se,0)/b.length:0,ae=b.length>1?Math.sqrt(b.reduce((te,se)=>te+(se-ne)**2,0)/(b.length-1)):0,re=ae>0?Math.max(0,Math.min(100,100-ae/2)):100;let G=0,q=0;for(let te=1;te<v.length;te++){const se=Math.abs(v[te]-v[te-1]);G+=se,q++}const ee=q>0?G/q*100/12:0,oe=l.filter(te=>te.hz<=0).length,ce=l.length>0?(1-oe/l.length)*100:0,fe=new Map;for(const te of c){const se=te.line??0;fe.has(se)||fe.set(se,[]),fe.get(se).push(te)}const Q=new Map;for(const te of y){const se=R(te.t);if(se<=0)continue;let Ne=0,De=k.length-1,Pe=-1;for(;Ne<=De;){const we=Ne+De>>>1,dt=k[we];if(te.t<dt.startTime)De=we-1;else if(te.t>dt.startTime+dt.duration)Ne=we+1;else{Pe=dt.line??0;break}}if(Pe<0)continue;const tt=Math.abs((Ut(te.hz)-se)*100);Q.has(Pe)||Q.set(Pe,[]),Q.get(Pe).push(tt)}const ue=d.map(te=>{const se=fe.get(te.verseIndex)??[],Ne=Q.get(te.verseIndex)??[],De=Ne.length>0?Ne.reduce((Pe,tt)=>Pe+tt,0)/Ne.length:0;return{verseIndex:te.verseIndex,label:te.label,hitFraction:te.hitFraction,avgCentDeviation:Math.round(De*10)/10,noteCount:se.length,notesHit:Math.round(te.hitFraction*se.length),comboBonus:te.comboBonus}}),ye=2,je=.5,Fe=l.length>0?l[l.length-1].t:0,Re=[],Se=C.filter(te=>te.sung>0&&te.expected>0);if(Se.length>0){let te=0,se=0,Ne=0;for(let De=0;De<=Fe;De+=je){const Pe=De-ye/2,tt=De+ye/2;for(;se<Se.length&&Se[se].t<tt;)Math.abs(Se[se].sung-Se[se].expected)<=.5&&Ne++,se++;for(;te<se&&Se[te].t<Pe;)Math.abs(Se[te].sung-Se[te].expected)<=.5&&Ne--,te++;const we=se-te;Re.push({t:De,accuracy:we>0?Ne/we*100:0})}}else for(let te=0;te<=Fe;te+=je)Re.push({t:te,accuracy:0});return{playerName:t,playerColor:n,songTitle:r,songArtist:a,songBpm:o,difficulty:i,timestamp:new Date().toISOString(),classicScore:f,bonusScore:g,totalScore:m,maxCombo:(h==null?void 0:h.maxCombo)??0,totalComboBonus:(h==null?void 0:h.totalComboBonus)??0,totalPitchPoints:l.length,avgCentDeviation:Math.round(w*10)/10,medianCentDeviation:Math.round(D*10)/10,stdDevCents:Math.round(_*10)/10,intonationAccuracyPct:Math.round(z*10)/10,perfectHitPct:Math.round(K*10)/10,pitchDeviationHistogram:X,lowestHz:Math.round(U*10)/10,highestHz:Math.round(L*10)/10,lowestNote:T>0?Wn(T):"—",highestNote:S>0?Wn(S):"—",rangeInSemitones:Math.round(I*10)/10,tessituraLow:F>0?Wn(F):"—",tessituraHigh:j>0?Wn(j):"—",pitchClassDistribution:Y,vibrato:J,avgOnsetDeviationMs:Math.round(ne*10)/10,rhythmStabilityPct:Math.round(re*10)/10,jitterPct:Math.round(ee*100)/100,shimmerProxy:Math.round(ce*10)/10,verseMetrics:ue,micSettings:p,pitchOverTime:C,accuracyOverTime:Re}}function fp(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(m=>Ut(m.hz)),n=e.map(m=>m.t),r=.5,a=[],o=[];let i=0,l=0,c=0;for(let m=0;m<e.length;m++){for(l+=t[m],c++;i<m&&n[m]-n[i]>=r;)l-=t[i],c--,i++;if(c<6||(m-i)%10!==0)continue;const p=l/c;let y=0,v=t[i]-p,x=Math.abs(v);for(let k=i+1;k<=m;k++){const R=t[k]-p;R*v<0&&y++,v=R;const A=Math.abs(R);A>x&&(x=A)}const C=n[m]-n[i];if(C<=0)continue;const b=y/2/C;b>=3&&b<=12&&(a.push(b),o.push(x*100))}if(a.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const d=a.reduce((m,p)=>m+p,0)/a.length,h=o.reduce((m,p)=>m+p,0)/o.length,f=Math.sqrt(a.reduce((m,p)=>m+(p-d)**2,0)/a.length),g=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(g)}}function fl(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 Rs(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 g=0;g<n;g++){const m=g+i+Math.floor((r-n)/2);if(m<0||m>=r)continue;const p=e[g],y=t[m];l+=p*y,c+=p*p,d+=y*y}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=fl(a,t,n,r),i=Rs(e,t,1e3),l=Rs(o,t,1e3),d=pp(l.env,i.env)*1e3/1e3;return Math.round(d)}catch{return null}}function pl(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 pl(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 ml{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 ml,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 gl(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 gl(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 yl=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(yl||{}),kt=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(kt||{}),bl=(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))(bl||{}),vl=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(vl||{});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))),xl=e=>Math.floor((e.valueFrom+e.valueTo)/2),zp=e=>{const t=_p(e);return t?xl(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=xl(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})}},Pr=e=>Math.max(0,Math.min(255,Math.round(e)));function Sl({service:e,pollInterval:t=500,className:n,style:r}){const[a,o]=u.useState([]),[i,l]=u.useState(null),[c,d]=u.useState(()=>Array(513).fill(0)),[h,f]=u.useState(30),[g,m]=u.useState(0),[p,y]=u.useState(!1),v=u.useRef(null);u.useEffect(()=>{let w=!1;return e.getDevices().then(D=>{w||(o(D),D.length>0&&l(D[0]))}).catch(()=>{}),()=>{w=!0}},[e]),u.useEffect(()=>{if(v.current&&window.clearInterval(v.current),!(t<=0))return v.current=window.setInterval(async()=>{try{const w=await e.getState();Array.isArray(w.frontSnapshot)&&w.frontSnapshot.length>=513&&d(w.frontSnapshot.slice(0,513)),typeof w.fps=="number"&&f(w.fps),typeof w.startCode=="number"&&m(w.startCode)}catch{}},t),()=>{v.current&&window.clearInterval(v.current)}},[e,t]);const x=async()=>{i&&(await e.openPort(i.serialNumber||i.description),y(!0))},C=async()=>{await e.closePort(),y(!1)},b=async()=>{await e.blackout(),d(w=>{const D=[...w];for(let _=1;_<D.length;_++)D[_]=0;return D})},k=()=>e.configure(h,g),R=(w,D)=>{const _=Pr(D);d(P=>{const B=[...P];return B[w]=_,B})},A=(w,D)=>e.setChannel(w,Pr(D)),$=(i==null?void 0:i.deviceInfo)??null,W=u.useMemo(()=>{var w;return(w=$==null?void 0:$.channels)!=null&&w.length?$.channels:Array.from({length:16},(D,_)=>({channel:_+1,name:`Channel ${_+1}`,type:kt.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[$]);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:(i==null?void 0:i.serialNumber)||"",onChange:w=>l(a.find(D=>D.serialNumber===w.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid #d1d5db"},children:a.map(w=>{var D,_;return s.jsxs("option",{value:w.serialNumber,children:[((D=w.deviceInfo)==null?void 0:D.manufacturer)??""," ",((_=w.deviceInfo)==null?void 0:_.model)??w.description," (",w.serialNumber||w.description,")"]},w.serialNumber||w.description)})}),$&&s.jsxs("div",{style:{marginTop:6,fontSize:12,color:"#6b7280"},children:["Mode: ",s.jsx("b",{children:$.modeName}),", footprint: ",s.jsx("b",{children:$.footprint})]})]}),s.jsx("button",{onClick:x,disabled:!i||p,style:{padding:"10px 14px",borderRadius:8,border:"1px solid #10b981",background:"#ecfdf5",cursor:"pointer"},children:"Open port"}),s.jsx("button",{onClick:C,disabled:!p,style:{padding:"10px 14px",borderRadius:8,border:"1px solid #ef4444",background:"#fef2f2",cursor:"pointer"},children:"Close port"}),s.jsx("button",{onClick:b,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:h,onChange:w=>f(Number(w.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:g,onChange:w=>m(Pr(Number(w.target.value))),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid #d1d5db"}})]}),s.jsx("div",{children:s.jsx("button",{onClick:k,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(w=>s.jsx(Ta,{channel:w,value:c[w.channel]??0,onChange:D=>R(w.channel,D),onCommit:D=>A(w.channel,D)},w.channel))})]})]})}const wl=[{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 Cl{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,wl.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 g=f;switch(a){case"ease-in":g=f*f;break;case"ease-out":g=1-(1-f)*(1-f);break;case"ease-in-out":g=f<.5?2*f*f:1-Math.pow(-2*f+2,2)/2;break}const m=l.map((p,y)=>{const v=n[y]??p;return Math.round(p+(v-p)*g)});this.setFixtureValues(t,m),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 g=new TextEncoder().encode(a.slice(0,63));l.set(g,44),l[108]=r,c.setUint16(109,0,!1),l[111]=n&255,l[112]=0,c.setUint16(113,e,!1);const m=o+11;return c.setUint16(115,28672|m&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:g,onPause:m,onStop:p,className:y=""})=>{const[v,x]=u.useState(1),[C,b]=u.useState(0),[k,R]=u.useState(!1),[A,$]=u.useState(null),[W,w]=u.useState(null),[D,_]=u.useState(!0),[P,B]=u.useState(1e3),z=u.useRef(null),K=u.useRef(null),Z=u.useRef(0),O=u.useMemo(()=>.1*v,[v]),X=u.useCallback(j=>j*O,[O]),N=u.useCallback(j=>j/O,[O]),U=u.useCallback(j=>{if(!D)return j;const E=6e4/o;return Math.round(j/E)*E},[D,o]);u.useEffect(()=>{if(k){const j=performance.now(),E=a,H=()=>{const Y=performance.now()-j,J=E+Y;if(J>=r){R(!1),i==null||i(0),p==null||p();return}L(J),i==null||i(J),K.current=requestAnimationFrame(H)};K.current=requestAnimationFrame(H),g==null||g()}else K.current!==null&&(cancelAnimationFrame(K.current),K.current=null),m==null||m();return()=>{K.current!==null&&cancelAnimationFrame(K.current)}},[k,a,r,i,g,m,p]);const L=u.useCallback(j=>{t.forEach(E=>{E.muted||E.cues.forEach(H=>{const Y=H.startTime,J=Y+H.duration;if(j>=Y&&j<J&&Z.current<Y){const ne=n.find(ae=>ae.id===H.sceneId);ne&&ne.fixtures.forEach(ae=>{H.fadeIn&&H.fadeIn>0?e.fadeFixture(ae.fixtureId,ae.values,H.fadeIn):e.setFixtureValues(ae.fixtureId,ae.values)})}if(Z.current<J&&j>=J){const ne=n.find(ae=>ae.id===H.sceneId);ne&&ne.fixtures.forEach(ae=>{if(e.getFixture(ae.fixtureId)&&H.fadeOut&&H.fadeOut>0){const G=new Array(ae.values.length).fill(0);e.fadeFixture(ae.fixtureId,G,H.fadeOut)}})}})}),Z.current=j},[t,n,e]),T=j=>{const E=Math.floor(j/1e3),H=Math.floor(E/60),Y=E%60,J=Math.floor(j%1e3/(1e3/30));return`${H}:${Y.toString().padStart(2,"0")}:${J.toString().padStart(2,"0")}`},S=u.useCallback(j=>{if(!z.current)return;const E=z.current.getBoundingClientRect(),H=j.clientX-E.left+C,Y=U(N(H));i==null||i(Math.max(0,Math.min(r,Y)))},[C,N,U,r,i]),I=u.useCallback((j,E,H)=>{const Y=t.find(ae=>ae.id===E),J=Y==null?void 0:Y.cues.find(ae=>ae.id===j);if(!J)return;const ne=U(Math.max(0,J.startTime+N(H)));c==null||c({...J,startTime:ne})},[t,N,U,c]),M=()=>{const j=6e4/o,E=Math.ceil(r/j),H=[];for(let Y=0;Y<=E;Y++){const J=Y*j,ne=X(J),ae=Y%4===0;H.push(s.jsx("div",{className:`nice-dmx-timeline__beat ${ae?"nice-dmx-timeline__beat--measure":""}`,style:{left:ne},children:ae&&s.jsx("span",{className:"nice-dmx-timeline__beat-label",children:Y/4+1})},Y))}return H},F=(j,E)=>{const H=X(j.startTime),Y=X(j.duration),J=n.find(ne=>ne.id===j.sceneId);return s.jsxs("div",{className:`nice-dmx-timeline__cue ${A===j.id?"nice-dmx-timeline__cue--selected":""}`,style:{left:H,width:Y,backgroundColor:(J==null?void 0:J.color)||E.color||"#8b5cf6"},onClick:ne=>{ne.stopPropagation(),$(j.id)},draggable:!E.locked,onDragEnd:ne=>{var re;const ae=(re=ne.target.parentElement)==null?void 0:re.getBoundingClientRect();ae&&I(j.id,E.id,ne.clientX-ae.left-H)},children:[s.jsx("span",{className:"nice-dmx-timeline__cue-name",children:j.name||(J==null?void 0:J.name)}),j.fadeIn&&j.fadeIn>0&&s.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--in",style:{width:X(j.fadeIn)}}),j.fadeOut&&j.fadeOut>0&&s.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--out",style:{width:X(j.fadeOut)}})]},j.id)};return s.jsxs("div",{className:`nice-dmx-timeline ${y}`,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:()=>R(!k),title:k?"Pause":"Play",children:k?"⏸":"▶"}),s.jsx("button",{type:"button",onClick:()=>{R(!1),i==null||i(0),e.blackout(),p==null||p()},title:"Stop",children:"⏹"})]}),s.jsx("div",{className:"nice-dmx-timeline__time",children:T(a)}),s.jsxs("div",{className:"nice-dmx-timeline__tools",children:[s.jsx("button",{type:"button",className:D?"active":"",onClick:()=>_(!D),title:"Snap to grid",children:"⊞"}),s.jsx("button",{type:"button",onClick:()=>x(Math.max(.25,v-.25)),title:"Zoom out",children:"−"}),s.jsxs("span",{className:"nice-dmx-timeline__zoom",children:[Math.round(v*100),"%"]}),s.jsx("button",{type:"button",onClick:()=>x(Math.min(4,v+.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(j=>s.jsxs("div",{className:`nice-dmx-timeline__header ${W===j.id?"nice-dmx-timeline__header--selected":""}`,onClick:()=>w(j.id),children:[s.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:j.color||"#8b5cf6"}}),s.jsx("span",{className:"nice-dmx-timeline__track-name",children:j.name}),s.jsxs("div",{className:"nice-dmx-timeline__track-controls",children:[s.jsx("button",{type:"button",className:j.muted?"active":"",onClick:E=>{E.stopPropagation(),f==null||f({...j,muted:!j.muted})},title:"Mute",children:"M"}),s.jsx("button",{type:"button",className:j.locked?"active":"",onClick:E=>{E.stopPropagation(),f==null||f({...j,locked:!j.locked})},title:"Lock",children:"🔒"})]})]},j.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:z,onClick:S,onScroll:j=>b(j.currentTarget.scrollLeft),children:[s.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:X(r)},children:M()}),t.map(j=>s.jsx("div",{className:`nice-dmx-timeline__track ${j.muted?"nice-dmx-timeline__track--muted":""}`,style:{width:X(r)},children:j.cues.map(E=>F(E,j))},j.id)),s.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:X(a)}})]})]})]})};function Zp(){const[e]=u.useState(()=>new Cl);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 kl(){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),g=u.useRef(null),m=u.useRef(null),p=u.useRef(null),y=u.useRef(null),v=u.useRef([]),x=u.useRef(null),C=u.useRef(null),b=u.useCallback(()=>{if(m.current)return;const z=new AudioContext;m.current=z;const K=z.createGain();K.gain.value=n,y.current=K;const Z=z.createAnalyser();Z.fftSize=256,x.current=Z,K.connect(Z).connect(z.destination)},[]),k=u.useCallback(()=>{const z=g.current,K=m.current,Z=y.current;if(!z||!K||!Z||p.current)return;const O=K.createMediaElementSource(z);p.current=O,v.current.length>0?(O.connect(v.current[0]),v.current[v.current.length-1].connect(Z)):O.connect(Z)},[]),R=u.useCallback(()=>{var K;const z=g.current;!z||!C.current||(Et(),b(),k(),((K=m.current)==null?void 0:K.state)==="suspended"&&m.current.resume(),z.play().catch(Z=>d(String(Z))))},[b,k]),A=u.useCallback(()=>{var z;(z=g.current)==null||z.pause()},[]),$=u.useCallback(()=>{e?A():R()},[e,R,A]),W=u.useCallback(z=>{const K=Math.max(0,Math.min(1,z));r(K),y.current&&(y.current.gain.value=K),g.current&&(g.current.volume=K)},[]),w=u.useCallback(z=>{C.current=z,d(null),l(null),o(!0),p.current&&(p.current.disconnect(),p.current=null),g.current||(g.current=new Audio,g.current.crossOrigin="anonymous",g.current.addEventListener("playing",()=>{t(!0),o(!1)}),g.current.addEventListener("pause",()=>t(!1)),g.current.addEventListener("waiting",()=>o(!0)),g.current.addEventListener("canplay",()=>o(!1)),g.current.addEventListener("error",()=>d("Failed to load stream"))),g.current.src=z.streamUrl,g.current.load(),l({genre:z.genre,bitrate:z.bitrate})},[]),D=u.useCallback(z=>{m.current||b();const Z=m.current;v.current.forEach(X=>X.disconnect());const O=z.bands.map(X=>{const N=Z.createBiquadFilter();return N.type="peaking",N.frequency.value=X.frequency,N.gain.value=X.gain,N.Q.value=X.Q??1.4,N});for(let X=0;X<O.length-1;X++)O[X].connect(O[X+1]);v.current=O,p.current&&y.current&&(p.current.disconnect(),p.current.connect(O[0]),O[O.length-1].connect(y.current)),f(z.name)},[b]),_=u.useCallback(()=>{v.current.forEach(z=>z.disconnect()),v.current=[],p.current&&y.current&&(p.current.disconnect(),p.current.connect(y.current)),f(null)},[]);return u.useEffect(()=>()=>{var z,K,Z;(z=g.current)==null||z.pause(),g.current=null,v.current.forEach(O=>O.disconnect()),(K=p.current)==null||K.disconnect(),(Z=m.current)==null||Z.close()},[]),[{isPlaying:e,volume:n,isBuffering:a,metadata:i,error:c,activePreset:h},{play:R,pause:A,toggle:$,setVolume:W,setStation:w,applyEQPreset:D,clearEQ:_}]}function Ml({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),g=u.useMemo(()=>[...new Set(e.map(p=>p.genre).filter(Boolean))],[e]),m=u.useMemo(()=>e.filter(p=>{var y,v;if(h&&!p.isFavorite||c&&p.genre!==c)return!1;if(i){const x=i.toLowerCase();return p.name.toLowerCase().includes(x)||(((y=p.genre)==null?void 0:y.toLowerCase().includes(x))??!1)||(((v=p.country)==null?void 0:v.toLowerCase().includes(x))??!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"}),g.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:[m.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:y=>{(y.key==="Enter"||y.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:y=>{y.stopPropagation(),r(p.id)},children:p.isFavorite?"★":"☆"})]},p.id)),m.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:g=!1,showMetadataHistory:m=!1,showRecording:p=!1,showSleepTimer:y=!1,className:v,style:x}){var F,j;const{t:C}=xe(),[b,k]=kl(),[R,A]=u.useState(()=>t?e.find(E=>E.id===t)??null:null),[$,W]=u.useState(f),w=u.useRef(null),D=u.useRef(0),[_,P]=u.useState([]),[B,z]=u.useState(!1),K=u.useRef(null),Z=u.useRef([]),[O,X]=u.useState(0),N=u.useRef(null),[U,L]=u.useState(0),[T,S]=u.useState(null),I=u.useRef(null);u.useEffect(()=>{o==null||o(b.isPlaying)},[b.isPlaying,o]),u.useEffect(()=>{b.metadata&&(i==null||i(b.metadata),(b.metadata.title||b.metadata.artist)&&P(E=>[{time:new Date,meta:b.metadata},...E.slice(0,49)]))},[b.metadata,i]);const M=u.useCallback(E=>{A(E),k.setStation(E),a==null||a(E),n&&setTimeout(()=>k.play(),100)},[k,a,n]);return u.useEffect(()=>{if(t&&!R){const E=e.find(H=>H.id===t);E&&M(E)}},[t,e]),u.useEffect(()=>{if(!g||!w.current)return;const E=w.current,H=E.getContext("2d");if(!H)return;const Y=()=>{D.current=requestAnimationFrame(Y),H.clearRect(0,0,E.width,E.height);const J=H.createLinearGradient(0,E.height,0,0);if(J.addColorStop(0,"rgba(99,102,241,0.8)"),J.addColorStop(.5,"rgba(168,85,247,0.6)"),J.addColorStop(1,"rgba(236,72,153,0.4)"),!b.isPlaying){const G=E.width/32;for(let q=0;q<32;q++){const ee=4+Math.sin(Date.now()/1e3+q*.3)*3;H.fillStyle=J,H.fillRect(q*G+1,E.height-ee,G-2,ee)}return}const ne=32,ae=E.width/ne;for(let re=0;re<ne;re++){const G=re/ne,ee=(Math.sin(Date.now()/200+re*.5)*.3+.5)*E.height*(1-G*.5)*(.5+Math.random()*.5);H.fillStyle=J,H.fillRect(re*ae+1,E.height-ee,ae-2,ee)}};return Y(),()=>cancelAnimationFrame(D.current)},[g,b.isPlaying]),u.useCallback(()=>{if(b.isPlaying)try{const H=new AudioContext().createMediaStreamDestination();Z.current=[];const Y=new MediaRecorder(H.stream,{mimeType:"audio/webm"});Y.ondataavailable=J=>{J.data.size>0&&Z.current.push(J.data)},Y.onstop=()=>{const J=new Blob(Z.current,{type:"audio/webm"});d==null||d(J),X(0),N.current&&window.clearInterval(N.current)},Y.start(1e3),K.current=Y,z(!0),X(0),N.current=window.setInterval(()=>{X(J=>J+1)},1e3),c==null||c()}catch{}},[b.isPlaying,c,d]),u.useCallback(()=>{K.current&&B&&(K.current.stop(),z(!1),N.current&&window.clearInterval(N.current))},[B]),u.useCallback(E=>{I.current&&window.clearInterval(I.current),L(E),S(E*60),I.current=window.setInterval(()=>{S(H=>!H||H<=1?(I.current&&window.clearInterval(I.current),I.current=null,k.pause(),null):H-1)},1e3)},[k]),u.useCallback(()=>{I.current&&window.clearInterval(I.current),I.current=null,S(null),L(0)},[]),u.useEffect(()=>()=>{N.current&&window.clearInterval(N.current),I.current&&window.clearInterval(I.current),cancelAnimationFrame(D.current)},[]),s.jsxs("div",{className:`nice-radio-player${v?` ${v}`:""}`,style:x,children:[s.jsx("div",{className:"nice-radio-player__now-playing",children:R?s.jsxs(s.Fragment,{children:[R.logoUrl&&s.jsx("img",{className:"nice-radio-player__cover",src:R.logoUrl,alt:R.name}),s.jsxs("div",{className:"nice-radio-player__info",children:[s.jsx("span",{className:"nice-radio-player__station-name",children:R.name}),((F=b.metadata)==null?void 0:F.title)&&s.jsx("span",{className:"nice-radio-player__track",children:b.metadata.artist?`${b.metadata.artist} — ${b.metadata.title}`:b.metadata.title}),((j=b.metadata)==null?void 0:j.genre)&&s.jsx("span",{className:"nice-radio-player__genre",children:b.metadata.genre}),b.isBuffering&&s.jsx("span",{className:"nice-radio-player__buffering",children:(C==null?void 0:C("buffering"))??"Buffering..."})]})]}):s.jsx("div",{className:"nice-radio-player__placeholder",children:(C==null?void 0:C("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:!R,"aria-label":b.isPlaying?"Pause":"Play",children:b.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:b.volume,onChange:E=>k.setVolume(parseFloat(E.target.value)),className:"nice-radio-player__volume-slider","aria-label":"Volume"})]}),s.jsx("button",{className:`nice-radio-player__eq-btn${$?" nice-radio-player__eq-btn--active":""}`,onClick:()=>W(!$),title:"Equalizer",children:"EQ"})]}),b.error&&s.jsx("div",{className:"nice-radio-player__error",children:b.error}),$&&s.jsx("div",{className:"nice-radio-player__equalizer",children:s.jsxs("div",{className:"nice-radio-player__eq-presets",children:[r.map(E=>s.jsx("button",{className:`nice-radio-player__eq-preset${b.activePreset===E.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>k.applyEQPreset(E),children:E.name},E.name)),b.activePreset&&s.jsx("button",{className:"nice-radio-player__eq-preset",onClick:k.clearEQ,children:(C==null?void 0:C("clear"))??"Clear"})]})}),h&&s.jsx(Ml,{stations:e,activeStationId:R==null?void 0:R.id,onSelect:M})]})}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 jl{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:g=-10,deviceId:m,autoStart:p=!1,onStart:y,onStop:v,onAudioLevel:x,onError:C,className:b,style:k,barBorderRadius:R=2,barGap:A=2,lineWidth:$=2}=t,W=u.useRef(null),w=u.useRef(null),D=u.useRef(null),_=u.useRef(null),P=u.useRef(0),B=u.useRef(null),z=u.useRef(0),[K,Z]=u.useState(!1),O=u.useCallback((M,F,j=!0)=>{const E=j?M.createLinearGradient(0,o,0,0):M.createLinearGradient(0,0,a,0);return F.forEach((H,Y)=>{E.addColorStop(Y/(F.length-1),H)}),E},[a,o]),X=u.useCallback((M,F)=>{const E=(a-(i-1)*A)/i,H=Math.floor(F.length/i),Y=Array.isArray(l)?l:[l],J=Y.length>1?O(M,Y):Y[0];M.fillStyle=J;for(let ne=0;ne<i;ne++){const re=F[ne*H]/255*o,G=ne*(E+A),q=o-re;R>0?(M.beginPath(),M.roundRect(G,q,E,re,R),M.fill()):M.fillRect(G,q,E,re)}},[i,l,A,R,a,o,O]),N=u.useCallback((M,F)=>{const j=o/2,H=(a-(i-1)*A)/i,Y=Math.floor(F.length/i),J=Array.isArray(l)?l:[l],ne=J.length>1?O(M,J):J[0];M.fillStyle=ne;for(let ae=0;ae<i;ae++){const G=F[ae*Y]/255*j,q=ae*(H+A);R>0?(M.beginPath(),M.roundRect(q,j-G,H,G,R),M.fill(),M.beginPath(),M.roundRect(q,j,H,G,R),M.fill()):(M.fillRect(q,j-G,H,G),M.fillRect(q,j,H,G))}},[i,l,A,R,a,o,O]),U=u.useCallback((M,F)=>{const j=Array.isArray(l)?l:[l];M.strokeStyle=j.length>1?O(M,j,!1):j[0],M.lineWidth=$,M.lineCap="round",M.lineJoin="round",M.beginPath();const E=a/F.length;let H=0;for(let Y=0;Y<F.length;Y++){const ne=F[Y]/128*o/2;Y===0?M.moveTo(H,ne):M.lineTo(H,ne),H+=E}M.stroke()},[l,$,a,o,O]),L=u.useCallback((M,F)=>{const j=a/2,E=o/2,H=Math.min(a,o)/3,Y=Array.isArray(l)?l:[l];M.strokeStyle=Y.length>1?O(M,Y):Y[0],M.lineWidth=$;const J=Math.floor(F.length/64),ne=Math.PI*2/64;M.beginPath();for(let ae=0;ae<64;ae++){const re=F[ae*J]/255,G=H+re*H*.5,q=ae*ne-Math.PI/2,ee=j+Math.cos(q)*G,oe=E+Math.sin(q)*G;ae===0?M.moveTo(ee,oe):M.lineTo(ee,oe)}M.closePath(),M.stroke()},[l,$,a,o,O]),T=u.useCallback(()=>{const M=W.current,F=D.current,j=B.current;if(!M||!F||!j)return;const E=M.getContext("2d");if(!E)return;r==="waveform"?F.getByteTimeDomainData(j):F.getByteFrequencyData(j);let H=0;for(let Y=0;Y<j.length;Y++)H+=j[Y];switch(z.current=H/(j.length*255),x==null||x(z.current),E.clearRect(0,0,a,o),c!=="transparent"&&(E.fillStyle=c,E.fillRect(0,0,a,o)),r){case"bars":X(E,j);break;case"mirror-bars":N(E,j);break;case"waveform":U(E,j);break;case"circle":L(E,j);break}P.current=requestAnimationFrame(T)},[r,a,o,c,X,N,U,L,x]),S=u.useCallback(async()=>{try{if(K)return;const M=await navigator.mediaDevices.getUserMedia({audio:m?{deviceId:{exact:m}}:!0,video:!1});_.current=M;const F=new AudioContext;w.current=F;const j=F.createMediaStreamSource(M),E=F.createAnalyser();E.fftSize=d,E.smoothingTimeConstant=h,E.minDecibels=f,E.maxDecibels=g,j.connect(E),D.current=E,B.current=new Uint8Array(E.frequencyBinCount),Z(!0),y==null||y(),T()}catch(M){C==null||C(M instanceof Error?M:new Error(String(M)))}},[K,m,d,h,f,g,y,C,T]),I=u.useCallback(()=>{cancelAnimationFrame(P.current),_.current&&(_.current.getTracks().forEach(F=>F.stop()),_.current=null),w.current&&(w.current.close(),w.current=null),D.current=null,B.current=null,z.current=0,Z(!1),v==null||v();const M=W.current;if(M){const F=M.getContext("2d");F&&(F.clearRect(0,0,a,o),c!=="transparent"&&(F.fillStyle=c,F.fillRect(0,0,a,o)))}},[a,o,c,v]);return u.useImperativeHandle(n,()=>({start:S,stop:I,isCapturing:()=>K,getAudioLevel:()=>z.current}),[S,I,K]),u.useEffect(()=>(p&&S(),()=>{I()}),[p]),s.jsx("canvas",{ref:W,width:a,height:o,className:b,style:{display:"block",...k},"aria-label":"Audio visualizer"})}),$s=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)"},Rl=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:g,onSpeakingChange:m,speakingThreshold:p=.1,theme:y="auto",className:v,style:x,zIndex:C=1e3}=t,b=u.useRef(null),k=u.useRef(null),R=u.useRef(new Map);u.useRef(new Map);const[A,$]=u.useState(!1),[W,w]=u.useState(!1),[D,_]=u.useState(!1),[P,B]=u.useState(d),K=u.useMemo(()=>y==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":y,[y])==="dark"?i0:o0;u.useEffect(()=>{const T=new jl(r,l);return T.onRemoteStream=(S,I)=>{let M=R.current.get(S);M||(M=new Audio,M.autoplay=!0,R.current.set(S,M)),M.srcObject=I},T.onSignalingMessage=S=>{h==null||h(S)},T.onPeerStateChange=(S,I)=>{I==="connected"&&w(!0)},b.current=T,T.initialize().then(()=>{var S;(S=k.current)==null||S.start()}),()=>{T.disconnect(),R.current.forEach(S=>{S.srcObject=null}),R.current.clear()}},[r,l,h]);const Z=u.useCallback(()=>{var S;const T=!A;$(T),(S=b.current)==null||S.setMuted(T),f==null||f(T)},[A,f]),O=u.useCallback(()=>{var T,S;(T=b.current)==null||T.disconnect(),(S=k.current)==null||S.stop(),w(!1),g==null||g()},[g]),X=u.useCallback(T=>{const S=T>p;S!==D&&(_(S),m==null||m(r,S))},[p,D,r,m]),N=u.useCallback(async T=>{var S;await((S=b.current)==null?void 0:S.createOffer(T))},[]),U=u.useCallback(async T=>{var S;await((S=b.current)==null?void 0:S.handleSignalingMessage(T))},[]);u.useImperativeHandle(n,()=>({connectToPeer:N,handleSignalingMessage:U,toggleMute:Z,isMuted:()=>A,leave:O,getManager:()=>b.current}),[N,U,Z,A,O]);const L=({participant:T,isLocal:S,isSpeaking:I})=>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:K.hoverBg,border:`2px solid ${I?K.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:K.text,transition:"border-color 0.15s ease"},children:T.avatarUrl?s.jsx("img",{src:T.avatarUrl,alt:T.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):T.name.charAt(0).toUpperCase()}),s.jsx("div",{style:{flex:1,minWidth:0},children:s.jsxs("div",{style:{color:K.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[T.name,S&&s.jsx("span",{style:{color:K.textSecondary,fontWeight:400},children:" (You)"})]})}),T.isMuted&&s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:K.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 P?s.jsxs("div",{className:v,style:{...s0,...$s(c),backgroundColor:K.background,border:`1px solid ${K.border}`,zIndex:C,...x},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${K.border}`},children:[s.jsx("span",{style:{color:K.text,fontWeight:600},children:"Voice Chat"}),s.jsx("button",{onClick:()=>B(!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:K.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(L,{participant:{id:r,name:a,avatarUrl:o,isMuted:A},isLocal:!0,isSpeaking:D&&!A}),i.map(T=>s.jsx(L,{participant:T,isSpeaking:T.isSpeaking},T.id))]}),s.jsx(Pa,{ref:k,mode:"bars",width:256,height:32,barCount:24,barColor:A?"#9ca3af":["#3b82f6","#8b5cf6"],barGap:3,barBorderRadius:2,autoStart:!1,onAudioLevel:X,style:{borderRadius:4,opacity:A?.5:1}}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{onClick:Z,style:{flex:1,padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:A?K.mutedBg:K.activeBg,color:A?K.mutedIcon:K.activeIcon,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":A?"Unmute":"Mute",children:A?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:v,style:{position:"fixed",...$s(c),zIndex:C,...x},children:s.jsxs("button",{onClick:()=>B(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:K.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:K.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:K.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 $l={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],aeolian:[0,2,3,5,7,8,10],locrian:[0,1,3,5,6,8,10],"harmonic-minor":[0,2,3,5,7,8,11],"melodic-minor":[0,2,3,5,7,9,11],"pentatonic-major":[0,2,4,7,9],"pentatonic-minor":[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11],"whole-tone":[0,2,4,6,8,10]};function f0(e,t,n){const r=$l[n],a=(e-t+120)%12;let o=r[0],i=999;for(const c of r){const d=Math.min(Math.abs(a-c),12-Math.abs(a-c));d<i&&(i=d,o=c)}const l=Math.floor((e-t)/12);return t+l*12+o}function 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=jo;exports.ARTNET_PORT=Gp;exports.ASYMMETRIC_CAPS=po;exports.ArpeggiatorPanel=Hs;exports.AudioEffectType=bl;exports.AudioPitchAnalyzer=$o;exports.AudioPlaybackEngine=Kh;exports.AudioRecorder=to;exports.AudioTimeline=Fs;exports.AutoSavePanel=Zs;exports.BarFillEditor=Ro;exports.CCAutomationLaneEditor=Bs;exports.CCLane=As;exports.CONTROLLER_PROFILES=ki;exports.ChaseRunner=Kp;exports.CollaboratorPermission=vl;exports.DEFAULT_ARP_CONFIG=Ws;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=yi;exports.DMXEngine=Cl;exports.DRUM_PATTERN_NAMES=df;exports.DefaultScoringPresets=la;exports.DmxChannelControl=Ta;exports.DmxChannelType=kt;exports.DmxEditor=Sl;exports.DmxOptionsControl=$a;exports.DmxSliderControl=kn;exports.DynamicRuleEditor=Qo;exports.DynamicRuleField=Ye;exports.DynamicRuleOperator=Ze;exports.EditorTrackProvider=Qr;exports.EditorUndoManager=nd;exports.FIXTURE_PROFILES=wl;exports.GENERIC_PROFILE=Sa;exports.GM_DRUM_MAP=y0;exports.GRADIENT_PRESETS=To;exports.GROOVE_TEMPLATES=Ma;exports.GenericPlayer=_o;exports.GenericPlayerControls=Bo;exports.GenericPlayerStage=Go;exports.GenericPlayerStageVisualizer=Wo;exports.GenericPlaylist=Vo;exports.GenericPlaylistItem=pa;exports.KARAOKE_FONT_OPTIONS=Kd;exports.KEY_MAPS=Ao;exports.KaraokeEditorManager=Fo;exports.KaraokeFormat=yl;exports.KaraokeLyrics=oo;exports.KaraokePhaserRenderer=Do;exports.KaraokeTimeline=ko;exports.LANE_COLORS=yn;exports.LAUNCH_CONTROL_PROFILE=Ci;exports.LAYER_COLORS=Lp;exports.LFOPanel=Ks;exports.MINILAB_PROFILE=wi;exports.MPK_MINI_PROFILE=Si;exports.MasterFXPanel=Js;exports.MidiCCMapper=uf;exports.ModeSwitcher=ha;exports.NOTE_NAMES=nf;exports.NiceArpeggiatorPanel=Hs;exports.NiceAudioErrorBoundary=zl;exports.NiceAudioPitchAnalyzer=$o;exports.NiceAudioTimeline=Fs;exports.NiceAutoSavePanel=Zs;exports.NiceBarFillEditor=Ro;exports.NiceCCAutomationLaneEditor=Bs;exports.NiceCCLane=As;exports.NiceDMXTimeline=Yp;exports.NiceDmxChannelControl=Ta;exports.NiceDmxEditor=Sl;exports.NiceDmxOptionsControl=$a;exports.NiceDmxSliderControl=kn;exports.NiceDynamicRuleEditor=Qo;exports.NiceEditorTrackProvider=Qr;exports.NiceGenericPlayer=_o;exports.NiceGenericPlayerControls=Bo;exports.NiceGenericPlayerStage=Go;exports.NiceGenericPlayerStageVisualizer=Wo;exports.NiceGenericPlaylist=Vo;exports.NiceGenericPlaylistItem=pa;exports.NiceI18nProvider=_l;exports.NiceKaraokeEditorManager=Fo;exports.NiceKaraokeLyrics=oo;exports.NiceKaraokePhaserRenderer=Do;exports.NiceKaraokeTimeline=ko;exports.NiceLFOPanel=Ks;exports.NiceMasterFXPanel=Js;exports.NiceModeSwitcher=ha;exports.NiceNoteParticles=mi;exports.NiceNoteRiver=pi;exports.NicePianoRoll=Es;exports.NicePlaylistBrowser=ni;exports.NicePlaylistDualPane=Jo;exports.NicePlaylistGridView=si;exports.NicePlaylistImportWizard=ci;exports.NicePlaylistList=ba;exports.NicePlaylistOverview=oi;exports.NicePlaylistSearchBar=ii;exports.NicePlaylistSidebar=ai;exports.NicePlaylistTagEditor=qo;exports.NicePlaylistTrackList=ga;exports.NiceRadioPlayer=Jp;exports.NiceRecordingOptionsPanel=eo;exports.NiceStageVisualizer=fa;exports.NiceStationBrowser=Ml;exports.NiceStepSequencerPanel=Ys;exports.NiceStreamingVisualizer=Pa;exports.NiceUndoRedoPanel=Xs;exports.NiceVoiceChatOverlay=Rl;exports.NiceWaveform=Ps;exports.NiceYouTubePlayer=Uo;exports.NiceZoomSnapControls=Qs;exports.NoteParticles=mi;exports.NoteRiver=pi;exports.OVERLAY_PATTERNS=nr;exports.OXYGEN25_PROFILE=xi;exports.PLAYER_COLORS=Pt;exports.PLAYER_COLOR_VARS=Zn;exports.PROGRESSION_NAMES=cf;exports.PadNotePlayer=Qd;exports.PaneSide=Ko;exports.PianoRoll=Es;exports.PlaylistBrowser=ni;exports.PlaylistDualPane=Jo;exports.PlaylistGridView=si;exports.PlaylistImportWizard=ci;exports.PlaylistList=ba;exports.PlaylistOverview=oi;exports.PlaylistSearchBar=ii;exports.PlaylistSidebar=ai;exports.PlaylistTagEditor=qo;exports.PlaylistTrackList=ga;exports.PlaylistType=ma;exports.RecordingOptionsPanel=eo;exports.SACN_PORT=Vp;exports.SCALE_INTERVALS=$l;exports.SCALE_NAMES=lf;exports.SKEW_CAPS=mo;exports.STANDARD_TUNINGS=g0;exports.SYMMETRIC_CAPS=oa;exports.ShortcutManager=ml;exports.SimpleSynth=gi;exports.SortDirection=qt;exports.SortField=Yo;exports.StageVisualizer=fa;exports.StepSequencerPanel=Ys;exports.StreamingVisualizer=Pa;exports.TEXTURE_CATEGORIES=ca;exports.TrackSource=lt;exports.UndoRedoPanel=Xs;exports.ViewMode=Ho;exports.VocalEffectsEngine=up;exports.VoiceChatOverlay=Rl;exports.Waveform=Ps;exports.WebRTCAudioManager=jl;exports.YouTubePlayer=Uo;exports.ZoomSnapControls=Qs;exports.addEffectToLayer=Bf;exports.addMidiNote=Vf;exports.analyzeAudioFileWithAlgorithm=ep;exports.applyGroove=ip;exports.applyGrooveTemplate=ul;exports.applyHumanize=dl;exports.applyKaraokeDisplayVars=ua;exports.applyMidiTransform=p0;exports.applySwing=cl;exports.arrow_L=Mt;exports.arrow_R=gt;exports.autoCorrelate=Ef;exports.bracket_L=na;exports.bracket_R=ho;exports.buildArpSequence=Us;exports.buildLanes=No;exports.buildNoteDescriptors=Af;exports.buildPadNoteEvents=Lo;exports.buildSegmentScores=Nf;exports.canRedo=Pi;exports.canUndo=Ti;exports.chamfer_L=Qn;exports.chamfer_R=Zt;exports.clearMidiNotes=Hf;exports.clearPattern=Ki;exports.computeGrade=m0;exports.computeTheoreticalMax=sl;exports.computeVocalPerformanceReport=hp;exports.convertBrowserSongToKaraokeSongFile=zf;exports.copyCCEvents=qr;exports.createAnalyserNode=Ji;exports.createArpPattern=bf;exports.createArtNetPacket=Up;exports.createBasslinePattern=vf;exports.createCCHistory=Mi;exports.createCompressorNode=tl;exports.createDefaultLFO=ir;exports.createDefaultShortcuts=Mp;exports.createDropZoneHandlers=Np;exports.createEmptyPattern=Nt;exports.createEmptyStep=wa;exports.createGainNode=el;exports.createHiHatPattern=yf;exports.createKickPattern=mf;exports.createLoopRegion=vp;exports.createSACNPacket=qp;exports.createSnarePattern=gf;exports.createVocoderNode=nl;exports.createVoiceChatAudioContext=a0;exports.cutCCEvents=Ai;exports.deleteCCEventsInRange=Ni;exports.deserializeLFO=hc;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=Fi;exports.extractBpmFromNotes=io;exports.findTextureByUrl=qd;exports.formatShortcut=jp;exports.generateArpEvents=mc;exports.generatePlaceholderWaveform=sp;exports.generateSeed=of;exports.generateUltrastarText=tp;exports.getActiveGradient=Eo;exports.getActiveLyrics=ld;exports.getActiveWords=cd;exports.getAlgorithmColor=Df;exports.getAlgorithmCssVar=Of;exports.getAlgorithmLabel=Ff;exports.getArpModes=Vs;exports.getArpRates=qs;exports.getAudioContext=tn;exports.getAudioInputDevices=r0;exports.getAudioWorkletProcessorCode=Xi;exports.getBackgroundUrl=Pf;exports.getCachedImage=Od;exports.getCapStyleByName=dn;exports.getComboMultiplier=al;exports.getCoverUrl=Tf;exports.getGrooveTemplate=lp;exports.getGrooveTemplateNames=cp;exports.getLaneForPitch=Io;exports.getNextPlayerColor=Fp;exports.getNextPlayerColorCss=Dp;exports.getOverlayCanvasPattern=gn;exports.getPatternByName=un;exports.getSACNMulticastAddress=Hp;exports.getScoringPreset=Co;exports.getTexturePattern=pn;exports.getVerseRatingLabel=rl;exports.handleAddCCEvent=Yf;exports.handleRedo=td;exports.handleRemoveCCEvent=Xf;exports.handleSelectCCLane=Kf;exports.handleUndo=ed;exports.handleUpdateCCEvent=Zf;exports.hexToHsl=rr;exports.humanizeMidiNotes=bp;exports.hydrateKaraokeDisplayFromBackend=Yd;exports.hydratePlayerKaraokeSettingsFromBackend=Td;exports.hzToUltrastarPitch=lo;exports.importCCLane=Di;exports.initKaraokeDisplaySettings=Xd;exports.instrumentPresets=Yh;exports.isAudioContextRunning=Ns;exports.isInLoopRegion=wp;exports.isWebRTCSupported=n0;exports.loadAllKaraokeSettings=Pd;exports.loadAudioWorkletModule=Qi;exports.loadKaraokeDisplaySettings=Po;exports.loadKaraokeSettings=bo;exports.loadPlayerBarStyle=vo;exports.loadPlayerBarStyles=Ad;exports.loadRemoteScoringPresets=Ud;exports.makeClickReference=fl;exports.makeClipSelectionId=np;exports.mergeWaveforms=ap;exports.midiToHz=Or;exports.normalizeHex=ar;exports.openAudioFilePicker=Ip;exports.ornate_L=aa;exports.ornate_R=tr;exports.parseLyrics=od;exports.parseNotes=ea;exports.parseVersesWithSyllables=so;exports.parseVersesWithWords=id;exports.parseVideoMetadata=il;exports.pasteCCEvents=Ei;exports.pill_L=$t;exports.pill_R=Ct;exports.preloadTexture=ia;exports.preloadTextures=_d;exports.probeAudioFile=gl;exports.pushCCState=ji;exports.pushOperation=l0;exports.quantizeMidiNotes=gp;exports.quantizeNotes=u0;exports.quantizeStepInBeats=pl;exports.quantizeStepInSeconds=ja;exports.randomizeVelocity=Hi;exports.recordCCEvent=Ii;exports.redoCC=$i;exports.redoOperation=d0;exports.removeEffectFromLayer=Gf;exports.removeMidiNote=qf;exports.renderGlossyBarSvg=xo;exports.resumeAudioContext=Et;exports.reversePattern=Vi;exports.sampleLFOForDisplay=zs;exports.sampleLFOToCCEvents=_s;exports.saveKaraokeDisplaySettings=Zd;exports.saveKaraokeSettings=$d;exports.savePlayerBarStyle=Ed;exports.scaleResult=$f;exports.scaleTo10k=ol;exports.scoreNotesWithPitchPoints=Rf;exports.selectCCEventsInRange=hf;exports.serializeLFO=uc;exports.serializePattern=xf;exports.setLoopFromSelection=xp;exports.setProjectWithUndo=ro;exports.setStepGate=Bi;exports.setStepNote=_i;exports.setStepProbability=Gi;exports.setStepVelocity=zi;exports.sharp_L=Kt;exports.sharp_R=Yt;exports.shield_L=Jn;exports.shield_R=uo;exports.shiftPattern=qi;exports.shouldTrigger=Zi;exports.skewTL_L=Un;exports.skewTL_R=Lr;exports.skewTR_L=Ir;exports.skewTR_R=Vn;exports.snapLoopToGrid=Sp;exports.snapTimeToQuantize=Hr;exports.snapToGrid=rp;exports.snapToScale=f0;exports.soft_L=ta;exports.soft_R=co;exports.stepDuration=Ca;exports.stepTimeOffset=Yi;exports.syncDivisionToHz=Ds;exports.tab_L=ra;exports.tab_R=fo;exports.thinCCEvents=Li;exports.toTrack=_f;exports.toggleEffectBypass=Wf;exports.toggleStep=Oi;exports.toggleStepSlide=Wi;exports.transposePattern=Ui;exports.undoCC=Ri;exports.undoOperation=c0;exports.updateEffectParams=Uf;exports.useAudioWorklet=jf;exports.useAutoSave=Zc;exports.useCCAutomation=pf;exports.useDMXAudioSync=Xp;exports.useDMXEngine=Zp;exports.useEditorTrack=sd;exports.useLocalPlaylists=ya;exports.useMPE=Jh;exports.useMidiLearn=Xh;exports.useNiceTranslation=xe;exports.useOxygen25=tf;exports.usePitchWorker=Cf;exports.usePlaybackEngine=Xc;exports.useProjectCRUD=ad;exports.useRadioStream=kl;exports.useRecording=Qc;exports.useScoringWorker=kf;exports.useStepSequencer=wf;exports.useWebMidi=pr;exports.useWorker=ka;exports.validateAudioFiles=Ra;exports.wave_L=er;exports.wave_R=sa;exports.waveformValue=Os;exports.wrapTimeInLoop=Cp;