@nice2dev/ui-audio 1.1.10 → 1.2.1
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/CHANGELOG.md +173 -0
- package/README.md +14 -20
- package/dist/assets/scoringWorker-3JjtDDtu.js +1 -0
- package/dist/core/i18n.d.ts +1 -0
- package/dist/dmx/DmxEditor.d.ts +1 -11
- package/dist/editor/panels/CCAutomationLaneEditor.d.ts +0 -10
- package/dist/editor/panels/StepSequencerPanel.d.ts +1 -6
- package/dist/editor/panels/selectValue.d.ts +2 -0
- package/dist/effects/noteThemeColors.d.ts +0 -4
- package/dist/index.cjs +43 -43
- package/dist/index.d.ts +2 -69
- package/dist/index.mjs +10863 -11010
- package/dist/karaoke/KaraokeManager.d.ts +1 -1
- package/dist/karaoke/KaraokeSelectionMode.d.ts +1 -1
- package/dist/karaoke/PadKaraokeOverlay.d.ts +4 -4
- package/dist/karaoke/rendering/glossyBarRenderer.d.ts +2 -2
- package/dist/karaoke/rendering/karaokeSettings.d.ts +0 -57
- package/dist/playlist/PlaylistDualPane.d.ts +0 -8
- package/dist/radio/NiceRadioPlayer.d.ts +1 -1
- package/dist/ui-audio.css +1 -1
- package/dist/utils/karaokeScoring.d.ts +0 -3
- package/dist/workers/scoringWorker.d.ts +0 -1
- package/package.json +6 -6
package/dist/index.cjs
CHANGED
|
@@ -1,52 +1,52 @@
|
|
|
1
|
-
"use strict";var Yc=Object.create;var Cs=Object.defineProperty;var Zc=Object.getOwnPropertyDescriptor;var Xc=Object.getOwnPropertyNames;var Qc=Object.getPrototypeOf,Jc=Object.prototype.hasOwnProperty;var ed=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Xc(t))!Jc.call(e,s)&&s!==r&&Cs(e,s,{get:()=>t[s],enumerable:!(a=Zc(t,s))||a.enumerable});return e};var Hr=(e,t,r)=>(r=e!=null?Yc(Qc(e)):{},ed(t||!e||!e.__esModule?Cs(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),u=require("react"),we=require("@nice2dev/ui-core"),ve=require("@nice2dev/ui"),G=require("@nice2dev/icons"),oa=require("pitchy"),Ta=require("react-youtube");var bt=typeof document<"u"?document.currentScript:null;const td=(e,t)=>t??e,Pi=u.createContext(td),nd=({t:e,children:t})=>n.jsx(Pi.Provider,{value:e,children:t});function Pe(){return{t:u.useContext(Pi)}}class rd extends u.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){var s,i;const a=this.props.componentName?`[${this.props.componentName}]`:"[AudioErrorBoundary]";console.error(`${a} Caught error:`,t,r),(i=(s=this.props).onError)==null||i.call(s,t,r)}render(){return this.state.hasError&&this.state.error?typeof this.props.fallback=="function"?this.props.fallback(this.state.error,this.reset):this.props.fallback?this.props.fallback:n.jsx("div",{className:"nice-audio-error-boundary",role:"alert",children:n.jsxs("div",{className:"nice-audio-error-boundary__content",children:[n.jsx("h3",{className:"nice-audio-error-boundary__title",children:this.props.componentName?`${this.props.componentName} encountered an error`:"Something went wrong"}),n.jsx("p",{className:"nice-audio-error-boundary__message",children:this.state.error.message}),n.jsx("button",{className:"nice-audio-error-boundary__retry",onClick:this.reset,children:"Try Again"})]})}):this.props.children}}function ad(e){if(!e)return[128,128,128];const t=e.match(/^#([0-9a-f]{3,8})$/i);if(t){let a=t[1];if(a.length===3&&(a=a[0]+a[0]+a[1]+a[1]+a[2]+a[2]),a.length>=6)return[parseInt(a.slice(0,2),16),parseInt(a.slice(2,4),16),parseInt(a.slice(4,6),16)]}const r=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);return r?[+r[1],+r[2],+r[3]]:[128,128,128]}const Kr={},la={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function sd(){const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:bt&&bt.tagName.toUpperCase()==="SCRIPT"&&bt.src||new URL("index.cjs",document.baseURI).href}<"u"?Kr==null?void 0:Kr.VITE_LOG_LEVEL:void 0;return e&&e in la?e:"WARN"}const id=sd();function Kn(e){return la[e]>=la[id]}function Yn(e){return`[${e}]`}const it={debug(e,t,...r){Kn("DEBUG")&&console.debug(Yn(e),t,...r)},info(e,t,...r){Kn("INFO")&&console.info(Yn(e),t,...r)},warn(e,t,...r){Kn("WARN")&&console.warn(Yn(e),t,...r)},error(e,t,...r){Kn("ERROR")&&console.error(Yn(e),t,...r)},scoped(e){return{debug:(t,...r)=>it.debug(e,t,...r),info:(t,...r)=>it.info(e,t,...r),warn:(t,...r)=>it.warn(e,t,...r),error:(t,...r)=>it.error(e,t,...r)}}},js=it.scoped("Waveform"),od=["audio/","video/"],$a=({audioBlob:e,currentTime:t,duration:r,width:a=600,height:s=200,zoom:i=1,onSeek:o,onRegionSelect:l,markers:c=[],regions:d=[],displayMode:h="waveform",multiChannel:f=!1,waveColor:p="#007bff",progressColor:y="rgba(255,0,0,0.8)",backgroundColor:m="transparent",showRuler:x=!1,showChannelLabels:b=!0,showPeakMeter:g=!1,className:S})=>{const v=u.useRef(null),k=u.useRef(null),[M,T]=u.useState(null),[N,j]=u.useState(0),[R,z]=u.useState(!1),[A,$]=u.useState(null),[O,I]=u.useState(null),[U,J]=u.useState(0),_=Math.max(a,a*i),W=x?24:0;u.useEffect(()=>{if(!e||e.size===0){T(null);return}e.type&&!od.some(E=>e.type.startsWith(E))&&js.warn("Unexpected blob MIME type:",e.type);let q=!1;return(async()=>{let E=null;try{const P=await e.arrayBuffer();if(P.byteLength===0||q)return;E=new AudioContext;const C=await E.decodeAudioData(P);q||T(C)}catch(P){js.error("Failed to decode audio:",P)}finally{E==null||E.close().catch(()=>{})}})(),()=>{q=!0}},[e]),u.useEffect(()=>{if(i>1&&r>0){const q=t/r*_;(q<N||q>N+a)&&j(Math.max(0,q-a/2))}},[t,r,i,a,_,N]),u.useEffect(()=>{const q=v.current,E=M;if(!q||!r||r===1/0)return;const P=q.getContext("2d");if(!P)return;const C=_,L=s;if(q.width=C,q.height=L+W,P.clearRect(0,0,C,L+W),m!=="transparent"&&(P.fillStyle=we.resolveCssColor(m),P.fillRect(0,0,C,L+W)),x){const w=we.resolveCssColor("var(--nice-text-secondary, #888)");P.fillStyle="rgba(128,128,128,0.15)",P.fillRect(0,0,C,W),P.fillStyle=w,P.font="10px monospace",P.textAlign="center";const D=Math.max(1,Math.floor(r/(_/80)));for(let F=0;F<=r;F+=D){const B=F/r*C;P.fillText(ud(F),B,W-4),P.fillStyle="rgba(128,128,128,0.3)",P.fillRect(B,W,1,L),P.fillStyle=w}}for(const w of d){const D=w.start/r*C,F=w.end/r*C;P.fillStyle=we.resolveCssColor(w.color??"var(--nice-accent-tint-15, rgba(99, 102, 241, 0.15))"),P.fillRect(D,W,F-D,L),w.label&&(P.fillStyle=we.resolveCssColor(w.color??"var(--nice-info, #6366f1)"),P.font="10px sans-serif",P.textAlign="left",P.fillText(w.label,D+2,W+12))}if(A!==null&&O!==null){const w=Math.min(A,O),D=Math.max(A,O);P.fillStyle="rgba(255,200,0,0.2)",P.fillRect(w,W,D-w,L)}if(E){const w=f?E.numberOfChannels:1,D=L/w,F=we.resolveCssColor(p);let B=0;for(let V=0;V<w;V++){const Y=E.getChannelData(V),oe=W+V*D;if(h==="waveform"?ld(P,Y,C,D,oe,F):h==="bars"?cd(P,Y,C,D,oe,F):h==="spectrogram"&&dd(P,Y,C,D,oe,E.sampleRate),g&&r>0){const ie=Math.floor(t/r*Y.length),ne=Math.floor(E.sampleRate*.05);let Z=0;for(let se=Math.max(0,ie-ne);se<Math.min(Y.length,ie+ne);se++)Z+=Y[se]*Y[se];const H=Math.sqrt(Z/(ne*2));B=Math.max(B,H)}f&&b&&w>1&&(P.fillStyle=we.resolveCssColor("var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"),P.font="bold 11px sans-serif",P.textAlign="left",P.fillText(V===0?"L":V===1?"R":`Ch${V+1}`,4,oe+14))}J(B)}if(r>0){const w=Math.max(0,Math.min(t/r*C,C));P.beginPath(),P.strokeStyle=we.resolveCssColor(y),P.lineWidth=2,P.moveTo(w,W),P.lineTo(w,L+W),P.stroke()}for(const w of c){const D=w.time/r*C,F=we.resolveCssColor(w.color??"var(--nice-warning, #f59e0b)");P.beginPath(),P.strokeStyle=F,P.lineWidth=2,P.setLineDash([4,4]),P.moveTo(D,W),P.lineTo(D,L+W),P.stroke(),P.setLineDash([]),w.label&&(P.fillStyle=F,P.font="bold 10px sans-serif",P.textAlign="center",P.fillText(w.label,D,W+L-4))}},[M,t,r,_,s,i,h,f,p,y,m,x,c,d,A,O,g,b,W]);const K=u.useCallback(q=>{var C;if(!r)return;const E=(C=v.current)==null?void 0:C.getBoundingClientRect();if(!E)return;const P=q.clientX-E.left+N;z(!0),$(P),I(P)},[r,N]),re=u.useCallback(q=>{if(!R||!v.current)return;const E=v.current.getBoundingClientRect(),P=q.clientX-E.left+N;I(P)},[R,N]),X=u.useCallback(()=>{if(!R||A===null||O===null||!r){z(!1),$(null),I(null);return}const q=Math.min(A,O),E=Math.max(A,O),P=(E-q)/_*r;if(z(!1),$(null),I(null),P<.2){const C=q/_*r;o==null||o(C)}else{const C=q/_*r,L=E/_*r;l==null||l({start:C,end:L})}},[R,A,O,r,_,o,l]);return n.jsxs("div",{ref:k,className:`nice-waveform${S?` ${S}`:""}`,style:{position:"relative",width:a,overflow:i>1?"auto":"hidden",cursor:o?"crosshair":"default"},onScroll:q=>j(q.target.scrollLeft),children:[n.jsx("canvas",{ref:v,width:_,height:s+W,style:{display:"block"},role:"img","aria-label":"Waveform canvas",onMouseDown:K,onMouseMove:re,onMouseUp:X,onMouseLeave:X}),g&&n.jsx("div",{style:{position:"absolute",right:4,top:W+4,bottom:4,width:12,background:"var(--nice-overlay-30, rgba(0, 0, 0, 0.3))",borderRadius:4,overflow:"hidden"},children:n.jsx("div",{style:{position:"absolute",bottom:0,width:"100%",height:`${Math.min(100,U*300)}%`,background:U>.8?"var(--nice-danger, #ef4444)":U>.5?"var(--nice-warning, #f59e0b)":"var(--nice-success, #22c55e)",borderRadius:4,transition:"height 50ms"}})})]})};function ld(e,t,r,a,s,i){const o=Math.floor(t.length/r),l=s+a/2;e.beginPath(),e.strokeStyle=i,e.lineWidth=1;for(let c=0;c<r;c++){const d=c*o,h=t.subarray(d,d+o);let f=0,p=0;for(let x=0;x<h.length;x++)h[x]<f&&(f=h[x]),h[x]>p&&(p=h[x]);const y=l-p*(a/2),m=l-f*(a/2);e.moveTo(c,y),e.lineTo(c,m)}e.stroke()}function cd(e,t,r,a,s,i){const o=Math.max(2,Math.floor(r/128)),l=Math.floor(r/o),c=Math.floor(t.length/l);for(let d=0;d<l;d++){const h=d*c,f=t.subarray(h,h+c);let p=0;for(let b=0;b<f.length;b++)p+=Math.abs(f[b]);const m=p/f.length*a*.9,x=d*o;e.fillStyle=i,e.fillRect(x+1,s+a-m,o-2,m)}}function dd(e,t,r,a,s,i){const l=Math.min(r,512),c=Math.floor(t.length/l),d=r/l;for(let h=0;h<l;h++){const f=h*c,p=new Float32Array(256/2);for(let m=0;m<256/2;m++){let x=0,b=0;for(let g=0;g<256&&f+g<t.length;g++){const S=2*Math.PI*m*g/256;x+=t[f+g]*Math.cos(S),b-=t[f+g]*Math.sin(S)}p[m]=Math.sqrt(x*x+b*b)/256}const y=a/p.length;for(let m=0;m<p.length;m++){const x=Math.min(1,p[m]*10),b=Math.floor(x*255),g=Math.floor(x*100),S=Math.floor((1-x)*200);e.fillStyle=`rgb(${b},${g},${S})`,e.fillRect(h*d,s+a-(m+1)*y,d+1,y+1)}}}function ud(e){const t=Math.floor(e/60),r=Math.floor(e%60);return`${t}:${r.toString().padStart(2,"0")}`}const Ms=88,Xt=16,Zn=16,hd=320;function pd(e){return e-21}function fd(e){return e+21}const Pa=({notes:e,onAddNote:t,onRemoveNote:r,selectedNoteId:a,setSelectedNoteId:s,duration:i=4,zoom:o=1})=>{const l=u.useRef(null),c=hd*o,d=Ms*Xt,h=u.useRef(null);u.useEffect(()=>{},[e,o,i]);const f=y=>{const m=l.current;if(!m)return;const x=m.getBoundingClientRect(),b=y.clientX-x.left,g=y.clientY-x.top,S=Math.floor(g/Xt),v=fd(S),k=b/c*i;h.current={drawing:!0,startX:b,key:S},t(v,k,i/Zn)},p=(y,m)=>{m.stopPropagation(),s==null||s(y)};return n.jsxs("svg",{ref:l,width:c,height:d,style:{background:"var(--nice-bg-secondary, #f8fafc)",border:"1px solid var(--nice-border-color, #cbd5e1)",userSelect:"none",display:"block"},onMouseDown:f,children:[[...Array(Ms)].map((y,m)=>n.jsx("rect",{x:0,y:m*Xt,width:c,height:Xt,fill:m%2===0?"var(--nice-bg-secondary, #f8fafc)":"var(--nice-bg-tertiary, #f1f5f9)"},m)),[...Array(Zn+1)].map((y,m)=>n.jsx("line",{x1:m*c/Zn,y1:0,x2:m*c/Zn,y2:d,stroke:"var(--nice-border-muted, #ccc)",strokeWidth:m%4===0?2:1},m)),e.map(y=>{const m=pd(y.pitch),x=y.start/i*c,b=y.duration/i*c;return n.jsx("rect",{x,y:m*Xt,width:Math.max(6,b),height:Xt-2,fill:y.id===a?"var(--nice-color-primary, #6366f1)":"color-mix(in srgb, var(--nice-color-primary, #6366f1) 55%, var(--nice-bg-primary, #ffffff))",stroke:"var(--nice-color-primary, #6366f1)",strokeWidth:y.id===a?2:1,rx:3,onClick:g=>p(y.id,g),onDoubleClick:()=>r(y.id),style:{cursor:"pointer"}},y.id)})]})},Ei=({ccEvents:e,onAddEvent:t,onUpdateEvent:r,onRemoveEvent:a,ccType:s,duration:i,width:o,height:l=60,curveType:c})=>{const d=u.useRef(null),{t:h}=Pe(),[f,p]=u.useState(null),[y,m]=u.useState(null),[x,b]=u.useState(null),g=[...e].sort((O,I)=>O.time-I.time),S=O=>[O.time/i*o,(127-O.value)/127*l],v=(O,I,U)=>Math.max(I,Math.min(U,O)),k=O=>{var K;if(O.target instanceof SVGCircleElement)return;const I=(K=d.current)==null?void 0:K.getBoundingClientRect();if(!I)return;const U=O.clientX-I.left,J=O.clientY-I.top,_=v(U/o*i,0,i),W=v(127-Math.round(J/l*127),0,127);t(s,W,_)},M=(O,I)=>{var W;I.stopPropagation(),p(O.id),b(O.id);const[U,J]=S(O),_=(W=d.current)==null?void 0:W.getBoundingClientRect();_&&m({dx:I.clientX-_.left-U,dy:I.clientY-_.top-J})},T=O=>{var K;if(f==null||!y)return;const I=(K=d.current)==null?void 0:K.getBoundingClientRect();if(!I)return;const U=v(O.clientX-I.left-y.dx,0,o),J=v(O.clientY-I.top-y.dy,0,l),_=v(U/o*i,0,i),W=v(127-Math.round(J/l*127),0,127);r(f,W,_)},N=()=>{p(null),m(null)};u.useEffect(()=>{const O=I=>{(I.key==="Delete"||I.key==="Backspace")&&x!=null&&(a(x),b(null))};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[x,a]),u.useEffect(()=>{if(f!=null)return window.addEventListener("mousemove",T),window.addEventListener("mouseup",N),()=>{window.removeEventListener("mousemove",T),window.removeEventListener("mouseup",N)}});const[j,R]=u.useState(null),z=(O,I)=>{const[U,J]=S(O);R({x:U+10,y:J-10,text:`Val: ${O.value}, Time: ${O.time.toFixed(2)}s`})},A=()=>R(null),$=O=>{var K;const I=(K=d.current)==null?void 0:K.getBoundingClientRect();if(!I)return;const U=O.clientX-I.left,J=O.clientY-I.top,_=v(U/o*i,0,i),W=v(127-Math.round(J/l*127),0,127);t(s,W,_)};return n.jsxs("svg",{ref:d,width:o,height:l,style:{background:"var(--nice-bg-tertiary, #f3f3f3)",border:"1px solid var(--nice-border, #bbb)",cursor:f?"grabbing":"crosshair",display:"block"},onClick:k,onDoubleClick:$,tabIndex:0,children:[[...Array(9)].map((O,I)=>n.jsx("line",{x1:0,y1:I*l/8,x2:o,y2:I*l/8,stroke:"var(--nice-border-muted, #ddd)",strokeWidth:I===0||I===8?2:1},I)),g.length>1&&n.jsx("polyline",{fill:"none",stroke:"var(--nice-color-accent, #1976d2)",strokeWidth:2,points:g.map(O=>S(O).join(",")).join(" ")}),g.map(O=>{const[I,U]=S(O);return n.jsxs("g",{children:[n.jsx("circle",{cx:I,cy:U,r:x===O.id?8:6,fill:x===O.id?"var(--nice-color-accent, #1976d2)":"var(--nice-color-accent-light, #90caf9)",stroke:"var(--nice-color-accent, #1976d2)",strokeWidth:x===O.id?3:2,style:{cursor:"pointer"},onMouseDown:J=>M(O,J),onContextMenu:J=>{J.preventDefault(),a(O.id)},onClick:J=>{J.stopPropagation(),b(O.id)},onMouseOver:J=>z(O),onMouseOut:A}),x===O.id&&n.jsx("foreignObject",{x:I+10,y:U-18,width:90,height:30,style:{pointerEvents:"auto"},children:n.jsxs("div",{style:{fontSize:12,background:"var(--nice-color-surface, #fff)",border:"1px solid var(--nice-border, #bbb)",borderRadius:4,padding:"2px 6px",display:"inline-block"},children:[n.jsxs("label",{style:{marginRight:4},children:[h("ccLane.curve","Curve"),":"]}),n.jsxs("select",{value:O.handleType||c||"linear",onChange:J=>{r(O.id,O.value,O.time,J.target.value)},children:[n.jsx("option",{value:"linear",children:h("ccLane.linear","Linear")}),n.jsx("option",{value:"step",children:h("ccLane.step","Step")}),n.jsx("option",{value:"exp",children:h("ccLane.exponential","Exponential")})]})]})})]},O.id)}),j&&n.jsxs("g",{pointerEvents:"none",children:[n.jsx("rect",{x:j.x,y:j.y-18,width:90,height:20,fill:"var(--nice-color-surface, #fff)",stroke:"var(--nice-color-accent, #1976d2)",rx:4}),n.jsx("text",{x:j.x+6,y:j.y-4,fontSize:13,fill:"var(--nice-color-accent, #1976d2)",children:j.text})]}),n.jsxs("text",{x:6,y:16,fontSize:14,fill:"var(--nice-color-accent, #1976d2)",children:["CC",s]})]})},md=it.scoped("audioContext");let Gn=null;function yn(){if(!Gn)try{Gn=new(window.AudioContext||window.webkitAudioContext)}catch(e){md.error("Error initializing AudioContext:",e)}return Gn}async function Bt(){const e=yn();e&&e.state==="suspended"&&await e.resume()}function Ai(){return!!Gn&&Gn.state==="running"}function Ii(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 gd(e,t){if(!t.snapEnabled)return e;const r=Ii(t);return Math.round(e/r)*r}function yd(e,t=!1){const r=Math.floor(e/60),a=Math.floor(e%60),s=Math.floor(e%1*1e3);return t?`${r}:${a.toString().padStart(2,"0")}.${s.toString().padStart(3,"0")}`:`${r}:${a.toString().padStart(2,"0")}`}function bd(e,t){const r=t/60,a=e*r,s=Math.floor(a/4),i=Math.floor(a%4);return`${s+1}:${i+1}`}function Li(e,t,r=!0){const a=e.getContext("2d");if(!a)return;const s=30*t.zoom*t.duration,i=Math.max(80,30*t.zoom);e.width=s,e.height=i,a.clearRect(0,0,s,i),a.fillStyle=we.resolveCssColor("var(--nice-color-surface, #f5f5f5)",a.canvas),a.fillRect(0,0,s,i);const o=s/t.duration;let l=1;o<30?l=5:o<60?l=2:o>150&&(l=.5),a.strokeStyle=we.resolveCssColor("var(--nice-border-secondary, #ddd)",a.canvas),a.lineWidth=1;for(let c=0;c<=t.duration;c+=l){const d=c/t.duration*s,h=c%1===0;if(a.strokeStyle=we.resolveCssColor(h?"var(--nice-border-secondary, #ccc)":"var(--nice-border-muted, #eee)",a.canvas),a.lineWidth=h?1.5:.5,a.beginPath(),a.moveTo(d,0),a.lineTo(d,i),a.stroke(),h&&o>40){a.fillStyle=we.resolveCssColor("var(--nice-text-muted, #666)",a.canvas),a.font="10px monospace",a.textAlign="center";const f=r?bd(c,t.bpm):yd(c);a.fillText(f,d,12)}}if(t.snapEnabled){const c=Ii(t);a.strokeStyle=we.resolveCssColor("var(--nice-color-accent, #ffeb3b)",a.canvas),a.lineWidth=.5;for(let d=0;d<=t.duration;d+=c){const h=d/t.duration*s;a.beginPath(),a.moveTo(h,i-5),a.lineTo(h,i),a.stroke()}}}function vd(e,t,r,a){const s=e.getContext("2d");if(!s)return;const i=30*t.zoom*t.duration,o=Math.max(80,30*t.zoom),l=r/t.duration*i;Li(e,t),s.strokeStyle=we.resolveCssColor(a?"var(--nice-color-danger, #f44336)":"var(--nice-color-accent, #2196f3)",s.canvas),s.lineWidth=2,s.beginPath(),s.moveTo(l,0),s.lineTo(l,o),s.stroke(),s.fillStyle=we.resolveCssColor(a?"var(--nice-color-danger, #f44336)":"var(--nice-color-accent, #2196f3)",s.canvas),s.beginPath(),s.moveTo(l,0),s.lineTo(l-5,-8),s.lineTo(l+5,-8),s.closePath(),s.fill()}function xd(e,t,r,a="var(--nice-color-success, #4caf50)"){const s=e.getContext("2d");if(!s||!(r!=null&&r.length))return;const i=30*t.zoom*t.duration,l=e.height/2,c=Math.max(10,l-6);s.save(),s.strokeStyle=a,s.lineWidth=1,s.beginPath(),r.forEach((d,h)=>{const f=h/(r.length-1)*i,p=l-d*c;h===0?s.moveTo(f,p):s.lineTo(f,p)}),s.stroke(),s.restore()}const Ea=({zoom:e=1,duration:t=4,isPlaying:r,isRecording:a,currentTime:s,bpm:i=120,snapEnabled:o=!1,snapMode:l="beat",waveform:c,waveformColor:d,onCurrentTimeChange:h,onZoomChange:f})=>{const p=u.useRef(null),[y,m]=u.useState(!1),x=u.useRef(s);x.current=s;const b=u.useRef(t);b.current=t;const g=u.useRef(h);g.current=h;const S={zoom:e,duration:t,bpm:i,snapEnabled:o,snapMode:l};u.useEffect(()=>{Bt(),v()},[e,t,s,a,i,o,l,c]),u.useEffect(()=>{if(!r)return;let R=performance.now(),z=0;const A=$=>{const O=Math.max(0,$-R)/1e3;R=$;const I=Math.min(x.current+O,b.current);x.current=I,g.current(I),I<b.current&&(z=requestAnimationFrame(A))};return z=requestAnimationFrame(A),()=>cancelAnimationFrame(z)},[r]);const v=()=>{p.current&&(Li(p.current,S),c!=null&&c.length&&xd(p.current,S,c,d),vd(p.current,S,s,a))},k=R=>{m(!0),N(R)},M=R=>{y&&N(R)},T=()=>{m(!1)},N=R=>{if(!p.current)return;const z=p.current.getBoundingClientRect();let $=(R.clientX-z.left)/z.width*t;$=gd($,S),h(Math.min(Math.max($,0),t))},j=R=>{if(!f)return;R.preventDefault();const z=R.deltaY>0?-.1:.1,A=Math.max(.5,Math.min(5,e+z));f(A)};return n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:n.jsx("canvas",{ref:p,style:{border:"1px solid black",backgroundColor:"white",width:`${30*e*t}px`,height:`${Math.max(80,30*e)}px`,cursor:y?"grabbing":"pointer"},onMouseDown:k,onMouseMove:M,onMouseUp:T,onMouseLeave:T,onWheel:j,role:"img","aria-label":"Audio timeline canvas"})})},et=["var(--nice-primary, #2196f3)","var(--nice-danger, #e53935)","var(--nice-warning, #ffeb3b)","var(--nice-success, #43a047)","var(--nice-warning, #ff9800)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-warning, #ffc107)","var(--nice-success, #8bc34a)","var(--nice-danger, #f44336)","var(--nice-accent, #3f51b5)","var(--nice-text-secondary, #607d8b)","var(--nice-warning-dark, #795548)","var(--nice-warning, #cddc39)","var(--nice-accent, #673ab7)","var(--nice-success, #009688)"];function Sd(e){for(const t of et)if(!e.includes(t))return t;return et[Math.floor(Math.random()*et.length)]}const ur=et.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function kd(e){for(let t=0;t<et.length;t++){const r=et[t],a=ur[t];if(!e.includes(r)&&!e.includes(a))return a}return ur[Math.floor(Math.random()*ur.length)]}const wd="_panelNarrow_1r7m9_3",Cd="_panelWide_1r7m9_9",jd="_smallLabel_1r7m9_19",Md="_noteText_1r7m9_29",Rd="_buttonRow_1r7m9_41",Nd="_noteTextMargin_1r7m9_49",Td="_rangeW100_1r7m9_63",$d="_zoomValue_1r7m9_69",Pd="_selectW100_1r7m9_77",Ed="_inputW70_1r7m9_83",Ad="_masterVolGroup_1r7m9_93",Id="_rangeW140_1r7m9_99",Ld="_volumeValue_1r7m9_105",Dd="_selectW140_1r7m9_115",zd="_freqGroup_1r7m9_121",_d="_freqValue_1r7m9_127",Fd="_narrowGroup_1r7m9_137",Od="_rangeW120_1r7m9_143",Bd="_smallValue_1r7m9_149",Gd="_presetDivider_1r7m9_159",Wd="_presetLabel_1r7m9_165",Ud="_presetBtn_1r7m9_175",Vd="_deletePresetSelect_1r7m9_183",qd="_presetNameInput_1r7m9_191",Hd="_savePresetBtn_1r7m9_199",Kd="_countInAlert_1r7m9_211",Yd="_inputW80_1r7m9_219",Zd="_levelLabel_1r7m9_225",Xd="_levelMeter_1r7m9_233",Qd="_levelBar_1r7m9_249",Ce={panelNarrow:wd,panelWide:Cd,smallLabel:jd,noteText:Md,buttonRow:Rd,noteTextMargin:Nd,rangeW100:Td,zoomValue:$d,selectW100:Pd,inputW70:Ed,masterVolGroup:Ad,rangeW140:Id,volumeValue:Ld,selectW140:Dd,freqGroup:zd,freqValue:_d,narrowGroup:Fd,rangeW120:Od,smallValue:Bd,presetDivider:Gd,presetLabel:Wd,presetBtn:Ud,deletePresetSelect:Vd,presetNameInput:qd,savePresetBtn:Hd,countInAlert:Kd,inputW80:Yd,levelLabel:Zd,levelMeter:Xd,levelBar:Qd},Di=({autoSaveMode:e,setAutoSaveMode:t,autoSaveInterval:r,setAutoSaveInterval:a})=>{const{t:s}=Pe();return n.jsxs("div",{className:`card p-3 mb-3 ${Ce.panelNarrow}`,children:[n.jsx("h6",{className:"mb-2",children:s("editorPanels.autoSaveTitle","Project auto-save")}),n.jsxs("div",{className:"mb-2",children:[n.jsxs("label",{className:"form-label",children:[s("editorPanels.autoSaveMode","Auto-save mode"),":"]}),n.jsxs("select",{className:"form-select",value:e,onChange:i=>t(i.target.value),children:[n.jsx("option",{value:"off",children:s("editorPanels.off","Off")}),n.jsx("option",{value:"onChange",children:s("editorPanels.onChange","On every change")}),n.jsx("option",{value:"interval",children:s("editorPanels.interval","At set interval")}),n.jsx("option",{value:"both",children:s("editorPanels.both","Both")})]})]}),(e==="interval"||e==="both")&&n.jsxs("div",{className:"mb-2",children:[n.jsxs("label",{className:"form-label",children:[s("editorPanels.autoSaveFrequency","Auto-save frequency (seconds)"),":"]}),n.jsx("input",{type:"number",className:"form-control",min:5,max:600,value:r,onChange:i=>a(Math.max(5,Math.min(600,Number(i.target.value))))})]}),n.jsxs("div",{className:Ce.noteText,children:[n.jsxs("b",{children:[s("editorPanels.noteLabel","Note"),":"]})," ",s("editorPanels.autoSaveNote","Auto-save works locally (localStorage/browser). Manual save (PUT) always overwrites the project on the server.")]})]})},zi=({undoCount:e,redoCount:t,onUndo:r,onRedo:a})=>{const{t:s}=Pe();return n.jsxs("div",{className:`card p-3 mb-3 ${Ce.panelNarrow}`,children:[n.jsx("h6",{className:"mb-2",children:s("editorPanels.changeHistory","Project change history")}),n.jsxs("div",{className:Ce.buttonRow,children:[n.jsxs("button",{className:"btn btn-secondary",onClick:r,disabled:e===0,title:s("editorPanels.undoTitle","Undo last change (Ctrl+Z)"),children:[n.jsx(G.NtdUndo,{size:14})," ",s("editorPanels.undo","Undo")]}),n.jsxs("button",{className:"btn btn-secondary",onClick:a,disabled:t===0,title:s("editorPanels.redoTitle","Redo change (Ctrl+Y or Ctrl+Shift+Z)"),children:[n.jsx(G.NtdRedo,{size:14})," ",s("editorPanels.redo","Redo")]})]}),n.jsx("div",{className:Ce.noteTextMargin,children:s("editorPanels.undoRedoNote","Undo/Redo works on the entire project (all editor changes). After each change Redo is cleared.")})]})},Aa=({zoom:e,setZoom:t,uiZoom:r,setUiZoom:a,snapEnabled:s,onToggleSnap:i,snapMode:o,onSnapModeChange:l,bpm:c,setBpm:d})=>{const{t:h}=Pe();return n.jsx("div",{className:`card p-2 mb-3 ${Ce.panelNarrow}`,children:n.jsxs("div",{className:"d-flex align-items-center gap-3",children:[n.jsxs("div",{className:"d-flex align-items-center gap-2",children:[n.jsx("label",{className:`form-label mb-0 ${Ce.smallLabel}`,children:"Zoom:"}),n.jsx("input",{type:"range",min:"0.5",max:"5",step:"0.1",value:e,onChange:f=>t(Number(f.target.value)),className:Ce.rangeW100}),n.jsxs("span",{className:Ce.zoomValue,children:[e.toFixed(1),"x"]})]}),n.jsxs("div",{className:"d-flex align-items-center gap-2",children:[n.jsx("label",{className:`form-label mb-0 ${Ce.smallLabel}`,children:"Zoom UI:"}),n.jsx("input",{type:"range",min:"1",max:"4",step:"0.1",value:r,onChange:f=>a(Number(f.target.value)),className:Ce.rangeW100}),n.jsxs("span",{className:Ce.zoomValue,children:[r.toFixed(1),"x"]})]}),n.jsxs("div",{className:"d-flex align-items-center gap-2",children:[n.jsx("input",{id:"snap-toggle",type:"checkbox",className:"form-check-input",checked:s,onChange:i}),n.jsx("label",{htmlFor:"snap-toggle",className:`form-check-label mb-0 ${Ce.smallLabel}`,children:"Snap"})]}),s&&n.jsxs("select",{className:`form-select form-select-sm ${Ce.selectW100}`,value:o,onChange:f=>l(f.target.value),children:[n.jsx("option",{value:"bar",children:h("editorPanels.snapBar","Bar")}),n.jsx("option",{value:"beat",children:h("editorPanels.snapBeat","Beat")}),n.jsx("option",{value:"sub-beat",children:h("editorPanels.snap16","1/16")}),n.jsx("option",{value:"second",children:h("editorPanels.snapSecond","Second")})]}),n.jsxs("div",{className:"d-flex align-items-center gap-2",children:[n.jsx("label",{className:`form-label mb-0 ${Ce.smallLabel}`,children:"BPM:"}),n.jsx("input",{type:"number",className:`form-control form-control-sm ${Ce.inputW70}`,value:c,onChange:f=>d(Number(f.target.value)),min:"20",max:"300"})]})]})})},_i=({masterVolume:e,onMasterVolumeChange:t,filterType:r,filterFreq:a,filterQ:s,filterGain:i,onFilterChange:o,masterEQPresets:l,customPresets:c,onLoadPreset:d,onSavePreset:h,onDeletePreset:f})=>{const{t:p}=Pe();return n.jsxs("div",{className:`card p-2 mb-3 ${Ce.panelWide}`,children:[n.jsxs("div",{className:"d-flex align-items-center flex-wrap gap-3",children:[n.jsxs("div",{className:`d-flex align-items-center gap-2 ${Ce.masterVolGroup}`,children:[n.jsx("label",{className:`form-label mb-0 ${Ce.smallLabel}`,children:"Master Vol"}),n.jsx("input",{type:"range",min:"0",max:"1",step:"0.01",value:e,onChange:y=>t(Number(y.target.value)),className:Ce.rangeW140}),n.jsxs("span",{className:Ce.volumeValue,children:[Math.round(e*100),"%"]})]}),n.jsxs("div",{className:"d-flex align-items-center gap-2",children:[n.jsx("label",{className:`form-label mb-0 ${Ce.smallLabel}`,children:"Filter"}),n.jsx("select",{className:`form-select form-select-sm ${Ce.selectW140}`,value:r,onChange:y=>o({type:y.target.value}),children:["peaking","lowpass","highpass","lowshelf","highshelf","notch","bandpass"].map(y=>n.jsx("option",{value:y,children:y},y))})]}),n.jsxs("div",{className:`d-flex align-items-center gap-2 ${Ce.freqGroup}`,children:[n.jsx("span",{className:Ce.smallLabel,children:"Freq"}),n.jsx("input",{type:"range",min:"40",max:"12000",step:"10",value:a,onChange:y=>o({frequency:Number(y.target.value)}),className:Ce.rangeW140}),n.jsxs("span",{className:Ce.freqValue,children:[Math.round(a)," Hz"]})]}),n.jsxs("div",{className:`d-flex align-items-center gap-2 ${Ce.narrowGroup}`,children:[n.jsx("span",{className:Ce.smallLabel,children:"Q"}),n.jsx("input",{type:"range",min:"0.1",max:"12",step:"0.1",value:s,onChange:y=>o({q:Number(y.target.value)}),className:Ce.rangeW120}),n.jsx("span",{className:Ce.smallValue,children:s.toFixed(1)})]}),(r==="peaking"||r==="lowshelf"||r==="highshelf")&&n.jsxs("div",{className:`d-flex align-items-center gap-2 ${Ce.narrowGroup}`,children:[n.jsx("span",{className:Ce.smallLabel,children:"Gain"}),n.jsx("input",{type:"range",min:"-18",max:"18",step:"0.5",value:i,onChange:y=>o({gain:Number(y.target.value)}),className:Ce.rangeW120}),n.jsxs("span",{className:Ce.smallValue,children:[i.toFixed(1)," dB"]})]})]}),n.jsxs("div",{className:`mt-2 pt-2 ${Ce.presetDivider}`,children:[n.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[n.jsxs("span",{className:Ce.presetLabel,children:[p("editorPanels.eqPresets","EQ Presets"),":"]}),[...l,...c].map(y=>n.jsx("button",{className:`btn btn-sm btn-outline-secondary ${Ce.presetBtn}`,onClick:()=>d(y),children:y.name},y.name)),c.length>0&&n.jsxs("select",{className:`form-select form-select-sm ${Ce.deletePresetSelect}`,onChange:y=>{y.target.value&&(f(y.target.value),y.target.value="")},defaultValue:"",children:[n.jsx("option",{value:"",children:p("editorPanels.deletePreset","Delete preset...")}),c.map(y=>n.jsx("option",{value:y.name,children:y.name},y.name))]})]}),n.jsxs("div",{className:"d-flex align-items-center gap-2",children:[n.jsx("input",{type:"text",className:`form-control form-control-sm ${Ce.presetNameInput}`,placeholder:p("editorPanels.presetName","Preset name..."),id:"presetNameInput"}),n.jsx("button",{className:`btn btn-sm btn-success ${Ce.savePresetBtn}`,onClick:()=>{const y=document.getElementById("presetNameInput");y!=null&&y.value.trim()&&(h(y.value.trim()),y.value="")},children:p("editorPanels.saveCurrent","Save Current")})]})]})]})},Fi=({countInBars:e,setCountInBars:t,isCountIn:r,countInRemaining:a,overdubEnabled:s,setOverdubEnabled:i,punchIn:o,setPunchIn:l,punchOut:c,setPunchOut:d,monitorLevel:h})=>{const{t:f}=Pe();return n.jsx("div",{className:`card p-2 mb-3 ${Ce.panelWide}`,children:n.jsxs("div",{className:"d-flex align-items-center flex-wrap gap-3",children:[n.jsxs("div",{className:"d-flex align-items-center gap-2",children:[n.jsxs("label",{className:`form-label mb-0 ${Ce.smallLabel}`,children:[f("editorPanels.countIn","Count-in (bars)"),":"]}),n.jsx("input",{type:"number",min:"0",max:"8",step:"1",className:`form-control form-control-sm ${Ce.inputW70}`,value:e,onChange:p=>t(Number(p.target.value))}),r&&n.jsxs("span",{className:Ce.countInAlert,children:["Count-in: ",a.toFixed(1),"s"]})]}),n.jsxs("div",{className:"form-check d-flex align-items-center gap-2",children:[n.jsx("input",{id:"overdub-toggle",className:"form-check-input",type:"checkbox",checked:s,onChange:p=>i(p.target.checked)}),n.jsx("label",{htmlFor:"overdub-toggle",className:`form-check-label ${Ce.smallLabel}`,children:f("editorPanels.overdub","Overdub (play background)")})]}),n.jsxs("div",{className:"d-flex align-items-center gap-1",children:[n.jsx("span",{className:Ce.smallLabel,children:"Punch In"}),n.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${Ce.inputW80}`,value:o??"",onChange:p=>l(p.target.value===""?null:Number(p.target.value))}),n.jsx("span",{className:Ce.smallLabel,children:"s"})]}),n.jsxs("div",{className:"d-flex align-items-center gap-1",children:[n.jsx("span",{className:Ce.smallLabel,children:"Punch Out"}),n.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${Ce.inputW80}`,value:c??"",onChange:p=>d(p.target.value===""?null:Number(p.target.value))}),n.jsx("span",{className:Ce.smallLabel,children:"s"})]}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>{l(null),d(null)},children:f("editorPanels.clearPunch","Clear punch")}),n.jsx("div",{className:Ce.levelLabel,children:"Level"}),n.jsx("div",{className:Ce.levelMeter,children:n.jsx("div",{className:Ce.levelBar,style:{width:`${Math.min(1,h*2)*100}%`,background:h>.7?"var(--nice-danger, #f44336)":"var(--nice-success, #4caf50)"}})})]})})},Jd=[{id:1,name:"Audio 1",type:"audio",color:et[0],volume:.8,audioBlob:null},{id:2,name:"MIDI 1",type:"midi",color:et[1],volume:.8,notes:[]}],eu=({initialTracks:e,tracks:t,onTracksChange:r,initialBpm:a=120,duration:s=30,height:i=480,title:o="Untitled project",displayMode:l="standard",onNew:c,onOpen:d,onSave:h,onExport:f,t:p})=>{var H,se;const{t:y}=Pe(),m=p??y,[x,b]=u.useState(l),g=x==="advanced",S=x!=="basic",[v,k]=u.useState(e??Jd),M=t??v,T=u.useCallback(ae=>{t===void 0&&k(ae),r==null||r(ae)},[t,r]),[N,j]=u.useState(!1),[R,z]=u.useState(0),[A,$]=u.useState(1),[O,I]=u.useState(2),[U,J]=u.useState(!0),[_,W]=u.useState("beat"),[K,re]=u.useState(a),[X,q]=u.useState(80),[E,P]=u.useState(((H=M[0])==null?void 0:H.id)??null),C=u.useRef(0),L=u.useRef(0);u.useEffect(()=>{if(!N)return;L.current=performance.now();const ae=ue=>{const ee=(ue-L.current)/1e3;L.current=ue,z(de=>{const fe=de+ee;return fe>=s?(j(!1),s):fe}),C.current=requestAnimationFrame(ae)};return C.current=requestAnimationFrame(ae),()=>cancelAnimationFrame(C.current)},[N,s]);const w=u.useCallback((ae,ue)=>T(M.map(ee=>ee.id===ae?{...ee,...ue}:ee)),[M,T]),D=u.useCallback(ae=>{const ue=M.reduce((de,fe)=>Math.max(de,fe.id),0)+1,ee=M.filter(de=>de.type===ae).length+1;T([...M,{id:ue,name:`${ae==="audio"?"Audio":"MIDI"} ${ee}`,type:ae,color:et[M.length%et.length],volume:.8,...ae==="audio"?{audioBlob:null}:{notes:[]}}]),P(ue)},[M,T]),F=u.useCallback(ae=>T(M.filter(ue=>ue.id!==ae)),[M,T]),B=u.useCallback(()=>{if(c){c();return}T([]),z(0),j(!1)},[c,T]),V=u.useCallback((ae,ue,ee,de)=>{const fe=M.find(be=>be.id===ae),xe=(fe==null?void 0:fe.notes)??[],ce=xe.reduce((be,Me)=>Math.max(be,Me.id),0)+1;w(ae,{notes:[...xe,{id:ce,pitch:ue,start:ee,duration:de,velocity:100}]})},[M,w]),Y=u.useCallback((ae,ue)=>{const ee=M.find(de=>de.id===ae);w(ae,{notes:((ee==null?void 0:ee.notes)??[]).filter(de=>de.id!==ue)})},[M,w]),oe=u.useMemo(()=>{const ae=Math.floor(R/60),ue=Math.floor(R%60),ee=Math.floor(R%1*100);return`${ae}:${ue.toString().padStart(2,"0")}.${ee.toString().padStart(2,"0")}`},[R]),ie=u.useMemo(()=>{const ae=(ee,de)=>({id:`mode-${ee}`,label:`${x===ee?"• ":" "}${de}`,onClick:()=>b(ee)}),ue=[{id:"file",label:m("studio.menu.file","File"),children:[{id:"new",label:m("studio.menu.new","New"),onClick:B},...d?[{id:"open",label:m("studio.menu.open","Open…"),onClick:d}]:[],{id:"save",label:m("studio.menu.save","Save"),onClick:()=>h==null?void 0:h(M)},{id:"export",label:m("studio.menu.export","Export…"),onClick:()=>f==null?void 0:f(M)}]}];return S&&ue.push({id:"edit",label:m("studio.menu.edit","Edit"),children:[{id:"add-audio",label:m("studio.addAudio","Add audio track"),onClick:()=>D("audio")},{id:"add-midi",label:m("studio.addMidi","Add MIDI track"),onClick:()=>D("midi")}]}),ue.push({id:"view",label:m("studio.menu.view","View"),children:[{id:"modes",label:m("studio.menu.modes","Display mode"),divider:!1,disabled:!0},ae("basic",m("studio.mode.basic","Basic")),ae("standard",m("studio.mode.standard","Standard")),ae("advanced",m("studio.mode.advanced","Advanced")),{id:"d1",divider:!0},{id:"snap",label:`${U?"• ":" "}${m("studio.snap","Snap to grid")}`,onClick:()=>J(ee=>!ee)}]}),ue.push({id:"help",label:m("studio.menu.help","Help"),children:[{id:"about",label:m("studio.menu.about","About NiceAudioStudio"),disabled:!0}]}),ue},[m,x,S,U,B,d,h,f,M,D]),ne=n.jsxs(n.Fragment,{children:[n.jsxs(ve.NiceButton,{variant:"primary",size:"sm",onClick:()=>j(ae=>!ae),children:[N?n.jsx(G.NtdPause,{size:14}):n.jsx(G.NtdPlay,{size:14})," ",N?m("studio.pause","Pause"):m("studio.play","Play")]}),n.jsxs(ve.NiceButton,{variant:"secondary",size:"sm",onClick:()=>{j(!1),z(0)},children:[n.jsx(G.NtdStop,{size:14})," ",m("studio.stop","Stop")]}),n.jsx("span",{style:{fontVariantNumeric:"tabular-nums",fontWeight:700,minWidth:80},children:oe}),n.jsx("span",{style:{flex:1}}),n.jsxs(ve.NiceButton,{variant:"outline",size:"sm",onClick:()=>D("audio"),children:[n.jsx(G.NtdPlus,{size:14})," ",m("studio.addAudio","Audio")]}),S&&n.jsxs(ve.NiceButton,{variant:"outline",size:"sm",onClick:()=>D("midi"),children:[n.jsx(G.NtdPlus,{size:14})," ",m("studio.addMidi","MIDI")]}),n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:m("studio.master","Master")}),n.jsx("div",{style:{width:90},children:n.jsx(ve.NiceSlider,{value:X,onChange:q,min:0,max:100})})]}),Z=n.jsxs(n.Fragment,{children:[n.jsxs("span",{children:[K," BPM"]}),n.jsx("span",{children:"·"}),n.jsx("span",{style:{fontVariantNumeric:"tabular-nums"},children:oe}),n.jsx("span",{children:"·"}),n.jsxs("span",{children:[M.length," ",m("studio.tracks","tracks")]}),g&&E!=null&&n.jsxs(n.Fragment,{children:[n.jsx("span",{children:"·"}),n.jsxs("span",{children:[m("studio.active","Active"),": ",((se=M.find(ae=>ae.id===E))==null?void 0:se.name)??"—"]})]}),n.jsx("span",{style:{flex:1}}),n.jsx("span",{style:{textTransform:"capitalize"},children:x})]});return n.jsxs(ve.NiceAppShell,{className:"nice-audio-studio",height:i,menubar:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[n.jsx(ve.NiceMenu,{items:ie,orientation:"horizontal"}),n.jsx("span",{style:{color:"var(--nice-text-secondary)",fontSize:13},children:o})]}),toolbar:ne,statusBar:Z,children:[S&&n.jsx("div",{style:{padding:"6px 12px",borderBottom:"1px solid var(--nice-border-color)"},children:n.jsx(Aa,{zoom:A,setZoom:$,uiZoom:O,setUiZoom:I,snapEnabled:U,onToggleSnap:()=>J(ae=>!ae),snapMode:_,onSnapModeChange:W,bpm:K,setBpm:re})}),n.jsx("div",{style:{padding:8},children:n.jsx(Ea,{zoom:A,duration:s,isPlaying:N,isRecording:!1,currentTime:R,bpm:K,snapEnabled:U,snapMode:_,onCurrentTimeChange:z,onZoomChange:$})}),M.length===0?n.jsx("div",{style:{padding:32,textAlign:"center",color:"var(--nice-text-muted, #94a3b8)"},children:m("studio.empty","No tracks — add an audio or MIDI track to start.")}):M.map(ae=>n.jsxs("div",{style:{display:"flex",gap:8,padding:8,borderTop:"1px solid var(--nice-border-color)",background:E===ae.id?"color-mix(in srgb, var(--nice-color-primary) 8%, transparent)":"transparent"},onClick:()=>P(ae.id),children:[n.jsxs("div",{style:{flex:"0 0 180px",display:"flex",flexDirection:"column",gap:6},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[n.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:ae.color||et[0],flex:"0 0 auto"}}),n.jsx("div",{style:{flex:1},children:n.jsx(ve.NiceTextInput,{value:ae.name,onChange:ue=>w(ae.id,{name:ue}),size:"sm"})})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx(ve.NiceButton,{variant:ae.muted?"danger":"ghost",size:"sm",onClick:()=>w(ae.id,{muted:!ae.muted}),children:"M"}),S&&n.jsx(ve.NiceButton,{variant:ae.solo?"warning":"ghost",size:"sm",onClick:()=>w(ae.id,{solo:!ae.solo}),children:"S"}),n.jsx("div",{style:{flex:1},children:n.jsx(ve.NiceSlider,{value:Math.round((ae.volume??.8)*100),onChange:ue=>w(ae.id,{volume:ue/100}),min:0,max:100})}),n.jsx(ve.NiceButton,{variant:"ghost",size:"sm",onClick:()=>F(ae.id),children:n.jsx(G.NtdClose,{size:14})})]})]}),n.jsx("div",{style:{flex:1,minWidth:0,opacity:ae.muted?.5:1},children:ae.type==="audio"?n.jsx($a,{audioBlob:ae.audioBlob??null,currentTime:R,duration:s,zoom:A,height:80,waveColor:ae.color,onSeek:z}):n.jsx(Pa,{notes:ae.notes??[],onAddNote:(ue,ee,de)=>V(ae.id,ue,ee,de),onRemoveNote:ue=>Y(ae.id,ue),duration:s,zoom:A})})]},ae.id))]})};let tu=Date.now();function gn(){return tu++}function nu(e,t,r=.01){if(e.length===0)return[];const a=[];let s=-1/0;for(const i of e)i.time-s>=r&&(a.push({id:gn(),cc:t,value:bn(i.value),time:i.time}),s=i.time);return a}function Rs(e,t,r,a=32){const s=[];for(let i=0;i<=a;i++){const o=i/a;s.push({id:gn(),cc:r,value:bn(jr(e.value,t.value,o)),time:jr(e.time,t.time,o)})}return s}function ru(e,t,r,a,s=48){const i=[];for(let o=0;o<=s;o++){const l=o/s,c=Ns(e.time,t.time,r.time,l),d=Ns(e.value,t.value,r.value,l);i.push({id:gn(),cc:a,value:bn(d),time:c})}return i}function au(e,t,r,a=8){const s=[],i=(t.time-e.time)/a,o=(t.value-e.value)/a;for(let l=0;l<a;l++){const c=e.time+l*i,d=bn(e.value+l*o);s.push({id:gn(),cc:r,value:d,time:c}),s.push({id:gn(),cc:r,value:d,time:c+i-.001})}return s}function su(e,t,r,a=2,s=32){const i=[];for(let o=0;o<=s;o++){const l=o/s,c=Math.pow(l,a);i.push({id:gn(),cc:r,value:bn(jr(e.value,t.value,c)),time:jr(e.time,t.time,l)})}return i}function iu(e,t=3){if(e.length<t)return e;const r=[...e].sort((a,s)=>a.time-s.time);return r.map((a,s)=>{const i=Math.max(0,s-Math.floor(t/2)),o=Math.min(r.length,i+t),l=r.slice(i,o),c=l.reduce((d,h)=>d+h.value,0)/l.length;return{...a,value:bn(Math.round(c))}})}function ou(e,t){let r;switch(e.mode){case"pencil":r=nu(t,e.cc,e.resolution);break;case"line":r=t.length>=2?Rs(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?r=ru(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?r=Rs(t[0],t[t.length-1],e.cc):r=[];break;case"step":r=t.length>=2?au(t[0],t[t.length-1],e.cc):[];break;case"ramp":r=t.length>=2?su(t[0],t[t.length-1],e.cc):[];break;default:r=[]}if(e.smoothing>0){const a=Math.max(2,Math.round(e.smoothing*8));r=iu(r,a)}return r}function bn(e){return Math.max(0,Math.min(127,Math.round(e)))}function jr(e,t,r){return e+(t-e)*r}function Ns(e,t,r,a){const s=1-a;return s*s*e+2*s*a*t+a*a*r}function Dr(){return{waveform:"sine",rate:1,depth:.5,phase:0,center:.5,syncToBpm:!1,syncDivision:"1/4",enabled:!0}}const lu={"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 Oi(e,t){return e/60*lu[t]/4}function Bi(e,t){const r=(t%1+1)%1;switch(e){case"sine":return Math.sin(r*2*Math.PI);case"triangle":return r<.5?4*r-1:3-4*r;case"sawtooth":return 2*r-1;case"square":return r<.5?1:-1;case"random":return Math.sin(r*127.1)*Math.cos(r*311.7)*2;case"sample-hold":return Math.sin(Math.floor(r*4)*2.399+.5)*2-1;default:return 0}}function Ia(e,t,r){if(!e.enabled)return e.center;const a=e.syncToBpm&&r?Oi(r,e.syncDivision):e.rate,s=t*a+e.phase/(2*Math.PI),i=Bi(e.waveform,s),o=e.center+i*e.depth*.5;return Math.max(0,Math.min(1,o))}function La(e,t,r){return Math.round(Ia(e,t,r)*127)}function Gi(e,t,r,a,s=30,i){const o=r-t,l=Math.max(2,Math.ceil(o*s)),c=[];for(let d=0;d<=l;d++){const h=t+d/l*o,f=La(e,h,i);c.push({time:h,value:f,cc:a})}return c}function Wi(e,t,r,a=2,s,i=200){const o=[];for(let l=0;l<=i;l++){const c=l/i*a,d=Ia(e,c,s);o.push({x:l/i*t,y:(1-d)*r})}return o}function cu(e){return JSON.stringify(e,null,2)}function du(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const Yr=140,vn=24,uu=[{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"}],Ui=({layerId:e=0,ccNumber:t=1,duration:r=8,zoom:a=1,automation:s,onChangeCCNumber:i,points:o,onChange:l})=>{const c=u.useRef({getEvents:()=>[],setEvents:()=>{},addEvent:()=>{},removeEvent:()=>{},updateEvent:()=>{},clearLane:()=>{},exportLane:()=>"",importLane:()=>{},undo:()=>{},redo:()=>{},canUndo:!1,canRedo:!1}).current,d=s??c,{t:h}=Pe(),f=u.useRef(null),[p,y]=u.useState("pencil"),[m,x]=u.useState(!1),b=u.useRef([]),[g,S]=u.useState(null),[v,k]=u.useState(!1),[M,T]=u.useState(Dr()),N=u.useRef(null),j=d.getEvents(e),R=j.filter(E=>E.cc===t),z=Math.max(400,r*30*a),A=u.useCallback(E=>E/z*r,[z,r]),$=u.useCallback(E=>Math.round(Math.max(0,Math.min(127,127-(E-vn)/Yr*127))),[]),O=u.useCallback(E=>E/r*z,[z,r]),I=u.useCallback(E=>vn+(127-E)/127*Yr,[]),U=u.useCallback(()=>{const E=f.current;if(!E)return;const P=E.getContext("2d");if(!P)return;const C=E.width,L=E.height;P.clearRect(0,0,C,L),P.fillStyle=we.resolveCssColor("var(--nice-bg, #1a1a2e)",P.canvas),P.fillRect(0,0,C,L),P.strokeStyle=we.resolveCssColor("var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",P.canvas),P.lineWidth=1;for(let F=0;F<=127;F+=16){const B=I(F);P.beginPath(),P.moveTo(0,B),P.lineTo(C,B),P.stroke()}P.fillStyle=we.resolveCssColor("var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))",P.canvas),P.font="10px monospace",P.textBaseline="middle";for(const F of[0,32,64,96,127])P.fillText(String(F),2,I(F));P.strokeStyle=we.resolveCssColor("var(--nice-overlay-light-4, rgba(255, 255, 255, 0.04))",P.canvas);for(let F=0;F<=r;F++){const B=O(F);P.beginPath(),P.moveTo(B,0),P.lineTo(B,L),P.stroke()}const w=[...R].sort((F,B)=>F.time-B.time);if(w.length>0){P.beginPath(),P.moveTo(O(w[0].time),L-vn);for(const F of w)P.lineTo(O(F.time),I(F.value));P.lineTo(O(w[w.length-1].time),L-vn),P.closePath(),P.fillStyle=we.resolveCssColor("var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",P.canvas),P.fill(),P.beginPath(),P.strokeStyle=we.resolveCssColor("var(--nice-primary, #3b82f6)",P.canvas),P.lineWidth=2;for(let F=0;F<w.length;F++){const B=O(w[F].time),V=I(w[F].value);F===0?P.moveTo(B,V):((w[F].handleType??"linear")==="step"&&P.lineTo(B,I(w[F-1].value)),P.lineTo(B,V))}P.stroke();for(const F of w){const B=O(F.time),V=I(F.value),Y=g===F.id;P.beginPath(),P.arc(B,V,Y?6:4,0,Math.PI*2),P.fillStyle=we.resolveCssColor(Y?"var(--nice-primary-light, #60a5fa)":"var(--nice-primary, #3b82f6)",P.canvas),P.fill(),P.strokeStyle=we.resolveCssColor("var(--nice-bg, #fff)",P.canvas),P.lineWidth=1.5,P.stroke()}}P.strokeStyle=we.resolveCssColor("var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))",P.canvas),P.lineWidth=1,P.setLineDash([4,4]);const D=I(0);P.beginPath(),P.moveTo(0,D),P.lineTo(C,D),P.stroke(),P.setLineDash([])},[R,r,z,O,I,g]);u.useEffect(()=>{U()},[U]);const J=E=>{var w;const P=(w=f.current)==null?void 0:w.getBoundingClientRect();if(!P)return;const C=E.clientX-P.left,L=E.clientY-P.top;p==="pencil"?(x(!0),b.current=[{time:A(C),value:$(L)}]):(x(!0),b.current=[{time:A(C),value:$(L)}])},_=E=>{var F;const P=(F=f.current)==null?void 0:F.getBoundingClientRect();if(!P)return;const C=E.clientX-P.left,L=E.clientY-P.top;m&&b.current.push({time:A(C),value:$(L)});const w=[...R].sort((B,V)=>B.time-V.time);let D=null;for(const B of w){const V=O(B.time),Y=I(B.value);if(Math.abs(C-V)<8&&Math.abs(L-Y)<8){D=B.id;break}}S(D)},W=()=>{if(!m)return;x(!1);const E=b.current;if(E.length===0)return;const P=ou({mode:p,cc:t,resolution:.02,smoothing:p==="pencil"?.3:0},E);P.length>0&&d.setEvents(e,[...j,...P]),b.current=[]},K=E=>{var w;const P=(w=f.current)==null?void 0:w.getBoundingClientRect();if(!P)return;const C=E.clientX-P.left,L=E.clientY-P.top;for(const D of R){const F=O(D.time),B=I(D.value);if(Math.abs(C-F)<8&&Math.abs(L-B)<8){d.removeEvent(e,D.id);return}}d.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:$(L),time:A(C)})},re=()=>{const P=Gi(M,0,r,t,Math.ceil(r*20),120).map((C,L)=>({...C,id:Date.now()+L}));d.setEvents(e,[...j,...P]),k(!1)},X=()=>{const E=d.exportLane(e),P=new Blob([E],{type:"application/json"}),C=URL.createObjectURL(P),L=document.createElement("a");L.href=C,L.download=`cc-lane-${t}-layer-${e}.json`,document.body.appendChild(L),L.click(),L.remove(),URL.revokeObjectURL(C)},q=E=>{var C;const P=(C=E.target.files)==null?void 0:C[0];P&&(P.text().then(L=>{d.importLane(e,L)}),N.current&&(N.current.value=""))};return n.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[n.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2 flex-wrap",children:[n.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:h("ccLane.title","CC Automation Lane")}),n.jsx("select",{className:"form-select form-select-sm",style:{width:160,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:t,onChange:E=>i(Number(E.target.value)),children:uu.map(E=>n.jsxs("option",{value:E.cc,children:[E.label," (CC",E.cc,")"]},E.cc))}),n.jsx("div",{className:"btn-group btn-group-sm",children:["pencil","line","curve","step","ramp"].map(E=>n.jsx("button",{className:`btn ${p===E?"btn-primary":"btn-outline-secondary"}`,onClick:()=>y(E),style:{fontSize:11,textTransform:"capitalize"},children:E},E))}),n.jsxs("div",{className:"btn-group btn-group-sm",children:[n.jsx("button",{className:"btn btn-outline-secondary",onClick:d.undo,disabled:!d.canUndo,title:"Undo",children:n.jsx(G.NtdUndo,{size:14})}),n.jsx("button",{className:"btn btn-outline-secondary",onClick:d.redo,disabled:!d.canRedo,title:"Redo",children:n.jsx(G.NtdRedo,{size:14})})]}),n.jsx("button",{className:"btn btn-sm btn-outline-info",onClick:()=>k(!v),title:"Apply LFO modulation",children:"LFO"}),n.jsx("button",{className:"btn btn-sm btn-outline-warning",onClick:X,title:"Export CC lane as JSON",children:"Export"}),n.jsx("button",{className:"btn btn-sm btn-outline-success",onClick:()=>{var E;return(E=N.current)==null?void 0:E.click()},title:"Import CC lane from JSON",children:"Import"}),n.jsx("input",{ref:N,type:"file",accept:".json",style:{display:"none"},onChange:q}),n.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:()=>d.setEvents(e,j.filter(E=>E.cc!==t)),title:"Clear all CC events for this lane",children:"Clear"}),n.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginLeft:"auto"},children:[R.length," ",h("ccLane.events","events")]})]}),v&&n.jsx("div",{className:"mb-2 p-2",style:{background:"var(--nice-bg-secondary, #161b22)",borderRadius:6,border:"1px solid var(--nice-border, #30363d)"},children:n.jsxs("div",{className:"d-flex gap-2 flex-wrap align-items-center mb-2",children:[n.jsxs("label",{style:{fontSize:12},children:["Wave:",n.jsx("select",{className:"form-select form-select-sm ms-1",style:{width:110,display:"inline-block",background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:M.waveform,onChange:E=>T(P=>({...P,waveform:E.target.value})),children:["sine","triangle","sawtooth","square","random","sample-hold"].map(E=>n.jsx("option",{value:E,children:E},E))})]}),n.jsxs("label",{style:{fontSize:12},children:["Rate:",n.jsx("input",{type:"number",className:"form-control form-control-sm ms-1",style:{width:70,display:"inline-block",background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},min:.01,max:20,step:.1,value:M.rate,onChange:E=>T(P=>({...P,rate:Number(E.target.value)}))})]}),n.jsxs("label",{style:{fontSize:12},children:["Depth:",n.jsx("input",{type:"range",min:0,max:1,step:.01,value:M.depth,onChange:E=>T(P=>({...P,depth:Number(E.target.value)})),style:{width:80}}),n.jsx("span",{style:{fontSize:11,marginLeft:4},children:M.depth.toFixed(2)})]}),n.jsxs("label",{style:{fontSize:12},children:["Center:",n.jsx("input",{type:"range",min:0,max:1,step:.01,value:M.center,onChange:E=>T(P=>({...P,center:Number(E.target.value)})),style:{width:80}}),n.jsx("span",{style:{fontSize:11,marginLeft:4},children:M.center.toFixed(2)})]}),n.jsx("button",{className:"btn btn-sm btn-primary",onClick:re,children:"Apply LFO"}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>k(!1),children:"Cancel"})]})}),n.jsx("div",{style:{overflowX:"auto",borderRadius:6},children:n.jsx("canvas",{ref:f,width:z,height:Yr+vn*2,style:{cursor:m?"crosshair":g?"pointer":"crosshair",display:"block",borderRadius:6},onMouseDown:J,onMouseMove:_,onMouseUp:W,onMouseLeave:()=>{m&&W()},onDoubleClick:K,role:"img","aria-label":"CC automation lane editor canvas"})}),n.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginTop:4},children:h("ccLane.hint","Click to draw. Double-click to add/remove points. Drag to draw curves.")})]})},Vi={"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},ca={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function hu(e,t){const r=[];for(let a=0;a<t;a++)for(const s of e)r.push({...s,pitch:s.pitch+a*12});return r}function qi(e,t){if(e.length===0)return[];const r=hu(e,t.octaves),a=[...r].sort((o,l)=>o.pitch-l.pitch),s=[...r].sort((o,l)=>l.pitch-o.pitch);let i;switch(t.mode){case"up":i=a;break;case"down":i=s;break;case"updown":i=[...a,...s.slice(1,-1)];break;case"downup":i=[...s,...a.slice(1,-1)];break;case"random":i=[...r].sort(()=>Math.random()-.5);break;case"as-played":i=[...r].sort((o,l)=>o.originalOrder-l.originalOrder);break;case"chord":i=r;break;default:i=a}if(t.repeats>1){const o=[];for(const l of i)for(let c=0;c<t.repeats;c++)o.push(l);i=o}return i}function pu(e,t,r,a=0,s=1){const i=qi(e,t);if(i.length===0)return[];const o=60/r,l=Vi[t.rate]*o,c=l*t.gate,d=[],h=t.mode==="chord",f=h?s:i.length*s;for(let p=0;p<f;p++){const y=p%2===1?l*t.swing*.5:0,m=a+p*l+y;if(h)for(const x of i){const b=t.velocityPattern?t.velocityPattern[p%t.velocityPattern.length]:x.velocity;d.push({pitch:x.pitch,velocity:b,startTime:m,duration:c,step:p})}else{const x=p%i.length,b=i[x],g=t.velocityPattern?t.velocityPattern[p%t.velocityPattern.length]:b.velocity;d.push({pitch:b.pitch,velocity:g,startTime:m,duration:c,step:p})}}return d}function Hi(){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 Ki(){return Object.keys(Vi)}const Yi=({config:e=ca,onChange:t=()=>{},active:r=!1,onToggleActive:a=()=>{}})=>{const{t:s}=Pe(),i=Hi(),o=Ki(),l=c=>t({...e,...c});return n.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8,opacity:r?1:.6},children:[n.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[n.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:s("arp.title","Arpeggiator")}),n.jsx("button",{className:`btn btn-sm ${r?"btn-success":"btn-outline-secondary"}`,onClick:a,children:r?"ON":"OFF"}),n.jsx("button",{className:`btn btn-sm ${e.latch?"btn-warning":"btn-outline-secondary"}`,onClick:()=>l({latch:!e.latch}),title:"Latch — keep arp running after releasing keys",children:"Latch"}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>t(ca),title:"Reset to defaults",children:"Reset"})]}),n.jsxs("div",{className:"row g-2",children:[n.jsxs("div",{className:"col-12",children:[n.jsx("label",{style:{fontSize:12},className:"mb-1",children:s("arp.mode","Mode")}),n.jsx("div",{className:"btn-group btn-group-sm w-100",children:i.map(c=>n.jsx("button",{className:`btn ${e.mode===c.mode?"btn-primary":"btn-outline-secondary"}`,onClick:()=>l({mode:c.mode}),title:c.description,style:{fontSize:11},children:c.label},c.mode))})]}),n.jsxs("div",{className:"col-6",children:[n.jsx("label",{style:{fontSize:12},className:"mb-1",children:s("arp.rate","Rate")}),n.jsx("select",{className:"form-select form-select-sm",style:{background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:e.rate,onChange:c=>l({rate:c.target.value}),children:o.map(c=>n.jsx("option",{value:c,children:c},c))})]}),n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.octaves","Octaves"),": ",e.octaves]}),n.jsx("input",{type:"range",className:"form-range",min:1,max:4,step:1,value:e.octaves,onChange:c=>l({octaves:Number(c.target.value)})})]}),n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.gate","Gate"),": ",Math.round(e.gate*100),"%"]}),n.jsx("input",{type:"range",className:"form-range",min:.05,max:1,step:.05,value:e.gate,onChange:c=>l({gate:Number(c.target.value)})})]}),n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.swing","Swing"),": ",Math.round(e.swing*100),"%"]}),n.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.swing,onChange:c=>l({swing:Number(c.target.value)})})]}),n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.repeats","Repeats"),": ",e.repeats]}),n.jsx("input",{type:"range",className:"form-range",min:1,max:4,step:1,value:e.repeats,onChange:c=>l({repeats:Number(c.target.value)})})]})]})]})},fu=["sine","triangle","sawtooth","square","random","sample-hold"],mu=["1/1","1/2","1/4","1/8","1/16","1/32"],xn=200,Qt=48,Zi=({config:e,onChange:t,index:r,onRemove:a})=>{const{t:s}=Pe(),i=u.useRef(null),o=c=>t({...e,...c}),l=u.useCallback(()=>{const c=i.current;if(!c)return;const d=c.getContext("2d");if(!d)return;d.clearRect(0,0,xn,Qt),d.fillStyle=we.resolveCssColor("var(--nice-bg-secondary, #161b22)",d.canvas),d.fillRect(0,0,xn,Qt),d.strokeStyle=we.resolveCssColor("var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",d.canvas),d.lineWidth=1,d.setLineDash([3,3]),d.beginPath(),d.moveTo(0,Qt/2),d.lineTo(xn,Qt/2),d.stroke(),d.setLineDash([]);const h=Wi(e,xn,Qt);if(h.length>0){d.beginPath(),d.strokeStyle=we.resolveCssColor(e.enabled?"var(--nice-primary, #3b82f6)":"var(--nice-text-secondary, #484f58)",d.canvas),d.lineWidth=1.5;for(let f=0;f<h.length;f++){const p=h[f].x,y=h[f].y;f===0?d.moveTo(p,y):d.lineTo(p,y)}d.stroke()}},[e]);return u.useEffect(()=>{l()},[l]),n.jsxs("div",{className:"card p-2 mb-2",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8,opacity:e.enabled?1:.5},children:[n.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[n.jsxs("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)",fontSize:13},children:[s("lfo.title","LFO")," ",r!==void 0?`#${r+1}`:""]}),n.jsx("button",{className:`btn btn-sm ${e.enabled?"btn-success":"btn-outline-secondary"}`,onClick:()=>o({enabled:!e.enabled}),style:{fontSize:11,padding:"1px 8px"},children:e.enabled?"ON":"OFF"}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>t(Dr()),style:{fontSize:11,padding:"1px 8px"},title:"Reset to defaults",children:"Reset"}),a&&n.jsx("button",{className:"btn btn-sm btn-outline-danger ms-auto",onClick:a,style:{fontSize:11,padding:"1px 8px"},"aria-label":s("lfo.remove","Remove LFO"),title:s("lfo.remove","Remove LFO"),children:n.jsx(G.NtdClose,{size:12})})]}),n.jsxs("div",{className:"d-flex gap-2 flex-wrap align-items-start",children:[n.jsx("canvas",{ref:i,width:xn,height:Qt,style:{borderRadius:4,border:"1px solid var(--nice-border, #30363d)",flexShrink:0},role:"img","aria-label":"LFO waveform preview canvas"}),n.jsxs("div",{className:"flex-grow-1",children:[n.jsx("div",{className:"mb-1",children:n.jsx("div",{className:"btn-group btn-group-sm w-100",children:fu.map(c=>n.jsx("button",{className:`btn ${e.waveform===c?"btn-primary":"btn-outline-secondary"}`,onClick:()=>o({waveform:c}),style:{fontSize:10,textTransform:"capitalize",padding:"1px 4px"},children:c==="sample-hold"?"S&H":c.slice(0,3)},c))})}),n.jsxs("div",{className:"row g-1",children:[n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:10},children:["Rate: ",e.rate.toFixed(1)," Hz"]}),n.jsx("input",{type:"range",className:"form-range",min:.01,max:20,step:.1,value:e.rate,onChange:c=>o({rate:Number(c.target.value)}),style:{height:16}})]}),n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:10},children:["Depth: ",Math.round(e.depth*100),"%"]}),n.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.depth,onChange:c=>o({depth:Number(c.target.value)}),style:{height:16}})]}),n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:10},children:["Center: ",Math.round(e.center*100),"%"]}),n.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.center,onChange:c=>o({center:Number(c.target.value)}),style:{height:16}})]}),n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:10},children:["Phase: ",Math.round(e.phase),"°"]}),n.jsx("input",{type:"range",className:"form-range",min:0,max:360,step:1,value:e.phase,onChange:c=>o({phase:Number(c.target.value)}),style:{height:16}})]})]}),n.jsxs("div",{className:"d-flex align-items-center gap-2 mt-1",children:[n.jsxs("label",{style:{fontSize:10},children:[n.jsx("input",{type:"checkbox",checked:e.syncToBpm,onChange:c=>o({syncToBpm:c.target.checked}),className:"form-check-input me-1",style:{marginTop:0,width:12,height:12}}),"BPM Sync"]}),e.syncToBpm&&n.jsx("select",{className:"form-select form-select-sm",style:{width:80,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)",fontSize:11},value:e.syncDivision??"1/4",onChange:c=>o({syncDivision:c.target.value}),children:mu.map(c=>n.jsx("option",{value:c,children:c},c))}),n.jsxs("label",{style:{fontSize:10},children:["CC:",n.jsx("input",{type:"number",className:"form-control form-control-sm ms-1",style:{width:55,display:"inline-block",background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)",fontSize:11},min:0,max:127,value:e.targetCC??1,onChange:c=>o({targetCC:Number(c.target.value)})})]})]})]})]})]})},gu=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function yu(e){const t=Math.floor(e/12)-1;return`${gu[e%12]}${t}`}const Xi=({seq:e,steps:t,tracks:r,bpm:a,pattern:s,onChange:i})=>{const{t:o}=Pe();if(!e)return n.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[n.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:o("stepSeq.title","Step Sequencer")}),n.jsx("small",{style:{color:"var(--nice-text-muted, #8b949e)"},children:"Provide a `seq` prop (useStepSequencer) for live editing."})]});const{pattern:l,currentStep:c,playing:d}=e,h=u.useMemo(()=>l.steps.slice(0,l.length),[l]);return n.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[n.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2 flex-wrap",children:[n.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:o("stepSeq.title","Step Sequencer")}),n.jsx("button",{className:`btn btn-sm ${d?"btn-danger":"btn-success"}`,onClick:e.togglePlayback,style:{minWidth:60,display:"inline-flex",alignItems:"center",gap:4},children:d?n.jsxs(n.Fragment,{children:[n.jsx(G.NtdStop,{size:12})," Stop"]}):n.jsxs(n.Fragment,{children:[n.jsx(G.NtdPlay,{size:12})," Play"]})}),n.jsxs("label",{style:{fontSize:12,display:"flex",alignItems:"center",gap:4},children:["BPM:",n.jsx("input",{type:"number",className:"form-control form-control-sm",style:{width:70,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},min:20,max:300,value:l.bpm,onChange:f=>e.setBpm(Number(f.target.value))})]}),n.jsxs("label",{style:{fontSize:12,display:"flex",alignItems:"center",gap:4},children:["Swing:",n.jsx("input",{type:"range",min:0,max:1,step:.01,value:l.swing,onChange:f=>e.setSwing(Number(f.target.value)),style:{width:60}}),n.jsxs("span",{style:{fontSize:11,minWidth:28},children:[Math.round(l.swing*100),"%"]})]}),n.jsx("div",{className:"btn-group btn-group-sm",children:[16,32,64].map(f=>n.jsx("button",{className:`btn ${l.length===f?"btn-primary":"btn-outline-secondary"}`,onClick:()=>e.setLength(f),style:{fontSize:11},children:f},f))})]}),n.jsxs("div",{className:"d-flex gap-1 mb-2 flex-wrap",children:[n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(1),"aria-label":"Transpose up one semitone",children:"+1"}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(-1),"aria-label":"Transpose down one semitone",children:"-1"}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(12),children:"+Oct"}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(-12),children:"-Oct"}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:e.reverse,children:"Reverse"}),n.jsxs("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.shift(1),children:["Shift ",n.jsx(G.NtdArrowRight,{size:12})]}),n.jsxs("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.shift(-1),children:[n.jsx(G.NtdArrowLeft,{size:12})," Shift"]}),n.jsx("button",{className:"btn btn-sm btn-outline-info",onClick:()=>e.randomizeVel(),children:"Rnd Vel"}),n.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:e.clear,children:"Clear"})]}),n.jsx("div",{style:{overflowX:"auto"},children:n.jsx("div",{style:{display:"flex",gap:2,minWidth:l.length*36},children:h.map((f,p)=>{const y=f.active,m=c===p,x=p%4===0;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2,minWidth:34},children:[n.jsx("span",{style:{fontSize:9,color:x?"var(--nice-text-muted, #8b949e)":"var(--nice-text-secondary, #30363d)"},children:p+1}),n.jsx("button",{onClick:()=>e.toggle(p),style:{width:32,height:32,borderRadius:4,border:m?"2px solid var(--nice-warning, #f0c040)":"1px solid var(--nice-border, #30363d)",background:y?`hsl(${210+f.velocity/127*40}, 80%, ${35+f.velocity/127*20}%)`:x?"var(--nice-bg-secondary, #21262d)":"var(--nice-bg-secondary, #161b22)",cursor:"pointer",padding:0,color:y?"var(--nice-text-primary, #fff)":"var(--nice-text-secondary, #484f58)",fontSize:8,fontWeight:600,transition:"background 0.1s"},children:y?yu(f.note):""}),n.jsx("div",{style:{width:32,height:20,background:"var(--nice-bg-secondary, #161b22)",borderRadius:2,position:"relative",overflow:"hidden"},children:n.jsx("div",{style:{position:"absolute",bottom:0,left:0,width:"100%",height:`${f.velocity/127*100}%`,background:y?"var(--nice-primary-tint-60, rgba(59, 130, 246, 0.6))":"var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",borderRadius:2,cursor:"ns-resize"},title:`Vel: ${f.velocity}`,onMouseDown:b=>{b.preventDefault();const g=b.target.parentElement.getBoundingClientRect(),S=k=>{const M=k.clientY-g.top,T=Math.round(Math.max(1,Math.min(127,(1-M/g.height)*127)));e.setVelocity(p,T)},v=()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",v)};document.addEventListener("mousemove",S),document.addEventListener("mouseup",v)}})}),y&&f.probability<1&&n.jsxs("span",{style:{fontSize:8,color:"var(--nice-warning, #f0c040)"},children:[Math.round(f.probability*100),"%"]})]},p)})})}),n.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginTop:6},children:o("stepSeq.hint","Click steps to toggle. Drag velocity bars vertically.")})]})};function bu(e,t,r){const[a,s]=u.useState("interval"),[i,o]=u.useState(30),l=u.useRef(null),c=u.useCallback(()=>{if(e)try{localStorage.setItem("audioEditor.autoSave",JSON.stringify(e)),t("Project auto-saved locally"),r("success"),setTimeout(()=>t(""),2e3)}catch(d){t("Auto-save error: "+d.message),r("error")}},[e,t,r]);return u.useEffect(()=>{(a==="onChange"||a==="both")&&c()},[e,a,c]),u.useEffect(()=>(l.current&&(clearInterval(l.current),l.current=null),(a==="interval"||a==="both")&&i>0&&(l.current=window.setInterval(c,i*1e3)),()=>{l.current&&(clearInterval(l.current),l.current=null)}),[a,i,c]),{autoSaveMode:a,setAutoSaveMode:s,autoSaveInterval:i,setAutoSaveInterval:o}}function vu(e,t,r){const a=u.useRef(null),[s,i]=u.useState(!1),[o,l]=u.useState(0),[c,d]=u.useState(10),[h,f]=u.useState(!1),[p,y]=u.useState(120),m=u.useCallback((N,j)=>`L${N}-C${j}`,[]),x=u.useCallback((N,j)=>{if(!a.current||!j.audioBuffer)return;const R=m(N,j.id),z=e[N];a.current.addClip({id:R,buffer:j.audioBuffer,startTime:j.start,offset:0,duration:j.duration,layerId:N,volume:(z==null?void 0:z.volume)??1,pan:(z==null?void 0:z.pan)??0,stretchFactor:j.stretchFactor||1,effectChain:(z==null?void 0:z.effectChain)||[]})},[e,m]),b=u.useCallback((N,j)=>{var R;(R=a.current)==null||R.removeClip(m(N,j))},[m]);u.useEffect(()=>{Object.entries(t).forEach(([N,j])=>{const R=Number(N);j==null||j.forEach(z=>x(R,z))})},[t,e,x]),u.useEffect(()=>{a.current&&Object.entries(r).forEach(([N,j])=>{const R=Number(N);a.current.setMidiCCEvents(R,j)})},[r]);const g=u.useCallback(()=>{a.current&&(s?a.current.pause():a.current.play())},[s]),S=u.useCallback(()=>{var N;(N=a.current)==null||N.stop()},[]),v=u.useCallback(N=>{var j;(j=a.current)==null||j.seek(N)},[]),k=u.useCallback(()=>{if(!a.current)return;const N=!h;f(N),a.current.setLoopRegion(0,c,N)},[h,c]),M=u.useCallback(N=>{var R;const j=Math.max(1,c+N);d(j),(R=a.current)==null||R.setLoopRegion(0,j,h)},[c,h]),T=u.useCallback(async(N,j=1024)=>{const R=await N.arrayBuffer(),z=new(window.AudioContext||window.webkitAudioContext),A=await z.decodeAudioData(R.slice(0)),$=A.getChannelData(0),O=$.length,I=Math.max(1,Math.floor(O/j)),U=[];for(let J=0;J<j;J++){const _=J*I;if(_>=O)break;U.push($[_])}return z.close(),{waveform:U.map(J=>Math.max(-1,Math.min(1,J))),duration:A.duration,buffer:A}},[]);return{engineRef:a,isPlaying:s,setIsPlaying:i,currentTime:o,setCurrentTime:l,duration:c,setDuration:d,isLooping:h,setIsLooping:f,bpm:p,setBpm:y,handlePlayPause:g,handleStop:S,handleSeek:v,handleToggleLoop:k,handleAdjustDuration:M,upsertEngineClip:x,removeEngineClip:b,makeEngineClipId:m,blobToWaveform:T}}class Da{constructor(){this.stream=null,this.mediaRecorder=null,this.audioChunks=[],this.isRecording=!1,this.audioContext=null,this.analyser=null,this.gainNode=null,this.monitorGain=null,this.levelRaf=null}async startRecording(t={}){if(this.isRecording)return;this.levelCallback=t.onLevel,this.stream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t.deviceId||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}});const r=t.mimeType||"audio/webm";this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:r}),this.audioChunks=[],this.audioContext=new(window.AudioContext||window.webkitAudioContext);let s=this.audioContext.createMediaStreamSource(this.stream);t.gain!==void 0&&t.gain>0&&(this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=t.gain,s.connect(this.gainNode),s=this.gainNode),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,s.connect(this.analyser),t.monitorEnabled&&(this.monitorGain=this.audioContext.createGain(),this.monitorGain.gain.value=(t.monitorVolume??100)/100,s.connect(this.monitorGain),this.monitorGain.connect(this.audioContext.destination));const i=()=>{if(!this.analyser)return;const o=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(o);let l=0;for(let d=0;d<o.length;d++){const h=(o[d]-128)/128;l+=h*h}const c=Math.sqrt(l/o.length);this.levelCallback&&this.levelCallback(c),this.isRecording&&(this.levelRaf=requestAnimationFrame(i))};this.mediaRecorder.ondataavailable=o=>{o.data&&o.data.size>0&&this.audioChunks.push(o.data)},this.mediaRecorder.start(),this.isRecording=!0,this.levelRaf=requestAnimationFrame(i)}getStream(){return this.stream}async stopRecording(){return!this.isRecording||!this.mediaRecorder?null:new Promise(t=>{const r=this.mediaRecorder;r.onstop=()=>{const a=new Blob(this.audioChunks,{type:r.mimeType});this.cleanup(),t(a)},r.stop(),this.isRecording=!1})}cleanup(){this.levelRaf&&(cancelAnimationFrame(this.levelRaf),this.levelRaf=null),this.levelCallback=void 0,this.monitorGain&&(this.monitorGain.disconnect(),this.monitorGain=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.analyser&&(this.analyser.disconnect(),this.analyser=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.stream&&(this.stream.getTracks().forEach(t=>t.stop()),this.stream=null),this.mediaRecorder=null,this.audioChunks=[]}}function xu(e){const[t,r]=u.useState(!1),[a,s]=u.useState(!1),[i,o]=u.useState(0),[l,c]=u.useState(0),[d,h]=u.useState(null),f=u.useRef(null),p=u.useRef(null),y=u.useRef(0),m=u.useRef(null),x=u.useRef(null),b=u.useCallback(()=>{m.current&&(clearInterval(m.current),m.current=null),x.current&&(clearTimeout(x.current),x.current=null)},[]),g=u.useCallback(async()=>{if(!e.activeLayer){e.showToast("Select a layer to record.","error");return}t||(f.current||(f.current=new Da),y.current=p.current??e.currentTime,r(!0),o(0),await f.current.startRecording({onLevel:o}))},[e,t]),S=u.useCallback(async()=>{var $;if(b(),s(!1),c(0),p.current=null,!f.current){r(!1),o(0);return}const M=await f.current.stopRecording();if(r(!1),o(0),!M||!e.activeLayer)return;const{waveform:T,duration:N,buffer:j}=await e.blobToWaveform(M),R=e.activeLayer.id;e.setWaveforms(O=>({...O,[R]:T}));const z=Math.max(0,y.current||0),A={id:Date.now(),label:"Recording",start:z,duration:N,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:($=e.layerSettings[R])==null?void 0:$.color,blob:M,blobUrl:URL.createObjectURL(M),audioBuffer:j};e.setLayerClips(O=>({...O,[R]:[...O[R]||[],A]})),e.upsertEngineClip(R,A),e.setSelectedClip({layerId:R,clipId:A.id})},[e,b]),v=u.useCallback(M=>{if(M<=0){g();return}s(!0),c(M);const T=performance.now();m.current=window.setInterval(()=>{const N=(performance.now()-T)/1e3;c(Math.max(0,M-N))},100),x.current=window.setTimeout(()=>{b(),s(!1),c(0),p.current||g()},M*1e3)},[g,b]),k=u.useCallback(async()=>{if(t||a){await S();return}if(!e.activeLayer){e.showToast("Select a layer before recording","error");return}const M=Math.max(0,e.countInBars)*4*(60/e.bpm),T=e.punchIn!=null&&e.punchIn>e.currentTime?e.punchIn:null;T&&(p.current=T),e.overdubEnabled&&!e.isPlaying&&e.playEngine(),T?M>0&&v(M):v(M)},[t,a,e,S,v]);return{isRecording:t,isCountIn:a,monitorLevel:i,countInRemaining:l,punchOut:d,setPunchOut:h,armedPunchInRef:p,recorderRef:f,clearCountInTimers:b,startRecordingNow:g,stopRecordingFlow:S,handleRecord:k}}var Qi=(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))(Qi||{});const Su={};class Xn{constructor(t,r,a,s={}){this.type=t,this.name=r,this.component=Su[t]??(()=>null),this.audioType=a,this.parameters=s}}new Xn("Recorder","Recorder","vocal",{deviceId:"",gain:1,sensitivity:"high"}),new Xn("Audio Clip","Audio Clip","instrumental",{clipId:null,octave:"4"}),new Xn("Speech Synth","Speech Synth","vocal",{text:"",voice:"default"}),new Xn("Keyboard/Pads","Keyboard","instrumental",{instrument:"piano",preset:"default",velocity:100});function Ji(e,t,r,a,s){r(i=>t?[...i,t]:i),a([]),s(e)}function ku(e,t,r,a){t(s=>{if(s.length===0)return s;const i=s[s.length-1];return r(o=>e?[e,...o]:o),a(i),s.slice(0,-1)})}function wu(e,t,r,a){r(s=>{if(s.length===0)return s;const i=s[0];return t(o=>e?[...o,e]:o),a(i),s.slice(1)})}class Cu{constructor(t={}){this.undoStack=[],this.redoStack=[],this.maxSize=t.maxSize??100,this.onChange=t.onChange}push(t,r,a,s){this.undoStack.push({label:t,category:r,timestamp:Date.now(),oldState:a,newState:s}),this.undoStack.length>this.maxSize&&this.undoStack.shift(),this.redoStack.length=0}undo(){var r;const t=this.undoStack.pop();return t?(this.redoStack.push(t),(r=this.onChange)==null||r.call(this,t,"undo"),t.oldState):null}redo(){var r;const t=this.redoStack.pop();return t?(this.undoStack.push(t),(r=this.onChange)==null||r.call(this,t,"redo"),t.newState):null}get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}get undoLabel(){return this.undoStack.length>0?this.undoStack[this.undoStack.length-1].label:null}get redoLabel(){return this.redoStack.length>0?this.redoStack[this.redoStack.length-1].label:null}get undoCount(){return this.undoStack.length}get redoCount(){return this.redoStack.length}getHistory(){return[...this.undoStack].reverse()}clear(){this.undoStack.length=0,this.redoStack.length=0}undoTo(t){const r=Math.min(t+1,this.undoStack.length);let a=null;for(let s=0;s<r;s++)a=this.undo();return a}}const ju=it.scoped("useProjectCRUD");function Mu(e){const{project:t,activeSection:r,setProject:a,setActiveSection:s,setLayers:i,setActiveLayer:o,setUndoStack:l,setRedoStack:c}=e,d=u.useCallback(b=>Ji(b,t,l,c,a),[t,l,c,a]),h=u.useCallback(async()=>{var v;if(!t)return;const b=(((v=t.sections)==null?void 0:v.length)??0)+1,S={id:await e.addSection(t.id,"Section",b),projectId:t.id,name:"Section",orderNumber:b,layers:[]};d({...t,sections:[...t.sections||[],S]}),s(S)},[t,d,s]),f=u.useCallback(async b=>{var v,k,M;if(!t||!await e.confirm("Delete this section?"))return;await e.deleteSection(b);const S=(t.sections??[]).filter(T=>T.id!==b);d({...t,sections:S}),s(S[0]??null),i(((v=S[0])==null?void 0:v.layers)??[]),o(((M=(k=S[0])==null?void 0:k.layers)==null?void 0:M[0])??null)},[t,d,s,i,o,e]),p=u.useCallback(async()=>{var g;if(!r)return;const b={id:-Date.now(),name:"New Layer",sectionId:r.id,audioSource:Qi.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};i(S=>[...S,b]),o(b);try{const S=await e.addLayer(r.id,b.name,b.audioSource,b.audioSourceParameters);i(v=>v.map(k=>k.id===b.id?{...b,id:S}:k)),t&&d({...t,sections:((g=t.sections)==null?void 0:g.map(v=>v.id===r.id?{...v,layers:[...(v.layers??[]).filter(k=>k.id!==S),{...b,id:S}]}:v))??[]})}catch(S){i(v=>v.filter(k=>k.id!==b.id)),ju.error("Failed to add layer:",S)}},[r,t,d,i,o]),y=u.useCallback(async b=>{var S,v;if((S=e.layerSettings[b])!=null&&S.locked){e.showToast("Layer is locked. Unlock to delete.","error");return}await e.confirm("Delete this layer?")&&((e.layerClips[b]||[]).forEach(k=>e.removeEngineClip(b,k.id)),e.setLayerMidiNotes(k=>{const M={...k};return delete M[b],M}),await e.deleteLayer(b),i(k=>k.filter(M=>M.id!==b)),o(k=>(k==null?void 0:k.id)===b?null:k),t&&d({...t,sections:((v=t.sections)==null?void 0:v.map(k=>k.id===(r==null?void 0:r.id)?{...k,layers:(k.layers??[]).filter(M=>M.id!==b)}:k))??[]}))},[t,r,d,i,o,e]),m=u.useCallback(async()=>{if(!t)return;const b=e.projectVolume===""?void 0:Number(e.projectVolume);if(Number.isNaN(b)){e.setStatusType("error"),e.setStatusMessage("Volume musi byc liczba");return}if(!e.projectName.trim()){e.setStatusType("error"),e.setStatusMessage("Nazwa projektu nie moze byc pusta");return}await e.updateProject(t.id,{name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:b}),d({...t,name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:b}),e.setStatusType("success"),e.setStatusMessage("Project saved")},[t,e,d]),x=u.useCallback(async()=>{var S;if(!r)return;const b=e.sectionName||r.name,g=e.sectionOrder===""?r.orderNumber:Number(e.sectionOrder);if(!b.trim()){e.setStatusType("error"),e.setStatusMessage("Section name cannot be empty");return}if(Number.isNaN(g)){e.setStatusType("error"),e.setStatusMessage("Order musi byc liczba");return}await e.updateSection(r.id,{name:b,orderNumber:g}),s({...r,name:b,orderNumber:g}),t&&d({...t,sections:((S=t.sections)==null?void 0:S.map(v=>v.id===r.id?{...v,name:b,orderNumber:g}:v))??[]}),e.setStatusType("success"),e.setStatusMessage("Section saved")},[r,t,e,d,s]);return{handleAddSection:h,handleDeleteSection:f,handleAddLayer:p,handleDeleteLayer:y,handleSaveProject:m,handleSaveSection:x}}const eo=u.createContext(null);function Ru(){const e=u.useContext(eo);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const za=({value:e,children:t})=>n.jsx(eo.Provider,{value:e,children:t});za.displayName="EditorTrackProvider";const cn=(e,t)=>t&&t>0?e*15/t:e/10,_a=e=>{for(const t of e){const r=t.trim();if(r.toUpperCase().startsWith("#BPM:")){const a=parseFloat(r.substring(5).replace(",","."));if(isFinite(a)&&a>0)return a}}return null},Nu=(e,t)=>{const r=t??_a(e),a=[];let s="",i=0,o="",l=!0;function c(){o.trim()!==""&&(s.length>0&&(s+=" "),s+=o.trim()),o=""}return e.forEach(d=>{if(!(d.startsWith("#")||d.startsWith("E"))){if(d.startsWith("-"))c(),s.trim().length>0&&(a.push({text:s.trim(),timestamp:i}),s=""),l=!0;else if(d.startsWith(":")||d.startsWith("*")){const h=d.indexOf(" "),f=d.indexOf(" ",h+1),p=d.indexOf(" ",f+1),y=d.indexOf(" ",p+1);if(y===-1)return;const m=cn(parseFloat(d.substring(h+1,f)),r);s===""&&(i=m);const x=d.substring(y+1);if(x.trim()==="~")return;let b=x;b.startsWith("~")&&(b=b.substring(1)),l?(c(),o=b.trimEnd()):o+=b.trimEnd(),l=x.endsWith(" ")}}}),c(),s.trim().length>0&&a.push({text:s.trim(),timestamp:i}),a},Tu=(e,t)=>{const r=t??_a(e),a=[];let s=[],i="",o=0,l=!0,c=null,d="";function h(){c&&d.trim()!==""&&(c.text=d.trim(),s.push({...c}),i.length>0&&(i+=" "),i+=c.text),c=null,d=""}return e.forEach(f=>{if(!(f.startsWith("#")||f.startsWith("E"))){if(f.startsWith("-"))h(),i.trim().length>0&&(a.push({text:i.trim(),timestamp:o,words:s}),i="",s=[]),l=!0;else if(f.startsWith(":")||f.startsWith("*")){const p=f.startsWith("*"),y=f.indexOf(" "),m=f.indexOf(" ",y+1),x=f.indexOf(" ",m+1),b=f.indexOf(" ",x+1);if(b===-1)return;const g=cn(parseFloat(f.substring(y+1,m)),r),S=cn(parseFloat(f.substring(m+1,x)),r),v=g+S;i===""&&(o=g);const k=f.substring(b+1);if(k.trim()==="~"){c&&(c.endTime=v);return}let M=k;M.startsWith("~")&&(M=M.substring(1)),l?(h(),d=M.trimEnd(),c={text:"",startTime:g,endTime:v,isGolden:p}):c?(d+=M.trimEnd(),c.endTime=v,p&&(c.isGolden=!0)):(d=M.trimEnd(),c={text:"",startTime:g,endTime:v,isGolden:p}),l=k.endsWith(" ")}}}),h(),i.trim().length>0&&a.push({text:i.trim(),timestamp:o,words:s}),a},to=(e,t)=>{const r=t??_a(e),a=[];let s=[],i=0;function o(){s.length>0&&(a.push({timestamp:i,syllables:[...s]}),s=[])}return e.forEach(l=>{if(!(l.startsWith("#")||l.startsWith("E"))){if(l.startsWith("-")){o();const c=l.trim().split(/\s+/);if(c.length>=2){const d=parseFloat(c[1]);isFinite(d)&&(i=cn(d,r))}}else if(l.startsWith(":")||l.startsWith("*")){const c=l.startsWith("*"),d=l.indexOf(" "),h=l.indexOf(" ",d+1),f=l.indexOf(" ",h+1),p=l.indexOf(" ",f+1);if(p===-1)return;const y=parseFloat(l.substring(d+1,h)),m=parseFloat(l.substring(h+1,f)),x=cn(y,r),b=x+cn(m,r);s.length===0&&(i=x);const g=l.substring(p+1);if(g.trim()==="~"){s.length>0&&(s[s.length-1].endTime=b);return}let S=g;S.startsWith("~")&&(S=S.substring(1));const v=g.endsWith(" "),k=v?S.slice(0,-1):S;s.push({text:k,startTime:x,endTime:b,isGolden:c,hasTrailingSpace:v})}}}),o(),a},$u=(e,t,r=3)=>{const a=[];let s=-1;for(let i=0;i<e.length;i++){const o=e[i].timestamp,l=e[i+1]?e[i+1].timestamp:o+5;if(t>=o&&t<l){s=i;break}}if(s>=0){const i=Math.max(0,s-(r-1));for(let o=i;o<=s;o++)a.push(e[o].text)}return a},Pu=(e,t)=>{const r=[];for(const a of e)for(const s of a.words)t>=s.startTime&&t<=s.endTime&&r.push(s);return r},Ts="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",$s="var(--karaoke-gold-glow-first, 0 0 12px #FFD700)",Eu="var(--karaoke-active-glow, 0 0 10px rgba(0,229,255,0.6), 0 0 4px rgba(255,230,0,0.4))",Au="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",Iu=({song:e,currentTime:t=0})=>{const r=u.useMemo(()=>!e||!e.notes.length?[]:to(e.notes.map(l=>l.noteLine),e.bpm??void 0),[e]),a=t-((e==null?void 0:e.gap)??0)/1e3;let s=-1;for(let l=0;l<r.length;l++){const c=r[l].timestamp,d=l+1<r.length?r[l+1].timestamp:c+30;if(a>=c&&a<d){s=l;break}}const i=s>=0?r[s]:null,o=s>=0&&s+1<r.length?r[s+1]:null;return n.jsx("div",{className:"karaoke-lyrics",style:{textAlign:"center",fontSize:"28px",marginTop:"20px",minHeight:"80px",textShadow:"var(--karaoke-outline, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000)",fontWeight:700,fontStyle:"italic",fontFamily:"var(--karaoke-font-family, Arial)"},children:i?n.jsxs(n.Fragment,{children:[n.jsx("p",{style:{color:"var(--karaoke-primary-text, #fff)",margin:"5px 0",lineHeight:1.4,textShadow:Eu,background:"var(--karaoke-active-bg, linear-gradient(90deg, transparent 0%, rgba(0,229,255,0.08) 20%, rgba(255,230,0,0.06) 80%, transparent 100%))",borderRadius:8,padding:"2px 10px",transition:"text-shadow 0.3s ease, background 0.3s ease"},children:i.syllables.map((l,c)=>{let d=0;a>=l.endTime?d=1:a>l.startTime&&(d=(a-l.startTime)/(l.endTime-l.startTime));const h=Math.round(d*100),f=l.text+(l.hasTrailingSpace?" ":""),p=d>0&&d<1,y=l.isGolden;return d<=0?n.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",transition:"color 0.15s ease"},children:f},c):d>=1?n.jsx("span",{style:{background:y?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Ts,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:y?`drop-shadow(${$s})`:"none",transition:"filter 0.2s ease"},children:f},c):n.jsxs("span",{style:{position:"relative",display:"inline",filter:p?y?`drop-shadow(${$s})`:`drop-shadow(${Au})`:"none",transition:"filter 0.15s ease"},children:[n.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",visibility:"visible"},children:f}),n.jsx("span",{style:{position:"absolute",left:0,top:0,background:y?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Ts,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",clipPath:`inset(0 ${100-h}% 0 0)`,pointerEvents:"none"},children:f})]},c)})}),o&&n.jsx("p",{style:{color:"var(--karaoke-next-text, #666)",margin:"5px 0",lineHeight:1.4,fontSize:"22px",transition:"opacity 0.3s ease"},children:o.syllables.map((l,c)=>n.jsx("span",{style:{color:l.isGolden?"var(--karaoke-golden-next, rgba(255,215,0,0.5))":"var(--karaoke-next-dim, #777)"},children:l.text+(l.hasTrailingSpace?" ":"")},c))})]}):r.length>0?n.jsx("p",{style:{color:"var(--karaoke-waiting-text, #999)"},children:n.jsx(G.NtdMusic,{size:20})}):n.jsxs("p",{style:{color:"var(--karaoke-waiting-text, #999)",display:"inline-flex",alignItems:"center",gap:6},children:[n.jsx(G.NtdMicrophone,{size:18})," Waiting for lyrics..."]})})},Fa=u.memo(Iu),Zr={},Lu=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:bt&&bt.tagName.toUpperCase()==="SCRIPT"&&bt.src||new URL("index.cjs",document.baseURI).href}<"u"&&(Zr==null?void 0:Zr.VITE_DEBUG_KARAOKE)==="true";function da(e,t,...r){(Lu||typeof window<"u"&&window.DEBUG_KARAOKE)&&console.log(`%c[KARAOKE-DEBUG]%c [${e}] ${t}`,"background:var(--nice-color-accent-hover, #6c3483);color:var(--nice-text-on-primary, #FFF);padding: var(--nice-space-px, 1px) var(--nice-space-1, 4px);border-radius:var(--nice-radius-sm, 3px);font-weight:bold","color:var(--nice-color-accent-hover, #6c3483);font-weight:bold",...r)}const no=e=>{for(const t of e){const r=t.trim();if(r.toUpperCase().startsWith("#BPM:")){const a=parseFloat(r.substring(5).replace(",","."));if(isFinite(a)&&a>0)return a}}return null},Ps=(e,t)=>t&&t>0?e*15/t:e/10,Hn=(e,t)=>{const r=t??no(e),a=[];let s=[];return e.forEach(i=>{const o=i.split(" ");if(!(o.length<4))if(i.startsWith("-"))s.length>0&&(a.push(s),s=[]);else{const l=(o[0]||"").charAt(0),c=l==="*"||l==="G";s.push({startTime:Ps(parseFloat(o[1]),r),duration:Ps(parseFloat(o[2]),r),pitch:parseInt(o[3],10),isGold:c})}}),s.length>0&&a.push(s),a},ro=(e,t)=>{let a=(Math.round(12*Math.log2(e/440)+69)%12+12)%12;if(t!==null){for(;a-t>6;)a-=12;for(;a-t<-6;)a+=12}return a},Du=it.scoped("karaokeScoringConfig"),Oa={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}},zu="karaoke.scoringPresets";function _u(){try{const e=localStorage.getItem(zu);return e?JSON.parse(e):null}catch(e){return Du.warn("Failed to parse scoring presets overrides",e),null}}function ao(e){const t={...Oa},r=_u();return r&&Object.keys(r).forEach(a=>{const s=r[a];s&&(t[a]={...t[a],...s})}),e&&Object.keys(e).forEach(a=>{const s=e[a];s&&(t[a]={...t[a],...s})}),t}exports.ScoringPresets=ao();const Fu=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=ao(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},zr=(e="normal")=>exports.ScoringPresets[e]||Oa.normal,Ou=3,te=Ou;function qt(e){const t=e/2|0;return{w:t,out:`M${t} 0H${t}V${e}H${t}A${t} ${t} 0 0 1 0 ${t}A${t} ${t} 0 0 1 ${t} 0Z`,inn:`M${t} ${te}V${e-te}A${t-te} ${t-te} 0 0 1 ${te} ${t}A${t-te} ${t-te} 0 0 1 ${t} ${te}Z`}}function dn(e){return{w:te+1,out:`M0 0H${te+1}V${e}H0Z`,inn:`M${te} ${te}H${te+1}V${e-te}H${te}Z`}}function Ba(e){const t=Math.min(14,e*.22)|0,r=t+2,a=Math.max(t-te,1);return{w:r,out:`M${t} 0H${r}V${e}H${t}Q0 ${e} 0 ${e-t}V${t}Q0 0 ${t} 0Z`,inn:`M${te+a} ${te}H${r}V${e-te}H${te+a}Q${te} ${e-te} ${te} ${e-te-a}V${te+a}Q${te} ${te} ${te+a} ${te}Z`}}function Mr(e){const t=e*.3|0,r=t+2,a=Math.max(t-te,1);return{w:r,out:`M${t} 0H${r}V${e}H${t}L0 ${e-t}V${t}Z`,inn:`M${te+a} ${te}H${r}V${e-te}H${te+a}L${te} ${e-te-a}V${te+a}Z`}}function Ft(e){const t=e*.42|0,r=t+2,a=Math.max(t-(te*1.4|0),2);return{w:r,out:`M${t} 0H${r}V${e}H${t}L0 ${e/2}Z`,inn:`M${te+a} ${te}H${r}V${e-te}H${te+a}L${te} ${e/2}Z`}}function Rr(e){const t=e*.3|0,r=t+4,a=Math.max(t-te,1);return{w:r,out:`M${t} 0H${r}V${e}H${t*.6|0}L0 ${e-t}V${t}Q0 0 ${t} 0Z`,inn:`M${te+a} ${te}H${r}V${e-te}H${te+(a*.6|0)}L${te} ${e-te-a}V${te+a}Q${te} ${te} ${te+a} ${te}Z`}}function Ga(e){const t=e*.16|0,r=t*2+4;return{w:r,out:`M${t*1.5|0} 0H${r}V${e}H${t*1.5|0}C${t*2.5|0} ${e*.35|0} ${t*2.5|0} ${e*.65|0} ${t*1.5|0} ${e}Z`,inn:`M${te+(t*1.2|0)} ${te}H${r}V${e-te}H${te+(t*1.2|0)}C${te+(t*2.2|0)} ${e*.37|0} ${te+(t*2.2|0)} ${e*.63|0} ${te+(t*1.2|0)} ${e-te}Z`}}function Wa(e){const t=e*.32|0,r=t+3,a=Math.max(t-te,1);return{w:r,out:`M0 0H${r}V${e}H${t}Q0 ${e} 0 ${e-t}Z`,inn:`M${te} ${te}H${r}V${e-te}H${te+a}Q${te} ${e-te} ${te} ${e-te-a}Z`}}function Nr(e){const t=e*.14|0,r=t*3+2;return{w:r,out:`M${t*2} 0H${r}V${e}H${t*2}C${t*.5|0} ${e*.8|0} ${t*3} ${e*.55|0} ${t*.5|0} ${e*.35|0}S${t} 0 ${t*2} 0Z`,inn:`M${te+(t*1.8|0)} ${te}H${r}V${e-te}H${te+(t*1.8|0)}C${te+(t*.4|0)} ${e*.78|0} ${te+(t*2.8|0)} ${e*.55|0} ${te+(t*.4|0)} ${e*.37|0}S${te+(t*.9|0)} ${te} ${te+(t*1.8|0)} ${te}Z`}}function Ua(e){const t=e*.09|0,r=e*.35|0;return{w:r,out:`M${t*3} 0H${r}V${e}H${t*3}L${t} ${e-t*2}L${t*2} ${e*.65|0}L0 ${e/2|0}L${t*2} ${e*.35|0}L${t} ${t*2}Z`,inn:`M${te+(t*2.5|0)} ${te}H${r}V${e-te}H${te+(t*2.5|0)}L${te+(t*.7|0)} ${e-te-(t*1.6|0)}L${te+(t*1.7|0)} ${e*.64|0}L${te} ${e/2|0}L${te+(t*1.7|0)} ${e*.36|0}L${te+(t*.7|0)} ${te+(t*1.6|0)}Z`}}function hr(e){const t=e*.42|0,r=t+2;return{w:r,out:`M${t} 0H${r}V${e}H0Z`,inn:`M${te+t-(te*1.3|0)} ${te}H${r}V${e-te}H${te+1}Z`}}function ua(e){const t=e*.42|0,r=t+2;return{w:r,out:`M0 0H${r}V${e}H${t}Z`,inn:`M${te} ${te}H${r}V${e-te}H${te+t-(te*1.3|0)+1}Z`}}function zt(e){const t=e/2|0;return{w:t,out:`M0 0A${t} ${t} 0 0 1 ${t} ${t}A${t} ${t} 0 0 1 0 ${e}Z`,inn:`M0 ${te}A${t-te} ${t-te} 0 0 1 ${t-te} ${t}A${t-te} ${t-te} 0 0 1 0 ${e-te}Z`}}function un(e){return{w:te+1,out:`M0 0H${te+1}V${e}H0Z`,inn:`M0 ${te}H1V${e-te}H0Z`}}function so(e){const t=Math.min(14,e*.22)|0,r=t+2,a=Math.max(t-te,1);return{w:r,out:`M0 0H${r-t}Q${r} 0 ${r} ${t}V${e-t}Q${r} ${e} ${r-t} ${e}H0Z`,inn:`M0 ${te}H${r-te-a}Q${r-te} ${te} ${r-te} ${te+a}V${e-te-a}Q${r-te} ${e-te} ${r-te-a} ${e-te}H0Z`}}function hn(e){const t=e*.3|0,r=t+2,a=Math.max(t-te,1);return{w:r,out:`M0 0H${r-t}L${r} ${t}V${e-t}L${r-t} ${e}H0Z`,inn:`M0 ${te}H${r-te-a}L${r-te} ${te+a}V${e-te-a}L${r-te-a} ${e-te}H0Z`}}function Nt(e){const t=e*.42|0,r=t+2,a=Math.max(t-(te*1.4|0),2);return{w:r,out:`M0 0H${r-t}L${r} ${e/2}L${r-t} ${e}H0Z`,inn:`M0 ${te}H${r-te-a}L${r-te} ${e/2}L${r-te-a} ${e-te}H0Z`}}function io(e){const t=e*.3|0,r=t+4,a=Math.max(t-te,1);return{w:r,out:`M0 0H${r-t}Q${r} 0 ${r} ${t}V${e-t}L${r-(t*.6|0)} ${e}H0Z`,inn:`M0 ${te}H${r-te-a}Q${r-te} ${te} ${r-te} ${te+a}V${e-te-a}L${r-te-(a*.6|0)} ${e-te}H0Z`}}function oo(e){const t=e*.16|0,r=t*2+4;return{w:r,out:`M0 0H${r-(t*1.5|0)}C${r-(t*2.5|0)} ${e*.35|0} ${r-(t*2.5|0)} ${e*.65|0} ${r-(t*1.5|0)} ${e}H0Z`,inn:`M0 ${te}H${r-te-(t*1.2|0)}C${r-te-(t*2.2|0)} ${e*.37|0} ${r-te-(t*2.2|0)} ${e*.63|0} ${r-te-(t*1.2|0)} ${e-te}H0Z`}}function lo(e){const t=e*.32|0,r=t+3,a=Math.max(t-te,1);return{w:r,out:`M0 0H${r}V${e-t}Q${r} ${e} ${r-t} ${e}H0Z`,inn:`M0 ${te}H${r-te}V${e-te-a}Q${r-te} ${e-te} ${r-te-a} ${e-te}H0Z`}}function Va(e){const t=e*.14|0,r=t*3+2;return{w:r,out:`M0 0H${r-t*2}C${r-t} 0 ${r+(t*.3|0)} ${e*.2|0} ${r-(t*.5|0)} ${e*.35|0}S${r-(t*.5|0)} ${e*.8|0} ${r-t*2} ${e}H0Z`,inn:`M0 ${te}H${r-te-(t*1.8|0)}C${r-te-(t*.9|0)} ${te} ${r-te+(t*.1|0)} ${e*.22|0} ${r-te-(t*.4|0)} ${e*.37|0}S${r-te-(t*.4|0)} ${e*.78|0} ${r-te-(t*1.8|0)} ${e-te}H0Z`}}function Tr(e){const t=e*.09|0,r=e*.35|0;return{w:r,out:`M0 0H${r-t*3}L${r-t} ${t*2}L${r-t*2} ${e*.35|0}L${r} ${e/2|0}L${r-t*2} ${e*.65|0}L${r-t} ${e-t*2}L${r-t*3} ${e}H0Z`,inn:`M0 ${te}H${r-te-(t*2.5|0)}L${r-te-(t*.7|0)} ${te+(t*1.6|0)}L${r-te-(t*1.7|0)} ${e*.36|0}L${r-te} ${e/2|0}L${r-te-(t*1.7|0)} ${e*.64|0}L${r-te-(t*.7|0)} ${e-te-(t*1.6|0)}L${r-te-(t*2.5|0)} ${e-te}H0Z`}}function ha(e){const t=e*.42|0,r=t+2;return{w:r,out:`M0 0H${r}L${r-t} ${e}H0Z`,inn:`M0 ${te}H${r-te}L${r-te-t+(te*1.3|0)} ${e-te}H0Z`}}function pr(e){const t=e*.42|0,r=t+2;return{w:r,out:`M0 0H${r-t}L${r} ${e}H0Z`,inn:`M0 ${te}H${r-te-t+(te*1.3|0)}L${r-te} ${e-te}H0Z`}}const qa=[{name:"Pill",L:qt,R:zt},{name:"Sharp",L:dn,R:un},{name:"Soft",L:Ba,R:so},{name:"Chamfer",L:Mr,R:hn},{name:"Arrow",L:Ft,R:Nt},{name:"Shield",L:Rr,R:io},{name:"Bracket",L:Ga,R:oo},{name:"Tab",L:Wa,R:lo},{name:"Wave",L:Nr,R:Va},{name:"Ornate",L:Ua,R:Tr}],co=[{name:"Pill→Arrow",L:qt,R:Nt},{name:"Arrow→Pill",L:Ft,R:zt},{name:"Pill→Sharp",L:qt,R:un},{name:"Sharp→Pill",L:dn,R:zt},{name:"Pill→Chamfer",L:qt,R:hn},{name:"Chamfer→Pill",L:Mr,R:zt},{name:"Arrow→Sharp",L:Ft,R:un},{name:"Sharp→Arrow",L:dn,R:Nt},{name:"Arrow→Chamfer",L:Ft,R:hn},{name:"Chamfer→Arrow",L:Mr,R:Nt},{name:"Soft→Arrow",L:Ba,R:Nt},{name:"Shield→Chamfer",L:Rr,R:hn},{name:"Pill→Wave",L:qt,R:Va},{name:"Wave→Arrow",L:Nr,R:Nt},{name:"Tab→Pill",L:Wa,R:zt},{name:"Ornate→Sharp",L:Ua,R:un},{name:"Sharp→Ornate",L:dn,R:Tr},{name:"Bracket→Arrow",L:Ga,R:Nt},{name:"Shield→Pill",L:Rr,R:zt},{name:"Wave→Ornate",L:Nr,R:Tr}],uo=[{name:"Skew ╲",L:hr,R:ha},{name:"Skew ╱",L:ua,R:pr},{name:"◇ Romb",L:Ft,R:Nt},{name:"╲→Pill",L:hr,R:zt},{name:"Pill→╲",L:qt,R:ha},{name:"╱→Sharp",L:ua,R:un},{name:"Sharp→╱",L:dn,R:pr},{name:"╲→Arrow",L:hr,R:Nt},{name:"Arrow→╱",L:Ft,R:pr},{name:"◇→Chamfer",L:Ft,R:hn}],Wn=[...qa,...co,...uo],ho=qa[0];function Rn(e){return Wn.find(t=>t.name===e)||ho}const $r=[{name:"Flames",mk:(e,t,r)=>{const a=r||t;return`<pattern id="${e}" width="12" height="16" patternUnits="userSpaceOnUse"><path d="M6 0C8 3 10 5 9 9C8 12 6 14 6 16C6 14 4 12 3 9C2 5 4 3 6 0Z" fill="${t}" opacity=".5"/><path d="M3 6C4 8 5 10 3 14C1 10 2 8 3 6Z" fill="${a}" opacity=".3"/><path d="M9 6C10 8 11 10 9 14C7 10 8 8 9 6Z" fill="${a}" opacity=".3"/></pattern>`}},{name:"Zigzag",mk:(e,t,r)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M0 5L5 0L10 5L5 10Z" fill="${r||t}" fill-opacity=".15" stroke="${t}" stroke-width="1.2" opacity=".55"/></pattern>`},{name:"Scales",mk:(e,t,r)=>{const a=r||t;return`<pattern id="${e}" width="12" height="8" patternUnits="userSpaceOnUse"><ellipse cx="6" cy="8" rx="6" ry="4.5" fill="none" stroke="${t}" stroke-width="1" opacity=".5"/><ellipse cx="0" cy="4" rx="6" ry="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".3"/><ellipse cx="12" cy="4" rx="6" ry="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".3"/></pattern>`}},{name:"Hex",mk:(e,t,r)=>`<pattern id="${e}" width="18" height="20" patternUnits="userSpaceOnUse"><path d="M9 2L16 6V14L9 18L2 14V6Z" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M9 12L13.5 14.5V19L9 21.5L4.5 19V14.5Z" fill="none" stroke="${r||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Dots",mk:(e,t,r)=>{const a=r||t;return`<pattern id="${e}" width="8" height="8" patternUnits="userSpaceOnUse"><circle cx="4" cy="4" r="2" fill="${t}" opacity=".5"/><circle cx="0" cy="0" r="1" fill="${a}" opacity=".3"/><circle cx="8" cy="8" r="1" fill="${a}" opacity=".3"/></pattern>`}},{name:"Stars",mk:(e,t,r)=>`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M7 1L8.8 5.2L13.2 5.2L9.7 7.8L11 12.2L7 9.4L3 12.2L4.3 7.8L.8 5.2L5.2 5.2Z" fill="${t}" opacity=".45" stroke="${r||t}" stroke-width=".4" stroke-opacity=".3"/></pattern>`},{name:"Diamonds",mk:(e,t,r)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M5 .5L9.5 5L5 9.5L.5 5Z" fill="${r||"none"}" fill-opacity=".15" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Waves",mk:(e,t,r)=>`<pattern id="${e}" width="16" height="8" patternUnits="userSpaceOnUse"><path d="M0 4Q4 0 8 4Q12 8 16 4" fill="none" stroke="${t}" stroke-width="1.3" opacity=".5"/><path d="M0 6Q4 2 8 6Q12 10 16 6" fill="none" stroke="${r||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Crosses",mk:(e,t,r)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M5 2V8" stroke="${t}" stroke-width="1.3" stroke-linecap="round" opacity=".5"/><path d="M2 5H8" stroke="${r||t}" stroke-width="1.3" stroke-linecap="round" opacity=".5"/></pattern>`},{name:"Triangles",mk:(e,t,r)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M6 1L11 9H1Z" fill="${r||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Chevrons",mk:(e,t,r)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M0 7L6 1.5L12 7" fill="none" stroke="${t}" stroke-width="1.2" opacity=".55"/><path d="M0 10L6 4.5L12 10" fill="none" stroke="${r||t}" stroke-width=".7" opacity=".25"/></pattern>`},{name:"Hatch ╲",mk:(e,t,r)=>`<pattern id="${e}" width="6" height="6" patternUnits="userSpaceOnUse"><path d="M0 6L6 0" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M-1 1L1 -1M5 7L7 5" stroke="${r||t}" stroke-width=".8" opacity=".3"/></pattern>`},{name:"Hatch ╳",mk:(e,t,r)=>`<pattern id="${e}" width="7" height="7" patternUnits="userSpaceOnUse"><path d="M0 7L7 0" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M0 0L7 7" stroke="${r||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Grid",mk:(e,t,r)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M10 0V10" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M0 10H10" fill="none" stroke="${r||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Bricks",mk:(e,t,r)=>`<pattern id="${e}" width="14" height="8" patternUnits="userSpaceOnUse"><rect width="14" height="8" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><line x1="7" y1="0" x2="7" y2="4" stroke="${r||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Hearts",mk:(e,t,r)=>`<pattern id="${e}" width="12" height="12" patternUnits="userSpaceOnUse"><path d="M6 10C4 8 1 6.5 1 4C1 2.3 2.8 1 4.5 2.2L6 4L7.5 2.2C9.2 1 11 2.3 11 4C11 6.5 8 8 6 10Z" fill="${t}" opacity=".4" stroke="${r||t}" stroke-width=".5" stroke-opacity=".3"/></pattern>`},{name:"Arrows",mk:(e,t,r)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M3 2L9 5L3 8" fill="${r||"none"}" fill-opacity=".15" stroke="${t}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity=".5"/></pattern>`},{name:"Bolts",mk:(e,t,r)=>`<pattern id="${e}" width="12" height="16" patternUnits="userSpaceOnUse"><path d="M7 1L4 7H8L3 15" fill="none" stroke="${t}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity=".5"/><circle cx="5" cy="11" r="1" fill="${r||t}" opacity=".3"/></pattern>`},{name:"Leaves",mk:(e,t,r)=>{const a=r||t;return`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M7 2C10 4 12 7 10 11C8 13 5 12 4 10C3 7 4 4 7 2Z" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M7 3L6 10" stroke="${a}" stroke-width=".6" opacity=".3"/><path d="M5 5L7 6M5 8L7 7.5" stroke="${a}" stroke-width=".4" opacity=".25"/></pattern>`}},{name:"Spirals",mk:(e,t,r)=>`<pattern id="${e}" width="16" height="16" patternUnits="userSpaceOnUse"><path d="M8 4A4 4 0 0 1 12 8A3.5 3.5 0 0 1 8.5 11.5A2.5 2.5 0 0 1 6 9A1.5 1.5 0 0 1 7.5 7.5" fill="none" stroke="${t}" stroke-width="1.2" stroke-linecap="round" opacity=".45"/><circle cx="8" cy="8" r="1" fill="${r||t}" opacity=".25"/></pattern>`},{name:"Moons",mk:(e,t,r)=>`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M9 2A5 5 0 1 0 9 12" fill="none" stroke="${t}" stroke-width="1" opacity=".4"/><path d="M9 2A3.5 3.5 0 0 1 9 12" fill="none" stroke="${r||t}" stroke-width="1" opacity=".3"/></pattern>`},{name:"Rings",mk:(e,t,r)=>`<pattern id="${e}" width="12" height="12" patternUnits="userSpaceOnUse"><circle cx="6" cy="6" r="4" fill="none" stroke="${t}" stroke-width="1.2" opacity=".5"/><circle cx="6" cy="6" r="2" fill="none" stroke="${r||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Teeth",mk:(e,t,r)=>`<pattern id="${e}" width="8" height="10" patternUnits="userSpaceOnUse"><path d="M0 10V4L4 0L8 4V10" fill="${r||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Swirl",mk:(e,t,r)=>`<pattern id="${e}" width="16" height="10" patternUnits="userSpaceOnUse"><path d="M0 5C3 0 6 0 8 5C10 10 13 10 16 5" fill="none" stroke="${t}" stroke-width="1.3" opacity=".5"/><path d="M0 7C3 2 6 2 8 7C10 12 13 12 16 7" fill="none" stroke="${r||t}" stroke-width=".6" opacity=".2"/></pattern>`},{name:"Chain",mk:(e,t,r)=>`<pattern id="${e}" width="10" height="16" patternUnits="userSpaceOnUse"><ellipse cx="5" cy="4" rx="3.5" ry="4" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><ellipse cx="5" cy="12" rx="3.5" ry="4" fill="none" stroke="${r||t}" stroke-width="1" opacity=".45"/></pattern>`},{name:"Feathers",mk:(e,t,r)=>`<pattern id="${e}" width="12" height="18" patternUnits="userSpaceOnUse"><path d="M6 1C9 5 10 9 6 17" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M6 1C3 5 2 9 6 17" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M4 5L6 4L8 5M4 9L6 8L8 9M4 13L6 12L8 13" stroke="${r||t}" stroke-width=".5" opacity=".3"/></pattern>`},{name:"DNA",mk:(e,t,r)=>`<pattern id="${e}" width="14" height="18" patternUnits="userSpaceOnUse"><path d="M3 0C3 4.5 11 4.5 11 9S3 13.5 3 18" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M11 0C11 4.5 3 4.5 3 9S11 13.5 11 18" fill="none" stroke="${r||t}" stroke-width="1" opacity=".45"/></pattern>`},{name:"Bubbles",mk:(e,t,r)=>{const a=r||t;return`<pattern id="${e}" width="18" height="18" patternUnits="userSpaceOnUse"><circle cx="5" cy="5" r="3.5" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><circle cx="14" cy="12" r="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".35"/><circle cx="11" cy="3" r="1.8" fill="${a}" opacity=".25"/></pattern>`}},{name:"Celtic",mk:(e,t,r)=>`<pattern id="${e}" width="16" height="16" patternUnits="userSpaceOnUse"><path d="M8 2C12 2 14 4 14 8C14 12 12 14 8 14C4 14 2 12 2 8C2 4 4 2 8 2Z" fill="none" stroke="${t}" stroke-width=".8" opacity=".35"/><path d="M4 4L12 12M12 4L4 12" stroke="${r||t}" stroke-width=".6" opacity=".2"/></pattern>`},{name:"Squares",mk:(e,t,r)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><rect x="1.5" y="1.5" width="7" height="7" rx="1" fill="${r||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`}];function Nn(e){return $r.find(t=>t.name===e)||null}const Gt={color:null,capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,glass:0,textureUrl:null,textureScale:1},_r={...Gt,glass:85},Fr={...Gt,patternName:"Stars"},Or={...Gt,patternName:"Stars"},Br={fontFamily:null,fontSize:18,fontColor:null,outlineColor:null,outlineWidth:0,shadow:null},po={filledBar:{...Gt},emptyBar:{..._r},goldFilledBar:{...Or},goldEmptyBar:{...Fr},font:{...Br},disableGoldNotes:!1},pn={capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,emptyGlass:85,filledTextureUrl:null,emptyTextureUrl:null,textureScale:1,emptyPreset:"custom",goldPatternName:"Stars",goldPatternColor:null,goldHitPatternName:"Stars",goldHitPatternColor:null,goldEmptyTextureUrl:null,goldFilledTextureUrl:null,fontFamily:null,fontSize:18,fontColor:null,fontOutlineColor:null,fontOutlineWidth:0,fontShadow:null},Es="nice2dev-player-bar-style",As="nice2dev-player-karaoke-settings";function fn(e){return e!=null?`${As}-${e}`:As}function Vn(e){return e!=null?`${Es}-${e}`:Es}function Is(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 Ls(e){const t=po,r=(s,i)=>!i||typeof i!="object"?{...s}:{...s,...i},a=(s,i)=>!i||typeof i!="object"?{...s}:{...s,...i};return{filledBar:r(t.filledBar,e.filledBar),emptyBar:r(t.emptyBar,e.emptyBar),goldFilledBar:r(t.goldFilledBar,e.goldFilledBar),goldEmptyBar:r(t.goldEmptyBar,e.goldEmptyBar),font:a(t.font,e.font),disableGoldNotes:typeof e.disableGoldNotes=="boolean"?e.disableGoldNotes:t.disableGoldNotes}}function Ha(e){try{const t=localStorage.getItem(fn(e));if(t){const a=JSON.parse(t);return Ls(a)}const r=localStorage.getItem(Vn(e));if(r){const a=JSON.parse(r),s=Is({...pn,...a});return localStorage.setItem(fn(e),JSON.stringify(s)),s}if(e!=null){const a=localStorage.getItem(fn());if(a)return Ls(JSON.parse(a));const s=localStorage.getItem(Vn());if(s)return Is({...pn,...JSON.parse(s)})}}catch{}return{filledBar:{...Gt},emptyBar:{..._r},goldFilledBar:{...Or},goldEmptyBar:{...Fr},font:{...Br}}}function Bu(e,t){const r=JSON.stringify(e);localStorage.setItem(fn(t),r)}let Ds=!1;async function Gu(e){if(Ds||(Ds=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(fn())||localStorage.setItem(fn(),t)}catch{}}function Wu(e){const t=new Map;for(const r of e)t.set(r,Ha(r));return t}function fo(e){try{const t=localStorage.getItem(Vn(e));if(t)return{...pn,...JSON.parse(t)};if(e!=null){const r=localStorage.getItem(Vn());if(r)return{...pn,...JSON.parse(r)}}}catch{}return{...pn}}function Uu(e,t){localStorage.setItem(Vn(t),JSON.stringify(e))}function Vu(e){const t=new Map;for(const r of e)t.set(r,fo(r));return t}const qu={"&":"&","<":"<",">":">",'"':""","'":"'"},Hu=/[&<>"']/g;function Ku(e){return e.replace(Hu,t=>qu[t])}function Yu(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 Zu=3,Qe=Zu;function Pr(e){const t=parseInt(e.slice(1,3),16)/255,r=parseInt(e.slice(3,5),16)/255,a=parseInt(e.slice(5,7),16)/255,s=Math.max(t,r,a),i=Math.min(t,r,a);let o=0,l=0;const c=(s+i)/2;if(s!==i){const d=s-i;switch(l=c>.5?d/(2-s-i):d/(s+i),s){case t:o=((r-a)/d+(r<a?6:0))/6;break;case r:o=((a-t)/d+2)/6;break;case a:o=((t-r)/d+4)/6;break}}return[Math.round(o*360),Math.round(l*100),Math.round(c*100)]}function Er(e){let t=e.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),"#"+t.toLowerCase()}function dt(e,t){return e.replace(/([MLHVCSQTAZ])/gi,`
|
|
1
|
+
"use strict";var Ec=Object.create;var gs=Object.defineProperty;var Ac=Object.getOwnPropertyDescriptor;var Ic=Object.getOwnPropertyNames;var Lc=Object.getPrototypeOf,_c=Object.prototype.hasOwnProperty;var zc=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ic(t))!_c.call(e,s)&&s!==n&&gs(e,s,{get:()=>t[s],enumerable:!(a=Ac(t,s))||a.enumerable});return e};var Hr=(e,t,n)=>(n=e!=null?Ec(Lc(e)):{},zc(t||!e||!e.__esModule?gs(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),we=require("@nice2dev/ui-core"),u=require("react"),ie=require("@nice2dev/ui"),O=require("@nice2dev/icons"),la=require("pitchy"),Pa=require("react-youtube");var bt=typeof document<"u"?document.currentScript:null;const Ti=u.createContext(null),Dc=({t:e,children:t})=>r.jsx(Ti.Provider,{value:e,children:t});function be(){const e=u.useContext(Ti),{t}=we.useNiceTranslation();return{t:u.useMemo(()=>e??((a,s)=>t(a,s??a)),[e,t])}}function Fc({componentName:e,error:t,onReset:n}){const{t:a}=be();return r.jsx("div",{className:"nice-audio-error-boundary",role:"alert",children:r.jsxs("div",{className:"nice-audio-error-boundary__content",children:[r.jsx("h3",{className:"nice-audio-error-boundary__title",children:e?a("audioErrorBoundary.componentError","{name} encountered an error").replace("{name}",e):a("audioErrorBoundary.somethingWentWrong","Something went wrong")}),r.jsx("p",{className:"nice-audio-error-boundary__message",children:t.message}),r.jsx("button",{className:"nice-audio-error-boundary__retry",onClick:n,children:a("audioErrorBoundary.tryAgain","Try Again")})]})})}class Oc 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 s,i;const a=this.props.componentName?`[${this.props.componentName}]`:"[AudioErrorBoundary]";console.error(`${a} Caught error:`,t,n),(i=(s=this.props).onError)==null||i.call(s,t,n)}render(){return this.state.hasError&&this.state.error?typeof this.props.fallback=="function"?this.props.fallback(this.state.error,this.reset):this.props.fallback?this.props.fallback:r.jsx(Fc,{componentName:this.props.componentName,error:this.state.error,onReset:this.reset}):this.props.children}}function Bc(e){if(!e)return[128,128,128];const t=e.match(/^#([0-9a-f]{3,8})$/i);if(t){let a=t[1];if(a.length===3&&(a=a[0]+a[0]+a[1]+a[1]+a[2]+a[2]),a.length>=6)return[parseInt(a.slice(0,2),16),parseInt(a.slice(2,4),16),parseInt(a.slice(4,6),16)]}const n=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);return n?[+n[1],+n[2],+n[3]]:[128,128,128]}const Kr={},ca={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function Gc(){const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:bt&&bt.tagName.toUpperCase()==="SCRIPT"&&bt.src||new URL("index.cjs",document.baseURI).href}<"u"?Kr==null?void 0:Kr.VITE_LOG_LEVEL:void 0;return e&&e in ca?e:"WARN"}const Wc=Gc();function Kn(e){return ca[e]>=ca[Wc]}function Yn(e){return`[${e}]`}const ot=(function(){return{debug(e,t,...n){Kn("DEBUG")&&console.debug(Yn(e),t,...n)},info(e,t,...n){Kn("INFO")&&console.info(Yn(e),t,...n)},warn(e,t,...n){Kn("WARN")&&console.warn(Yn(e),t,...n)},error(e,t,...n){Kn("ERROR")&&console.error(Yn(e),t,...n)},scoped(e){return{debug:(t,...n)=>ot.debug(e,t,...n),info:(t,...n)=>ot.info(e,t,...n),warn:(t,...n)=>ot.warn(e,t,...n),error:(t,...n)=>ot.error(e,t,...n)}}}})(),ys=ot.scoped("Waveform"),Vc=["audio/","video/"],Pi=({audioBlob:e,currentTime:t,duration:n,width:a=600,height:s=200,zoom:i=1,onSeek:o,onRegionSelect:l,markers:c=[],regions:d=[],displayMode:h="waveform",multiChannel:p=!1,waveColor:g="var(--nice-color-primary, #007bff)",progressColor:y="var(--nice-color-error, rgba(255,0,0,0.8))",backgroundColor:m="transparent",showRuler:x=!1,showChannelLabels:v=!0,showPeakMeter:f=!1,className:k})=>{const{t:b}=be(),w=u.useRef(null),N=u.useRef(null),[$,M]=u.useState(null),[E,R]=u.useState(0),[L,A]=u.useState(!1),[z,j]=u.useState(null),[I,Y]=u.useState(null),[H,D]=u.useState(0),V=Math.max(a,a*i),Z=x?24:0;u.useEffect(()=>{if(!e||e.size===0){M(null);return}e.type&&!Vc.some(T=>e.type.startsWith(T))&&ys.warn("Unexpected blob MIME type:",e.type);let C=!1;return(async()=>{let T=null;try{const S=await e.arrayBuffer();if(S.byteLength===0||C)return;T=new AudioContext;const F=await T.decodeAudioData(S);C||M(F)}catch(S){ys.error("Failed to decode audio:",S)}finally{T==null||T.close().catch(()=>{})}})(),()=>{C=!0}},[e]),u.useEffect(()=>{if(i>1&&n>0){const C=t/n*V;(C<E||C>E+a)&&R(Math.max(0,C-a/2))}},[t,n,i,a,V,E]),u.useEffect(()=>{const C=w.current,T=$;if(!C||!n||n===1/0)return;const S=C.getContext("2d");if(!S)return;const F=V,K=s;if(C.width=F,C.height=K+Z,S.clearRect(0,0,F,K+Z),m!=="transparent"&&(S.fillStyle=we.resolveCssColor(m),S.fillRect(0,0,F,K+Z)),x){const P=we.resolveCssColor("var(--nice-text-secondary, #888)");S.fillStyle=we.resolveCssColor("var(--nice-bg-secondary, rgba(128,128,128,0.15))"),S.fillRect(0,0,F,Z),S.fillStyle=P,S.font="10px monospace",S.textAlign="center";const B=Math.max(1,Math.floor(n/(V/80)));for(let _=0;_<=n;_+=B){const U=_/n*F;S.fillText(Kc(_),U,Z-4),S.fillStyle=we.resolveCssColor("var(--nice-border-color, rgba(128,128,128,0.3))"),S.fillRect(U,Z,1,K),S.fillStyle=P}}for(const P of d){const B=P.start/n*F,_=P.end/n*F;S.fillStyle=we.resolveCssColor(P.color??"var(--nice-accent-tint-15, rgba(99, 102, 241, 0.15))"),S.fillRect(B,Z,_-B,K),P.label&&(S.fillStyle=we.resolveCssColor(P.color??"var(--nice-info, #6366f1)"),S.font="10px sans-serif",S.textAlign="left",S.fillText(P.label,B+2,Z+12))}if(z!==null&&I!==null){const P=Math.min(z,I),B=Math.max(z,I);S.fillStyle=we.resolveCssColor("var(--nice-warning-tint-20, rgba(255,200,0,0.2))"),S.fillRect(P,Z,B-P,K)}if(T){const P=p?T.numberOfChannels:1,B=K/P,_=we.resolveCssColor(g);let U=0;for(let J=0;J<P;J++){const se=T.getChannelData(J),oe=Z+J*B;if(h==="waveform"?Uc(S,se,F,B,oe,_):h==="bars"?qc(S,se,F,B,oe,_):h==="spectrogram"&&Hc(S,se,F,B,oe,T.sampleRate),f&&n>0){const re=Math.floor(t/n*se.length),W=Math.floor(T.sampleRate*.05);let ee=0;for(let le=Math.max(0,re-W);le<Math.min(se.length,re+W);le++)ee+=se[le]*se[le];const ae=Math.sqrt(ee/(W*2));U=Math.max(U,ae)}p&&v&&P>1&&(S.fillStyle=we.resolveCssColor("var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"),S.font="bold 11px sans-serif",S.textAlign="left",S.fillText(J===0?"L":J===1?"R":`Ch${J+1}`,4,oe+14))}D(U)}if(n>0){const P=Math.max(0,Math.min(t/n*F,F));S.beginPath(),S.strokeStyle=we.resolveCssColor(y),S.lineWidth=2,S.moveTo(P,Z),S.lineTo(P,K+Z),S.stroke()}for(const P of c){const B=P.time/n*F,_=we.resolveCssColor(P.color??"var(--nice-warning, #f59e0b)");S.beginPath(),S.strokeStyle=_,S.lineWidth=2,S.setLineDash([4,4]),S.moveTo(B,Z),S.lineTo(B,K+Z),S.stroke(),S.setLineDash([]),P.label&&(S.fillStyle=_,S.font="bold 10px sans-serif",S.textAlign="center",S.fillText(P.label,B,Z+K-4))}},[$,t,n,V,s,i,h,p,g,y,m,x,c,d,z,I,f,v,Z]);const X=u.useCallback(C=>{var F;if(!n)return;const T=(F=w.current)==null?void 0:F.getBoundingClientRect();if(!T)return;const S=C.clientX-T.left+E;A(!0),j(S),Y(S)},[n,E]),q=u.useCallback(C=>{if(!L||!w.current)return;const T=w.current.getBoundingClientRect(),S=C.clientX-T.left+E;Y(S)},[L,E]),G=u.useCallback(()=>{if(!L||z===null||I===null||!n){A(!1),j(null),Y(null);return}const C=Math.min(z,I),T=Math.max(z,I),S=(T-C)/V*n;if(A(!1),j(null),Y(null),S<.2){const F=C/V*n;o==null||o(F)}else{const F=C/V*n,K=T/V*n;l==null||l({start:F,end:K})}},[L,z,I,n,V,o,l]);return r.jsxs("div",{ref:N,className:`nice-waveform${k?` ${k}`:""}`,style:{position:"relative",width:a,overflow:i>1?"auto":"hidden",cursor:o?"crosshair":"default"},onScroll:C=>R(C.target.scrollLeft),children:[r.jsx("canvas",{ref:w,width:V,height:s+Z,style:{display:"block"},role:"img","aria-label":b("waveform.waveformCanvas","Waveform canvas"),onMouseDown:X,onMouseMove:q,onMouseUp:G,onMouseLeave:G}),f&&r.jsx("div",{style:{position:"absolute",right:4,top:Z+4,bottom:4,width:12,background:"var(--nice-overlay-30, rgba(0, 0, 0, 0.3))",borderRadius:4,overflow:"hidden"},children:r.jsx("div",{style:{position:"absolute",bottom:0,width:"100%",height:`${Math.min(100,H*300)}%`,background:H>.8?"var(--nice-danger, #ef4444)":H>.5?"var(--nice-warning, #f59e0b)":"var(--nice-success, #22c55e)",borderRadius:4,transition:"height 50ms"}})})]})};function Uc(e,t,n,a,s,i){const o=Math.floor(t.length/n),l=s+a/2;e.beginPath(),e.strokeStyle=i,e.lineWidth=1;for(let c=0;c<n;c++){const d=c*o,h=t.subarray(d,d+o);let p=0,g=0;for(let x=0;x<h.length;x++)h[x]<p&&(p=h[x]),h[x]>g&&(g=h[x]);const y=l-g*(a/2),m=l-p*(a/2);e.moveTo(c,y),e.lineTo(c,m)}e.stroke()}function qc(e,t,n,a,s,i){const o=Math.max(2,Math.floor(n/128)),l=Math.floor(n/o),c=Math.floor(t.length/l);for(let d=0;d<l;d++){const h=d*c,p=t.subarray(h,h+c);let g=0;for(let v=0;v<p.length;v++)g+=Math.abs(p[v]);const m=g/p.length*a*.9,x=d*o;e.fillStyle=i,e.fillRect(x+1,s+a-m,o-2,m)}}function Hc(e,t,n,a,s,i){const l=Math.min(n,512),c=Math.floor(t.length/l),d=n/l;for(let h=0;h<l;h++){const p=h*c,g=new Float32Array(256/2);for(let m=0;m<256/2;m++){let x=0,v=0;for(let f=0;f<256&&p+f<t.length;f++){const k=2*Math.PI*m*f/256;x+=t[p+f]*Math.cos(k),v-=t[p+f]*Math.sin(k)}g[m]=Math.sqrt(x*x+v*v)/256}const y=a/g.length;for(let m=0;m<g.length;m++){const x=Math.min(1,g[m]*10),v=Math.floor(x*255),f=Math.floor(x*100),k=Math.floor((1-x)*200);e.fillStyle=`rgb(${v},${f},${k})`,e.fillRect(h*d,s+a-(m+1)*y,d+1,y+1)}}}function Kc(e){const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const vs=88,Jt=16,Zn=16,Yc=320;function Zc(e){return e-21}function Xc(e){return e+21}const $a=({notes:e,onAddNote:t,onRemoveNote:n,selectedNoteId:a,setSelectedNoteId:s,duration:i=4,zoom:o=1})=>{const l=u.useRef(null),c=Yc*o,d=vs*Jt,h=u.useRef(null);u.useEffect(()=>{},[e,o,i]);const p=y=>{const m=l.current;if(!m)return;const x=m.getBoundingClientRect(),v=y.clientX-x.left,f=y.clientY-x.top,k=Math.floor(f/Jt),b=Xc(k),w=v/c*i;h.current={drawing:!0,startX:v,key:k},t(b,w,i/Zn)},g=(y,m)=>{m.stopPropagation(),s==null||s(y)};return r.jsxs("svg",{ref:l,width:c,height:d,style:{background:"var(--nice-bg-secondary, #f8fafc)",border:"1px solid var(--nice-border-color, #cbd5e1)",userSelect:"none",display:"block"},onMouseDown:p,children:[[...Array(vs)].map((y,m)=>r.jsx("rect",{x:0,y:m*Jt,width:c,height:Jt,fill:m%2===0?"var(--nice-bg-secondary, #f8fafc)":"var(--nice-bg-tertiary, #f1f5f9)"},m)),[...Array(Zn+1)].map((y,m)=>r.jsx("line",{x1:m*c/Zn,y1:0,x2:m*c/Zn,y2:d,stroke:"var(--nice-border-muted, #ccc)",strokeWidth:m%4===0?2:1},m)),e.map(y=>{const m=Zc(y.pitch),x=y.start/i*c,v=y.duration/i*c;return r.jsx("rect",{x,y:m*Jt,width:Math.max(6,v),height:Jt-2,fill:y.id===a?"var(--nice-color-primary, #6366f1)":"color-mix(in srgb, var(--nice-color-primary, #6366f1) 55%, var(--nice-bg-primary, #ffffff))",stroke:"var(--nice-color-primary, #6366f1)",strokeWidth:y.id===a?2:1,rx:3,onClick:f=>g(y.id,f),onDoubleClick:()=>n(y.id),style:{cursor:"pointer"}},y.id)})]})},Qc=({ccEvents:e,onAddEvent:t,onUpdateEvent:n,onRemoveEvent:a,ccType:s,duration:i,width:o,height:l=60,curveType:c})=>{const d=u.useRef(null),{t:h}=be(),[p,g]=u.useState(null),[y,m]=u.useState(null),[x,v]=u.useState(null),f=[...e].sort((j,I)=>j.time-I.time),k=j=>[j.time/i*o,(127-j.value)/127*l],b=(j,I,Y)=>Math.max(I,Math.min(Y,j)),w=j=>{var Z;if(j.target instanceof SVGCircleElement)return;const I=(Z=d.current)==null?void 0:Z.getBoundingClientRect();if(!I)return;const Y=j.clientX-I.left,H=j.clientY-I.top,D=b(Y/o*i,0,i),V=b(127-Math.round(H/l*127),0,127);t(s,V,D)},N=(j,I)=>{var V;I.stopPropagation(),g(j.id),v(j.id);const[Y,H]=k(j),D=(V=d.current)==null?void 0:V.getBoundingClientRect();D&&m({dx:I.clientX-D.left-Y,dy:I.clientY-D.top-H})},$=j=>{var Z;if(p==null||!y)return;const I=(Z=d.current)==null?void 0:Z.getBoundingClientRect();if(!I)return;const Y=b(j.clientX-I.left-y.dx,0,o),H=b(j.clientY-I.top-y.dy,0,l),D=b(Y/o*i,0,i),V=b(127-Math.round(H/l*127),0,127);n(p,V,D)},M=()=>{g(null),m(null)};u.useEffect(()=>{const j=I=>{(I.key==="Delete"||I.key==="Backspace")&&x!=null&&(a(x),v(null))};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[x,a]),u.useEffect(()=>{if(p!=null)return window.addEventListener("mousemove",$),window.addEventListener("mouseup",M),()=>{window.removeEventListener("mousemove",$),window.removeEventListener("mouseup",M)}});const[E,R]=u.useState(null),L=(j,I)=>{const[Y,H]=k(j);R({x:Y+10,y:H-10,text:`Val: ${j.value}, Time: ${j.time.toFixed(2)}s`})},A=()=>R(null),z=j=>{var Z;const I=(Z=d.current)==null?void 0:Z.getBoundingClientRect();if(!I)return;const Y=j.clientX-I.left,H=j.clientY-I.top,D=b(Y/o*i,0,i),V=b(127-Math.round(H/l*127),0,127);t(s,V,D)};return r.jsxs("svg",{ref:d,width:o,height:l,style:{background:"var(--nice-bg-tertiary, #f3f3f3)",border:"1px solid var(--nice-border, #bbb)",cursor:p?"grabbing":"crosshair",display:"block"},onClick:w,onDoubleClick:z,tabIndex:0,children:[[...Array(9)].map((j,I)=>r.jsx("line",{x1:0,y1:I*l/8,x2:o,y2:I*l/8,stroke:"var(--nice-border-muted, #ddd)",strokeWidth:I===0||I===8?2:1},I)),f.length>1&&r.jsx("polyline",{fill:"none",stroke:"var(--nice-color-accent, #1976d2)",strokeWidth:2,points:f.map(j=>k(j).join(",")).join(" ")}),f.map(j=>{const[I,Y]=k(j);return r.jsxs("g",{children:[r.jsx("circle",{cx:I,cy:Y,r:x===j.id?8:6,fill:x===j.id?"var(--nice-color-accent, #1976d2)":"var(--nice-color-accent-light, #90caf9)",stroke:"var(--nice-color-accent, #1976d2)",strokeWidth:x===j.id?3:2,style:{cursor:"pointer"},onMouseDown:H=>N(j,H),onContextMenu:H=>{H.preventDefault(),a(j.id)},onClick:H=>{H.stopPropagation(),v(j.id)},onMouseOver:H=>L(j),onMouseOut:A}),x===j.id&&r.jsx("foreignObject",{x:I+10,y:Y-18,width:90,height:30,style:{pointerEvents:"auto"},children:r.jsxs("div",{style:{fontSize:12,background:"var(--nice-color-surface, #fff)",border:"1px solid var(--nice-border, #bbb)",borderRadius:4,padding:"2px 6px",display:"inline-block"},children:[r.jsxs("label",{style:{marginRight:4},children:[h("ccLane.curve","Curve"),":"]}),r.jsxs("select",{value:j.handleType||c||"linear",onChange:H=>{n(j.id,j.value,j.time,H.target.value)},children:[r.jsx("option",{value:"linear",children:h("ccLane.linear","Linear")}),r.jsx("option",{value:"step",children:h("ccLane.step","Step")}),r.jsx("option",{value:"exp",children:h("ccLane.exponential","Exponential")})]})]})})]},j.id)}),E&&r.jsxs("g",{pointerEvents:"none",children:[r.jsx("rect",{x:E.x,y:E.y-18,width:90,height:20,fill:"var(--nice-color-surface, #fff)",stroke:"var(--nice-color-accent, #1976d2)",rx:4}),r.jsx("text",{x:E.x+6,y:E.y-4,fontSize:13,fill:"var(--nice-color-accent, #1976d2)",children:E.text})]}),r.jsxs("text",{x:6,y:16,fontSize:14,fill:"var(--nice-color-accent, #1976d2)",children:["CC",s]})]})},Jc=ot.scoped("audioContext");let Gn=null;function qn(){if(!Gn)try{Gn=new(window.AudioContext||window.webkitAudioContext)}catch(e){Jc.error("Error initializing AudioContext:",e)}return Gn}async function Yt(){const e=qn();e&&e.state==="suspended"&&await e.resume()}function $i(){return!!Gn&&Gn.state==="running"}function Ei(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 ed(e,t){if(!t.snapEnabled)return e;const n=Ei(t);return Math.round(e/n)*n}function td(e,t=!1){const n=Math.floor(e/60),a=Math.floor(e%60),s=Math.floor(e%1*1e3);return t?`${n}:${a.toString().padStart(2,"0")}.${s.toString().padStart(3,"0")}`:`${n}:${a.toString().padStart(2,"0")}`}function nd(e,t){const n=t/60,a=e*n,s=Math.floor(a/4),i=Math.floor(a%4);return`${s+1}:${i+1}`}function Ai(e,t,n=!0){const a=e.getContext("2d");if(!a)return;const s=30*t.zoom*t.duration,i=Math.max(80,30*t.zoom);e.width=s,e.height=i,a.clearRect(0,0,s,i),a.fillStyle=we.resolveCssColor("var(--nice-color-surface, #f5f5f5)",a.canvas),a.fillRect(0,0,s,i);const o=s/t.duration;let l=1;o<30?l=5:o<60?l=2:o>150&&(l=.5),a.strokeStyle=we.resolveCssColor("var(--nice-border-secondary, #ddd)",a.canvas),a.lineWidth=1;for(let c=0;c<=t.duration;c+=l){const d=c/t.duration*s,h=c%1===0;if(a.strokeStyle=we.resolveCssColor(h?"var(--nice-border-secondary, #ccc)":"var(--nice-border-muted, #eee)",a.canvas),a.lineWidth=h?1.5:.5,a.beginPath(),a.moveTo(d,0),a.lineTo(d,i),a.stroke(),h&&o>40){a.fillStyle=we.resolveCssColor("var(--nice-text-muted, #666)",a.canvas),a.font="10px monospace",a.textAlign="center";const p=n?nd(c,t.bpm):td(c);a.fillText(p,d,12)}}if(t.snapEnabled){const c=Ei(t);a.strokeStyle=we.resolveCssColor("var(--nice-color-accent, #ffeb3b)",a.canvas),a.lineWidth=.5;for(let d=0;d<=t.duration;d+=c){const h=d/t.duration*s;a.beginPath(),a.moveTo(h,i-5),a.lineTo(h,i),a.stroke()}}}function rd(e,t,n,a){const s=e.getContext("2d");if(!s)return;const i=30*t.zoom*t.duration,o=Math.max(80,30*t.zoom),l=n/t.duration*i;Ai(e,t),s.strokeStyle=we.resolveCssColor(a?"var(--nice-color-danger, #f44336)":"var(--nice-color-accent, #2196f3)",s.canvas),s.lineWidth=2,s.beginPath(),s.moveTo(l,0),s.lineTo(l,o),s.stroke(),s.fillStyle=we.resolveCssColor(a?"var(--nice-color-danger, #f44336)":"var(--nice-color-accent, #2196f3)",s.canvas),s.beginPath(),s.moveTo(l,0),s.lineTo(l-5,-8),s.lineTo(l+5,-8),s.closePath(),s.fill()}function ad(e,t,n,a="var(--nice-color-success, #4caf50)"){const s=e.getContext("2d");if(!s||!(n!=null&&n.length))return;const i=30*t.zoom*t.duration,l=e.height/2,c=Math.max(10,l-6);s.save(),s.strokeStyle=we.resolveCssColor(a,s.canvas),s.lineWidth=1,s.beginPath(),n.forEach((d,h)=>{const p=h/(n.length-1)*i,g=l-d*c;h===0?s.moveTo(p,g):s.lineTo(p,g)}),s.stroke(),s.restore()}const Ii=({zoom:e=1,duration:t=4,isPlaying:n,isRecording:a,currentTime:s,bpm:i=120,snapEnabled:o=!1,snapMode:l="beat",waveform:c,waveformColor:d,onCurrentTimeChange:h,onZoomChange:p})=>{const{t:g}=be(),y=u.useRef(null),[m,x]=u.useState(!1),v=u.useRef(s);v.current=s;const f=u.useRef(t);f.current=t;const k=u.useRef(h);k.current=h;const b={zoom:e,duration:t,bpm:i,snapEnabled:o,snapMode:l};u.useEffect(()=>{Yt(),w()},[e,t,s,a,i,o,l,c]),u.useEffect(()=>{if(!n)return;let L=performance.now(),A=0;const z=j=>{const I=Math.max(0,j-L)/1e3;L=j;const Y=Math.min(v.current+I,f.current);v.current=Y,k.current(Y),Y<f.current&&(A=requestAnimationFrame(z))};return A=requestAnimationFrame(z),()=>cancelAnimationFrame(A)},[n]);const w=()=>{y.current&&(Ai(y.current,b),c!=null&&c.length&&ad(y.current,b,c,d),rd(y.current,b,s,a))},N=L=>{x(!0),E(L)},$=L=>{m&&E(L)},M=()=>{x(!1)},E=L=>{if(!y.current)return;const A=y.current.getBoundingClientRect();let j=(L.clientX-A.left)/A.width*t;j=ed(j,b),h(Math.min(Math.max(j,0),t))},R=L=>{if(!p)return;L.preventDefault();const A=L.deltaY>0?-.1:.1,z=Math.max(.5,Math.min(5,e+A));p(z)};return r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:r.jsx("canvas",{ref:y,style:{border:"1px solid black",backgroundColor:"white",width:`${30*e*t}px`,height:`${Math.max(80,30*e)}px`,cursor:m?"grabbing":"pointer"},onMouseDown:N,onMouseMove:$,onMouseUp:M,onMouseLeave:M,onWheel:R,role:"img","aria-label":g("audioTimeline.audioTimelineCanvas","Audio timeline canvas")})})},et=["var(--nice-primary, #2196f3)","var(--nice-danger, #e53935)","var(--nice-warning, #ffeb3b)","var(--nice-success, #43a047)","var(--nice-warning, #ff9800)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-warning, #ffc107)","var(--nice-success, #8bc34a)","var(--nice-danger, #f44336)","var(--nice-accent, #3f51b5)","var(--nice-text-secondary, #607d8b)","var(--nice-warning-dark, #795548)","var(--nice-warning, #cddc39)","var(--nice-accent, #673ab7)","var(--nice-success, #009688)"];function sd(e){for(const t of et)if(!e.includes(t))return t;return et[Math.floor(Math.random()*et.length)]}const ur=et.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function id(e){for(let t=0;t<et.length;t++){const n=et[t],a=ur[t];if(!e.includes(n)&&!e.includes(a))return a}return ur[Math.floor(Math.random()*ur.length)]}const od="_panel_3bj7x_3",ld="_panelCompact_3bj7x_19",cd="_panelNarrow_3bj7x_25",dd="_panelWide_3bj7x_31",ud="_heading_3bj7x_37",hd="_row_3bj7x_53",pd="_field_3bj7x_65",fd="_buttonRow_3bj7x_71",md="_sliderW200_3bj7x_83",gd="_sliderW240_3bj7x_89",yd="_selectW160_3bj7x_95",vd="_inputW120_3bj7x_101",bd="_inputW160_3bj7x_107",xd="_inputW200_3bj7x_113",Sd="_noteText_3bj7x_123",kd="_noteTextMargin_3bj7x_131",wd="_presetDivider_3bj7x_145",Cd="_presetLabel_3bj7x_159",jd="_countInAlert_3bj7x_173",Md="_levelLabel_3bj7x_181",Rd="_levelMeter_3bj7x_189",Nd="_levelBar_3bj7x_205",Td="_panelInactive_3bj7x_225",Pd="_header_3bj7x_231",$d="_title_3bj7x_245",Ed="_grid2_3bj7x_257",Ad="_full_3bj7x_267",Id="_label_3bj7x_275",Ld="_grow_3bj7x_291",_d="_pushRight_3bj7x_299",zd="_alignStart_3bj7x_305",Dd="_toolbar_3bj7x_311",Fd="_subPanel_3bj7x_325",me={panel:od,panelCompact:ld,panelNarrow:cd,panelWide:dd,heading:ud,row:hd,field:pd,buttonRow:fd,sliderW200:md,sliderW240:gd,selectW160:yd,inputW120:vd,inputW160:bd,inputW200:xd,noteText:Sd,noteTextMargin:kd,presetDivider:wd,presetLabel:Cd,countInAlert:jd,levelLabel:Md,levelMeter:Rd,levelBar:Nd,panelInactive:Td,header:Pd,title:$d,grid2:Ed,full:Ad,label:Id,grow:Ld,pushRight:_d,alignStart:zd,toolbar:Dd,subPanel:Fd},Pt=e=>Array.isArray(e)?e[0]??"":e,Li=({autoSaveMode:e,setAutoSaveMode:t,autoSaveInterval:n,setAutoSaveInterval:a})=>{const{t:s}=be();return r.jsxs("div",{className:`${me.panel} ${me.panelNarrow}`,children:[r.jsx("h6",{className:me.heading,children:s("editorPanels.autoSaveTitle","Project auto-save")}),r.jsx("div",{className:me.field,children:r.jsx(ie.NiceSelect,{label:s("editorPanels.autoSaveMode","Auto-save mode"),size:"sm",value:e,onChange:i=>t(Pt(i)),options:[{value:"off",label:s("editorPanels.off","Off")},{value:"onChange",label:s("editorPanels.onChange","On every change")},{value:"interval",label:s("editorPanels.interval","At set interval")},{value:"both",label:s("editorPanels.both","Both")}]})}),(e==="interval"||e==="both")&&r.jsx("div",{className:me.field,children:r.jsx(ie.NiceNumberInput,{label:s("editorPanels.autoSaveFrequency","Auto-save frequency (seconds)"),size:"sm",min:5,max:600,value:n,onChange:i=>a(Math.max(5,Math.min(600,i??5)))})}),r.jsxs("div",{className:me.noteText,children:[r.jsxs("b",{children:[s("editorPanels.noteLabel","Note"),":"]})," ",s("editorPanels.autoSaveNote","Auto-save works locally (localStorage/browser). Manual save (PUT) always overwrites the project on the server.")]})]})},_i=({undoCount:e,redoCount:t,onUndo:n,onRedo:a})=>{const{t:s}=be();return r.jsxs("div",{className:`${me.panel} ${me.panelNarrow}`,children:[r.jsx("h6",{className:me.heading,children:s("editorPanels.changeHistory","Project change history")}),r.jsxs("div",{className:me.buttonRow,children:[r.jsxs(ie.NiceButton,{variant:"secondary",size:"sm",onClick:n,disabled:e===0,title:s("editorPanels.undoTitle","Undo last change (Ctrl+Z)"),children:[r.jsx(O.NtdUndo,{size:14})," ",s("editorPanels.undo","Undo")]}),r.jsxs(ie.NiceButton,{variant:"secondary",size:"sm",onClick:a,disabled:t===0,title:s("editorPanels.redoTitle","Redo change (Ctrl+Y or Ctrl+Shift+Z)"),children:[r.jsx(O.NtdRedo,{size:14})," ",s("editorPanels.redo","Redo")]})]}),r.jsx("div",{className:me.noteTextMargin,children:s("editorPanels.undoRedoNote","Undo/Redo works on the entire project (all editor changes). After each change Redo is cleared.")})]})},bs=e=>`${e.toFixed(1)}x`,Ea=({zoom:e,setZoom:t,uiZoom:n,setUiZoom:a,snapEnabled:s,onToggleSnap:i,snapMode:o,onSnapModeChange:l,bpm:c,setBpm:d})=>{const{t:h}=be();return r.jsx("div",{className:`${me.panel} ${me.panelCompact} ${me.panelNarrow}`,children:r.jsxs("div",{className:me.row,children:[r.jsx("div",{className:me.sliderW200,children:r.jsx(ie.NiceSlider,{label:h("editorPanels.zoom","Zoom"),size:"sm",min:.5,max:5,step:.1,value:e,onChange:t,showValue:!0,formatValue:bs})}),r.jsx("div",{className:me.sliderW200,children:r.jsx(ie.NiceSlider,{label:h("editorPanels.uiZoom","Zoom UI"),size:"sm",min:1,max:4,step:.1,value:n,onChange:a,showValue:!0,formatValue:bs})}),r.jsx(ie.NiceCheckbox,{label:h("editorPanels.snap","Snap"),size:"sm",checked:s,onChange:()=>i()}),s&&r.jsx("div",{className:me.selectW160,children:r.jsx(ie.NiceSelect,{size:"sm","aria-label":h("editorPanels.snapTo","Snap to"),value:o,onChange:p=>l(Pt(p)),options:[{value:"bar",label:h("editorPanels.snapBar","Bar")},{value:"beat",label:h("editorPanels.snapBeat","Beat")},{value:"sub-beat",label:h("editorPanels.snap16","1/16")},{value:"second",label:h("editorPanels.snapSecond","Second")}]})}),r.jsx("div",{className:me.inputW120,children:r.jsx(ie.NiceNumberInput,{label:h("editorPanels.bpm","BPM"),size:"sm",min:20,max:300,value:c,onChange:p=>d(p??c)})})]})})},Od=[["peaking","Peaking"],["lowpass","Low-pass"],["highpass","High-pass"],["lowshelf","Low shelf"],["highshelf","High shelf"],["notch","Notch"],["bandpass","Band-pass"]],zi=({masterVolume:e,onMasterVolumeChange:t,filterType:n,filterFreq:a,filterQ:s,filterGain:i,onFilterChange:o,masterEQPresets:l,customPresets:c,onLoadPreset:d,onSavePreset:h,onDeletePreset:p})=>{const{t:g}=be(),[y,m]=u.useState(""),x=()=>{y.trim()&&(h(y.trim()),m(""))};return r.jsxs("div",{className:`${me.panel} ${me.panelCompact} ${me.panelWide}`,children:[r.jsxs("div",{className:me.row,children:[r.jsx("div",{className:me.sliderW240,children:r.jsx(ie.NiceSlider,{label:g("editorPanels.masterVolume","Master Vol"),size:"sm",min:0,max:1,step:.01,value:e,onChange:t,showValue:!0,formatValue:v=>`${Math.round(v*100)}%`})}),r.jsx("div",{className:me.selectW160,children:r.jsx(ie.NiceSelect,{label:g("editorPanels.filter","Filter"),size:"sm",value:n,onChange:v=>o({type:Pt(v)}),options:Od.map(([v,f])=>({value:v,label:g(`editorPanels.filter.${v}`,f)}))})}),r.jsx("div",{className:me.sliderW240,children:r.jsx(ie.NiceSlider,{label:g("editorPanels.frequency","Freq"),size:"sm",min:40,max:12e3,step:10,value:a,onChange:v=>o({frequency:v}),showValue:!0,formatValue:v=>`${Math.round(v)} Hz`})}),r.jsx("div",{className:me.sliderW200,children:r.jsx(ie.NiceSlider,{label:"Q",size:"sm",min:.1,max:12,step:.1,value:s,onChange:v=>o({q:v}),showValue:!0,formatValue:v=>v.toFixed(1)})}),(n==="peaking"||n==="lowshelf"||n==="highshelf")&&r.jsx("div",{className:me.sliderW200,children:r.jsx(ie.NiceSlider,{label:g("editorPanels.gain","Gain"),size:"sm",min:-18,max:18,step:.5,value:i,onChange:v=>o({gain:v}),showValue:!0,formatValue:v=>`${v.toFixed(1)} dB`})})]}),r.jsxs("div",{className:me.presetDivider,children:[r.jsxs("div",{className:me.row,children:[r.jsxs("span",{className:me.presetLabel,children:[g("editorPanels.eqPresets","EQ Presets"),":"]}),[...l,...c].map(v=>r.jsx(ie.NiceButton,{variant:"outline",size:"xs",onClick:()=>d(v),children:v.name},v.name)),c.length>0&&r.jsx("div",{className:me.selectW160,children:r.jsx(ie.NiceSelect,{size:"sm","aria-label":g("editorPanels.deletePreset","Delete preset..."),placeholder:g("editorPanels.deletePreset","Delete preset..."),value:"",onChange:v=>{const f=Pt(v);f&&p(f)},options:c.map(v=>({value:v.name,label:v.name}))})})]}),r.jsxs("div",{className:me.row,children:[r.jsx("div",{className:me.inputW200,children:r.jsx(ie.NiceTextInput,{size:"sm",controlWidth:"100%","aria-label":g("editorPanels.presetName","Preset name..."),placeholder:g("editorPanels.presetName","Preset name..."),value:y,onChange:m,onKeyDown:v=>v.key==="Enter"&&x()})}),r.jsx(ie.NiceButton,{variant:"success",size:"xs",onClick:x,disabled:!y.trim(),children:g("editorPanels.saveCurrent","Save Current")})]})]})]})},Di=({countInBars:e,setCountInBars:t,isCountIn:n,countInRemaining:a,overdubEnabled:s,setOverdubEnabled:i,punchIn:o,setPunchIn:l,punchOut:c,setPunchOut:d,monitorLevel:h})=>{const{t:p}=be();return r.jsx("div",{className:`${me.panel} ${me.panelCompact} ${me.panelWide}`,children:r.jsxs("div",{className:me.row,children:[r.jsx("div",{className:me.inputW200,children:r.jsx(ie.NiceNumberInput,{label:p("editorPanels.countIn","Count-in (bars)"),size:"sm",min:0,max:8,step:1,value:e,onChange:g=>t(g??0)})}),n&&r.jsx("span",{className:me.countInAlert,children:p("editorPanels.countInRemaining","Count-in: {seconds}s").replace("{seconds}",a.toFixed(1))}),r.jsx(ie.NiceCheckbox,{label:p("editorPanels.overdub","Overdub (play background)"),size:"sm",checked:s,onChange:i}),r.jsx("div",{className:me.inputW160,children:r.jsx(ie.NiceNumberInput,{label:p("editorPanels.punchIn","Punch In (s)"),size:"sm",min:0,step:.1,value:o,onChange:l})}),r.jsx("div",{className:me.inputW160,children:r.jsx(ie.NiceNumberInput,{label:p("editorPanels.punchOut","Punch Out (s)"),size:"sm",min:0,step:.1,value:c,onChange:d})}),r.jsx(ie.NiceButton,{variant:"outline",size:"xs",onClick:()=>{l(null),d(null)},children:p("editorPanels.clearPunch","Clear punch")}),r.jsx("div",{className:me.levelLabel,children:p("editorPanels.level","Level")}),r.jsx("div",{className:me.levelMeter,role:"meter","aria-label":p("editorPanels.level","Level"),"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(Math.min(1,h*2)*100),children:r.jsx("div",{className:me.levelBar,style:{width:`${Math.min(1,h*2)*100}%`,background:h>.7?"var(--nice-danger, #f44336)":"var(--nice-success, #4caf50)"}})})]})})},Bd=[{id:1,name:"Audio 1",type:"audio",color:et[0],volume:.8,audioBlob:null},{id:2,name:"MIDI 1",type:"midi",color:et[1],volume:.8,notes:[]}],Gd=({initialTracks:e,tracks:t,onTracksChange:n,initialBpm:a=120,duration:s=30,height:i=480,title:o,displayMode:l="standard",onNew:c,onOpen:d,onSave:h,onExport:p,t:g})=>{var ae,le;const{t:y}=be(),m=g??y,x=o??m("audioStudio.untitledProject","Untitled project"),[v,f]=u.useState(l),k=v==="advanced",b=v!=="basic",[w,N]=u.useState(e??Bd),$=t??w,M=u.useCallback(ce=>{t===void 0&&N(ce),n==null||n(ce)},[t,n]),[E,R]=u.useState(!1),[L,A]=u.useState(0),[z,j]=u.useState(1),[I,Y]=u.useState(2),[H,D]=u.useState(!0),[V,Z]=u.useState("beat"),[X,q]=u.useState(a),[G,C]=u.useState(80),[T,S]=u.useState(((ae=$[0])==null?void 0:ae.id)??null),F=u.useRef(0),K=u.useRef(0);u.useEffect(()=>{if(!E)return;K.current=performance.now();const ce=te=>{const he=(te-K.current)/1e3;K.current=te,A(ue=>{const xe=ue+he;return xe>=s?(R(!1),s):xe}),F.current=requestAnimationFrame(ce)};return F.current=requestAnimationFrame(ce),()=>cancelAnimationFrame(F.current)},[E,s]);const P=u.useCallback((ce,te)=>M($.map(he=>he.id===ce?{...he,...te}:he)),[$,M]),B=u.useCallback(ce=>{const te=$.reduce((ue,xe)=>Math.max(ue,xe.id),0)+1,he=$.filter(ue=>ue.type===ce).length+1;M([...$,{id:te,name:`${ce==="audio"?"Audio":"MIDI"} ${he}`,type:ce,color:et[$.length%et.length],volume:.8,...ce==="audio"?{audioBlob:null}:{notes:[]}}]),S(te)},[$,M]),_=u.useCallback(ce=>M($.filter(te=>te.id!==ce)),[$,M]),U=u.useCallback(()=>{if(c){c();return}M([]),A(0),R(!1)},[c,M]),J=u.useCallback((ce,te,he,ue)=>{const xe=$.find(je=>je.id===ce),pe=(xe==null?void 0:xe.notes)??[],Se=pe.reduce((je,$e)=>Math.max(je,$e.id),0)+1;P(ce,{notes:[...pe,{id:Se,pitch:te,start:he,duration:ue,velocity:100}]})},[$,P]),se=u.useCallback((ce,te)=>{const he=$.find(ue=>ue.id===ce);P(ce,{notes:((he==null?void 0:he.notes)??[]).filter(ue=>ue.id!==te)})},[$,P]),oe=u.useMemo(()=>{const ce=Math.floor(L/60),te=Math.floor(L%60),he=Math.floor(L%1*100);return`${ce}:${te.toString().padStart(2,"0")}.${he.toString().padStart(2,"0")}`},[L]),re=u.useMemo(()=>{const ce=(he,ue)=>({id:`mode-${he}`,label:`${v===he?"• ":" "}${ue}`,onClick:()=>f(he)}),te=[{id:"file",label:m("studio.menu.file","File"),children:[{id:"new",label:m("studio.menu.new","New"),onClick:U},...d?[{id:"open",label:m("studio.menu.open","Open…"),onClick:d}]:[],{id:"save",label:m("studio.menu.save","Save"),onClick:()=>h==null?void 0:h($)},{id:"export",label:m("studio.menu.export","Export…"),onClick:()=>p==null?void 0:p($)}]}];return b&&te.push({id:"edit",label:m("studio.menu.edit","Edit"),children:[{id:"add-audio",label:m("studio.addAudio","Add audio track"),onClick:()=>B("audio")},{id:"add-midi",label:m("studio.addMidi","Add MIDI track"),onClick:()=>B("midi")}]}),te.push({id:"view",label:m("studio.menu.view","View"),children:[{id:"modes",label:m("studio.menu.modes","Display mode"),divider:!1,disabled:!0},ce("basic",m("studio.mode.basic","Basic")),ce("standard",m("studio.mode.standard","Standard")),ce("advanced",m("studio.mode.advanced","Advanced")),{id:"d1",divider:!0},{id:"snap",label:`${H?"• ":" "}${m("studio.snap","Snap to grid")}`,onClick:()=>D(he=>!he)}]}),te.push({id:"help",label:m("studio.menu.help","Help"),children:[{id:"about",label:m("studio.menu.about","About NiceAudioStudio"),disabled:!0}]}),te},[m,v,b,H,U,d,h,p,$,B]),W=r.jsxs(r.Fragment,{children:[r.jsxs(ie.NiceButton,{variant:"primary",size:"sm",onClick:()=>R(ce=>!ce),children:[E?r.jsx(O.NtdPause,{size:14}):r.jsx(O.NtdPlay,{size:14})," ",E?m("studio.pause","Pause"):m("studio.play","Play")]}),r.jsxs(ie.NiceButton,{variant:"secondary",size:"sm",onClick:()=>{R(!1),A(0)},children:[r.jsx(O.NtdStop,{size:14})," ",m("studio.stop","Stop")]}),r.jsx("span",{style:{fontVariantNumeric:"tabular-nums",fontWeight:700,minWidth:80},children:oe}),r.jsx("span",{style:{flex:1}}),r.jsxs(ie.NiceButton,{variant:"outline",size:"sm",onClick:()=>B("audio"),children:[r.jsx(O.NtdPlus,{size:14})," ",m("studio.addAudioShort","Audio")]}),b&&r.jsxs(ie.NiceButton,{variant:"outline",size:"sm",onClick:()=>B("midi"),children:[r.jsx(O.NtdPlus,{size:14})," ",m("studio.addMidiShort","MIDI")]}),r.jsx("span",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:m("studio.master","Master")}),r.jsx("div",{style:{width:90},children:r.jsx(ie.NiceSlider,{value:G,onChange:C,min:0,max:100})})]}),ee=r.jsxs(r.Fragment,{children:[r.jsxs("span",{children:[X," BPM"]}),r.jsx("span",{children:"·"}),r.jsx("span",{style:{fontVariantNumeric:"tabular-nums"},children:oe}),r.jsx("span",{children:"·"}),r.jsxs("span",{children:[$.length," ",m("studio.tracks","tracks")]}),k&&T!=null&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"·"}),r.jsxs("span",{children:[m("studio.active","Active"),": ",((le=$.find(ce=>ce.id===T))==null?void 0:le.name)??"—"]})]}),r.jsx("span",{style:{flex:1}}),r.jsx("span",{style:{textTransform:"capitalize"},children:v})]});return r.jsxs(ie.NiceAppShell,{className:"nice-audio-studio",height:i,menubar:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[r.jsx(ie.NiceMenu,{items:re,orientation:"horizontal"}),r.jsx("span",{style:{color:"var(--nice-text-secondary)",fontSize:13},children:x})]}),toolbar:W,statusBar:ee,children:[b&&r.jsx("div",{style:{padding:"6px 12px",borderBottom:"1px solid var(--nice-border-color)"},children:r.jsx(Ea,{zoom:z,setZoom:j,uiZoom:I,setUiZoom:Y,snapEnabled:H,onToggleSnap:()=>D(ce=>!ce),snapMode:V,onSnapModeChange:Z,bpm:X,setBpm:q})}),r.jsx("div",{style:{padding:8},children:r.jsx(Ii,{zoom:z,duration:s,isPlaying:E,isRecording:!1,currentTime:L,bpm:X,snapEnabled:H,snapMode:V,onCurrentTimeChange:A,onZoomChange:j})}),$.length===0?r.jsx("div",{style:{padding:32,textAlign:"center",color:"var(--nice-text-muted, #94a3b8)"},children:m("studio.empty","No tracks — add an audio or MIDI track to start.")}):$.map(ce=>r.jsxs("div",{onFocus:()=>S(ce.id),style:{display:"flex",gap:8,padding:8,borderTop:"1px solid var(--nice-border-color)",background:T===ce.id?"color-mix(in srgb, var(--nice-color-primary) 8%, transparent)":"transparent"},onClick:()=>S(ce.id),children:[r.jsxs("div",{style:{flex:"0 0 180px",display:"flex",flexDirection:"column",gap:6},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:ce.color||et[0],flex:"0 0 auto"}}),r.jsx("div",{style:{flex:1},children:r.jsx(ie.NiceTextInput,{value:ce.name,onChange:te=>P(ce.id,{name:te}),size:"sm"})})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[r.jsx(ie.NiceButton,{variant:ce.muted?"danger":"ghost",size:"sm",onClick:()=>P(ce.id,{muted:!ce.muted}),children:"M"}),b&&r.jsx(ie.NiceButton,{variant:ce.solo?"warning":"ghost",size:"sm",onClick:()=>P(ce.id,{solo:!ce.solo}),children:"S"}),r.jsx("div",{style:{flex:1},children:r.jsx(ie.NiceSlider,{value:Math.round((ce.volume??.8)*100),onChange:te=>P(ce.id,{volume:te/100}),min:0,max:100})}),r.jsx(ie.NiceButton,{variant:"ghost",size:"sm",onClick:()=>_(ce.id),children:r.jsx(O.NtdClose,{size:14})})]})]}),r.jsx("div",{style:{flex:1,minWidth:0,opacity:ce.muted?.5:1},children:ce.type==="audio"?r.jsx(Pi,{audioBlob:ce.audioBlob??null,currentTime:L,duration:s,zoom:z,height:80,waveColor:ce.color,onSeek:A}):r.jsx($a,{notes:ce.notes??[],onAddNote:(te,he,ue)=>J(ce.id,te,he,ue),onRemoveNote:te=>se(ce.id,te),duration:s,zoom:z})})]},ce.id))]})},Fi=({data:e,width:t=200,height:n=40,color:a="var(--nice-accent, #8b5cf6)",progress:s=0,onClick:i})=>{const o=u.useRef(null);u.useEffect(()=>{const c=o.current;if(!c||!e)return;const d=c.getContext("2d");if(!d)return;const h=window.devicePixelRatio||1;c.width=t*h,c.height=n*h,d.scale(h,h),d.clearRect(0,0,t,n);const p=t/e.length,g=n/2;for(let y=0;y<e.length;y++){const m=y*p,x=e[y]*n*.9,v=y/e.length<s;d.fillStyle=v?a:`${a}66`,d.fillRect(m,g-x/2,Math.max(1,p-1),x)}s>0&&s<1&&(d.strokeStyle=we.resolveCssColor("var(--nice-bg, #fff)",d.canvas),d.lineWidth=2,d.beginPath(),d.moveTo(s*t,0),d.lineTo(s*t,n),d.stroke())},[e,t,n,a,s]);const l=u.useCallback(c=>{if(!i)return;const d=c.currentTarget.getBoundingClientRect(),h=c.clientX-d.left;i(h/d.width)},[i]);return r.jsx("canvas",{ref:o,className:"nice-sample-waveform",width:t,height:n,style:{width:t,height:n},onClick:l})},Wd=({sample:e,isSelected:t,isPlaying:n,playProgress:a,showWaveform:s,showAnalysis:i,onSelect:o,onPlay:l,onStop:c,onDragStart:d,onFavorite:h})=>{const{t:p}=be(),g=m=>{const x=Math.floor(m/60),v=Math.floor(m%60);return`${x}:${v.toString().padStart(2,"0")}`},y=m=>m<1024?`${m} B`:m<1024*1024?`${(m/1024).toFixed(1)} KB`:`${(m/(1024*1024)).toFixed(1)} MB`;return r.jsxs("div",{className:`nice-sample-row ${t?"nice-sample-row--selected":""} ${n?"nice-sample-row--playing":""}`,onClick:o,draggable:!0,onDragStart:d,children:[r.jsx("button",{type:"button",className:"nice-sample-row__play",onClick:m=>{m.stopPropagation(),n?c():l()},"aria-label":n?"Stop":"Play",title:n?"Stop":"Play",children:n?r.jsx(O.NtdStop,{size:14}):r.jsx(O.NtdPlay,{size:14})}),r.jsx("button",{type:"button",className:`nice-sample-row__fav ${e.favorite?"nice-sample-row__fav--active":""}`,onClick:m=>{m.stopPropagation(),h()},"aria-label":p("sampleBrowser.favorite","Favorite"),children:r.jsx(O.NtdStar,{size:14,style:{color:e.favorite?"var(--nice-warning, #facc15)":"var(--nice-text-muted)"}})}),r.jsx("div",{className:"nice-sample-row__name",title:e.name,children:e.name}),s&&r.jsx("div",{className:"nice-sample-row__waveform",children:r.jsx(Fi,{data:e.waveformData,progress:a})}),r.jsx("div",{className:"nice-sample-row__duration",children:g(e.duration)}),i&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"nice-sample-row__bpm",children:e.bpm?`${e.bpm} BPM`:"—"}),r.jsx("div",{className:"nice-sample-row__key",children:e.key||"—"})]}),r.jsx("div",{className:"nice-sample-row__size",children:y(e.fileSize)}),e.tags&&e.tags.length>0&&r.jsx("div",{className:"nice-sample-row__tags",children:e.tags.slice(0,2).map(m=>r.jsx("span",{className:"nice-sample-row__tag",children:m},m))})]})},Vd=({folders:e=[],samples:t=[],onSampleSelect:n,onSampleDragStart:a,onFolderSelect:s,onAnalyze:i,audioContext:o,showWaveform:l=!0,showAnalysis:c=!0,sortBy:d="name",sortDirection:h="asc",filterTags:p,searchQuery:g="",className:y=""})=>{const{t:m}=be(),[x,v]=u.useState(null),[f,k]=u.useState(null),[b,w]=u.useState(null),[N,$]=u.useState(0),[M,E]=u.useState(new Map),[R,L]=u.useState(t),A=u.useRef(null),z=u.useRef(null);u.useEffect(()=>(A.current=new Audio,A.current.addEventListener("ended",()=>{w(null),$(0)}),()=>{A.current&&(A.current.pause(),A.current=null),z.current&&clearInterval(z.current)}),[]);const j=u.useMemo(()=>{let X=[...R];if(g){const q=g.toLowerCase();X=X.filter(G=>{var C;return G.name.toLowerCase().includes(q)||((C=G.tags)==null?void 0:C.some(T=>T.toLowerCase().includes(q)))})}return p&&p.length>0&&(X=X.filter(q=>{var G;return(G=q.tags)==null?void 0:G.some(C=>p.includes(C))})),f&&(X=f.samples||[]),X.sort((q,G)=>{var T,S;let C=0;switch(d){case"name":C=q.name.localeCompare(G.name);break;case"duration":C=q.duration-G.duration;break;case"bpm":C=(q.bpm||0)-(G.bpm||0);break;case"key":C=(q.key||"").localeCompare(G.key||"");break;case"date":C=(((T=q.dateAdded)==null?void 0:T.getTime())||0)-(((S=G.dateAdded)==null?void 0:S.getTime())||0);break}return h==="asc"?C:-C}),X},[R,g,p,f,d,h]),I=u.useCallback(X=>{v(X),n==null||n(X)},[n]),Y=u.useCallback(async X=>{if(A.current&&(A.current.pause(),z.current&&clearInterval(z.current),A.current.src=X.url||X.path,A.current.play(),w(X.id),$(0),z.current=window.setInterval(()=>{A.current&&$(A.current.currentTime/A.current.duration)},50),c&&!M.has(X.id)&&i))try{const q=await i(X);E(G=>new Map(G).set(X.id,q)),L(G=>G.map(C=>C.id===X.id?{...C,bpm:q.bpm,key:q.key,waveformData:q.waveformData}:C))}catch(q){console.error("Failed to analyze sample:",q)}},[c,M,i]),H=u.useCallback(()=>{A.current&&(A.current.pause(),A.current.currentTime=0),z.current&&clearInterval(z.current),w(null),$(0)},[]),D=u.useCallback(X=>{L(q=>q.map(G=>G.id===X?{...G,favorite:!G.favorite}:G))},[]),V=u.useCallback((X,q)=>{q.dataTransfer.setData("application/json",JSON.stringify(X)),q.dataTransfer.effectAllowed="copy",a==null||a(X,q)},[a]),Z=(X,q=0)=>{var G;return r.jsxs("div",{className:"nice-sample-folder",style:{paddingLeft:q*16},children:[r.jsxs("button",{type:"button",className:`nice-sample-folder__btn ${(f==null?void 0:f.id)===X.id?"nice-sample-folder__btn--selected":""}`,onClick:()=>{k(X),s==null||s(X)},children:[r.jsx("span",{className:"nice-sample-folder__icon","aria-hidden":"true",children:r.jsx(O.NtdFolder,{size:14})}),r.jsx("span",{className:"nice-sample-folder__name",children:X.name}),X.samples&&r.jsx("span",{className:"nice-sample-folder__count",children:X.samples.length})]}),(G=X.children)==null?void 0:G.map(C=>Z(C,q+1))]},X.id)};return r.jsxs("div",{className:`nice-sample-browser ${y}`,children:[e.length>0&&r.jsx("div",{className:"nice-sample-browser__sidebar",children:r.jsxs("div",{className:"nice-sample-browser__folders",children:[r.jsxs("button",{type:"button",className:`nice-sample-folder__btn ${f?"":"nice-sample-folder__btn--selected"}`,onClick:()=>k(null),children:[r.jsx("span",{className:"nice-sample-folder__icon","aria-hidden":"true",children:r.jsx(O.NtdMusic,{size:14})}),r.jsx("span",{className:"nice-sample-folder__name",children:m("sampleBrowser.allSamples","All Samples")}),r.jsx("span",{className:"nice-sample-folder__count",children:R.length})]}),e.map(X=>Z(X))]})}),r.jsxs("div",{className:"nice-sample-browser__main",children:[r.jsxs("div",{className:"nice-sample-browser__header",children:[r.jsx("div",{className:"nice-sample-browser__col nice-sample-browser__col--play"}),r.jsx("div",{className:"nice-sample-browser__col nice-sample-browser__col--fav"}),r.jsx("div",{className:"nice-sample-browser__col nice-sample-browser__col--name",children:m("sampleBrowser.name","Name")}),l&&r.jsx("div",{className:"nice-sample-browser__col nice-sample-browser__col--waveform",children:m("sampleBrowser.waveform","Waveform")}),r.jsx("div",{className:"nice-sample-browser__col nice-sample-browser__col--duration",children:m("sampleBrowser.duration","Duration")}),c&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"nice-sample-browser__col nice-sample-browser__col--bpm",children:"BPM"}),r.jsx("div",{className:"nice-sample-browser__col nice-sample-browser__col--key",children:"Key"})]}),r.jsx("div",{className:"nice-sample-browser__col nice-sample-browser__col--size",children:m("sampleBrowser.size","Size")}),r.jsx("div",{className:"nice-sample-browser__col nice-sample-browser__col--tags",children:m("sampleBrowser.tags","Tags")})]}),r.jsx("div",{className:"nice-sample-browser__list",children:j.length===0?r.jsx("div",{className:"nice-sample-browser__empty",children:m("sampleBrowser.noSamplesFound","No samples found")}):j.map(X=>r.jsx(Wd,{sample:X,isSelected:(x==null?void 0:x.id)===X.id,isPlaying:b===X.id,playProgress:b===X.id?N:0,showWaveform:l,showAnalysis:c,onSelect:()=>I(X),onPlay:()=>Y(X),onStop:H,onDragStart:q=>V(X,q),onFavorite:()=>D(X.id)},X.id))})]}),x&&r.jsxs("div",{className:"nice-sample-browser__preview",children:[r.jsx("h3",{className:"nice-sample-browser__preview-title",children:x.name}),r.jsx(Fi,{data:x.waveformData,width:300,height:80,progress:b===x.id?N:0}),r.jsxs("div",{className:"nice-sample-browser__preview-info",children:[r.jsxs("div",{children:["Duration: ",x.duration.toFixed(2),"s"]}),r.jsxs("div",{children:["Sample Rate: ",x.sampleRate," Hz"]}),r.jsxs("div",{children:["Channels: ",x.channels]}),x.bpm&&r.jsxs("div",{children:["BPM: ",x.bpm]}),x.key&&r.jsxs("div",{children:["Key: ",x.key]})]})]})]})};function Oi(e){return{past:[],present:e,future:[]}}function Bi(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function Gi(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 Wi(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 Vi(e){return e.past.length>0}function Ui(e){return e.future.length>0}function da(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>({...n}))}function qi(e,t,n){if(t.length===0)return e;const a=Math.min(...t.map(o=>o.time)),s=n-a,i=t.map(o=>({...o,id:Date.now()+Math.floor(Math.random()*1e4)+o.id,time:o.time+s}));return[...e,...i]}function Hi(e,t){const n=[],a=[];for(const s of e)s.time>=t.start&&s.time<=t.end?n.push({...s}):a.push(s);return{remaining:a,cut:n}}function Ki(e,t){return e.filter(n=>n.time<t.start||n.time>t.end)}function Ud(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>n.id)}function Yi(e,t,n,a){const s={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:a};return[...e,s]}function Zi(e,t=3){if(e.length<=2)return e;const n=[...e].sort((s,i)=>s.time-i.time),a=[n[0]];for(let s=1;s<n.length-1;s++)s%t===0&&a.push(n[s]);return a.push(n[n.length-1]),a}function Xi(e){return JSON.stringify(e,null,2)}function Qi(e){try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&"id"in n&&"cc"in n&&"value"in n&&"time"in n):[]}catch{return[]}}function yt(e,t){var n;return((n=e.find(a=>a.layerId===t))==null?void 0:n.events)??[]}function Mt(e,t,n){return e.find(s=>s.layerId===t)?e.map(s=>s.layerId===t?{...s,events:n}:s):[...e,{layerId:t,events:n}]}function qd(e,t){switch(t.type){case"UNDO":return Gi(e);case"REDO":return Wi(e);default:{let n=e.present;switch(t.type){case"ADD_EVENT":{const a=[...yt(n,t.layerId),t.event];n=Mt(n,t.layerId,a);break}case"UPDATE_EVENT":{const a=yt(n,t.layerId).map(s=>s.id===t.id?{...s,value:t.value,time:t.time,handleType:t.handleType??s.handleType}:s);n=Mt(n,t.layerId,a);break}case"REMOVE_EVENT":{const a=yt(n,t.layerId).filter(s=>s.id!==t.id);n=Mt(n,t.layerId,a);break}case"SET_EVENTS":n=Mt(n,t.layerId,t.events);break;case"PASTE":{const a=yt(n,t.layerId),s=qi(a,t.clipboard,t.targetTime);n=Mt(n,t.layerId,s);break}case"CUT":{const a=yt(n,t.layerId),{remaining:s}=Hi(a,t.range);n=Mt(n,t.layerId,s);break}case"DELETE_RANGE":{const a=yt(n,t.layerId),s=Ki(a,t.range);n=Mt(n,t.layerId,s);break}case"RECORD":{const a=yt(n,t.layerId),s=Yi(a,t.cc,t.value,t.time);n=Mt(n,t.layerId,s);break}case"THIN":{const a=yt(n,t.layerId),s=Zi(a,t.keepEveryN);n=Mt(n,t.layerId,s);break}case"IMPORT":{const a=Qi(t.json);a.length>0&&(n=Mt(n,t.layerId,a));break}}return Bi(e,n)}}}function Ji(e=[]){const[t,n]=u.useReducer(qd,Oi(e)),a=u.useRef([]),s=u.useCallback(b=>yt(t.present,b),[t.present]),i=u.useCallback((b,w)=>n({type:"ADD_EVENT",layerId:b,event:w}),[]),o=u.useCallback((b,w,N,$,M)=>n({type:"UPDATE_EVENT",layerId:b,id:w,value:N,time:$,handleType:M}),[]),l=u.useCallback((b,w)=>n({type:"REMOVE_EVENT",layerId:b,id:w}),[]),c=u.useCallback((b,w)=>n({type:"SET_EVENTS",layerId:b,events:w}),[]),d=u.useCallback(()=>n({type:"UNDO"}),[]),h=u.useCallback(()=>n({type:"REDO"}),[]),p=u.useCallback((b,w)=>{a.current=da(yt(t.present,b),w)},[t.present]),g=u.useCallback((b,w)=>{a.current=da(yt(t.present,b),w),n({type:"CUT",layerId:b,range:w})},[t.present]),y=u.useCallback((b,w)=>{a.current.length>0&&n({type:"PASTE",layerId:b,clipboard:a.current,targetTime:w})},[]),m=u.useCallback((b,w)=>n({type:"DELETE_RANGE",layerId:b,range:w}),[]),x=u.useCallback((b,w,N,$)=>n({type:"RECORD",layerId:b,cc:w,value:N,time:$}),[]),v=u.useCallback((b,w)=>n({type:"THIN",layerId:b,keepEveryN:w}),[]),f=u.useCallback(b=>Xi(yt(t.present,b)),[t.present]),k=u.useCallback((b,w)=>n({type:"IMPORT",layerId:b,json:w}),[]);return{snapshots:t.present,getEvents:s,addEvent:i,updateEvent:o,removeEvent:l,setEvents:c,undo:d,redo:h,canUndo:Vi(t),canRedo:Ui(t),copy:p,cut:g,paste:y,clipboard:a.current,deleteRange:m,record:x,thin:v,exportLane:f,importLane:k}}let Hd=Date.now();function yn(){return Hd++}function Kd(e,t,n=.01){if(e.length===0)return[];const a=[];let s=-1/0;for(const i of e)i.time-s>=n&&(a.push({id:yn(),cc:t,value:vn(i.value),time:i.time}),s=i.time);return a}function xs(e,t,n,a=32){const s=[];for(let i=0;i<=a;i++){const o=i/a;s.push({id:yn(),cc:n,value:vn(jr(e.value,t.value,o)),time:jr(e.time,t.time,o)})}return s}function Yd(e,t,n,a,s=48){const i=[];for(let o=0;o<=s;o++){const l=o/s,c=Ss(e.time,t.time,n.time,l),d=Ss(e.value,t.value,n.value,l);i.push({id:yn(),cc:a,value:vn(d),time:c})}return i}function Zd(e,t,n,a=8){const s=[],i=(t.time-e.time)/a,o=(t.value-e.value)/a;for(let l=0;l<a;l++){const c=e.time+l*i,d=vn(e.value+l*o);s.push({id:yn(),cc:n,value:d,time:c}),s.push({id:yn(),cc:n,value:d,time:c+i-.001})}return s}function Xd(e,t,n,a=2,s=32){const i=[];for(let o=0;o<=s;o++){const l=o/s,c=Math.pow(l,a);i.push({id:yn(),cc:n,value:vn(jr(e.value,t.value,c)),time:jr(e.time,t.time,l)})}return i}function Qd(e,t=3){if(e.length<t)return e;const n=[...e].sort((a,s)=>a.time-s.time);return n.map((a,s)=>{const i=Math.max(0,s-Math.floor(t/2)),o=Math.min(n.length,i+t),l=n.slice(i,o),c=l.reduce((d,h)=>d+h.value,0)/l.length;return{...a,value:vn(Math.round(c))}})}function Jd(e,t){let n;switch(e.mode){case"pencil":n=Kd(t,e.cc,e.resolution);break;case"line":n=t.length>=2?xs(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?n=Yd(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?n=xs(t[0],t[t.length-1],e.cc):n=[];break;case"step":n=t.length>=2?Zd(t[0],t[t.length-1],e.cc):[];break;case"ramp":n=t.length>=2?Xd(t[0],t[t.length-1],e.cc):[];break;default:n=[]}if(e.smoothing>0){const a=Math.max(2,Math.round(e.smoothing*8));n=Qd(n,a)}return n}function vn(e){return Math.max(0,Math.min(127,Math.round(e)))}function jr(e,t,n){return e+(t-e)*n}function Ss(e,t,n,a){const s=1-a;return s*s*e+2*s*a*t+a*a*n}function _r(){return{waveform:"sine",rate:1,depth:.5,phase:0,center:.5,syncToBpm:!1,syncDivision:"1/4",enabled:!0}}const eu={"4/1":.25,"2/1":.5,"1/1":1,"1/2":2,"1/4":4,"1/8":8,"1/16":16,"1/32":32,"1/2t":3,"1/4t":6,"1/8t":12,"1/16t":24};function eo(e,t){return e/60*eu[t]/4}function to(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 Aa(e,t,n){if(!e.enabled)return e.center;const a=e.syncToBpm&&n?eo(n,e.syncDivision):e.rate,s=t*a+e.phase/(2*Math.PI),i=to(e.waveform,s),o=e.center+i*e.depth*.5;return Math.max(0,Math.min(1,o))}function Ia(e,t,n){return Math.round(Aa(e,t,n)*127)}function no(e,t,n,a,s=30,i){const o=n-t,l=Math.max(2,Math.ceil(o*s)),c=[];for(let d=0;d<=l;d++){const h=t+d/l*o,p=Ia(e,h,i);c.push({time:h,value:p,cc:a})}return c}function ro(e,t,n,a=2,s,i=200){const o=[];for(let l=0;l<=i;l++){const c=l/i*a,d=Aa(e,c,s);o.push({x:l/i*t,y:(1-d)*n})}return o}function tu(e){return JSON.stringify(e,null,2)}function nu(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const Yr=140,bn=24,ru=[{cc:1,key:"modWheel",label:"Mod Wheel"},{cc:7,key:"volume",label:"Volume"},{cc:10,key:"pan",label:"Pan"},{cc:11,key:"expression",label:"Expression"},{cc:64,key:"sustain",label:"Sustain"},{cc:74,key:"brightness",label:"Brightness"}],au=[{mode:"pencil",label:"Pencil"},{mode:"line",label:"Line"},{mode:"curve",label:"Curve"},{mode:"step",label:"Step"},{mode:"ramp",label:"Ramp"}],su=["sine","triangle","sawtooth","square","random","sample-hold"],iu=({layerId:e=0,ccNumber:t,duration:n=8,zoom:a=1,automation:s,onChangeCCNumber:i})=>{const o=Ji(),l=s??o,[c,d]=we.useControllableState({value:t,fallbackValue:1,onChange:i,componentName:"NiceCCAutomationLaneEditor"}),{t:h}=be(),p=u.useRef(null),[g,y]=u.useState("pencil"),[m,x]=u.useState(!1),v=u.useRef([]),[f,k]=u.useState(null),[b,w]=u.useState(!1),[N,$]=u.useState(_r()),M=u.useRef(null),E=l.getEvents(e),R=E.filter(C=>C.cc===c),L=Math.max(400,n*30*a),A=u.useCallback(C=>C/L*n,[L,n]),z=u.useCallback(C=>Math.round(Math.max(0,Math.min(127,127-(C-bn)/Yr*127))),[]),j=u.useCallback(C=>C/n*L,[L,n]),I=u.useCallback(C=>bn+(127-C)/127*Yr,[]),Y=u.useCallback(()=>{const C=p.current;if(!C)return;const T=C.getContext("2d");if(!T)return;const S=C.width,F=C.height;T.clearRect(0,0,S,F),T.fillStyle=we.resolveCssColor("var(--nice-bg, #1a1a2e)",T.canvas),T.fillRect(0,0,S,F);const K=we.resolveCssColor("var(--nice-border-color, #cbd5e1)",T.canvas);T.strokeStyle=K,T.lineWidth=1,T.globalAlpha=.5;for(let _=0;_<=127;_+=16){const U=I(_);T.beginPath(),T.moveTo(0,U),T.lineTo(S,U),T.stroke()}T.globalAlpha=1,T.fillStyle=we.resolveCssColor("var(--nice-text-muted, #64748b)",T.canvas),T.font="10px monospace",T.textBaseline="middle";for(const _ of[0,32,64,96,127])T.fillText(String(_),2,I(_));T.strokeStyle=K,T.globalAlpha=.3;for(let _=0;_<=n;_++){const U=j(_);T.beginPath(),T.moveTo(U,0),T.lineTo(U,F),T.stroke()}T.globalAlpha=1;const P=[...R].sort((_,U)=>_.time-U.time);if(P.length>0){T.beginPath(),T.moveTo(j(P[0].time),F-bn);for(const _ of P)T.lineTo(j(_.time),I(_.value));T.lineTo(j(P[P.length-1].time),F-bn),T.closePath(),T.fillStyle=we.resolveCssColor("var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",T.canvas),T.fill(),T.beginPath(),T.strokeStyle=we.resolveCssColor("var(--nice-primary, #3b82f6)",T.canvas),T.lineWidth=2;for(let _=0;_<P.length;_++){const U=j(P[_].time),J=I(P[_].value);_===0?T.moveTo(U,J):((P[_].handleType??"linear")==="step"&&T.lineTo(U,I(P[_-1].value)),T.lineTo(U,J))}T.stroke();for(const _ of P){const U=j(_.time),J=I(_.value),se=f===_.id;T.beginPath(),T.arc(U,J,se?6:4,0,Math.PI*2),T.fillStyle=we.resolveCssColor(se?"var(--nice-primary-light, #60a5fa)":"var(--nice-primary, #3b82f6)",T.canvas),T.fill(),T.strokeStyle=we.resolveCssColor("var(--nice-bg, #fff)",T.canvas),T.lineWidth=1.5,T.stroke()}}T.strokeStyle=K,T.lineWidth=1,T.setLineDash([4,4]);const B=I(0);T.beginPath(),T.moveTo(0,B),T.lineTo(S,B),T.stroke(),T.setLineDash([])},[R,n,L,j,I,f]);u.useEffect(()=>{Y()},[Y]);const H=C=>{var K;const T=(K=p.current)==null?void 0:K.getBoundingClientRect();if(!T)return;const S=C.clientX-T.left,F=C.clientY-T.top;g==="pencil"?(x(!0),v.current=[{time:A(S),value:z(F)}]):(x(!0),v.current=[{time:A(S),value:z(F)}])},D=C=>{var B;const T=(B=p.current)==null?void 0:B.getBoundingClientRect();if(!T)return;const S=C.clientX-T.left,F=C.clientY-T.top;m&&v.current.push({time:A(S),value:z(F)});const K=[...R].sort((_,U)=>_.time-U.time);let P=null;for(const _ of K){const U=j(_.time),J=I(_.value);if(Math.abs(S-U)<8&&Math.abs(F-J)<8){P=_.id;break}}k(P)},V=()=>{if(!m)return;x(!1);const C=v.current;if(C.length===0)return;const T=Jd({mode:g,cc:c,resolution:.02,smoothing:g==="pencil"?.3:0},C);T.length>0&&l.setEvents(e,[...E,...T]),v.current=[]},Z=C=>{var K;const T=(K=p.current)==null?void 0:K.getBoundingClientRect();if(!T)return;const S=C.clientX-T.left,F=C.clientY-T.top;for(const P of R){const B=j(P.time),_=I(P.value);if(Math.abs(S-B)<8&&Math.abs(F-_)<8){l.removeEvent(e,P.id);return}}l.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:c,value:z(F),time:A(S)})},X=()=>{const T=no(N,0,n,c,Math.ceil(n*20),120).map((S,F)=>({...S,id:Date.now()+F}));l.setEvents(e,[...E,...T]),w(!1)},q=()=>{const C=l.exportLane(e),T=new Blob([C],{type:"application/json"}),S=URL.createObjectURL(T),F=document.createElement("a");F.href=S,F.download=`cc-lane-${c}-layer-${e}.json`,document.body.appendChild(F),F.click(),F.remove(),URL.revokeObjectURL(S)},G=C=>{var S;const T=(S=C.target.files)==null?void 0:S[0];T&&(T.text().then(F=>{l.importLane(e,F)}),M.current&&(M.current.value=""))};return r.jsxs("div",{className:me.panel,children:[r.jsxs("div",{className:me.header,children:[r.jsx("h6",{className:me.title,children:h("ccLane.title","CC Automation Lane")}),r.jsx(ie.NiceSelect,{size:"sm",controlWidth:180,"aria-label":h("ccLane.controller","Controller"),value:String(c),onChange:C=>d(Number(Pt(C))),options:ru.map(C=>({value:String(C.cc),label:`${h(`ccLane.preset.${C.key}`,C.label)} (CC${C.cc})`}))}),r.jsx(ie.NiceSegmentedControl,{size:"sm",value:g,onChange:y,options:au.map(C=>({value:C.mode,label:h(`ccLane.mode.${C.mode}`,C.label)}))}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(O.NtdUndo,{size:14}),ariaLabel:h("ccLane.undo","Undo"),title:h("ccLane.undo","Undo"),onClick:l.undo,disabled:!l.canUndo,children:null}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(O.NtdRedo,{size:14}),ariaLabel:h("ccLane.redo","Redo"),title:h("ccLane.redo","Redo"),onClick:l.redo,disabled:!l.canRedo,children:null})]}),r.jsxs("div",{className:me.toolbar,children:[r.jsx(ie.NiceButton,{size:"sm",variant:b?"primary":"outline","aria-pressed":b,onClick:()=>w(!b),title:h("ccLane.lfoHint","Apply LFO modulation"),children:h("ccLane.lfo","LFO")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:q,title:h("ccLane.exportHint","Export CC lane as JSON"),children:h("ccLane.export","Export")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:()=>{var C;return(C=M.current)==null?void 0:C.click()},title:h("ccLane.importHint","Import CC lane from JSON"),children:h("ccLane.import","Import")}),r.jsx("input",{ref:M,type:"file",accept:".json",hidden:!0,onChange:G}),r.jsx(ie.NiceButton,{size:"sm",variant:"danger",onClick:()=>l.setEvents(e,E.filter(C=>C.cc!==c)),title:h("ccLane.clearHint","Clear all CC events for this lane"),children:h("ccLane.clear","Clear")}),r.jsxs("span",{className:`${me.noteText} ${me.pushRight}`,children:[R.length," ",h("ccLane.events","events")]})]}),b&&r.jsxs("div",{className:me.subPanel,children:[r.jsxs("div",{className:`${me.row} ${me.alignStart} ${me.field}`,children:[r.jsx(ie.NiceSelect,{size:"sm",controlWidth:130,label:h("ccLane.lfoWave","Wave"),value:N.waveform,onChange:C=>$(T=>({...T,waveform:Pt(C)})),options:su.map(C=>({value:C,label:C}))}),r.jsx(ie.NiceNumberInput,{size:"sm",className:me.inputW120,label:h("ccLane.lfoRate","Rate (Hz)"),min:.01,max:20,step:.1,precision:2,value:N.rate,onChange:C=>{C!==null&&$(T=>({...T,rate:C}))}}),r.jsx("div",{className:me.sliderW200,children:r.jsx(ie.NiceSlider,{size:"sm",label:h("ccLane.lfoDepth","Depth"),min:0,max:1,step:.01,value:N.depth,onChange:C=>$(T=>({...T,depth:C})),showValue:!0,formatValue:C=>C.toFixed(2)})}),r.jsx("div",{className:me.sliderW200,children:r.jsx(ie.NiceSlider,{size:"sm",label:h("ccLane.lfoCenter","Center"),min:0,max:1,step:.01,value:N.center,onChange:C=>$(T=>({...T,center:C})),showValue:!0,formatValue:C=>C.toFixed(2)})})]}),r.jsxs("div",{className:me.buttonRow,children:[r.jsx(ie.NiceButton,{size:"sm",variant:"primary",onClick:X,children:h("ccLane.applyLfo","Apply LFO")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:()=>w(!1),children:h("ccLane.cancel","Cancel")})]})]}),r.jsx("div",{style:{overflowX:"auto",borderRadius:6},children:r.jsx("canvas",{ref:p,width:L,height:Yr+bn*2,style:{cursor:m?"crosshair":f?"pointer":"crosshair",display:"block",borderRadius:6},onMouseDown:H,onMouseMove:D,onMouseUp:V,onMouseLeave:()=>{m&&V()},onDoubleClick:Z,role:"img","aria-label":h("ccLane.canvas","CC automation lane")})}),r.jsx("div",{className:me.noteTextMargin,children:h("ccLane.hint","Click to draw. Double-click to add/remove points. Drag to draw curves.")})]})},ao={"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},ua={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function ou(e,t){const n=[];for(let a=0;a<t;a++)for(const s of e)n.push({...s,pitch:s.pitch+a*12});return n}function so(e,t){if(e.length===0)return[];const n=ou(e,t.octaves),a=[...n].sort((o,l)=>o.pitch-l.pitch),s=[...n].sort((o,l)=>l.pitch-o.pitch);let i;switch(t.mode){case"up":i=a;break;case"down":i=s;break;case"updown":i=[...a,...s.slice(1,-1)];break;case"downup":i=[...s,...a.slice(1,-1)];break;case"random":i=[...n].sort(()=>Math.random()-.5);break;case"as-played":i=[...n].sort((o,l)=>o.originalOrder-l.originalOrder);break;case"chord":i=n;break;default:i=a}if(t.repeats>1){const o=[];for(const l of i)for(let c=0;c<t.repeats;c++)o.push(l);i=o}return i}function lu(e,t,n,a=0,s=1){const i=so(e,t);if(i.length===0)return[];const o=60/n,l=ao[t.rate]*o,c=l*t.gate,d=[],h=t.mode==="chord",p=h?s:i.length*s;for(let g=0;g<p;g++){const y=g%2===1?l*t.swing*.5:0,m=a+g*l+y;if(h)for(const x of i){const v=t.velocityPattern?t.velocityPattern[g%t.velocityPattern.length]:x.velocity;d.push({pitch:x.pitch,velocity:v,startTime:m,duration:c,step:g})}else{const x=g%i.length,v=i[x],f=t.velocityPattern?t.velocityPattern[g%t.velocityPattern.length]:v.velocity;d.push({pitch:v.pitch,velocity:f,startTime:m,duration:c,step:g})}}return d}function io(){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 oo(){return Object.keys(ao)}const ks=e=>`${Math.round(e*100)}%`,cu=({config:e=ua,onChange:t=()=>{},active:n=!1,onToggleActive:a=()=>{}})=>{const{t:s}=be(),i=io(),o=oo(),l=c=>t({...e,...c});return r.jsxs("div",{className:`${me.panel} ${n?"":me.panelInactive}`,children:[r.jsxs("div",{className:me.header,children:[r.jsx("h6",{className:me.title,children:s("arp.title","Arpeggiator")}),r.jsx(ie.NiceButton,{size:"sm",variant:n?"success":"outline","aria-pressed":n,onClick:a,children:n?s("arp.on","ON"):s("arp.off","OFF")}),r.jsx(ie.NiceButton,{size:"sm",variant:e.latch?"warning":"outline","aria-pressed":!!e.latch,onClick:()=>l({latch:!e.latch}),title:s("arp.latchHint","Latch — keep arp running after releasing keys"),children:s("arp.latch","Latch")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:()=>t(ua),title:s("arp.resetHint","Reset to defaults"),children:s("arp.reset","Reset")})]}),r.jsxs("div",{className:me.grid2,children:[r.jsxs("div",{className:me.full,children:[r.jsx("span",{className:me.label,children:s("arp.mode","Mode")}),r.jsx(ie.NiceSegmentedControl,{size:"sm",block:!0,value:e.mode,onChange:c=>l({mode:c}),options:i.map(c=>({value:c.mode,label:r.jsx("span",{title:c.description,children:c.label})}))})]}),r.jsx(ie.NiceSelect,{size:"sm",label:s("arp.rate","Rate"),value:e.rate,onChange:c=>l({rate:Pt(c)}),options:o.map(c=>({value:c,label:c}))}),r.jsx(ie.NiceSlider,{size:"sm",label:s("arp.octaves","Octaves"),min:1,max:4,step:1,value:e.octaves,onChange:c=>l({octaves:c}),showValue:!0}),r.jsx(ie.NiceSlider,{size:"sm",label:s("arp.gate","Gate"),min:.05,max:1,step:.05,value:e.gate,onChange:c=>l({gate:c}),showValue:!0,formatValue:ks}),r.jsx(ie.NiceSlider,{size:"sm",label:s("arp.swing","Swing"),min:0,max:1,step:.01,value:e.swing,onChange:c=>l({swing:c}),showValue:!0,formatValue:ks}),r.jsx(ie.NiceSlider,{size:"sm",label:s("arp.repeats","Repeats"),min:1,max:4,step:1,value:e.repeats,onChange:c=>l({repeats:c}),showValue:!0})]})]})},ws=e=>`${Math.round(e*100)}%`,du=["sine","triangle","sawtooth","square","random","sample-hold"],uu=["1/1","1/2","1/4","1/8","1/16","1/32"],xn=200,en=48,hu=({config:e,onChange:t,index:n,onRemove:a})=>{const{t:s}=be(),i=u.useRef(null),o=c=>t({...e,...c}),l=u.useCallback(()=>{const c=i.current;if(!c)return;const d=c.getContext("2d");if(!d)return;d.clearRect(0,0,xn,en),d.fillStyle=we.resolveCssColor("var(--nice-bg-secondary, #161b22)",d.canvas),d.fillRect(0,0,xn,en),d.strokeStyle=we.resolveCssColor("var(--nice-border-color, #cbd5e1)",d.canvas),d.lineWidth=1,d.setLineDash([3,3]),d.beginPath(),d.moveTo(0,en/2),d.lineTo(xn,en/2),d.stroke(),d.setLineDash([]);const h=ro(e,xn,en);if(h.length>0){d.beginPath(),d.strokeStyle=we.resolveCssColor(e.enabled?"var(--nice-primary, #3b82f6)":"var(--nice-text-secondary, #484f58)",d.canvas),d.lineWidth=1.5;for(let p=0;p<h.length;p++){const g=h[p].x,y=h[p].y;p===0?d.moveTo(g,y):d.lineTo(g,y)}d.stroke()}},[e]);return u.useEffect(()=>{l()},[l]),r.jsxs("div",{className:`${me.panel} ${me.panelCompact} ${e.enabled?"":me.panelInactive}`,children:[r.jsxs("div",{className:me.header,children:[r.jsxs("h6",{className:me.title,children:[s("lfo.title","LFO")," ",n!==void 0?`#${n+1}`:""]}),r.jsx(ie.NiceButton,{size:"xs",variant:e.enabled?"success":"outline","aria-pressed":e.enabled,onClick:()=>o({enabled:!e.enabled}),children:e.enabled?s("lfo.on","ON"):s("lfo.off","OFF")}),r.jsx(ie.NiceButton,{size:"xs",variant:"outline",onClick:()=>t(_r()),title:s("lfo.resetHint","Reset to defaults"),children:s("lfo.reset","Reset")}),a&&r.jsx("span",{className:me.pushRight,children:r.jsx(ie.NiceButton,{size:"xs",variant:"ghost",onClick:a,"aria-label":s("lfo.remove","Remove LFO"),title:s("lfo.remove","Remove LFO"),children:r.jsx(O.NtdClose,{size:12})})})]}),r.jsxs("div",{className:`${me.row} ${me.alignStart}`,children:[r.jsx("canvas",{ref:i,width:xn,height:en,style:{borderRadius:4,border:"1px solid var(--nice-border-color, #30363d)",flexShrink:0},role:"img","aria-label":s("lfo.preview","LFO waveform preview")}),r.jsxs("div",{className:me.grow,children:[r.jsx("div",{className:me.field,children:r.jsx(ie.NiceSegmentedControl,{size:"xs",block:!0,value:e.waveform,onChange:c=>o({waveform:c}),options:du.map(c=>({value:c,label:r.jsx("span",{title:c,children:c==="sample-hold"?"S&H":c.slice(0,3)})}))})}),r.jsxs("div",{className:me.grid2,children:[r.jsx(ie.NiceSlider,{size:"xs",label:s("lfo.rate","Rate"),min:.01,max:20,step:.1,value:e.rate,onChange:c=>o({rate:c}),showValue:!0,formatValue:c=>`${c.toFixed(1)} Hz`}),r.jsx(ie.NiceSlider,{size:"xs",label:s("lfo.depth","Depth"),min:0,max:1,step:.01,value:e.depth,onChange:c=>o({depth:c}),showValue:!0,formatValue:ws}),r.jsx(ie.NiceSlider,{size:"xs",label:s("lfo.center","Center"),min:0,max:1,step:.01,value:e.center,onChange:c=>o({center:c}),showValue:!0,formatValue:ws}),r.jsx(ie.NiceSlider,{size:"xs",label:s("lfo.phase","Phase"),min:0,max:360,step:1,value:e.phase,onChange:c=>o({phase:c}),showValue:!0,formatValue:c=>`${Math.round(c)}°`})]}),r.jsxs("div",{className:me.row,children:[r.jsx(ie.NiceCheckbox,{size:"xs",label:s("lfo.bpmSync","BPM Sync"),checked:e.syncToBpm,onChange:c=>o({syncToBpm:c})}),e.syncToBpm&&r.jsx(ie.NiceSelect,{size:"xs","aria-label":s("lfo.syncDivision","Sync division"),value:e.syncDivision??"1/4",onChange:c=>o({syncDivision:Pt(c)}),options:uu.map(c=>({value:c,label:c}))}),r.jsx(ie.NiceNumberInput,{size:"xs",label:s("lfo.cc","CC"),min:0,max:127,value:e.targetCC??1,onChange:c=>o({targetCC:c??1})})]})]})]})]})},pu=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],fu=[16,32,64],mu=e=>`${Math.round(e*100)}%`;function Cs(e){const t=Math.floor(e/12)-1;return`${pu[e%12]}${t}`}const gu=({seq:e})=>{const{t}=be(),n=e==null?void 0:e.pattern,a=u.useMemo(()=>n?n.steps.slice(0,n.length):[],[n]);if(!e||!n)return r.jsxs("div",{className:me.panel,children:[r.jsx("h6",{className:me.title,children:t("stepSeq.title","Step Sequencer")}),r.jsx("div",{className:me.noteTextMargin,children:t("stepSeq.noSeq","Provide a `seq` prop (useStepSequencer) for live editing.")})]});const{currentStep:s,playing:i}=e,o=l=>c=>{var m;c.preventDefault();const d=c.currentTarget,h=d.getBoundingClientRect(),p=x=>e.setVelocity(l,Math.round(Math.max(1,Math.min(127,(1-(x-h.top)/h.height)*127)))),g=x=>p(x.clientY),y=()=>{d.removeEventListener("pointermove",g),d.removeEventListener("pointerup",y),d.removeEventListener("pointercancel",y)};(m=d.setPointerCapture)==null||m.call(d,c.pointerId),d.addEventListener("pointermove",g),d.addEventListener("pointerup",y),d.addEventListener("pointercancel",y),p(c.clientY)};return r.jsxs("div",{className:me.panel,children:[r.jsxs("div",{className:me.header,children:[r.jsx("h6",{className:me.title,children:t("stepSeq.title","Step Sequencer")}),r.jsx(ie.NiceButton,{size:"sm",variant:i?"danger":"success",leftIcon:i?r.jsx(O.NtdStop,{size:12}):r.jsx(O.NtdPlay,{size:12}),onClick:e.togglePlayback,children:i?t("stepSeq.stop","Stop"):t("stepSeq.play","Play")})]}),r.jsxs("div",{className:`${me.row} ${me.alignStart} ${me.field}`,children:[r.jsx(ie.NiceNumberInput,{size:"sm",className:me.inputW120,label:t("stepSeq.bpm","BPM"),min:20,max:300,value:n.bpm,onChange:l=>{l!==null&&e.setBpm(l)}}),r.jsx("div",{className:me.sliderW200,children:r.jsx(ie.NiceSlider,{size:"sm",label:t("stepSeq.swing","Swing"),min:0,max:1,step:.01,value:n.swing,onChange:e.setSwing,showValue:!0,formatValue:mu})}),r.jsxs("div",{children:[r.jsx("span",{className:me.label,children:t("stepSeq.length","Steps")}),r.jsx(ie.NiceSegmentedControl,{size:"sm",value:n.length,onChange:e.setLength,options:fu.map(l=>({value:l,label:String(l)}))})]})]}),r.jsxs("div",{className:me.toolbar,children:[r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:()=>e.transpose(1),title:t("stepSeq.transposeUp","Transpose up one semitone"),children:"+1"}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:()=>e.transpose(-1),title:t("stepSeq.transposeDown","Transpose down one semitone"),children:"-1"}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:()=>e.transpose(12),title:t("stepSeq.octaveUpHint","Transpose up one octave"),children:t("stepSeq.octaveUp","+Oct")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:()=>e.transpose(-12),title:t("stepSeq.octaveDownHint","Transpose down one octave"),children:t("stepSeq.octaveDown","-Oct")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:e.reverse,children:t("stepSeq.reverse","Reverse")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",rightIcon:r.jsx(O.NtdArrowRight,{size:12}),onClick:()=>e.shift(1),children:t("stepSeq.shift","Shift")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(O.NtdArrowLeft,{size:12}),onClick:()=>e.shift(-1),children:t("stepSeq.shift","Shift")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:()=>e.randomizeVel(),title:t("stepSeq.randomVelocityHint","Randomize velocities"),children:t("stepSeq.randomVelocity","Rnd Vel")}),r.jsx(ie.NiceButton,{size:"sm",variant:"danger",onClick:e.clear,children:t("stepSeq.clear","Clear")})]}),r.jsx("div",{style:{overflowX:"auto"},children:r.jsx("div",{style:{display:"flex",gap:2,minWidth:n.length*36},children:a.map((l,c)=>{const d=l.active,h=s===c,p=c%4===0;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2,minWidth:34},children:[r.jsx("span",{style:{fontSize:9,color:p?"var(--nice-text-muted, #8b949e)":"var(--nice-text-secondary, #30363d)"},children:c+1}),r.jsx("button",{type:"button","aria-pressed":d,"aria-label":`${t("stepSeq.step","Step")} ${c+1}${d?`, ${Cs(l.note)}`:""}`,onClick:()=>e.toggle(c),style:{width:32,height:32,borderRadius:4,border:h?"2px solid var(--nice-warning, #f0c040)":"1px solid var(--nice-border, #30363d)",background:d?`hsl(${210+l.velocity/127*40}, 80%, ${35+l.velocity/127*20}%)`:p?"var(--nice-bg-secondary, #21262d)":"var(--nice-bg-secondary, #161b22)",cursor:"pointer",padding:0,color:d?"var(--nice-color-white, #ffffff)":"var(--nice-text-secondary, #484f58)",fontSize:8,fontWeight:600,transition:"background 0.1s"},children:d?Cs(l.note):""}),r.jsx("div",{style:{width:32,height:20,background:"var(--nice-bg-secondary, #161b22)",borderRadius:2,position:"relative",overflow:"hidden",cursor:"ns-resize",touchAction:"none"},title:`${t("stepSeq.velocity","Velocity")}: ${l.velocity}`,onPointerDown:o(c),children:r.jsx("div",{style:{position:"absolute",bottom:0,left:0,width:"100%",height:`${l.velocity/127*100}%`,background:d?"var(--nice-primary-tint-60, rgba(59, 130, 246, 0.6))":"var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",borderRadius:2,pointerEvents:"none"}})}),d&&l.probability<1&&r.jsxs("span",{style:{fontSize:8,color:"var(--nice-warning, #f0c040)"},children:[Math.round(l.probability*100),"%"]})]},c)})})}),r.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginTop:6},children:t("stepSeq.hint","Click steps to toggle. Drag velocity bars vertically.")})]})};function yu(e,t,n){const[a,s]=u.useState("interval"),[i,o]=u.useState(30),l=u.useRef(null),c=u.useCallback(()=>{if(e)try{localStorage.setItem("audioEditor.autoSave",JSON.stringify(e)),t("Project auto-saved locally"),n("success"),setTimeout(()=>t(""),2e3)}catch(d){t("Auto-save error: "+d.message),n("error")}},[e,t,n]);return u.useEffect(()=>{(a==="onChange"||a==="both")&&c()},[e,a,c]),u.useEffect(()=>(l.current&&(clearInterval(l.current),l.current=null),(a==="interval"||a==="both")&&i>0&&(l.current=window.setInterval(c,i*1e3)),()=>{l.current&&(clearInterval(l.current),l.current=null)}),[a,i,c]),{autoSaveMode:a,setAutoSaveMode:s,autoSaveInterval:i,setAutoSaveInterval:o}}function vu(e,t,n){const a=u.useRef(null),[s,i]=u.useState(!1),[o,l]=u.useState(0),[c,d]=u.useState(10),[h,p]=u.useState(!1),[g,y]=u.useState(120),m=u.useCallback((M,E)=>`L${M}-C${E}`,[]),x=u.useCallback((M,E)=>{if(!a.current||!E.audioBuffer)return;const R=m(M,E.id),L=e[M];a.current.addClip({id:R,buffer:E.audioBuffer,startTime:E.start,offset:0,duration:E.duration,layerId:M,volume:(L==null?void 0:L.volume)??1,pan:(L==null?void 0:L.pan)??0,stretchFactor:E.stretchFactor||1,effectChain:(L==null?void 0:L.effectChain)||[]})},[e,m]),v=u.useCallback((M,E)=>{var R;(R=a.current)==null||R.removeClip(m(M,E))},[m]);u.useEffect(()=>{Object.entries(t).forEach(([M,E])=>{const R=Number(M);E==null||E.forEach(L=>x(R,L))})},[t,e,x]),u.useEffect(()=>{a.current&&Object.entries(n).forEach(([M,E])=>{const R=Number(M);a.current.setMidiCCEvents(R,E)})},[n]);const f=u.useCallback(()=>{a.current&&(s?a.current.pause():a.current.play())},[s]),k=u.useCallback(()=>{var M;(M=a.current)==null||M.stop()},[]),b=u.useCallback(M=>{var E;(E=a.current)==null||E.seek(M)},[]),w=u.useCallback(()=>{if(!a.current)return;const M=!h;p(M),a.current.setLoopRegion(0,c,M)},[h,c]),N=u.useCallback(M=>{var R;const E=Math.max(1,c+M);d(E),(R=a.current)==null||R.setLoopRegion(0,E,h)},[c,h]),$=u.useCallback(async(M,E=1024)=>{const R=await M.arrayBuffer(),L=new(window.AudioContext||window.webkitAudioContext),A=await L.decodeAudioData(R.slice(0)),z=A.getChannelData(0),j=z.length,I=Math.max(1,Math.floor(j/E)),Y=[];for(let H=0;H<E;H++){const D=H*I;if(D>=j)break;Y.push(z[D])}return L.close(),{waveform:Y.map(H=>Math.max(-1,Math.min(1,H))),duration:A.duration,buffer:A}},[]);return{engineRef:a,isPlaying:s,setIsPlaying:i,currentTime:o,setCurrentTime:l,duration:c,setDuration:d,isLooping:h,setIsLooping:p,bpm:g,setBpm:y,handlePlayPause:f,handleStop:k,handleSeek:b,handleToggleLoop:w,handleAdjustDuration:N,upsertEngineClip:x,removeEngineClip:v,makeEngineClipId:m,blobToWaveform:$}}class La{constructor(){this.stream=null,this.mediaRecorder=null,this.audioChunks=[],this.isRecording=!1,this.audioContext=null,this.analyser=null,this.gainNode=null,this.monitorGain=null,this.levelRaf=null}async startRecording(t={}){if(this.isRecording)return;this.levelCallback=t.onLevel,this.stream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t.deviceId||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}});const n=t.mimeType||"audio/webm";this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:n}),this.audioChunks=[],this.audioContext=new(window.AudioContext||window.webkitAudioContext);let s=this.audioContext.createMediaStreamSource(this.stream);t.gain!==void 0&&t.gain>0&&(this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=t.gain,s.connect(this.gainNode),s=this.gainNode),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,s.connect(this.analyser),t.monitorEnabled&&(this.monitorGain=this.audioContext.createGain(),this.monitorGain.gain.value=(t.monitorVolume??100)/100,s.connect(this.monitorGain),this.monitorGain.connect(this.audioContext.destination));const i=()=>{if(!this.analyser)return;const o=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(o);let l=0;for(let d=0;d<o.length;d++){const h=(o[d]-128)/128;l+=h*h}const c=Math.sqrt(l/o.length);this.levelCallback&&this.levelCallback(c),this.isRecording&&(this.levelRaf=requestAnimationFrame(i))};this.mediaRecorder.ondataavailable=o=>{o.data&&o.data.size>0&&this.audioChunks.push(o.data)},this.mediaRecorder.start(),this.isRecording=!0,this.levelRaf=requestAnimationFrame(i)}getStream(){return this.stream}async stopRecording(){return!this.isRecording||!this.mediaRecorder?null:new Promise(t=>{const n=this.mediaRecorder;n.onstop=()=>{const a=new Blob(this.audioChunks,{type:n.mimeType});this.cleanup(),t(a)},n.stop(),this.isRecording=!1})}cleanup(){this.levelRaf&&(cancelAnimationFrame(this.levelRaf),this.levelRaf=null),this.levelCallback=void 0,this.monitorGain&&(this.monitorGain.disconnect(),this.monitorGain=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.analyser&&(this.analyser.disconnect(),this.analyser=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.stream&&(this.stream.getTracks().forEach(t=>t.stop()),this.stream=null),this.mediaRecorder=null,this.audioChunks=[]}}function bu(e){const[t,n]=u.useState(!1),[a,s]=u.useState(!1),[i,o]=u.useState(0),[l,c]=u.useState(0),[d,h]=u.useState(null),p=u.useRef(null),g=u.useRef(null),y=u.useRef(0),m=u.useRef(null),x=u.useRef(null),v=u.useCallback(()=>{m.current&&(clearInterval(m.current),m.current=null),x.current&&(clearTimeout(x.current),x.current=null)},[]),f=u.useCallback(async()=>{if(!e.activeLayer){e.showToast("Select a layer to record.","error");return}t||(p.current||(p.current=new La),y.current=g.current??e.currentTime,n(!0),o(0),await p.current.startRecording({onLevel:o}))},[e,t]),k=u.useCallback(async()=>{var z;if(v(),s(!1),c(0),g.current=null,!p.current){n(!1),o(0);return}const N=await p.current.stopRecording();if(n(!1),o(0),!N||!e.activeLayer)return;const{waveform:$,duration:M,buffer:E}=await e.blobToWaveform(N),R=e.activeLayer.id;e.setWaveforms(j=>({...j,[R]:$}));const L=Math.max(0,y.current||0),A={id:Date.now(),label:"Recording",start:L,duration:M,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:(z=e.layerSettings[R])==null?void 0:z.color,blob:N,blobUrl:URL.createObjectURL(N),audioBuffer:E};e.setLayerClips(j=>({...j,[R]:[...j[R]||[],A]})),e.upsertEngineClip(R,A),e.setSelectedClip({layerId:R,clipId:A.id})},[e,v]),b=u.useCallback(N=>{if(N<=0){f();return}s(!0),c(N);const $=performance.now();m.current=window.setInterval(()=>{const M=(performance.now()-$)/1e3;c(Math.max(0,N-M))},100),x.current=window.setTimeout(()=>{v(),s(!1),c(0),g.current||f()},N*1e3)},[f,v]),w=u.useCallback(async()=>{if(t||a){await k();return}if(!e.activeLayer){e.showToast("Select a layer before recording","error");return}const N=Math.max(0,e.countInBars)*4*(60/e.bpm),$=e.punchIn!=null&&e.punchIn>e.currentTime?e.punchIn:null;$&&(g.current=$),e.overdubEnabled&&!e.isPlaying&&e.playEngine(),$?N>0&&b(N):b(N)},[t,a,e,k,b]);return{isRecording:t,isCountIn:a,monitorLevel:i,countInRemaining:l,punchOut:d,setPunchOut:h,armedPunchInRef:g,recorderRef:p,clearCountInTimers:v,startRecordingNow:f,stopRecordingFlow:k,handleRecord:w}}var lo=(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))(lo||{});const xu={};class Xn{constructor(t,n,a,s={}){this.type=t,this.name=n,this.component=xu[t]??(()=>null),this.audioType=a,this.parameters=s}}new Xn("Recorder","Recorder","vocal",{deviceId:"",gain:1,sensitivity:"high"}),new Xn("Audio Clip","Audio Clip","instrumental",{clipId:null,octave:"4"}),new Xn("Speech Synth","Speech Synth","vocal",{text:"",voice:"default"}),new Xn("Keyboard/Pads","Keyboard","instrumental",{instrument:"piano",preset:"default",velocity:100});function co(e,t,n,a,s){n(i=>t?[...i,t]:i),a([]),s(e)}function Su(e,t,n,a){t(s=>{if(s.length===0)return s;const i=s[s.length-1];return n(o=>e?[e,...o]:o),a(i),s.slice(0,-1)})}function ku(e,t,n,a){n(s=>{if(s.length===0)return s;const i=s[0];return t(o=>e?[...o,e]:o),a(i),s.slice(1)})}class wu{constructor(t={}){this.undoStack=[],this.redoStack=[],this.maxSize=t.maxSize??100,this.onChange=t.onChange}push(t,n,a,s){this.undoStack.push({label:t,category:n,timestamp:Date.now(),oldState:a,newState:s}),this.undoStack.length>this.maxSize&&this.undoStack.shift(),this.redoStack.length=0}undo(){var n;const t=this.undoStack.pop();return t?(this.redoStack.push(t),(n=this.onChange)==null||n.call(this,t,"undo"),t.oldState):null}redo(){var n;const t=this.redoStack.pop();return t?(this.undoStack.push(t),(n=this.onChange)==null||n.call(this,t,"redo"),t.newState):null}get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}get undoLabel(){return this.undoStack.length>0?this.undoStack[this.undoStack.length-1].label:null}get redoLabel(){return this.redoStack.length>0?this.redoStack[this.redoStack.length-1].label:null}get undoCount(){return this.undoStack.length}get redoCount(){return this.redoStack.length}getHistory(){return[...this.undoStack].reverse()}clear(){this.undoStack.length=0,this.redoStack.length=0}undoTo(t){const n=Math.min(t+1,this.undoStack.length);let a=null;for(let s=0;s<n;s++)a=this.undo();return a}}const Cu=ot.scoped("useProjectCRUD");function ju(e){const{project:t,activeSection:n,setProject:a,setActiveSection:s,setLayers:i,setActiveLayer:o,setUndoStack:l,setRedoStack:c}=e,d=u.useCallback(v=>co(v,t,l,c,a),[t,l,c,a]),h=u.useCallback(async()=>{var b;if(!t)return;const v=(((b=t.sections)==null?void 0:b.length)??0)+1,k={id:await e.addSection(t.id,"Section",v),projectId:t.id,name:"Section",orderNumber:v,layers:[]};d({...t,sections:[...t.sections||[],k]}),s(k)},[t,d,s]),p=u.useCallback(async v=>{var b,w,N;if(!t||!await e.confirm("Delete this section?"))return;await e.deleteSection(v);const k=(t.sections??[]).filter($=>$.id!==v);d({...t,sections:k}),s(k[0]??null),i(((b=k[0])==null?void 0:b.layers)??[]),o(((N=(w=k[0])==null?void 0:w.layers)==null?void 0:N[0])??null)},[t,d,s,i,o,e]),g=u.useCallback(async()=>{var f;if(!n)return;const v={id:-Date.now(),name:"New Layer",sectionId:n.id,audioSource:lo.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};i(k=>[...k,v]),o(v);try{const k=await e.addLayer(n.id,v.name,v.audioSource,v.audioSourceParameters);i(b=>b.map(w=>w.id===v.id?{...v,id:k}:w)),t&&d({...t,sections:((f=t.sections)==null?void 0:f.map(b=>b.id===n.id?{...b,layers:[...(b.layers??[]).filter(w=>w.id!==k),{...v,id:k}]}:b))??[]})}catch(k){i(b=>b.filter(w=>w.id!==v.id)),Cu.error("Failed to add layer:",k)}},[n,t,d,i,o]),y=u.useCallback(async v=>{var k,b;if((k=e.layerSettings[v])!=null&&k.locked){e.showToast("Layer is locked. Unlock to delete.","error");return}await e.confirm("Delete this layer?")&&((e.layerClips[v]||[]).forEach(w=>e.removeEngineClip(v,w.id)),e.setLayerMidiNotes(w=>{const N={...w};return delete N[v],N}),await e.deleteLayer(v),i(w=>w.filter(N=>N.id!==v)),o(w=>(w==null?void 0:w.id)===v?null:w),t&&d({...t,sections:((b=t.sections)==null?void 0:b.map(w=>w.id===(n==null?void 0:n.id)?{...w,layers:(w.layers??[]).filter(N=>N.id!==v)}:w))??[]}))},[t,n,d,i,o,e]),m=u.useCallback(async()=>{if(!t)return;const v=e.projectVolume===""?void 0:Number(e.projectVolume);if(Number.isNaN(v)){e.setStatusType("error"),e.setStatusMessage("Volume musi byc liczba");return}if(!e.projectName.trim()){e.setStatusType("error"),e.setStatusMessage("Nazwa projektu nie moze byc pusta");return}await e.updateProject(t.id,{name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:v}),d({...t,name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:v}),e.setStatusType("success"),e.setStatusMessage("Project saved")},[t,e,d]),x=u.useCallback(async()=>{var k;if(!n)return;const v=e.sectionName||n.name,f=e.sectionOrder===""?n.orderNumber:Number(e.sectionOrder);if(!v.trim()){e.setStatusType("error"),e.setStatusMessage("Section name cannot be empty");return}if(Number.isNaN(f)){e.setStatusType("error"),e.setStatusMessage("Order musi byc liczba");return}await e.updateSection(n.id,{name:v,orderNumber:f}),s({...n,name:v,orderNumber:f}),t&&d({...t,sections:((k=t.sections)==null?void 0:k.map(b=>b.id===n.id?{...b,name:v,orderNumber:f}:b))??[]}),e.setStatusType("success"),e.setStatusMessage("Section saved")},[n,t,e,d,s]);return{handleAddSection:h,handleDeleteSection:p,handleAddLayer:g,handleDeleteLayer:y,handleSaveProject:m,handleSaveSection:x}}const uo=u.createContext(null);function Mu(){const e=u.useContext(uo);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const _a=({value:e,children:t})=>r.jsx(uo.Provider,{value:e,children:t});process.env.NODE_ENV!=="production"&&(_a.displayName="EditorTrackProvider");const un=(e,t)=>t&&t>0?e*15/t:e/10,za=e=>{for(const t of e){const n=t.trim();if(n.toUpperCase().startsWith("#BPM:")){const a=parseFloat(n.substring(5).replace(",","."));if(isFinite(a)&&a>0)return a}}return null},Ru=(e,t)=>{const n=t??za(e),a=[];let s="",i=0,o="",l=!0;function c(){o.trim()!==""&&(s.length>0&&(s+=" "),s+=o.trim()),o=""}return e.forEach(d=>{if(!(d.startsWith("#")||d.startsWith("E"))){if(d.startsWith("-"))c(),s.trim().length>0&&(a.push({text:s.trim(),timestamp:i}),s=""),l=!0;else if(d.startsWith(":")||d.startsWith("*")){const h=d.indexOf(" "),p=d.indexOf(" ",h+1),g=d.indexOf(" ",p+1),y=d.indexOf(" ",g+1);if(y===-1)return;const m=un(parseFloat(d.substring(h+1,p)),n);s===""&&(i=m);const x=d.substring(y+1);if(x.trim()==="~")return;let v=x;v.startsWith("~")&&(v=v.substring(1)),l?(c(),o=v.trimEnd()):o+=v.trimEnd(),l=x.endsWith(" ")}}}),c(),s.trim().length>0&&a.push({text:s.trim(),timestamp:i}),a},Nu=(e,t)=>{const n=t??za(e),a=[];let s=[],i="",o=0,l=!0,c=null,d="";function h(){c&&d.trim()!==""&&(c.text=d.trim(),s.push({...c}),i.length>0&&(i+=" "),i+=c.text),c=null,d=""}return e.forEach(p=>{if(!(p.startsWith("#")||p.startsWith("E"))){if(p.startsWith("-"))h(),i.trim().length>0&&(a.push({text:i.trim(),timestamp:o,words:s}),i="",s=[]),l=!0;else if(p.startsWith(":")||p.startsWith("*")){const g=p.startsWith("*"),y=p.indexOf(" "),m=p.indexOf(" ",y+1),x=p.indexOf(" ",m+1),v=p.indexOf(" ",x+1);if(v===-1)return;const f=un(parseFloat(p.substring(y+1,m)),n),k=un(parseFloat(p.substring(m+1,x)),n),b=f+k;i===""&&(o=f);const w=p.substring(v+1);if(w.trim()==="~"){c&&(c.endTime=b);return}let N=w;N.startsWith("~")&&(N=N.substring(1)),l?(h(),d=N.trimEnd(),c={text:"",startTime:f,endTime:b,isGolden:g}):c?(d+=N.trimEnd(),c.endTime=b,g&&(c.isGolden=!0)):(d=N.trimEnd(),c={text:"",startTime:f,endTime:b,isGolden:g}),l=w.endsWith(" ")}}}),h(),i.trim().length>0&&a.push({text:i.trim(),timestamp:o,words:s}),a},ho=(e,t)=>{const n=t??za(e),a=[];let s=[],i=0;function o(){s.length>0&&(a.push({timestamp:i,syllables:[...s]}),s=[])}return e.forEach(l=>{if(!(l.startsWith("#")||l.startsWith("E"))){if(l.startsWith("-")){o();const c=l.trim().split(/\s+/);if(c.length>=2){const d=parseFloat(c[1]);isFinite(d)&&(i=un(d,n))}}else if(l.startsWith(":")||l.startsWith("*")){const c=l.startsWith("*"),d=l.indexOf(" "),h=l.indexOf(" ",d+1),p=l.indexOf(" ",h+1),g=l.indexOf(" ",p+1);if(g===-1)return;const y=parseFloat(l.substring(d+1,h)),m=parseFloat(l.substring(h+1,p)),x=un(y,n),v=x+un(m,n);s.length===0&&(i=x);const f=l.substring(g+1);if(f.trim()==="~"){s.length>0&&(s[s.length-1].endTime=v);return}let k=f;k.startsWith("~")&&(k=k.substring(1));const b=f.endsWith(" "),w=b?k.slice(0,-1):k;s.push({text:w,startTime:x,endTime:v,isGolden:c,hasTrailingSpace:b})}}}),o(),a},Tu=(e,t,n=3)=>{const a=[];let s=-1;for(let i=0;i<e.length;i++){const o=e[i].timestamp,l=e[i+1]?e[i+1].timestamp:o+5;if(t>=o&&t<l){s=i;break}}if(s>=0){const i=Math.max(0,s-(n-1));for(let o=i;o<=s;o++)a.push(e[o].text)}return a},Pu=(e,t)=>{const n=[];for(const a of e)for(const s of a.words)t>=s.startTime&&t<=s.endTime&&n.push(s);return n},js="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",Ms="var(--karaoke-gold-glow-first, 0 0 12px #FFD700)",$u="var(--karaoke-active-glow, 0 0 10px rgba(0,229,255,0.6), 0 0 4px rgba(255,230,0,0.4))",Eu="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",Au=({song:e,currentTime:t=0})=>{const{t:n}=be(),a=u.useMemo(()=>!e||!e.notes.length?[]:ho(e.notes.map(c=>c.noteLine),e.bpm??void 0),[e]),s=t-((e==null?void 0:e.gap)??0)/1e3;let i=-1;for(let c=0;c<a.length;c++){const d=a[c].timestamp,h=c+1<a.length?a[c+1].timestamp:d+30;if(s>=d&&s<h){i=c;break}}const o=i>=0?a[i]:null,l=i>=0&&i+1<a.length?a[i+1]:null;return r.jsx("div",{className:"karaoke-lyrics",style:{textAlign:"center",fontSize:"28px",marginTop:"20px",minHeight:"80px",textShadow:"var(--karaoke-outline, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000)",fontWeight:700,fontStyle:"italic",fontFamily:"var(--karaoke-font-family, Arial)"},children:o?r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"var(--karaoke-primary-text, #fff)",margin:"5px 0",lineHeight:1.4,textShadow:$u,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((c,d)=>{let h=0;s>=c.endTime?h=1:s>c.startTime&&(h=(s-c.startTime)/(c.endTime-c.startTime));const p=Math.round(h*100),g=c.text+(c.hasTrailingSpace?" ":""),y=h>0&&h<1,m=c.isGolden;return h<=0?r.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",transition:"color 0.15s ease"},children:g},d):h>=1?r.jsx("span",{style:{background:m?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":js,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:m?`drop-shadow(${Ms})`:"none",transition:"filter 0.2s ease"},children:g},d):r.jsxs("span",{style:{position:"relative",display:"inline",filter:y?m?`drop-shadow(${Ms})`:`drop-shadow(${Eu})`:"none",transition:"filter 0.15s ease"},children:[r.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",visibility:"visible"},children:g}),r.jsx("span",{style:{position:"absolute",left:0,top:0,background:m?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":js,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",clipPath:`inset(0 ${100-p}% 0 0)`,pointerEvents:"none"},children:g})]},d)})}),l&&r.jsx("p",{style:{color:"var(--karaoke-next-text, #666)",margin:"5px 0",lineHeight:1.4,fontSize:"22px",transition:"opacity 0.3s ease"},children:l.syllables.map((c,d)=>r.jsx("span",{style:{color:c.isGolden?"var(--karaoke-golden-next, rgba(255,215,0,0.5))":"var(--karaoke-next-dim, #777)"},children:c.text+(c.hasTrailingSpace?" ":"")},d))})]}):a.length>0?r.jsx("p",{style:{color:"var(--karaoke-waiting-text, #999)"},children:r.jsx(O.NtdMusic,{size:20})}):r.jsxs("p",{style:{color:"var(--karaoke-waiting-text, #999)",display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(O.NtdMicrophone,{size:18})," ",n("karaokeLyrics.waitingForLyrics","Waiting for lyrics...")]})})},po=u.memo(Au),Zr={},Iu=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:bt&&bt.tagName.toUpperCase()==="SCRIPT"&&bt.src||new URL("index.cjs",document.baseURI).href}<"u"&&(Zr==null?void 0:Zr.VITE_DEBUG_KARAOKE)==="true";function ha(e,t,...n){(Iu||typeof window<"u"&&window.DEBUG_KARAOKE)&&console.log(`%c[KARAOKE-DEBUG]%c [${e}] ${t}`,"background:var(--nice-color-accent-hover, #6c3483);color:var(--nice-text-on-primary, #FFF);padding: var(--nice-space-px, 1px) var(--nice-space-1, 4px);border-radius:var(--nice-radius-sm, 3px);font-weight:bold","color:var(--nice-color-accent-hover, #6c3483);font-weight:bold",...n)}const fo=e=>{for(const t of e){const n=t.trim();if(n.toUpperCase().startsWith("#BPM:")){const a=parseFloat(n.substring(5).replace(",","."));if(isFinite(a)&&a>0)return a}}return null},Rs=(e,t)=>t&&t>0?e*15/t:e/10,Hn=(e,t)=>{const n=t??fo(e),a=[];let s=[];return e.forEach(i=>{const o=i.split(" ");if(!(o.length<4))if(i.startsWith("-"))s.length>0&&(a.push(s),s=[]);else{const l=(o[0]||"").charAt(0),c=l==="*"||l==="G";s.push({startTime:Rs(parseFloat(o[1]),n),duration:Rs(parseFloat(o[2]),n),pitch:parseInt(o[3],10),isGold:c})}}),s.length>0&&a.push(s),a},mo=(e,t)=>{let a=(Math.round(12*Math.log2(e/440)+69)%12+12)%12;if(t!==null){for(;a-t>6;)a-=12;for(;a-t<-6;)a+=12}return a},go=ot.scoped("karaokeScoringConfig"),Da={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}},Lu="karaoke.scoringPresets";function _u(){try{const e=localStorage.getItem(Lu);return e?JSON.parse(e):null}catch(e){return go.warn("Failed to parse scoring presets overrides",e),null}}function yo(e){const t={...Da},n=_u();return n&&Object.keys(n).forEach(a=>{const s=n[a];s&&(t[a]={...t[a],...s})}),e&&Object.keys(e).forEach(a=>{const s=e[a];s&&(t[a]={...t[a],...s})}),t}exports.ScoringPresets=yo();const zu=async e=>{try{let t=null;if(e?t=await e.getKaraokeScoringConfig():(go.debug("No fetcher provided, using defaults"),t=null),t&&t.presets)return exports.ScoringPresets=yo(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},zr=(e="normal")=>exports.ScoringPresets[e]||Da.normal,Du=3,ne=Du;function qt(e){const t=e/2|0;return{w:t,out:`M${t} 0H${t}V${e}H${t}A${t} ${t} 0 0 1 0 ${t}A${t} ${t} 0 0 1 ${t} 0Z`,inn:`M${t} ${ne}V${e-ne}A${t-ne} ${t-ne} 0 0 1 ${ne} ${t}A${t-ne} ${t-ne} 0 0 1 ${t} ${ne}Z`}}function hn(e){return{w:ne+1,out:`M0 0H${ne+1}V${e}H0Z`,inn:`M${ne} ${ne}H${ne+1}V${e-ne}H${ne}Z`}}function Fa(e){const t=Math.min(14,e*.22)|0,n=t+2,a=Math.max(t-ne,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${ne+a} ${ne}H${n}V${e-ne}H${ne+a}Q${ne} ${e-ne} ${ne} ${e-ne-a}V${ne+a}Q${ne} ${ne} ${ne+a} ${ne}Z`}}function Mr(e){const t=e*.3|0,n=t+2,a=Math.max(t-ne,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e-t}V${t}Z`,inn:`M${ne+a} ${ne}H${n}V${e-ne}H${ne+a}L${ne} ${e-ne-a}V${ne+a}Z`}}function Ot(e){const t=e*.42|0,n=t+2,a=Math.max(t-(ne*1.4|0),2);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e/2}Z`,inn:`M${ne+a} ${ne}H${n}V${e-ne}H${ne+a}L${ne} ${e/2}Z`}}function Rr(e){const t=e*.3|0,n=t+4,a=Math.max(t-ne,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${ne+a} ${ne}H${n}V${e-ne}H${ne+(a*.6|0)}L${ne} ${e-ne-a}V${ne+a}Q${ne} ${ne} ${ne+a} ${ne}Z`}}function Oa(e){const t=e*.16|0,n=t*2+4;return{w:n,out:`M${t*1.5|0} 0H${n}V${e}H${t*1.5|0}C${t*2.5|0} ${e*.35|0} ${t*2.5|0} ${e*.65|0} ${t*1.5|0} ${e}Z`,inn:`M${ne+(t*1.2|0)} ${ne}H${n}V${e-ne}H${ne+(t*1.2|0)}C${ne+(t*2.2|0)} ${e*.37|0} ${ne+(t*2.2|0)} ${e*.63|0} ${ne+(t*1.2|0)} ${e-ne}Z`}}function Ba(e){const t=e*.32|0,n=t+3,a=Math.max(t-ne,1);return{w:n,out:`M0 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}Z`,inn:`M${ne} ${ne}H${n}V${e-ne}H${ne+a}Q${ne} ${e-ne} ${ne} ${e-ne-a}Z`}}function Nr(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${ne+(t*1.8|0)} ${ne}H${n}V${e-ne}H${ne+(t*1.8|0)}C${ne+(t*.4|0)} ${e*.78|0} ${ne+(t*2.8|0)} ${e*.55|0} ${ne+(t*.4|0)} ${e*.37|0}S${ne+(t*.9|0)} ${ne} ${ne+(t*1.8|0)} ${ne}Z`}}function Ga(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${ne+(t*2.5|0)} ${ne}H${n}V${e-ne}H${ne+(t*2.5|0)}L${ne+(t*.7|0)} ${e-ne-(t*1.6|0)}L${ne+(t*1.7|0)} ${e*.64|0}L${ne} ${e/2|0}L${ne+(t*1.7|0)} ${e*.36|0}L${ne+(t*.7|0)} ${ne+(t*1.6|0)}Z`}}function hr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M${t} 0H${n}V${e}H0Z`,inn:`M${ne+t-(ne*1.3|0)} ${ne}H${n}V${e-ne}H${ne+1}Z`}}function pa(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}V${e}H${t}Z`,inn:`M${ne} ${ne}H${n}V${e-ne}H${ne+t-(ne*1.3|0)+1}Z`}}function Dt(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 ${ne}A${t-ne} ${t-ne} 0 0 1 ${t-ne} ${t}A${t-ne} ${t-ne} 0 0 1 0 ${e-ne}Z`}}function pn(e){return{w:ne+1,out:`M0 0H${ne+1}V${e}H0Z`,inn:`M0 ${ne}H1V${e-ne}H0Z`}}function vo(e){const t=Math.min(14,e*.22)|0,n=t+2,a=Math.max(t-ne,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 ${ne}H${n-ne-a}Q${n-ne} ${ne} ${n-ne} ${ne+a}V${e-ne-a}Q${n-ne} ${e-ne} ${n-ne-a} ${e-ne}H0Z`}}function fn(e){const t=e*.3|0,n=t+2,a=Math.max(t-ne,1);return{w:n,out:`M0 0H${n-t}L${n} ${t}V${e-t}L${n-t} ${e}H0Z`,inn:`M0 ${ne}H${n-ne-a}L${n-ne} ${ne+a}V${e-ne-a}L${n-ne-a} ${e-ne}H0Z`}}function Tt(e){const t=e*.42|0,n=t+2,a=Math.max(t-(ne*1.4|0),2);return{w:n,out:`M0 0H${n-t}L${n} ${e/2}L${n-t} ${e}H0Z`,inn:`M0 ${ne}H${n-ne-a}L${n-ne} ${e/2}L${n-ne-a} ${e-ne}H0Z`}}function bo(e){const t=e*.3|0,n=t+4,a=Math.max(t-ne,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 ${ne}H${n-ne-a}Q${n-ne} ${ne} ${n-ne} ${ne+a}V${e-ne-a}L${n-ne-(a*.6|0)} ${e-ne}H0Z`}}function xo(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 ${ne}H${n-ne-(t*1.2|0)}C${n-ne-(t*2.2|0)} ${e*.37|0} ${n-ne-(t*2.2|0)} ${e*.63|0} ${n-ne-(t*1.2|0)} ${e-ne}H0Z`}}function So(e){const t=e*.32|0,n=t+3,a=Math.max(t-ne,1);return{w:n,out:`M0 0H${n}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${ne}H${n-ne}V${e-ne-a}Q${n-ne} ${e-ne} ${n-ne-a} ${e-ne}H0Z`}}function Wa(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 ${ne}H${n-ne-(t*1.8|0)}C${n-ne-(t*.9|0)} ${ne} ${n-ne+(t*.1|0)} ${e*.22|0} ${n-ne-(t*.4|0)} ${e*.37|0}S${n-ne-(t*.4|0)} ${e*.78|0} ${n-ne-(t*1.8|0)} ${e-ne}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 ${ne}H${n-ne-(t*2.5|0)}L${n-ne-(t*.7|0)} ${ne+(t*1.6|0)}L${n-ne-(t*1.7|0)} ${e*.36|0}L${n-ne} ${e/2|0}L${n-ne-(t*1.7|0)} ${e*.64|0}L${n-ne-(t*.7|0)} ${e-ne-(t*1.6|0)}L${n-ne-(t*2.5|0)} ${e-ne}H0Z`}}function fa(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}L${n-t} ${e}H0Z`,inn:`M0 ${ne}H${n-ne}L${n-ne-t+(ne*1.3|0)} ${e-ne}H0Z`}}function pr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n-t}L${n} ${e}H0Z`,inn:`M0 ${ne}H${n-ne-t+(ne*1.3|0)}L${n-ne} ${e-ne}H0Z`}}const Va=[{name:"Pill",L:qt,R:Dt},{name:"Sharp",L:hn,R:pn},{name:"Soft",L:Fa,R:vo},{name:"Chamfer",L:Mr,R:fn},{name:"Arrow",L:Ot,R:Tt},{name:"Shield",L:Rr,R:bo},{name:"Bracket",L:Oa,R:xo},{name:"Tab",L:Ba,R:So},{name:"Wave",L:Nr,R:Wa},{name:"Ornate",L:Ga,R:Tr}],ko=[{name:"Pill→Arrow",L:qt,R:Tt},{name:"Arrow→Pill",L:Ot,R:Dt},{name:"Pill→Sharp",L:qt,R:pn},{name:"Sharp→Pill",L:hn,R:Dt},{name:"Pill→Chamfer",L:qt,R:fn},{name:"Chamfer→Pill",L:Mr,R:Dt},{name:"Arrow→Sharp",L:Ot,R:pn},{name:"Sharp→Arrow",L:hn,R:Tt},{name:"Arrow→Chamfer",L:Ot,R:fn},{name:"Chamfer→Arrow",L:Mr,R:Tt},{name:"Soft→Arrow",L:Fa,R:Tt},{name:"Shield→Chamfer",L:Rr,R:fn},{name:"Pill→Wave",L:qt,R:Wa},{name:"Wave→Arrow",L:Nr,R:Tt},{name:"Tab→Pill",L:Ba,R:Dt},{name:"Ornate→Sharp",L:Ga,R:pn},{name:"Sharp→Ornate",L:hn,R:Tr},{name:"Bracket→Arrow",L:Oa,R:Tt},{name:"Shield→Pill",L:Rr,R:Dt},{name:"Wave→Ornate",L:Nr,R:Tr}],wo=[{name:"Skew ╲",L:hr,R:fa},{name:"Skew ╱",L:pa,R:pr},{name:"◇ Romb",L:Ot,R:Tt},{name:"╲→Pill",L:hr,R:Dt},{name:"Pill→╲",L:qt,R:fa},{name:"╱→Sharp",L:pa,R:pn},{name:"Sharp→╱",L:hn,R:pr},{name:"╲→Arrow",L:hr,R:Tt},{name:"Arrow→╱",L:Ot,R:pr},{name:"◇→Chamfer",L:Ot,R:fn}],Wn=(function(){return[...Va,...ko,...wo]})(),Co=Va[0];function Rn(e){return Wn.find(t=>t.name===e)||Co}const Pr=[{name:"Flames",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="12" height="16" patternUnits="userSpaceOnUse"><path d="M6 0C8 3 10 5 9 9C8 12 6 14 6 16C6 14 4 12 3 9C2 5 4 3 6 0Z" fill="${t}" opacity=".5"/><path d="M3 6C4 8 5 10 3 14C1 10 2 8 3 6Z" fill="${a}" opacity=".3"/><path d="M9 6C10 8 11 10 9 14C7 10 8 8 9 6Z" fill="${a}" opacity=".3"/></pattern>`}},{name:"Zigzag",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M0 5L5 0L10 5L5 10Z" fill="${n||t}" fill-opacity=".15" stroke="${t}" stroke-width="1.2" opacity=".55"/></pattern>`},{name:"Scales",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="12" height="8" patternUnits="userSpaceOnUse"><ellipse cx="6" cy="8" rx="6" ry="4.5" fill="none" stroke="${t}" stroke-width="1" opacity=".5"/><ellipse cx="0" cy="4" rx="6" ry="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".3"/><ellipse cx="12" cy="4" rx="6" ry="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".3"/></pattern>`}},{name:"Hex",mk:(e,t,n)=>`<pattern id="${e}" width="18" height="20" patternUnits="userSpaceOnUse"><path d="M9 2L16 6V14L9 18L2 14V6Z" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M9 12L13.5 14.5V19L9 21.5L4.5 19V14.5Z" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Dots",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="8" height="8" patternUnits="userSpaceOnUse"><circle cx="4" cy="4" r="2" fill="${t}" opacity=".5"/><circle cx="0" cy="0" r="1" fill="${a}" opacity=".3"/><circle cx="8" cy="8" r="1" fill="${a}" opacity=".3"/></pattern>`}},{name:"Stars",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M7 1L8.8 5.2L13.2 5.2L9.7 7.8L11 12.2L7 9.4L3 12.2L4.3 7.8L.8 5.2L5.2 5.2Z" fill="${t}" opacity=".45" stroke="${n||t}" stroke-width=".4" stroke-opacity=".3"/></pattern>`},{name:"Diamonds",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M5 .5L9.5 5L5 9.5L.5 5Z" fill="${n||"none"}" fill-opacity=".15" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Waves",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="8" patternUnits="userSpaceOnUse"><path d="M0 4Q4 0 8 4Q12 8 16 4" fill="none" stroke="${t}" stroke-width="1.3" opacity=".5"/><path d="M0 6Q4 2 8 6Q12 10 16 6" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Crosses",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M5 2V8" stroke="${t}" stroke-width="1.3" stroke-linecap="round" opacity=".5"/><path d="M2 5H8" stroke="${n||t}" stroke-width="1.3" stroke-linecap="round" opacity=".5"/></pattern>`},{name:"Triangles",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M6 1L11 9H1Z" fill="${n||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Chevrons",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M0 7L6 1.5L12 7" fill="none" stroke="${t}" stroke-width="1.2" opacity=".55"/><path d="M0 10L6 4.5L12 10" fill="none" stroke="${n||t}" stroke-width=".7" opacity=".25"/></pattern>`},{name:"Hatch ╲",mk:(e,t,n)=>`<pattern id="${e}" width="6" height="6" patternUnits="userSpaceOnUse"><path d="M0 6L6 0" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M-1 1L1 -1M5 7L7 5" stroke="${n||t}" stroke-width=".8" opacity=".3"/></pattern>`},{name:"Hatch ╳",mk:(e,t,n)=>`<pattern id="${e}" width="7" height="7" patternUnits="userSpaceOnUse"><path d="M0 7L7 0" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M0 0L7 7" stroke="${n||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Grid",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M10 0V10" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M0 10H10" fill="none" stroke="${n||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Bricks",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="8" patternUnits="userSpaceOnUse"><rect width="14" height="8" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><line x1="7" y1="0" x2="7" y2="4" stroke="${n||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Hearts",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="12" patternUnits="userSpaceOnUse"><path d="M6 10C4 8 1 6.5 1 4C1 2.3 2.8 1 4.5 2.2L6 4L7.5 2.2C9.2 1 11 2.3 11 4C11 6.5 8 8 6 10Z" fill="${t}" opacity=".4" stroke="${n||t}" stroke-width=".5" stroke-opacity=".3"/></pattern>`},{name:"Arrows",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M3 2L9 5L3 8" fill="${n||"none"}" fill-opacity=".15" stroke="${t}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity=".5"/></pattern>`},{name:"Bolts",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="16" patternUnits="userSpaceOnUse"><path d="M7 1L4 7H8L3 15" fill="none" stroke="${t}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity=".5"/><circle cx="5" cy="11" r="1" fill="${n||t}" opacity=".3"/></pattern>`},{name:"Leaves",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M7 2C10 4 12 7 10 11C8 13 5 12 4 10C3 7 4 4 7 2Z" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M7 3L6 10" stroke="${a}" stroke-width=".6" opacity=".3"/><path d="M5 5L7 6M5 8L7 7.5" stroke="${a}" stroke-width=".4" opacity=".25"/></pattern>`}},{name:"Spirals",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="16" patternUnits="userSpaceOnUse"><path d="M8 4A4 4 0 0 1 12 8A3.5 3.5 0 0 1 8.5 11.5A2.5 2.5 0 0 1 6 9A1.5 1.5 0 0 1 7.5 7.5" fill="none" stroke="${t}" stroke-width="1.2" stroke-linecap="round" opacity=".45"/><circle cx="8" cy="8" r="1" fill="${n||t}" opacity=".25"/></pattern>`},{name:"Moons",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M9 2A5 5 0 1 0 9 12" fill="none" stroke="${t}" stroke-width="1" opacity=".4"/><path d="M9 2A3.5 3.5 0 0 1 9 12" fill="none" stroke="${n||t}" stroke-width="1" opacity=".3"/></pattern>`},{name:"Rings",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="12" patternUnits="userSpaceOnUse"><circle cx="6" cy="6" r="4" fill="none" stroke="${t}" stroke-width="1.2" opacity=".5"/><circle cx="6" cy="6" r="2" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Teeth",mk:(e,t,n)=>`<pattern id="${e}" width="8" height="10" patternUnits="userSpaceOnUse"><path d="M0 10V4L4 0L8 4V10" fill="${n||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Swirl",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="10" patternUnits="userSpaceOnUse"><path d="M0 5C3 0 6 0 8 5C10 10 13 10 16 5" fill="none" stroke="${t}" stroke-width="1.3" opacity=".5"/><path d="M0 7C3 2 6 2 8 7C10 12 13 12 16 7" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".2"/></pattern>`},{name:"Chain",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="16" patternUnits="userSpaceOnUse"><ellipse cx="5" cy="4" rx="3.5" ry="4" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><ellipse cx="5" cy="12" rx="3.5" ry="4" fill="none" stroke="${n||t}" stroke-width="1" opacity=".45"/></pattern>`},{name:"Feathers",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="18" patternUnits="userSpaceOnUse"><path d="M6 1C9 5 10 9 6 17" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M6 1C3 5 2 9 6 17" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M4 5L6 4L8 5M4 9L6 8L8 9M4 13L6 12L8 13" stroke="${n||t}" stroke-width=".5" opacity=".3"/></pattern>`},{name:"DNA",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="18" patternUnits="userSpaceOnUse"><path d="M3 0C3 4.5 11 4.5 11 9S3 13.5 3 18" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M11 0C11 4.5 3 4.5 3 9S11 13.5 11 18" fill="none" stroke="${n||t}" stroke-width="1" opacity=".45"/></pattern>`},{name:"Bubbles",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="18" height="18" patternUnits="userSpaceOnUse"><circle cx="5" cy="5" r="3.5" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><circle cx="14" cy="12" r="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".35"/><circle cx="11" cy="3" r="1.8" fill="${a}" opacity=".25"/></pattern>`}},{name:"Celtic",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="16" patternUnits="userSpaceOnUse"><path d="M8 2C12 2 14 4 14 8C14 12 12 14 8 14C4 14 2 12 2 8C2 4 4 2 8 2Z" fill="none" stroke="${t}" stroke-width=".8" opacity=".35"/><path d="M4 4L12 12M12 4L4 12" stroke="${n||t}" stroke-width=".6" opacity=".2"/></pattern>`},{name:"Squares",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><rect x="1.5" y="1.5" width="7" height="7" rx="1" fill="${n||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`}];function Nn(e){return Pr.find(t=>t.name===e)||null}const Gt={color:null,capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,glass:0,textureUrl:null,textureScale:1},Dr=(function(){return{...Gt,glass:85}})(),Fr=(function(){return{...Gt,patternName:"Stars"}})(),Or=(function(){return{...Gt,patternName:"Stars"}})(),Br={fontFamily:null,fontSize:18,fontColor:null,outlineColor:null,outlineWidth:0,shadow:null},jo=(function(){return{filledBar:{...Gt},emptyBar:{...Dr},goldFilledBar:{...Or},goldEmptyBar:{...Fr},font:{...Br},disableGoldNotes:!1}})(),Ns={capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,emptyGlass:85,filledTextureUrl:null,emptyTextureUrl:null,textureScale:1,emptyPreset:"custom",goldPatternName:"Stars",goldPatternColor:null,goldHitPatternName:"Stars",goldHitPatternColor:null,goldEmptyTextureUrl:null,goldFilledTextureUrl:null,fontFamily:null,fontSize:18,fontColor:null,fontOutlineColor:null,fontOutlineWidth:0,fontShadow:null},Ts="nice2dev-player-bar-style",Ps="nice2dev-player-karaoke-settings";function mn(e){return e!=null?`${Ps}-${e}`:Ps}function $s(e){return e!=null?`${Ts}-${e}`:Ts}function Es(e){return{filledBar:{color:null,capStyleName:e.capStyleName,patternName:e.patternName,patternColor:e.patternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.filledTextureUrl,textureScale:e.textureScale},emptyBar:{color:null,capStyleName:e.capStyleName,patternName:e.patternName,patternColor:e.patternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:e.emptyGlass,textureUrl:e.emptyTextureUrl,textureScale:e.textureScale},goldFilledBar:{color:null,capStyleName:e.capStyleName,patternName:e.goldHitPatternName,patternColor:e.goldHitPatternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.goldFilledTextureUrl,textureScale:e.textureScale},goldEmptyBar:{color:null,capStyleName:e.capStyleName,patternName:e.goldPatternName,patternColor:e.goldPatternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.goldEmptyTextureUrl,textureScale:e.textureScale},font:{fontFamily:e.fontFamily,fontSize:e.fontSize,fontColor:e.fontColor,outlineColor:e.fontOutlineColor,outlineWidth:e.fontOutlineWidth,shadow:e.fontShadow}}}function As(e){const t=jo,n=(s,i)=>!i||typeof i!="object"?{...s}:{...s,...i},a=(s,i)=>!i||typeof i!="object"?{...s}:{...s,...i};return{filledBar:n(t.filledBar,e.filledBar),emptyBar:n(t.emptyBar,e.emptyBar),goldFilledBar:n(t.goldFilledBar,e.goldFilledBar),goldEmptyBar:n(t.goldEmptyBar,e.goldEmptyBar),font:a(t.font,e.font),disableGoldNotes:typeof e.disableGoldNotes=="boolean"?e.disableGoldNotes:t.disableGoldNotes}}function Ua(e){try{const t=localStorage.getItem(mn(e));if(t){const a=JSON.parse(t);return As(a)}const n=localStorage.getItem($s(e));if(n){const a=JSON.parse(n),s=Es({...Ns,...a});return localStorage.setItem(mn(e),JSON.stringify(s)),s}if(e!=null){const a=localStorage.getItem(mn());if(a)return As(JSON.parse(a));const s=localStorage.getItem($s());if(s)return Es({...Ns,...JSON.parse(s)})}}catch{}return{filledBar:{...Gt},emptyBar:{...Dr},goldFilledBar:{...Or},goldEmptyBar:{...Fr},font:{...Br}}}function Fu(e,t){const n=JSON.stringify(e);localStorage.setItem(mn(t),n)}let Is=!1;async function Ou(e){if(Is||(Is=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(mn())||localStorage.setItem(mn(),t)}catch{}}function Bu(e){const t=new Map;for(const n of e)t.set(n,Ua(n));return t}const Gu={"&":"&","<":"<",">":">",'"':""","'":"'"},Wu=/[&<>"']/g;function Vu(e){return e.replace(Wu,t=>Gu[t])}function Uu(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 qu=3,Qe=qu;function $r(e){const t=parseInt(e.slice(1,3),16)/255,n=parseInt(e.slice(3,5),16)/255,a=parseInt(e.slice(5,7),16)/255,s=Math.max(t,n,a),i=Math.min(t,n,a);let o=0,l=0;const c=(s+i)/2;if(s!==i){const d=s-i;switch(l=c>.5?d/(2-s-i):d/(s+i),s){case t:o=((n-a)/d+(n<a?6:0))/6;break;case n:o=((a-t)/d+2)/6;break;case a:o=((t-n)/d+4)/6;break}}return[Math.round(o*360),Math.round(l*100),Math.round(c*100)]}function Er(e){let t=e.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),"#"+t.toLowerCase()}function ut(e,t){return e.replace(/([MLHVCSQTAZ])/gi,`
|
|
2
2
|
$1`).split(`
|
|
3
|
-
`).filter(Boolean).map(
|
|
4
|
-
${
|
|
5
|
-
${
|
|
6
|
-
<clipPath id="${
|
|
3
|
+
`).filter(Boolean).map(n=>{const a=n[0],s=n.slice(1).trim().split(/[\s,]+/).map(Number);if(a==="H")return`H${s[0]+t}`;if(a==="V"||a==="Z")return n;if("MLCSQT".includes(a.toUpperCase())){for(let i=0;i<s.length;i+=2)s[i]+=t;return a+s.join(" ")}return a==="A"&&s.length>=7?(s[5]+=t,a+s.join(" ")):n}).join("")}function Mo(e){const{width:t,height:n,capStyle:a,color:s,highlight:i=70,glow:o=55,glass:l=0,pattern:c=null,patternColor:d=null,patternOnly:h=!1,textureUrl:p=null,textureScale:g=1}=e,y=p&&Uu(p)?Vu(p):null,[m,x,v]=$r(Er(s)),f="c"+Math.random().toString(36).slice(2,7),k=a.L(n),b=a.R(n),w=t-k.w-b.w;if(w<4)return"";if(h&&c){const J=`hsl(${m},${x}%,${v}%)`,se=`hsl(${m},${Math.max(x-20,0)}%,${Math.min(v+30,95)}%)`,oe=d||se,re=k.w,W=k.w+w,ee=k.inn,ae=`M${re} ${Qe}H${W}V${n-Qe}H${re}Z`,le=ut(b.inn,W),ce=k.out,te=`M${re} 0H${W}V${n}H${re}Z`,he=ut(b.out,W),ue=c.mk(f+"pat",oe,d||void 0),xe=Math.round(256*g),pe=Math.round(256*g),Se=y?`<pattern id="${f}tex" patternUnits="userSpaceOnUse" width="${xe}" height="${pe}"><image href="${y}" width="${xe}" height="${pe}" preserveAspectRatio="none"/></pattern>`:"",je=y?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${f}tex)" opacity=".85" clip-path="url(#${f}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
|
|
4
|
+
${ue}
|
|
5
|
+
${Se}
|
|
6
|
+
<clipPath id="${f}c"><path d="${ee}"/><path d="${ae}"/><path d="${le}"/></clipPath>
|
|
7
7
|
</defs>
|
|
8
|
-
<path d="${
|
|
9
|
-
<path d="${
|
|
10
|
-
${
|
|
11
|
-
<rect x="0" y="0" width="${t}" height="${
|
|
12
|
-
</svg>`}const
|
|
13
|
-
${
|
|
14
|
-
${
|
|
15
|
-
<linearGradient id="${
|
|
16
|
-
<linearGradient id="${
|
|
17
|
-
<linearGradient id="${
|
|
18
|
-
<linearGradient id="${
|
|
19
|
-
<clipPath id="${
|
|
8
|
+
<path d="${ce}" fill="rgba(255,255,255,.18)"/><path d="${te}" fill="rgba(255,255,255,.18)"/><path d="${he}" fill="rgba(255,255,255,.18)"/>
|
|
9
|
+
<path d="${ee}" fill="${J}" opacity=".22"/><path d="${ae}" fill="${J}" opacity=".22"/><path d="${le}" fill="${J}" opacity=".22"/>
|
|
10
|
+
${je}
|
|
11
|
+
<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${f}pat)" clip-path="url(#${f}c)"/>
|
|
12
|
+
</svg>`}const N=`hsl(${m},${Math.min(x+10,100)}%,${Math.max(v-22,4)}%)`,$=`hsl(${m},${x}%,${v}%)`,M=`hsl(${m},${Math.max(x-12,0)}%,${Math.min(v+18,88)}%)`,E=`hsl(${m},${Math.min(x+20,100)}%,${Math.min(v+30,93)}%)`,R=`hsl(${m},${Math.max(x-20,0)}%,${Math.min(v+30,95)}%)`,L=d||R,A=i/100*.78,z=o/100*.65,j=1-l/100*.87,I=Qe,Y=n-Qe,H=I+(Y-I)*.44,D=I+(Y-I)*.58,V=k.w,Z=k.w+w,X=k.out,q=`M${V} 0H${Z}V${n}H${V}Z`,G=ut(b.out,Z),C=k.inn,T=`M${V} ${Qe}H${Z}V${n-Qe}H${V}Z`,S=ut(b.inn,Z),F=c?c.mk(f+"pat",L,d||void 0):"",K=c?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${f}pat)" clip-path="url(#${f}c)"/>`:"",P=Math.round(256*g),B=Math.round(256*g),_=y?`<pattern id="${f}tex" patternUnits="userSpaceOnUse" width="${P}" height="${B}"><image href="${y}" width="${P}" height="${B}" preserveAspectRatio="none"/></pattern>`:"",U=y?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${f}tex)" opacity="${j*.9}" clip-path="url(#${f}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
|
|
13
|
+
${F}
|
|
14
|
+
${_}
|
|
15
|
+
<linearGradient id="${f}b" x1="0" y1="0" x2="0" y2="${n}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="rgba(255,255,255,.55)"/><stop offset=".3" stop-color="rgba(255,255,255,.35)"/><stop offset="1" stop-color="rgba(255,255,255,.08)"/></linearGradient>
|
|
16
|
+
<linearGradient id="${f}f" x1="0" y1="${I}" x2="0" y2="${Y}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${M}"/><stop offset=".5" stop-color="${$}"/><stop offset="1" stop-color="${N}"/></linearGradient>
|
|
17
|
+
<linearGradient id="${f}h" x1="0" y1="${I}" x2="0" y2="${H}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fff" stop-opacity="${A}"/><stop offset=".5" stop-color="#fff" stop-opacity="${A*.25}"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient>
|
|
18
|
+
<linearGradient id="${f}g" x1="0" y1="${D}" x2="0" y2="${Y}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${E}" stop-opacity="0"/><stop offset=".6" stop-color="${E}" stop-opacity="${z*.6}"/><stop offset="1" stop-color="${E}" stop-opacity="${z}"/></linearGradient>
|
|
19
|
+
<clipPath id="${f}c"><path d="${C}"/><path d="${T}"/><path d="${S}"/></clipPath>
|
|
20
20
|
</defs>
|
|
21
|
-
<path d="${
|
|
22
|
-
<path d="${
|
|
23
|
-
${
|
|
24
|
-
${
|
|
25
|
-
<rect x="0" y="${
|
|
26
|
-
<rect x="0" y="${I}" width="${t}" height="${
|
|
27
|
-
</svg>`}function nt(e,t){const
|
|
21
|
+
<path d="${X}" fill="url(#${f}b)"/><path d="${q}" fill="url(#${f}b)"/><path d="${G}" fill="url(#${f}b)"/>
|
|
22
|
+
<path d="${C}" fill="url(#${f}f)" opacity="${j}"/><path d="${T}" fill="url(#${f}f)" opacity="${j}"/><path d="${S}" fill="url(#${f}f)" opacity="${j}"/>
|
|
23
|
+
${U}
|
|
24
|
+
${K}
|
|
25
|
+
<rect x="0" y="${D}" width="${t}" height="${Y-D}" fill="url(#${f}g)" clip-path="url(#${f}c)"/>
|
|
26
|
+
<rect x="0" y="${I}" width="${t}" height="${H-I}" fill="url(#${f}h)" clip-path="url(#${f}c)"/>
|
|
27
|
+
</svg>`}function nt(e,t){const n=t.match(/[MLHVCSQTAZmlhvcsqtaz][^MLHVCSQTAZmlhvcsqtaz]*/g);if(!n)return;let a=0,s=0;for(const i of n){const o=i[0],l=i.slice(1).trim().split(/[\s,]+/).filter(Boolean).map(Number);switch(o){case"M":a=l[0],s=l[1],e.moveTo(a,s);break;case"L":a=l[0],s=l[1],e.lineTo(a,s);break;case"H":a=l[0],e.lineTo(a,s);break;case"V":s=l[0],e.lineTo(a,s);break;case"C":e.bezierCurveTo(l[0],l[1],l[2],l[3],l[4],l[5]),a=l[4],s=l[5];break;case"Q":e.quadraticCurveTo(l[0],l[1],l[2],l[3]),a=l[2],s=l[3];break;case"S":{e.bezierCurveTo(a,s,l[0],l[1],l[2],l[3]),a=l[2],s=l[3];break}case"A":{const c=Math.abs(l[0]),d=Math.abs(l[1]),h=l[3]!==0,p=l[4]!==0,g=l[5],y=l[6],m=a,x=s;if(Math.abs(m-g)<.001&&Math.abs(x-y)<.001||c<.001||d<.001){e.lineTo(g,y),a=g,s=y;break}const v=(c+d)/2,f=(m-g)/2,k=(x-y)/2,b=f*f+k*k,w=b>v*v?Math.sqrt(b):v,N=w*w,$=Math.sqrt(Math.max(0,(N-b)/b)),M=h!==p?1:-1,E=(m+g)/2+M*$*k,R=(x+y)/2-M*$*f,L=Math.atan2(x-R,m-E),A=Math.atan2(y-R,g-E);e.arc(E,R,w,L,A,!p),a=g,s=y;break}case"Z":e.closePath();break}}}function Tn(e,t,n,a,s,i,o,l=70,c=55,d=0,h,p,g=!1,y,m){const[x,v,f]=$r(Er(o)),k=i.L(s),b=i.R(s),w=a-k.w-b.w;if(w<0){const[C,,T]=$r(Er(o));e.save(),e.translate(t,n),e.globalAlpha=1-d/100*.87,e.fillStyle=`hsl(${C},50%,${Math.min(T+10,80)}%)`;const S=Math.min(a/2,s/2);e.beginPath(),e.moveTo(S,0),e.lineTo(a-S,0),e.quadraticCurveTo(a,0,a,S),e.lineTo(a,s-S),e.quadraticCurveTo(a,s,a-S,s),e.lineTo(S,s),e.quadraticCurveTo(0,s,0,s-S),e.lineTo(0,S),e.quadraticCurveTo(0,0,S,0),e.closePath(),e.fill(),e.restore();return}const N=k.w,$=k.w+w;if(g){const C=`hsla(${x},${v}%,${f}%,0.22)`;e.save(),e.translate(t,n),e.fillStyle="rgba(255,255,255,0.18)",e.beginPath(),nt(e,k.out),e.fill(),e.fillRect(N,0,w,s),e.beginPath(),nt(e,ut(b.out,$)),e.fill(),e.fillStyle=C,e.beginPath(),nt(e,k.inn),e.fill(),e.fillRect(N,Qe,w,s-2*Qe),e.beginPath(),nt(e,ut(b.inn,$)),e.fill(),y&&(e.save(),e.beginPath(),nt(e,k.inn),e.rect(N,Qe,w,s-2*Qe),nt(e,ut(b.inn,$)),e.clip(),e.globalAlpha=.85,e.fillStyle=y,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),m&&(e.save(),e.beginPath(),nt(e,k.inn),e.rect(N,Qe,w,s-2*Qe),nt(e,ut(b.inn,$)),e.clip(),e.globalAlpha=.85,e.fillStyle=m,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),e.restore();return}const M=`hsl(${x},${Math.min(v+10,100)}%,${Math.max(f-22,4)}%)`,E=`hsl(${x},${v}%,${f}%)`,R=`hsl(${x},${Math.max(v-12,0)}%,${Math.min(f+18,88)}%)`,L=`hsl(${x},${Math.min(v+20,100)}%,${Math.min(f+30,93)}%)`,A=l/100*.78,z=c/100*.65,j=1-d/100*.87,I=Qe,Y=s-Qe,H=Y-I,D=I+H*.44,V=I+H*.58;e.save(),e.translate(t,n);const Z=e.createLinearGradient(0,0,0,s);Z.addColorStop(0,"rgba(255,255,255,0.55)"),Z.addColorStop(.3,"rgba(255,255,255,0.35)"),Z.addColorStop(1,"rgba(255, 255, 255, 0.08)"),e.fillStyle=Z,e.beginPath(),nt(e,k.out),e.fill(),e.fillRect(N,0,w,s),e.beginPath(),nt(e,ut(b.out,$)),e.fill();const X=e.createLinearGradient(0,I,0,Y);X.addColorStop(0,R),X.addColorStop(.5,E),X.addColorStop(1,M),e.globalAlpha=j,e.fillStyle=X,e.beginPath(),nt(e,k.inn),e.fill(),e.fillRect(N,Qe,w,s-2*Qe),e.beginPath(),nt(e,ut(b.inn,$)),e.fill(),e.globalAlpha=1,y&&(e.save(),e.beginPath(),nt(e,k.inn),e.rect(N,Qe,w,s-2*Qe),nt(e,ut(b.inn,$)),e.clip(),e.globalAlpha=j*.9,e.fillStyle=y,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),m&&(e.save(),e.beginPath(),nt(e,k.inn),e.rect(N,Qe,w,s-2*Qe),nt(e,ut(b.inn,$)),e.clip(),e.globalAlpha=j*.85,e.fillStyle=m,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),e.save(),e.beginPath(),nt(e,k.inn),e.rect(N,Qe,w,s-2*Qe),nt(e,ut(b.inn,$)),e.clip();const q=e.createLinearGradient(0,V,0,Y);q.addColorStop(0,"transparent"),q.addColorStop(.6,L.replace(")",`, ${z*.6})`).replace("hsl","hsla")),q.addColorStop(1,L.replace(")",`, ${z})`).replace("hsl","hsla")),e.fillStyle=q,e.fillRect(0,V,a,Y-V);const G=e.createLinearGradient(0,I,0,D);G.addColorStop(0,`rgba(255,255,255,${A})`),G.addColorStop(.5,`rgba(255,255,255,${A*.25})`),G.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=G,e.fillRect(0,I,a,D-I),e.restore(),e.restore()}const Ht="var(--nice-warning, #FFD700)",Ro="var(--nice-warning-bg, #fff0a8)";function Hu(e){const{ctx:t,ballX:n,height:a,playerColor:s,currentTime:i}=e;t.save(),t.globalCompositeOperation="source-over";const o=t.createLinearGradient(Math.max(0,n-60),0,n,0);o.addColorStop(0,"transparent"),o.addColorStop(1,s),t.globalAlpha=.18,t.fillStyle=o,t.fillRect(Math.max(0,n-60),0,60,a),t.globalAlpha=.9,t.strokeStyle=s,t.lineWidth=3,t.shadowColor=s,t.shadowBlur=12,t.beginPath(),t.moveTo(n,0),t.lineTo(n,a),t.stroke();const l=6+Math.sin(i*6)*2;t.fillStyle=e.ballIsGold?we.resolveCssColor(Ht,t.canvas):s,t.beginPath(),t.moveTo(n,e.ballY-l),t.lineTo(n+l*.7,e.ballY),t.lineTo(n,e.ballY+l),t.lineTo(n-l*.7,e.ballY),t.closePath(),t.fill(),t.restore(),t.save(),t.globalCompositeOperation="source-atop",t.globalAlpha=.35;for(const c of e.visibleNotes)c.isSung&&(t.fillStyle=c.isGold?we.resolveCssColor(Ht,t.canvas):s,t.fillRect(c.x,c.y,c.w,c.h));t.restore()}function Ku(e){const{ctx:t,ballX:n,ballY:a,ballRadius:s,playerColor:i,ballIsGold:o,currentTime:l}=e,c=3,d=s*1.5,h=l*4;t.save();for(let g=0;g<c;g++){const y=(h+g*2.1)%(Math.PI*2),m=Math.sin(y)*.5+.5,x=d+m*s*3,v=(1-m)*.5;t.globalAlpha=v,t.strokeStyle=o?we.resolveCssColor(Ht,t.canvas):i,t.lineWidth=2-m,t.beginPath(),t.arc(n,a,x,0,Math.PI*2),t.stroke()}t.globalAlpha=.8,t.shadowColor=o?we.resolveCssColor(Ht,t.canvas):i,t.shadowBlur=16+Math.sin(l*8)*4,t.fillStyle=o?we.resolveCssColor(Ro,t.canvas):i;const p=s*(.8+Math.sin(l*10)*.2);t.beginPath(),t.arc(n,a,p,0,Math.PI*2),t.fill();for(const g of e.visibleNotes){if(!g.isSung)continue;const y=(l*6+g.x*.01)%(Math.PI*2),m=.15+Math.sin(y)*.1;t.globalAlpha=m,t.fillStyle=g.isGold?we.resolveCssColor(Ht,t.canvas):i,t.fillRect(g.x,g.y,g.w,g.h)}t.restore()}function Yu(e){const{ctx:t,ballX:n,ballY:a,ballRadius:s,playerColor:i,ballIsGold:o,currentTime:l}=e,c=20+Math.abs(Math.sin(l*3))*15,d=l*5%(Math.PI*2),h=-Math.abs(Math.sin(d))*c,p=a+h;t.save(),t.globalAlpha=.3,t.fillStyle=we.resolveCssColor("var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",t.canvas);const g=1-Math.abs(h)/(c+20);t.beginPath(),t.ellipse(n,a+s*.5,s*g*1.5,s*.3*g,0,0,Math.PI*2),t.fill(),t.restore(),t.save();const y=5;for(let v=0;v<y;v++){const f=(v+1)*.04,k=(l-f)*5%(Math.PI*2),b=a+-Math.abs(Math.sin(k))*c,w=.15*(1-v/y),N=s*(.6-v*.08);t.globalAlpha=w,t.fillStyle=i,t.beginPath(),t.arc(n-v*3,b,Math.max(2,N),0,Math.PI*2),t.fill()}t.restore(),t.save();const m=1+Math.abs(Math.sin(d))*.15,x=1/m;if(t.translate(n,p),t.scale(x,m),t.shadowColor=o?we.resolveCssColor(Ht,t.canvas):i,t.shadowBlur=12,t.fillStyle=o?we.resolveCssColor(Ro,t.canvas):i,t.beginPath(),t.arc(0,0,s,0,Math.PI*2),t.fill(),t.lineWidth=1.5,t.strokeStyle=we.resolveCssColor("var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",t.canvas),t.stroke(),t.restore(),Math.abs(Math.sin(d))<.1){t.save(),t.globalAlpha=.6,t.fillStyle=o?we.resolveCssColor(Ht,t.canvas):i;for(let v=0;v<4;v++){const f=v/4*Math.PI*2+l,k=n+Math.cos(f)*(s+4),b=a+Math.sin(f)*2;t.beginPath(),t.arc(k,b,2,0,Math.PI*2),t.fill()}t.restore()}}function Zu(e,t){switch(e){case"wipe":return Hu(t),!0;case"pulse":return Ku(t),!0;case"bounce":return Yu(t),!0;case"ball":default:return!1}}const Xu=1e3,Qu=20,Ju=70,eh=5,Ls=26,_s="rgba(255,215,70,0.98)",zs=new Map,th=(e,t,n,a,s)=>{const i=`g${s}`,o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
28
28
|
<svg xmlns='http://www.w3.org/2000/svg' width='${a}' height='${a}' viewBox='0 0 ${a} ${a}'>
|
|
29
29
|
<defs>
|
|
30
30
|
<radialGradient id='g${i}' cx='50%' cy='40%' r='60%'>
|
|
31
|
-
<stop offset='0%' stop-color='hsl(${e} ${t}% ${
|
|
32
|
-
<stop offset='60%' stop-color='hsl(${e} ${Math.max(10,t-30)}% ${Math.min(90,
|
|
31
|
+
<stop offset='0%' stop-color='hsl(${e} ${t}% ${n}%)' stop-opacity='1'/>
|
|
32
|
+
<stop offset='60%' stop-color='hsl(${e} ${Math.max(10,t-30)}% ${Math.min(90,n+10)}%)' stop-opacity='0.9'/>
|
|
33
33
|
<stop offset='100%' stop-color='transparent' stop-opacity='0'/>
|
|
34
34
|
</radialGradient>
|
|
35
35
|
</defs>
|
|
36
36
|
<g transform='translate(${a/2}, ${a/2})'>
|
|
37
37
|
<circle cx='0' cy='0' r='${a*.45}' fill='url(#g${i})' />
|
|
38
38
|
</g>
|
|
39
|
-
</svg>`;return`data:image/svg+xml;utf8,${encodeURIComponent(o)}`},ih=(e,t,r,a,s)=>{const i=`${e}-${t}-${r}-${Math.round(a)}-${s}`;let o=Fs.get(i);return o||(o=new Image,o.src=sh(e,t,r,a,s),Fs.set(i,o),o)},oh=e=>{const t=e.replace("#",""),r=parseInt(t.length===3?t[0]+t[0]:t.substring(0,2),16)/255,a=parseInt(t.length===3?t[1]+t[1]:t.substring(2,4),16)/255,s=parseInt(t.length===3?t[2]+t[2]:t.substring(4,6),16)/255,i=Math.max(r,a,s),o=Math.min(r,a,s);let l=0,c=0;const d=(i+o)/2;if(i!==o){const h=i-o;switch(c=d>.5?h/(2-i-o):h/(i+o),i){case r:l=(a-s)/h+(a<s?6:0);break;case a:l=(s-r)/h+2;break;case s:l=(r-a)/h+4;break}l/=6}return{h:Math.round(l*360),s:Math.round(c*100),l:Math.round(d*100)}},lh=(e,t,r,a=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(r)}%, ${a})`;function Qn(e){try{const t=we.resolveCssColor(e),[r,a,s]=ad(t),i=o=>o.toString(16).padStart(2,"0");return`#${i(r)}${i(a)}${i(s)}`.toLowerCase()}catch{return"var(--nice-warning, #ffcc00)"}}function ch(e,t,r,a,s,i){const o=Math.min(i,a/2,s/2);e.beginPath(),e.moveTo(t+o,r),e.lineTo(t+a-o,r),e.quadraticCurveTo(t+a,r,t+a,r+o),e.lineTo(t+a,r+s-o),e.quadraticCurveTo(t+a,r+s,t+a-o,r+s),e.lineTo(t+o,r+s),e.quadraticCurveTo(t,r+s,t,r+s-o),e.lineTo(t,r+o),e.quadraticCurveTo(t,r,t+o,r),e.closePath()}const on=new Map,$n=new Set,fr=new Set;function Ka(e){const t=on.get(e);return t?Promise.resolve(t):fr.has(e)?Promise.reject(new Error(`Texture failed: ${e}`)):$n.has(e)?new Promise((r,a)=>{const s=()=>{on.has(e)?r(on.get(e)):fr.has(e)?a(new Error(`Texture failed: ${e}`)):requestAnimationFrame(s)};s()}):($n.add(e),new Promise((r,a)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{on.set(e,s),$n.delete(e),r(s)},s.onerror=()=>{$n.delete(e),fr.add(e),a(new Error(`Failed to load texture: ${e}`))},s.src=e}))}function dh(e){return on.get(e)??null}function Pn(e,t,r=1){const a=on.get(t);if(!a)return!$n.has(t)&&!fr.has(t)&&Ka(t).catch(()=>{}),null;const s=e.createPattern(a,"repeat");if(!s)return null;if(r!==1){const i=new DOMMatrix;i.scaleSelf(r,r),s.setTransform(i)}return s}function uh(e){for(const t of e)t&&Ka(t).catch(()=>{})}const En=new Map,rn=new Set;function yo(e,t,r){return`${e}|${t}|${r??""}`}function hh(e,t,r){const a=yo(e.name,t,r),s=En.get(a);if(s)return Promise.resolve(s);if(rn.has(a))return new Promise((m,x)=>{const b=()=>{En.has(a)?m(En.get(a)):rn.has(a)?requestAnimationFrame(b):x(new Error(`Pattern render failed: ${a}`))};b()});rn.add(a);const i="p",o=e.mk(i,t,r??void 0),l=o.match(/width="(\d+)"/),c=o.match(/height="(\d+)"/),d=l?parseInt(l[1],10):16,h=c?parseInt(c[1],10):16,f=`<svg xmlns="http://www.w3.org/2000/svg" width="${d}" height="${h}"><defs>${o}</defs><rect width="${d}" height="${h}" fill="url(#${i})"/></svg>`,p=new Blob([f],{type:"image/svg+xml;charset=utf-8"}),y=URL.createObjectURL(p);return new Promise((m,x)=>{const b=new Image;b.onload=()=>{En.set(a,b),rn.delete(a),URL.revokeObjectURL(y),m(b)},b.onerror=()=>{rn.delete(a),URL.revokeObjectURL(y),x(new Error(`Failed to render pattern tile: ${e.name}`))},b.src=y})}function An(e,t,r,a){const s=yo(t.name,r,a),i=En.get(s);return i?e.createPattern(i,"repeat"):(rn.has(s)||hh(t,r,a).catch(()=>{}),null)}let jt=null,at=null,pt=null,Tt=null,xt=null,qe=null,Os="",Bs=0,Gs="";const pa=(e,t,r,a,s,i,o,l,c,d,h,f,p,y,m,x,b,g,S,v,k,M,T,N)=>{e.clearRect(0,0,t,r);const j=N??null,R=(j==null?void 0:j.filledBar)??Gt,z=(j==null?void 0:j.emptyBar)??_r,A=(j==null?void 0:j.goldFilledBar)??Or,$=(j==null?void 0:j.goldEmptyBar)??Fr,O=(j==null?void 0:j.font)??Br,I=Rn(R.capStyleName),U=Rn(z.capStyleName),J=Rn(A.capStyleName),_=Rn($.capStyleName),W=R.patternName?Nn(R.patternName):null,K=z.patternName?Nn(z.patternName):null,re=A.patternName?Nn(A.patternName):null,X=$.patternName?Nn($.patternName):null,q=W?An(e,W,R.patternColor??R.color??"var(--nice-bg, #fff)",R.patternColor):null,E=K?An(e,K,z.patternColor??z.color??"var(--nice-border, #d1d5db)",z.patternColor):null,P=re?An(e,re,A.patternColor??"var(--nice-warning, #FFD700)",A.patternColor):null,C=X?An(e,X,$.patternColor??"var(--nice-warning, #FFD700)",$.patternColor):null;Gs!==i&&(Gs=i,da("RENDER",`Renderer using settings for "${i}" — filled: cap=${R.capStyleName}, glass=${R.glass} | empty: cap=${z.capStyleName}, glass=${z.glass} | goldFilled: cap=${A.capStyleName}, pattern=${A.patternName??"none"} | goldEmpty: cap=${$.capStyleName}, pattern=${$.patternName??"none"} | hasSettings=${!!j}`,{filledBar:R,emptyBar:z,goldFilledBar:A,goldEmptyBar:$,filledOverlay:!!q,emptyOverlay:!!E,goldFilledOverlay:!!P,goldEmptyOverlay:!!C}));const L=R.textureUrl?Pn(e,R.textureUrl,R.textureScale):null,w=z.textureUrl?Pn(e,z.textureUrl,z.textureScale):null,D=A.textureUrl?Pn(e,A.textureUrl,A.textureScale):null,F=$.textureUrl?Pn(e,$.textureUrl,$.textureScale):null,B=typeof document<"u"?we.resolveCssColor(l||"var(--nice-color-accent, #ffcc00)"):l||"var(--nice-color-accent, #ffcc00)",V=Qn(B||"var(--nice-warning, #ffcc00)"),Y=he=>we.resolveCssColor(he),oe=O.fontFamily||"Arial",ie=O.fontSize||18,ne=Y(O.fontColor||"var(--btn-text, #fff)"),Z=O.outlineColor?Y(O.outlineColor):null,H=typeof O.outlineWidth=="number"?O.outlineWidth:0,se=O.shadow||null;typeof document<"u"&&((!jt||jt.width!==t||jt.height!==r)&&(jt=document.createElement("canvas"),jt.width=t,jt.height=r,at=jt.getContext("2d")),at&&at.clearRect(0,0,t,r),(!pt||pt.width!==t||pt.height!==r)&&(pt=document.createElement("canvas"),pt.width=t,pt.height=r,Tt=pt.getContext("2d")),Tt&&Tt.clearRect(0,0,t,r),(!xt||xt.width!==t||xt.height!==r)&&(xt=document.createElement("canvas"),xt.width=t,xt.height=r,qe=xt.getContext("2d")),qe&&qe.clearRect(0,0,t,r));const ae=S?-S:0,ue=v||t;e.fillStyle=B,e.font=`bold ${ie}px ${oe}`;const de=e.measureText(i).width+20;if(e.fillRect(ae+10,5,de,25),e.save(),e.fillStyle=ne,se){const he=se.match(/(-?\d+)px\s+(-?\d+)px\s+(\d+)px\s+(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\)|[a-zA-Z]+)/);he&&(e.shadowOffsetX=parseInt(he[1],10),e.shadowOffsetY=parseInt(he[2],10),e.shadowBlur=parseInt(he[3],10),e.shadowColor=he[4])}if(e.fillText(i,ae+20,22),Z&&H>0&&(e.lineWidth=H,e.strokeStyle=Z,e.strokeText(i,ae+20,22)),e.restore(),b){const he=Y(g||"var(--nice-text-secondary, #6b7280)");e.font=`bold 12px ${oe}`;const Se=e.measureText(b).width,Ve=8,Ie=ae+10+de+6,Re=20,$e=7,Be=Se+Ve*2,Ge=4;e.beginPath(),e.moveTo(Ie+Ge,$e),e.lineTo(Ie+Be-Ge,$e),e.quadraticCurveTo(Ie+Be,$e,Ie+Be,$e+Ge),e.lineTo(Ie+Be,$e+Re-Ge),e.quadraticCurveTo(Ie+Be,$e+Re,Ie+Be-Ge,$e+Re),e.lineTo(Ie+Ge,$e+Re),e.quadraticCurveTo(Ie,$e+Re,Ie,$e+Re-Ge),e.lineTo(Ie,$e+Ge),e.quadraticCurveTo(Ie,$e,Ie+Ge,$e),e.closePath(),e.fillStyle=he,e.fill(),e.fillStyle=ne,e.fillText(b,Ie+Ve,$e+14),e.font=`bold ${ie}px ${oe}`}const fe=120;if(e.fillStyle=B,e.fillRect(ae+ue-fe-10,5,fe,25),e.fillStyle=ne,e.fillText(`${o} pts`,ae+ue-fe+15,22),k&&k.currentCombo>=5){const he=k.currentCombo>=50?"3x":k.currentCombo>=30?"2.5x":k.currentCombo>=20?"2x":k.currentCombo>=10?"1.5x":"",Se=`${k.currentCombo} combo${he?" "+he:""}`;e.font=`bold 12px ${oe}`;const Ie=e.measureText(Se).width+16,Re=ae+ue-fe-10-Ie-6;e.fillStyle=Y(k.currentCombo>=20?"var(--nice-color-success, #FFD700)":"var(--nice-color-warning, #ff9800)"),e.globalAlpha=.9,ch(e,Re,7,Ie,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=Y(k.currentCombo>=20?"var(--nice-text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(Se,Re+8,22),e.font=`bold 14px ${oe}`}if(M&&M.length>0){const he=M[M.length-1];if(he.label){const Se=`${M.length}-${he.label}`;Se!==Os&&(Os=Se,Bs=Date.now());const Ve=Date.now()-Bs;if(Ve<2500){const Ie=Ve<2e3?1:1-(Ve-2e3)/500,Re={Perfect:Y("var(--nice-color-success, #00e676)"),Great:Y("var(--nice-color-success, #66bb6a)"),Good:Y("var(--nice-color-accent, #ffeb3b)"),OK:Y("var(--nice-color-warning, #ff9800)"),Bad:Y("var(--nice-color-error, #ef5350)"),Awful:Y("var(--nice-color-error, #b71c1c)")};e.save(),e.globalAlpha=Ie,e.font=`bold ${Math.round(ie*1.2)}px ${oe}`;const $e=he.label,Be=e.measureText($e).width,Ge=ae+ue/2-Be/2;e.fillStyle=Re[$e]||ne,e.shadowColor=we.resolveCssColor("var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",e.canvas),e.shadowBlur=6,e.fillText($e,Ge,58),Z&&H>0&&(e.lineWidth=H,e.strokeStyle=Z,e.strokeText($e,Ge,58)),e.restore()}}}const xe=s-2,ce=s+5,be=40;let Me=1/0,Te=-1/0;if(a.forEach(he=>{he.forEach(Se=>{Se.pitch<Me&&(Me=Se.pitch),Se.pitch>Te&&(Te=Se.pitch)})}),c&&Array.isArray(c)&&c.length>0){let he=null;isFinite(Me)&&isFinite(Te)&&(he=Math.round((Me+Te)/2));let Se=1/0,Ve=-1/0;c.forEach(({t:Ie,hz:Re})=>{if(!Re||Re<=0)return;let $e=he;for(const Ge of a)for(const Je of Ge)Ie>=Je.startTime&&Ie<=Je.startTime+Je.duration&&($e=Je.pitch);const Be=ro(Re,$e);Be<Se&&(Se=Be),Be>Ve&&(Ve=Be)}),Se!==1/0&&Ve!==-1/0&&(Se<Me&&(Me=Math.floor(Se-2)),Ve>Te&&(Te=Math.ceil(Ve+2)))}(!isFinite(Me)||!isFinite(Te))&&(Me=40,Te=80),Me===Te&&(Me=Math.max(0,Me-6),Te=Te+6);const je=he=>{const Se=r-be-10;return be+Se-(he-Me)/(Te-Me)*Se},le=zr(p||"normal"),De=(r-be-10)/Math.max(1,Te-Me),ke=Math.max(10,Math.round(De*(1+2*le.semitoneTolerance)*.3)),ze=Math.max(5,Math.round(ke*.45));((he,Se,Ve,Ie,Re,$e)=>{he.lineWidth=1;for(let Be=Math.ceil(Re);Be<=Math.floor($e);Be++){const Ge=je(Be);he.strokeStyle=Y(Be%2===0?"var(--guide-line-strong, rgba(255, 255, 255, 0.12))":"var(--guide-line-weak, rgba(255, 255, 255, 0.06))"),he.beginPath(),he.moveTo(0,Math.round(Ge)+.5),he.lineTo(Se,Math.round(Ge)+.5),he.stroke()}})(e,t,r-be,be,Me,Te),Tt&&Tt.clearRect(0,0,t,r);const Ye=(s-xe)/(ce-xe)*t;let He=r*.5,At=!1,ht=!1;const It=(he,Se,Ve,Ie,Re,$e,Be=0)=>{const Ge=(Ae,Oe,ge,Ne,Ee,We)=>{const _e=Math.min(We,Ne/2,Ee/2);Ae.beginPath(),Ae.moveTo(Oe+_e,ge),Ae.lineTo(Oe+Ne-_e,ge),Ae.quadraticCurveTo(Oe+Ne,ge,Oe+Ne,ge+_e),Ae.lineTo(Oe+Ne,ge+Ee-_e),Ae.quadraticCurveTo(Oe+Ne,ge+Ee,Oe+Ne-_e,ge+Ee),Ae.lineTo(Oe+_e,ge+Ee),Ae.quadraticCurveTo(Oe,ge+Ee,Oe,ge+Ee-_e),Ae.lineTo(Oe,ge+_e),Ae.quadraticCurveTo(Oe,ge,Oe+_e,ge),Ae.closePath()},Je=Math.max(2,ke/2);Ie.forEach(Ae=>{if(Ae.startTime+Ae.duration<Re||Ae.startTime>$e)return;const Oe=(Ae.startTime-Re)/($e-Re)*Se,ge=Ae.duration/($e-Re)*Se,Ne=je(Ae.pitch)-ke/2,Ee=[];if(Array.isArray(f)){const We=Ae.startTime+Ae.duration;f.forEach(_e=>{if(_e.pitch!==Ae.pitch||_e.noteStart!=null&&_e.noteEnd!=null&&(Math.abs(_e.noteStart-Ae.startTime)>.01||Math.abs(_e.noteEnd-We)>.01))return;const rt=Math.max(_e.start,Ae.startTime),Ze=Math.min(_e.end,We);if(rt>=Ze)return;const Wt=(rt-Re)/($e-Re)*Se,Zt=(Ze-Re)/($e-Re)*Se;Ee.push({x1:Wt,x2:Zt,frac:_e.frac})})}if(Ae.isGold){he.save();const We=m&&m.shadowColor?m.shadowColor:_s,_e=m&&typeof m.glowBlur=="number"?m.glowBlur:zs;he.shadowColor=We,he.shadowBlur=Math.max(4,_e-12),he.fillStyle=Y("var(--gold-overlay, rgba(255, 215, 0, 0.15))"),Ge(he,Oe-1,Ne-1,ge+2,ke+2,Je),he.fill(),he.restore();const rt=Qn("var(--gold-base, #b4af9f)");Tn(he,Oe,Ne,ge,ke,_,$.color??rt,$.highlight,$.glow,$.glass,X,$.patternColor,$.patternOnly,F,C),he.save(),Ge(he,Oe,Ne,ge,ke,Je),he.clip(),he.globalAlpha=.18,he.fillStyle=Y("var(--nice-color-success, #FFD700)"),he.fillRect(Oe,Ne,ge,Math.max(1,ke*.25)),he.globalAlpha=1,he.restore(),Ee.length>0&&(he.save(),Ge(he,Oe,Ne,ge,ke,Je),he.clip(),Ee.forEach(Ze=>{const Wt=Math.max(1,Ze.x2-Ze.x1);Tn(he,Ze.x1,Ne,Wt,ke,J,A.color??"var(--nice-warning, #FFD700)",A.highlight,A.glow,A.glass,re,A.patternColor,A.patternOnly,D,P)}),he.restore()),Ee.length===0&&(he.lineWidth=1,he.strokeStyle=Y("var(--gold-outline, rgba(255, 215, 0, 0.35))"),Ge(he,Oe+.5,Ne+.5,ge-1,Math.max(1,ke-1),Je),he.stroke())}else{const We=Qn("var(--note-base, #d1d5db)");Tn(he,Oe,Ne,ge,ke,U,z.color??We,z.highlight,z.glow,z.glass,K,z.patternColor,z.patternOnly,w,E),Ee.length>0&&(he.save(),Ge(he,Oe,Ne,ge,ke,Je),he.clip(),Ee.forEach(_e=>{const rt=Math.max(1,_e.x2-_e.x1);Tn(he,_e.x1,Ne,rt,ke,I,R.color??V,R.highlight,R.glow,R.glass,W,R.patternColor,R.patternOnly,L,q)}),he.restore())}Tt&&(Tt.fillStyle=we.resolveCssColor("var(--nice-bg, #fff)",Tt.canvas),Tt.fillRect(Oe,Ne,ge,ke))})};if(a.forEach(he=>{It(e,t,r-be,he,xe,ce,be);for(const Se of he)if(s>=Se.startTime&&s<=Se.startTime+Se.duration){He=je(Se.pitch),At=!0,ht=!!Se.isGold;break}}),!At){let he=null,Se=null;for(const Ve of a)for(const Ie of Ve)Ie.startTime>s&&(!he||Ie.startTime<he.startTime)&&(he=Ie),Ie.startTime<=s&&(!Se||Ie.startTime>Se.startTime)&&(Se=Ie);he?(He=je(he.pitch),ht=!!he.isGold):Se?(He=je(Se.pitch),ht=!!Se.isGold):He=r*.5}const ct=B||Y("var(--nice-color-accent, #ffcc00)"),pe=1+Math.sin((s||0)*8)*.06,ye=ze*pe,Fe=[];for(const he of a)for(const Se of he){if(Se.startTime+Se.duration<xe||Se.startTime>ce)continue;const Ve=(Se.startTime-xe)/(ce-xe)*t,Ie=Se.duration/(ce-xe)*t,Re=je(Se.pitch)-ke/2,$e=Se.startTime+Se.duration<=s;Fe.push({x:Ve,y:Re,w:Ie,h:ke,isGold:Se.isGold,isSung:$e})}if(!eh(T||"ball",{ctx:e,ballX:Ye,ballY:He,ballRadius:ye,playerColor:ct,ballIsGold:ht,currentTime:s,height:r,visibleNotes:Fe})){jt&&e.drawImage(jt,0,0),xt&&e.drawImage(xt,0,0),e.save(),e.globalCompositeOperation="source-over",e.globalAlpha=.28;const he=Math.max(18,ye*5),Se=e.createRadialGradient(Ye,He,0,Ye,He,he);if(Se.addColorStop(0,ct),Se.addColorStop(1,"transparent"),e.fillStyle=Se,e.beginPath(),e.arc(Ye,He,he,0,Math.PI*2),e.fill(),e.restore(),y&&at&&pt&&(at.save(),at.globalCompositeOperation="source-over",at.globalAlpha=.95,at.fillStyle=ct,at.beginPath(),at.arc(Ye,He,ye+4,0,Math.PI*2),at.fill(),at.restore(),at.save(),at.globalCompositeOperation="destination-in",at.drawImage(pt,0,0),at.restore(),e.drawImage(jt,0,0)),y&&qe&&pt)try{const Re=Qn(ct),{h:$e,s:Be,l:Ge}=oh(Re),Ae=lh($e,Math.max(10,Math.round(Be*(typeof h=="number"?h:.25))),Ge,.85);qe.save(),qe.globalCompositeOperation="multiply",qe.globalAlpha=.65,qe.fillStyle=Ae,qe.beginPath(),qe.arc(Ye,He,Math.max(8,ye+6),0,Math.PI*2),qe.fill(),qe.restore(),qe.save(),qe.globalCompositeOperation="destination-out",qe.drawImage(pt,0,0),qe.restore(),e.drawImage(xt,0,0)}catch{qe.save(),qe.globalCompositeOperation="source-over",qe.globalAlpha=.6,qe.fillStyle=ct,qe.beginPath(),qe.arc(Ye,He,Math.max(8,ye+6),0,Math.PI*2),qe.fill(),qe.restore(),qe.save(),qe.globalCompositeOperation="destination-out",qe.drawImage(pt,0,0),qe.restore(),e.drawImage(xt,0,0)}const Ve=m&&m.shadowColor?m.shadowColor:_s,Ie=m&&typeof m.glowBlur=="number"?m.glowBlur:zs;e.save(),ht?(e.shadowColor=Ve,e.shadowBlur=Ie,e.fillStyle=Y("var(--gold-light, #FFF0A8)")):(e.shadowColor=ct,e.shadowBlur=10,e.fillStyle=ct),e.globalCompositeOperation="source-over",e.globalAlpha=1,e.beginPath(),e.arc(Ye,He,ye,0,Math.PI*2),e.fill(),e.lineWidth=1.5,e.strokeStyle=Y("var(--nice-shadow-md, rgba(0,0,0,0.35))"),e.stroke(),e.restore()}try{if(Array.isArray(x)&&x.length>0){const he=Date.now(),Se=m&&typeof m.lifeMs=="number"?m.lifeMs:th,Ve=(Re,$e,Be,Ge=5)=>{const Je=Be,Ae=Be*.45;e.beginPath();let Oe=Math.PI/2*3,ge=Re,Ne=$e;const Ee=Math.PI/Ge;e.moveTo(Re,$e-Je);for(let We=0;We<Ge;We++)ge=Re+Math.cos(Oe)*Je,Ne=$e+Math.sin(Oe)*Je,e.lineTo(ge,Ne),Oe+=Ee,ge=Re+Math.cos(Oe)*Ae,Ne=$e+Math.sin(Oe)*Ae,e.lineTo(ge,Ne),Oe+=Ee;e.lineTo(Re,$e-Je),e.closePath()},Ie=Re=>{let $e=Re>>>0;return()=>($e=$e*1664525+1013904223>>>0,($e&2147483647)/2147483647)};x.forEach(Re=>{const $e=he-Re.createdAt;if($e<0||$e>Se)return;const Be=$e/Se,Ge=(Re.noteStart-(s-2))/7*t,Je=je(Re.notePitch),Ae=Ie(Re.seed||Math.floor(Re.createdAt%1e5)),Oe=m&&typeof m.count=="number"?m.count:nh,ge=m&&typeof m.baseSpeed=="number"?m.baseSpeed:rh,Ne=m&&typeof m.baseSize=="number"?m.baseSize:ah;for(let Ee=0;Ee<Oe;Ee++){const We=Ae(),_e=Ae(),rt=Ee/Oe*Math.PI*2+We*Math.PI*.6+Be*1.5,Ze=6+ge*(1-Be)*(.5+_e*.8),Wt=Ge+Math.cos(rt)*Ze,Zt=Je+Math.sin(rt)*Ze*(.8+We*.6),Ct=Math.max(1,Ne*(1-Be)*(.5+_e)),ks=40+Math.round(20*Ae()),ws=70+Math.round(20*Ae()),Vr=Math.max(0,1-Be)*(.9-Ae()*.3),Kc=Math.max(6,Ct*2.6),qr=ih(ks,ws,60,Math.round(Kc),(Re.seed||0)+Ee);qr&&qr.complete?(e.save(),e.translate(Wt,Zt+4),e.rotate(rt+Be*4+(Ae()-.5)*1.2),e.globalAlpha=Vr,e.drawImage(qr,-Ct/2,-Ct/2,Ct,Ct),e.restore()):(e.save(),e.translate(Wt,Zt+4),e.rotate(rt+Be*4),e.fillStyle=`hsla(${ks}, ${ws}%, 60%, ${Vr})`,e.fillRect(-Ct/2,-Ct/2,Ct,Ct),e.restore()),Ae()>.85&&(e.save(),e.globalAlpha=Math.max(.35,1-Be),e.fillStyle=`hsla(${30+Math.round(10*Ae())}, ${60+Math.round(30*Ae())}%, ${70+Math.round(10*Ae())}%, ${Vr})`,e.strokeStyle=`rgba(0,0,0,${.12*(1-Be)})`,e.lineWidth=.8,Ve(Wt,Zt+4,Ct*(1.4+Ae())),e.fill(),e.stroke(),e.restore())}})}}catch{}return{ballX:Ye,ballY:He,ballIsGold:ht}},Ya=({song:e,currentTime:t,playerRef:r,config:a={},userPitch:s,segmentScores:i,goldBursts:o,combo:l,verseRatings:c})=>{const{isPlaying:d=!1,playerName:h="Ziom",score:f=1e4,playerBgColor:p="var(--karaoke-player-bg, #2196f3)",playerCount:y=2,gapDesaturation:m,goldSettings:x,difficultyLevel:b,algorithmLabel:g,algorithmColor:S,latencyMs:v=null,top:k,animationMode:M,karaokeSettings:T=null}=a,N=u.useRef(null),j=u.useRef(null),[R,z]=u.useState({width:600,height:150,top:250,visibleWidth:600}),[A,$]=u.useState(0),O=u.useRef(0),I=u.useRef(null),U=u.useRef(null),J=u.useRef(null),_=u.useRef(t),W=u.useRef(performance.now()),K=u.useRef(e),re=u.useRef(R),X=u.useRef(s),q=u.useRef(d),E=u.useRef(0),P=u.useRef(!1),C=u.useRef(null),L=u.useRef(null),w=()=>{const D=(e==null?void 0:e.id)??null;if(D!==L.current||!C.current){L.current=D;const F=e.notes.map(ne=>ne.noteLine);C.current=Hn(F,e.bpm??void 0);const B=C.current.reduce((ne,Z)=>ne+Z.length,0),V=C.current.reduce((ne,Z)=>ne+Z.filter(H=>H.isGold).length,0),Y=C.current.flat().map(ne=>ne.pitch),oe=Y.length?Math.min(...Y):0,ie=Y.length?Math.max(...Y):0;da("BARS",`Parsed notes for "${e.title}" — ${C.current.length} verses, ${B} notes (including ${V} golden), pitch range: ${oe}–${ie}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:F.length,verseCount:C.current.length,totalNotes:B,goldCount:V,minPitch:oe,maxPitch:ie})}return C.current};return u.useEffect(()=>{const D=(B,V,Y)=>B+(V-B)*Y,F=B=>{U.current===null&&(U.current=B);const V=Math.min(.1,(B-(U.current||B))/1e3);U.current=B;const Y=E.current,oe=O.current,ie=1-Math.exp(-12*V),ne=Math.abs(oe-Y)<.25?oe:D(Y,oe,ie);Math.abs(ne-Y)>1e-4&&($(ne),E.current=ne,N.current&&(N.current.style.transform=`translateX(${ne}px)`)),I.current=requestAnimationFrame(F)};return I.current=requestAnimationFrame(F),()=>{I.current&&cancelAnimationFrame(I.current),I.current=null,U.current=null}},[]),u.useEffect(()=>{const D=()=>{if(!r.current)return;const F=r.current.getBoundingClientRect(),B=2/Math.max(1,y),V=Math.round(F.width*B),Y=Math.round(F.width),oe=V*(150/600);z({width:V,height:oe,top:30,visibleWidth:Y})};return D(),window.addEventListener("resize",D),()=>window.removeEventListener("resize",D)},[r,y]),u.useEffect(()=>{var Y;if(d||!N.current)return;const D=N.current.getContext("2d");if(!D)return;const F=w(),B=t-(e.gap??0)/1e3,V=pa(D,R.width,R.height,F,B,h,f,p,s,e.id,m??void 0,i,b??void 0,d,x??void 0,o,g,S,E.current,R.visibleWidth,l,c,M,T);if(V&&N.current){const oe=R.visibleWidth||(((Y=j.current)==null?void 0:Y.getBoundingClientRect().width)??R.width),ie=R.width;let ne=Math.round(oe/2-V.ballX);const Z=oe-ie;ne=Math.max(Z,Math.min(0,ne)),O.current=ne}},[t,e,R,s,d,i,o,M,T]),u.useEffect(()=>{_.current=t,W.current=performance.now()},[t]),u.useEffect(()=>{K.current=e},[e]),u.useEffect(()=>{re.current=R},[R]),u.useEffect(()=>{X.current=s},[s]),u.useEffect(()=>{q.current=d},[d]),u.useEffect(()=>{const D=()=>{var se;const F=N.current,B=K.current,V=re.current;if(!F||!B||!V)return;const Y=F.getContext("2d");if(!Y)return;const oe=w(),ie=Math.min(.5,(performance.now()-W.current)/1e3),Z=(q.current?_.current+ie:_.current)-(B.gap??0)/1e3,H=pa(Y,V.width,V.height,oe,Z,h,f,p,X.current,B.id,m??void 0,i,b??void 0,q.current,x??void 0,o,g,S,E.current,V.visibleWidth,l,c,M,T);if(H){const ae=V.visibleWidth||(((se=j.current)==null?void 0:se.getBoundingClientRect().width)??V.width),ue=V.width;let ee=Math.round(ae/2-H.ballX);const de=ae-ue;ee=Math.max(de,Math.min(0,ee)),O.current=ee}};if(d){P.current||(P.current=!0,da("BARS",`Drawing bars in RAF loop — canvas: ${re.current.width}×${re.current.height}px, player: ${h}`,{canvasSize:re.current}));const F=()=>{D(),J.current=requestAnimationFrame(F)};return J.current=requestAnimationFrame(F),()=>{J.current&&cancelAnimationFrame(J.current),J.current=null}}P.current=!1},[d,h,f,p,m,i,b,x,o,M,T]),n.jsxs("div",{ref:j,style:{position:"absolute",left:"50%",top:`${k??R.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:R.visibleWidth,height:R.height,overflow:"hidden"},children:[n.jsx("style",{children:"@keyframes av-latency-pulse {0% { transform: scale(1); box-shadow: 0 4px 10px var(--nice-overlay-20, rgba(0, 0, 0, 0.2));} 50% { transform: scale(1.08); box-shadow: 0 8px 18px var(--nice-overlay-30, rgba(0,0,0,0.32));} 100% { transform: scale(1); box-shadow: 0 4px 10px var(--nice-overlay-20, rgba(0, 0, 0, 0.2));} } .av-latency-pulse { animation: av-latency-pulse 1s ease-in-out infinite; }"}),n.jsx("div",{style:{position:"absolute",right:8,top:6,zIndex:40,pointerEvents:"none",display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--nice-text-inverse, #fff)"},children:typeof v<"u"&&v!==null?(()=>{const D=v,F=D<=120?"var(--latency-good, #10b981)":D<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",B=`${D}ms`;return n.jsxs("div",{className:D>250?"av-latency-pulse":"",style:{background:F,padding:"6px 10px",borderRadius:12,boxShadow:"0 4px 10px var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",fontWeight:700,minWidth:56,textAlign:"center",display:"flex",alignItems:"center",gap:6},children:[n.jsx(G.NtdStopwatch,{size:12}),n.jsx("span",{children:B})]})})():n.jsx("div",{style:{background:"var(--latency-none-bg, rgba(75,85,99,0.9))",padding:"6px 8px",borderRadius:12,boxShadow:"0 4px 10px var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",minWidth:44,textAlign:"center"},children:"—"})}),n.jsx("canvas",{ref:N,width:R.width,height:R.height,role:"img","aria-label":`Pitch timeline for ${h??"player"}. Score: ${f??0}`,style:{position:"absolute",left:0,top:0,transform:`translateX(${A}px)`,willChange:"transform"}})]})},bo="/textures/seamless/256x256";function $t(e,t,r){return{name:e,icon:r,entries:Array.from({length:t},(a,s)=>{const i=String(s+1).padStart(2,"0");return{label:`${e} ${i}`,url:`${bo}/${e}/Photoreal_${e}_${i}-512x512.png`}})}}function Lt(e,t,r){return{name:e,icon:r,entries:Array.from({length:t},(a,s)=>{const i=String(s+1).padStart(2,"0");return{label:`${e} ${i}`,url:`${bo}/${e}/${e}_${i}-256x256.png`}})}}const Za=[$t("Fire",8,"fire"),$t("Metal",8,"metal"),$t("Ice",8,"ice"),$t("Stone",8,"stone"),$t("Wood",8,"wood"),$t("Tile",8,"tile"),$t("Concrete",8,"concrete"),$t("Trees",8,"trees"),$t("Grass",8,"grass"),Lt("Wall",24,"wall"),Lt("Rust",24,"rust"),Lt("Woven",24,"woven"),Lt("Ground",24,"ground"),Lt("Pebbles",24,"pebbles"),Lt("Plant",24,"plant"),Lt("Roof",24,"roof"),Lt("Misc",24,"misc")],vo=Za.flatMap(e=>e.entries);function ph(e){return vo.find(t=>t.url===e)}const fh={fire:G.NtdFire,metal:G.NtdSettings,ice:G.NtdSnowflake,stone:G.NtdMountain,wood:G.NtdTree,tile:G.NtdGrid,concrete:G.NtdLayers,trees:G.NtdTree,grass:G.NtdLeaf,wall:G.NtdHome,rust:G.NtdCircle,woven:G.NtdGrid,ground:G.NtdMountain,pebbles:G.NtdDroplet,plant:G.NtdLeaf,roof:G.NtdHome,misc:G.NtdPalette},mh=({icon:e})=>{const t=fh[e];return t?n.jsx(t,{size:14}):n.jsx(n.Fragment,{children:e})},Pt=({children:e,inline:t,strong:r})=>n.jsx("div",{style:{fontSize:13,fontWeight:r?600:void 0,color:"var(--nice-text-secondary, #ccc)",marginBottom:t?0:4},children:e}),xo=({fill:e=Gt,onChange:t=()=>{},previewColor:r="var(--nice-primary, #2196f3)",accentColor:a="var(--nice-primary, #0d6efd)",width:s,height:i})=>{const{t:o}=Pe(),[l,c]=u.useState(null),d=(g,S)=>{t({...e,[g]:S})},h=u.useMemo(()=>{const g=e.color||r||"var(--nice-primary, #2196f3)";return(S,v,k)=>{const M=Wn.find(N=>N.name===S)||Wn[0],T=v?$r.find(N=>N.name===v)??null:null;return mo({width:80,height:22,capStyle:M,color:g,highlight:e.highlight,glow:e.glow,glass:e.glass,pattern:T,patternColor:e.patternColor,patternOnly:e.patternOnly,textureUrl:k??null,textureScale:e.textureScale})}},[e,r]),f=`2px solid ${a}`,p=a==="var(--nice-warning-dark, #d4a017)"?"var(--nice-warning-bg, #fff8e1)":"var(--nice-info-bg, #e7f1ff)",y=u.useRef(null),m=u.useRef(null),x=u.useCallback((g,S)=>{g.current&&g.current.scrollBy({left:S*180,behavior:"smooth"})},[]),b={position:"absolute",top:0,width:28,height:"100%",border:"none",cursor:"pointer",zIndex:2,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,fontWeight:700,color:"var(--nice-text-on-primary, #ccc)",background:"linear-gradient(90deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"};return n.jsxs("div",{style:{padding:"4px 0",width:"100%",minWidth:0},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[n.jsx(Pt,{inline:!0,children:o("playerForm.barColor","Color")}),n.jsx(ve.NiceCheckbox,{label:o("playerForm.auto","Auto"),checked:!e.color,onChange:g=>d("color",g?null:r||"var(--nice-primary, #2196f3)")}),e.color&&n.jsx("input",{type:"color",value:e.color,onChange:g=>d("color",g.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),n.jsx(Pt,{children:o("playerForm.capShape","Cap shape")}),n.jsxs("div",{style:{position:"relative",marginBottom:10},children:[n.jsx("button",{type:"button",style:{...b,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>x(y,-1),"aria-label":o("playerForm.scrollLeft","Scroll left"),children:n.jsx(G.NtdChevronLeft,{size:16})}),n.jsx("button",{type:"button",style:{...b,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>x(y,1),"aria-label":o("playerForm.scrollRight","Scroll right"),children:n.jsx(G.NtdChevronRight,{size:16})}),n.jsx("div",{ref:y,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:Wn.map(g=>{const S=e.capStyleName===g.name;return n.jsx("div",{title:g.name,onClick:()=>d("capStyleName",g.name),style:{cursor:"pointer",flexShrink:0,border:S?f:"1px solid var(--nice-border-color, #555)",borderRadius:6,padding:3,background:S?p:"var(--nice-bg-secondary, #222)"},dangerouslySetInnerHTML:{__html:h(g.name,null)}},g.name)})})]}),n.jsx(Pt,{children:o("playerForm.pattern","Pattern")}),n.jsxs("div",{style:{position:"relative",marginBottom:10},children:[n.jsx("button",{type:"button",style:{...b,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>x(m,-1),"aria-label":o("playerForm.scrollLeft","Scroll left"),children:n.jsx(G.NtdChevronLeft,{size:16})}),n.jsx("button",{type:"button",style:{...b,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>x(m,1),"aria-label":o("playerForm.scrollRight","Scroll right"),children:n.jsx(G.NtdChevronRight,{size:16})}),n.jsxs("div",{ref:m,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:[n.jsx("div",{title:"None",onClick:()=>d("patternName",null),style:{cursor:"pointer",flexShrink:0,border:e.patternName?"1px solid var(--nice-border-color, #555)":f,borderRadius:6,padding:"3px 8px",background:e.patternName?"var(--nice-text, #222)":p,fontSize:12,lineHeight:"22px",color:"var(--nice-text-inverse, #ccc)"},children:"—"}),$r.map(g=>{const S=e.patternName===g.name;return n.jsx("div",{title:g.name,onClick:()=>d("patternName",g.name),style:{cursor:"pointer",flexShrink:0,border:S?f:"1px solid var(--nice-border-color, #555)",borderRadius:6,padding:3,background:S?p:"var(--nice-bg-secondary, #222)"},dangerouslySetInnerHTML:{__html:h(e.capStyleName,g.name)}},g.name)})]})]}),n.jsx("div",{style:{marginBottom:8},children:n.jsx(ve.NiceToggle,{label:o("playerForm.patternOnly","Pattern only (flat, no 3D)"),checked:e.patternOnly,onChange:g=>d("patternOnly",g)})}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[n.jsx(Pt,{inline:!0,children:o("playerForm.patternColor","Pattern color")}),n.jsx(ve.NiceCheckbox,{label:o("playerForm.auto","Auto"),checked:!e.patternColor,onChange:g=>d("patternColor",g?null:r||"var(--nice-bg, #fff)")}),e.patternColor&&n.jsx("input",{type:"color",value:e.patternColor,onChange:g=>d("patternColor",g.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),!e.patternOnly&&n.jsxs(n.Fragment,{children:[n.jsxs(Pt,{children:[o("playerForm.highlight","Highlight"),": ",e.highlight,"%"]}),n.jsx("div",{style:{marginBottom:8},children:n.jsx(ve.NiceSlider,{min:0,max:100,value:e.highlight,onChange:g=>d("highlight",g)})}),n.jsxs(Pt,{children:[o("playerForm.glow","Glow"),": ",e.glow,"%"]}),n.jsx("div",{style:{marginBottom:8},children:n.jsx(ve.NiceSlider,{min:0,max:100,value:e.glow,onChange:g=>d("glow",g)})})]}),n.jsxs(Pt,{children:[o("playerForm.glass","Transparency (glass)"),": ",e.glass,"%"]}),n.jsx("div",{style:{marginBottom:8},children:n.jsx(ve.NiceSlider,{min:0,max:100,value:e.glass,onChange:g=>d("glass",g)})}),n.jsx("div",{style:{marginTop:4},children:n.jsx(Pt,{strong:!0,children:o("playerForm.texture","Texture")})}),n.jsxs("div",{style:{marginBottom:6},children:[n.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",marginBottom:6},children:[n.jsx(ve.NiceButton,{size:"sm",variant:e.textureUrl?"outline":"primary",onClick:()=>{d("textureUrl",null),c(null)},children:o("playerForm.texNone","None")}),Za.map(g=>n.jsx(ve.NiceButton,{size:"sm",variant:(l==null?void 0:l.name)===g.name?"primary":"outline",onClick:()=>c(S=>(S==null?void 0:S.name)===g.name?null:g),title:g.name,ariaLabel:g.name,children:n.jsx(mh,{icon:g.icon})},g.name))]}),l&&n.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap",maxHeight:130,overflowY:"auto",padding:4,border:"1px solid var(--nice-border, #dee2e6)",borderRadius:6,background:"var(--nice-bg-secondary, #f8f9fa)"},children:l.entries.map(g=>{const S=e.textureUrl===g.url;return n.jsx("div",{title:g.label,onClick:()=>d("textureUrl",S?null:g.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:S?`3px solid ${a}`:"1px solid var(--nice-text-muted, #bbb)",backgroundImage:`url(${g.url})`,backgroundSize:"cover",boxShadow:S?`0 0 6px ${a}`:void 0}},g.url)})}),e.textureUrl&&n.jsxs("div",{style:{marginTop:4,display:"flex",alignItems:"center",gap:8},children:[n.jsx("div",{style:{width:80,height:22,borderRadius:6,backgroundImage:`url(${e.textureUrl})`,backgroundSize:`${Math.round(256*e.textureScale)}px`,border:"1px solid var(--nice-border-color, #aaa)"}}),n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #666)"},children:e.textureUrl.split("/").pop()})]})]}),e.textureUrl&&n.jsxs(n.Fragment,{children:[n.jsxs(Pt,{children:[o("playerForm.textureScale","Texture scale"),": ",e.textureScale.toFixed(1),"×"]}),n.jsx("div",{style:{marginBottom:8},children:n.jsx(ve.NiceSlider,{min:10,max:200,step:10,value:Math.round(e.textureScale*100),onChange:g=>d("textureScale",g/100)})})]})]})},st=it.scoped("AudioPitchAnalyzer");function So({onSegments:e,defaultCompareAll:t=!1,externalFile:r=null,postPitch:a,postLibrosaPitchTrack:s}){const{t:i}=Pe(),[o,l]=u.useState("pitchy"),[c,d]=u.useState(null),[h,f]=u.useState(t),[p,y]=u.useState({}),[m,x]=u.useState({}),[b,g]=u.useState([]),[S,v]=u.useState([]),[k,M]=u.useState(!1),[T,N]=u.useState(null),[j]=u.useState(null),[R]=u.useState(null),[z,A]=u.useState(null),$=u.useRef(null);function O(X){try{if(X instanceof Error){let E=`${X.message}
|
|
40
|
-
${
|
|
41
|
-
Attempted URLs: ${Array.isArray(
|
|
42
|
-
Attempted URLs: ${String(
|
|
43
|
-
Attempted URLs: ${Array.isArray(q.attemptedUrls)?q.attemptedUrls.join(", "):String(q.attemptedUrls)}`:String(X)}catch{return"Unknown error"}}function I(X){if(!X||X<=0)return null;const q=12*Math.log2(X/440)+69;return Math.round(q-12)}async function U(X){var E;const q=(E=X.target.files)==null?void 0:E[0];q&&await J(q,h)}async function J(X,q){N(null),v([]),M(!0);try{const E=await X.arrayBuffer(),P=window.AudioContext??window.webkitAudioContext,L=await new P().decodeAudioData(E),w=L.getChannelData(0);d(w);const D=L.sampleRate,F=Math.floor(D*.1),B=F,V=()=>{const H=[],se=oa.PitchDetector.forFloat32Array(F);for(let ae=0;ae<w.length-F;ae+=B){const ue=w.slice(ae,ae+F),[ee,de]=se.findPitch(ue,D),fe=I(ee);fe&&ee>50&&ee<2e3&&de>.7&&H.push({start:ae/D,duration:F/D,pitch:fe,freq:ee})}return H},Y=()=>{const H=[];for(let se=0;se<w.length-F;se+=B){const ae=w.slice(se,se+F),ue=W(ae,D),ee=I(ue);ee&&ue>50&&ue<2e3&&H.push({start:se/D,duration:F/D,pitch:ee,freq:ue})}return H};if(q){M(!0),N(null);const H={};try{const se={};try{H.pitchy=V(),se.pitchy=null}catch(ae){H.pitchy=[],se.pitchy=O(ae),st.warn("pitchy failed",ae)}try{H["ultrastar-wp"]=Y(),se["ultrastar-wp"]=null}catch(ae){H["ultrastar-wp"]=[],se["ultrastar-wp"]=O(ae),st.warn("ultrastar-wp failed",ae)}H.aubio=[],se.aubio="disabled";try{if(!a)throw new Error("CREPE backend not configured");const ue=(await a(X)).track??[];H.crepe=ue.map((ee,de)=>{var fe;return{start:ee.t,duration:(fe=ue[de+1])!=null&&fe.t?ue[de+1].t-ee.t:.1,pitch:I(ee.hz)??0,freq:ee.hz}}),se.crepe=null}catch(ae){H.crepe=[],se.crepe=O(ae),st.warn("crepe failed",ae)}try{if(!s)throw new Error("Librosa backend not configured");const ue=(await s(new File([X],X.name,{type:X.type}))).track??[];H.librosa=ue.map((ee,de)=>{var fe;return{start:ee.t,duration:(fe=ue[de+1])!=null&&fe.t?ue[de+1].t-ee.t:.1,pitch:I(ee.hz)??0,freq:ee.hz}}),se.librosa=null}catch(ae){H.librosa=[],se.librosa=O(ae),st.warn("librosa failed",ae)}x(se),y(H),v(H[o]??[])}catch(se){st.error("compareAll overall failed",se);const ae=se instanceof Error?se.message:String(se);N(i("audioPitch.errorComparing","Error comparing algorithms: ")+ae)}finally{M(!1)}return}const oe=[],ie=[];let ne=0;if(o==="pitchy"){const H=oa.PitchDetector.forFloat32Array(F);for(let se=0;se<w.length-F;se+=B){const ae=w.slice(se,se+F);let ue=0;for(let xe=0;xe<ae.length;xe++)ue+=ae[xe]*ae[xe];ue=Math.sqrt(ue/ae.length),ie.push(ue);const[ee,de]=H.findPitch(ae,D),fe=I(ee);fe&&ee>50&&ee<2e3&&de>.7&&(oe.push({start:se/D,duration:F/D,pitch:fe,freq:ee}),ne++)}}else if(o==="crepe")try{if(!a)throw new Error("CREPE backend not configured");const H=await a(X);if(!H.track||H.track.length===0)N(i("audioPitch.crepeNoNotes","CREPE detected no notes")),st.warn("Crepe: No notes detected in audio file.");else{const se=H.track.map((ae,ue)=>{const ee=I(ae.hz);return ee&&ae.hz>50&&ae.hz<2e3?{start:ae.t,duration:ue<H.track.length-1?H.track[ue+1].t-ae.t:.1,pitch:ee,freq:ae.hz}:null}).filter(ae=>ae!==null);if(v(se),e)try{e(se)}catch(ae){st.error("Error in onSegments:",ae)}g([]),d(null);return}}catch(H){N(i("audioPitch.crepeBackendError","CREPE backend error")),A(O(H)),st.error("Crepe: Error calling backend:",H)}else if(o==="librosa")try{await _(X),g([]),d(null);return}catch(H){N(i("audioPitch.librosaBackendError","Librosa backend error")),A(O(H)),st.error("Librosa: Error calling backend:",H)}else if(o==="ultrastar-wp")for(let H=0;H<w.length-F;H+=B){const se=w.slice(H,H+F);let ae=0;for(let de=0;de<se.length;de++)ae+=se[de]*se[de];ae=Math.sqrt(ae/se.length),ie.push(ae);const ue=W(se,D),ee=I(ue);ee&&ue>50&&ue<2e3&&(oe.push({start:H/D,duration:F/D,pitch:ee,freq:ue}),ne++)}g(ie);const Z=K(oe);if(v(Z),e)try{e(Z)}catch(H){st.error("Error in onSegments:",H)}Z.length===0&&o!=="crepe"&&(N(i("audioPitch.noNotesDetected","No notes detected")),st.warn("No notes detected in audio file."))}catch(E){N(i("audioPitch.errorAnalyzing","Error analyzing the file: ")+(E instanceof Error?E.message:String(E))),A(O(E)),st.error("Error analyzing audio file:",E)}finally{M(!1)}}u.useEffect(()=>{r&&J(r,!0)},[r]);async function _(X){try{if(!s)throw new Error("Librosa backend not configured");const q=new File([X],"capture.wav",{type:"audio/wav"}),P=((await s(q)).track??[]).map(C=>({t:C.t,hz:C.hz}));if(e){const C=P.map((L,w)=>{var B;const D=((B=P[w+1])==null?void 0:B.t)??L.t+.1,F=I(L.hz)??0;return{start:L.t,duration:Math.max(.05,D-L.t),pitch:F,freq:L.hz}});e(C),v(C)}}catch(q){st.warn("Librosa analysis failed, falling back to local detectors",q);const P=(typeof q=="object"&&q!==null?q:{}).attemptedUrls;P&&st.error("Librosa attempted URLs:",P);const C=P?Array.isArray(P)?P.join(", "):String(P):null,L=q instanceof Error?q.message:String(q);N(i("audioPitch.librosaBackendError","Librosa backend error")+": "+L+(C?" (attempted: "+C+")":"")),A(O(q))}}function W(X,q){const C=Math.floor(q/50),L=Math.max(2,Math.floor(q/2e3));let w=0;for(let V=0;V<X.length;V++)w+=X[V]*X[V];if(w<=1e-8)return 0;let D=-1,F=0;const B=1e-10;for(let V=L;V<=Math.min(C,X.length-2);V++){let Y=0;const oe=X.length-V;for(let ne=0;ne<oe;ne++)Y+=X[ne]*X[ne+V];const ie=Y/(oe+B)/(w/X.length+B);ie>F&&(F=ie,D=V)}return D>0&&F>.01?q/D:0}function K(X){if(X.length===0)return[];const q=[];let E=X[0];for(let P=1;P<X.length;P++){const C=X[P];C.pitch===E.pitch&&Math.abs(C.freq-E.freq)<1?E.duration+=C.duration:(q.push(E),E=C)}return q.push(E),q}function re(){try{const X=Object.keys(p).length>0?Object.keys(p):["pitchy","ultrastar-wp","aubio","crepe","librosa"],q=(()=>{let ne=0;for(const Z of X){const H=p[Z]??[];for(const se of H)ne=Math.max(ne,se.start+(se.duration||0))}return ne||0})(),E=(ne,Z)=>!ne||!Z?1/0:1200*Math.log2(ne/Z),P=(ne,Z)=>{if(!ne||!Z)return!1;const H=Math.round(Math.log2(Z/ne)),se=ne*Math.pow(2,H),ae=Math.abs(E(se,Z));return Math.abs(H)>=1&&ae<50},C=ne=>{const Z={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!ne||ne.length===0)return Z;Z.count=ne.length,Z.totalDur=ne.reduce((ue,ee)=>ue+(ee.duration||0),0);const H=ne.map(ue=>ue.freq).filter(Boolean);if(H.length===0)return Z;const se=H.reduce((ue,ee)=>ue+ee,0)/H.length,ae=H.reduce((ue,ee)=>ue+(ee-se)*(ee-se),0)/H.length;return Z.meanFreq=se,Z.stdFreq=Math.sqrt(ae||0),Z.meanDur=Z.totalDur/Z.count,Z.voicedFraction=q>0?Z.totalDur/q:null,Z},L=(ne,Z)=>{let H=0,se=0;const ae=[];for(const ee of ne){const de=ee.start,fe=ee.start+(ee.duration||.05);let xe=null,ce=0;for(const be of Z){const Me=be.start,Te=be.start+(be.duration||.05),je=Math.max(0,Math.min(fe,Te)-Math.max(de,Me));je>ce&&(ce=je,xe=be)}if(xe&&ce>0){const be=Math.abs(E(ee.freq,xe.freq));ae.push(be),be<50&&H++,P(ee.freq,xe.freq)&&se++}}const ue=ae.length?ae.reduce((ee,de)=>ee+de,0)/ae.length:null;return{matches:H,compared:ne.length,meanCents:ue,octaveErrors:se}},w=[];w.push("# AudioPitchAnalyzer — Comparative Report"),w.push(`Generated: ${new Date().toISOString()}`),w.push(""),w.push("## Summary"),w.push(`- Selected algorithm in UI: **${o}**`),w.push(`- Total analyzed duration (approx): **${q.toFixed(3)} s**`),w.push(""),w.push("## Per-algorithm statistics"),w.push("| Algorithm | Segments | Total voiced (s) | Voiced fraction | Mean freq (Hz) | Std freq (Hz) | Mean dur (s) |"),w.push("|---|---:|---:|---:|---:|---:|---:|");const D={};for(const ne of X){const Z=p[ne]??[],H=C(Z);D[ne]=H,w.push(`| ${ne} | ${H.count||0} | ${(H.totalDur||0).toFixed(3)} | ${H.voicedFraction!==null?(H.voicedFraction*100).toFixed(1)+"%":"N/A"} | ${H.meanFreq?H.meanFreq.toFixed(1):"N/A"} | ${H.stdFreq?H.stdFreq.toFixed(1):"N/A"} | ${H.meanDur?H.meanDur.toFixed(3):"N/A"} |`)}w.push(""),w.push("## Pairwise agreement (reference -> test)");const F=X.includes("crepe")?"crepe":X.includes("librosa")?"librosa":X.includes("pitchy")?"pitchy":X[0];w.push(`Reference algorithm: **${F}**`),w.push(""),w.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),w.push("|---|---:|---:|---:|---:|---:|");for(const ne of X){if(ne===F)continue;const Z=L(p[F]??[],p[ne]??[]),H=Z.compared?(Z.matches/Z.compared*100).toFixed(1)+"%":"N/A";w.push(`| ${F} -> ${ne} | ${Z.matches} | ${Z.compared} | ${H} | ${Z.meanCents!==null?Z.meanCents.toFixed(1):"N/A"} | ${Z.octaveErrors} |`)}w.push(""),w.push("## Observations and analysis"),w.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."),w.push("- Pairwise match rate shows how often algorithms agree on the same regions (within ~50 cents). Octave error counts highlight typical autocorrelation octave mistakes."),w.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."),w.push("");for(const ne of X){w.push(`### ${ne}`);const Z=D[ne];w.push(`- Segments: ${Z.count||0}`),w.push(`- Total voiced (s): ${(Z.totalDur||0).toFixed(3)}`),w.push(`- Voiced fraction: ${Z.voicedFraction!==null?(Z.voicedFraction*100).toFixed(1)+"%":"N/A"}`),w.push(`- Mean frequency: ${Z.meanFreq?Z.meanFreq.toFixed(2)+" Hz":"N/A"}`),w.push(`- Std frequency: ${Z.stdFreq?Z.stdFreq.toFixed(2)+" Hz":"N/A"}`),w.push("")}w.push("## Conclusions & recommendation");const B=[];for(const ne of X){if(ne===F){B.push({alg:ne,score:100});continue}const Z=L(p[F]??[],p[ne]??[]),H=Z.compared?Z.matches/Z.compared:0,se=Z.compared?Z.octaveErrors/Z.compared:0,ae=H-se*.5;B.push({alg:ne,score:ae})}B.sort((ne,Z)=>Z.score-ne.score),w.push(`- Based on this recording, recommended authoritative detector: **${B[0].alg}** (best agreement with reference).`),w.push("- For live, low-latency feedback use Pitchy (YIN) with smoothing/hysteresis; use Crepe/Librosa for authoritative scoring or post-processing."),w.push("- If octave errors are frequent, consider octave-correction heuristics (prefer lower octave when ambiguity) or combine detectors via voting."),w.push(""),w.push("## Raw data (per-algorithm segments)");for(const ne of X){const Z=p[ne]??[];w.push(`### ${ne} — ${Z.length} segments`);for(const se of Z)w.push(`- ${se.start.toFixed(3)} .. ${(se.start+(se.duration||0)).toFixed(3)} : ${se.freq.toFixed(2)} Hz (pitch ${se.pitch})`);const H=m[ne];H&&w.push(`- Error: ${H}`),w.push("")}const V=w.join(`
|
|
44
|
-
`),
|
|
39
|
+
</svg>`;return`data:image/svg+xml;utf8,${encodeURIComponent(o)}`},nh=(e,t,n,a,s)=>{const i=`${e}-${t}-${n}-${Math.round(a)}-${s}`;let o=zs.get(i);return o||(o=new Image,o.src=th(e,t,n,a,s),zs.set(i,o),o)},rh=e=>{const t=e.replace("#",""),n=parseInt(t.length===3?t[0]+t[0]:t.substring(0,2),16)/255,a=parseInt(t.length===3?t[1]+t[1]:t.substring(2,4),16)/255,s=parseInt(t.length===3?t[2]+t[2]:t.substring(4,6),16)/255,i=Math.max(n,a,s),o=Math.min(n,a,s);let l=0,c=0;const d=(i+o)/2;if(i!==o){const h=i-o;switch(c=d>.5?h/(2-i-o):h/(i+o),i){case n:l=(a-s)/h+(a<s?6:0);break;case a:l=(s-n)/h+2;break;case s:l=(n-a)/h+4;break}l/=6}return{h:Math.round(l*360),s:Math.round(c*100),l:Math.round(d*100)}},ah=(e,t,n,a=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(n)}%, ${a})`;function Qn(e){try{const t=we.resolveCssColor(e),[n,a,s]=Bc(t),i=o=>o.toString(16).padStart(2,"0");return`#${i(n)}${i(a)}${i(s)}`.toLowerCase()}catch{return"var(--nice-warning, #ffcc00)"}}function sh(e,t,n,a,s,i){const o=Math.min(i,a/2,s/2);e.beginPath(),e.moveTo(t+o,n),e.lineTo(t+a-o,n),e.quadraticCurveTo(t+a,n,t+a,n+o),e.lineTo(t+a,n+s-o),e.quadraticCurveTo(t+a,n+s,t+a-o,n+s),e.lineTo(t+o,n+s),e.quadraticCurveTo(t,n+s,t,n+s-o),e.lineTo(t,n+o),e.quadraticCurveTo(t,n,t+o,n),e.closePath()}const cn=new Map,Pn=new Set,fr=new Set;function qa(e){const t=cn.get(e);return t?Promise.resolve(t):fr.has(e)?Promise.reject(new Error(`Texture failed: ${e}`)):Pn.has(e)?new Promise((n,a)=>{const s=()=>{cn.has(e)?n(cn.get(e)):fr.has(e)?a(new Error(`Texture failed: ${e}`)):requestAnimationFrame(s)};s()}):(Pn.add(e),new Promise((n,a)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{cn.set(e,s),Pn.delete(e),n(s)},s.onerror=()=>{Pn.delete(e),fr.add(e),a(new Error(`Failed to load texture: ${e}`))},s.src=e}))}function ih(e){return cn.get(e)??null}function $n(e,t,n=1){const a=cn.get(t);if(!a)return!Pn.has(t)&&!fr.has(t)&&qa(t).catch(()=>{}),null;const s=e.createPattern(a,"repeat");if(!s)return null;if(n!==1){const i=new DOMMatrix;i.scaleSelf(n,n),s.setTransform(i)}return s}function oh(e){for(const t of e)t&&qa(t).catch(()=>{})}const En=new Map,sn=new Set;function No(e,t,n){return`${e}|${t}|${n??""}`}function lh(e,t,n){const a=No(e.name,t,n),s=En.get(a);if(s)return Promise.resolve(s);if(sn.has(a))return new Promise((m,x)=>{const v=()=>{En.has(a)?m(En.get(a)):sn.has(a)?requestAnimationFrame(v):x(new Error(`Pattern render failed: ${a}`))};v()});sn.add(a);const i="p",o=e.mk(i,t,n??void 0),l=o.match(/width="(\d+)"/),c=o.match(/height="(\d+)"/),d=l?parseInt(l[1],10):16,h=c?parseInt(c[1],10):16,p=`<svg xmlns="http://www.w3.org/2000/svg" width="${d}" height="${h}"><defs>${o}</defs><rect width="${d}" height="${h}" fill="url(#${i})"/></svg>`,g=new Blob([p],{type:"image/svg+xml;charset=utf-8"}),y=URL.createObjectURL(g);return new Promise((m,x)=>{const v=new Image;v.onload=()=>{En.set(a,v),sn.delete(a),URL.revokeObjectURL(y),m(v)},v.onerror=()=>{sn.delete(a),URL.revokeObjectURL(y),x(new Error(`Failed to render pattern tile: ${e.name}`))},v.src=y})}function An(e,t,n,a){const s=No(t.name,n,a),i=En.get(s);return i?e.createPattern(i,"repeat"):(sn.has(s)||lh(t,n,a).catch(()=>{}),null)}let Rt=null,at=null,ft=null,Et=null,xt=null,qe=null,Ds="",Fs=0,Os="";const ma=(e,t,n,a,s,i,o,l,c,d,h,p,g,y,m,x,v,f,k,b,w,N,$,M)=>{e.clearRect(0,0,t,n);const E=M??null,R=(E==null?void 0:E.filledBar)??Gt,L=(E==null?void 0:E.emptyBar)??Dr,A=(E==null?void 0:E.goldFilledBar)??Or,z=(E==null?void 0:E.goldEmptyBar)??Fr,j=(E==null?void 0:E.font)??Br,I=Rn(R.capStyleName),Y=Rn(L.capStyleName),H=Rn(A.capStyleName),D=Rn(z.capStyleName),V=R.patternName?Nn(R.patternName):null,Z=L.patternName?Nn(L.patternName):null,X=A.patternName?Nn(A.patternName):null,q=z.patternName?Nn(z.patternName):null,G=V?An(e,V,R.patternColor??R.color??"var(--nice-bg, #fff)",R.patternColor):null,C=Z?An(e,Z,L.patternColor??L.color??"var(--nice-border, #d1d5db)",L.patternColor):null,T=X?An(e,X,A.patternColor??"var(--nice-warning, #FFD700)",A.patternColor):null,S=q?An(e,q,z.patternColor??"var(--nice-warning, #FFD700)",z.patternColor):null;Os!==i&&(Os=i,ha("RENDER",`Renderer using settings for "${i}" — filled: cap=${R.capStyleName}, glass=${R.glass} | empty: cap=${L.capStyleName}, glass=${L.glass} | goldFilled: cap=${A.capStyleName}, pattern=${A.patternName??"none"} | goldEmpty: cap=${z.capStyleName}, pattern=${z.patternName??"none"} | hasSettings=${!!E}`,{filledBar:R,emptyBar:L,goldFilledBar:A,goldEmptyBar:z,filledOverlay:!!G,emptyOverlay:!!C,goldFilledOverlay:!!T,goldEmptyOverlay:!!S}));const F=R.textureUrl?$n(e,R.textureUrl,R.textureScale):null,K=L.textureUrl?$n(e,L.textureUrl,L.textureScale):null,P=A.textureUrl?$n(e,A.textureUrl,A.textureScale):null,B=z.textureUrl?$n(e,z.textureUrl,z.textureScale):null,_=typeof document<"u"?we.resolveCssColor(l||"var(--nice-color-accent, #ffcc00)"):l||"var(--nice-color-accent, #ffcc00)",U=Qn(_||"var(--nice-warning, #ffcc00)"),J=ge=>we.resolveCssColor(ge),se=j.fontFamily||"Arial",oe=j.fontSize||18,re=J(j.fontColor||"var(--btn-text, #fff)"),W=j.outlineColor?J(j.outlineColor):null,ee=typeof j.outlineWidth=="number"?j.outlineWidth:0,ae=j.shadow||null;typeof document<"u"&&((!Rt||Rt.width!==t||Rt.height!==n)&&(Rt=document.createElement("canvas"),Rt.width=t,Rt.height=n,at=Rt.getContext("2d")),at&&at.clearRect(0,0,t,n),(!ft||ft.width!==t||ft.height!==n)&&(ft=document.createElement("canvas"),ft.width=t,ft.height=n,Et=ft.getContext("2d")),Et&&Et.clearRect(0,0,t,n),(!xt||xt.width!==t||xt.height!==n)&&(xt=document.createElement("canvas"),xt.width=t,xt.height=n,qe=xt.getContext("2d")),qe&&qe.clearRect(0,0,t,n));const le=k?-k:0,ce=b||t;e.fillStyle=_,e.font=`bold ${oe}px ${se}`;const he=e.measureText(i).width+20;if(e.fillRect(le+10,5,he,25),e.save(),e.fillStyle=re,ae){const ge=ae.match(/(-?\d+)px\s+(-?\d+)px\s+(\d+)px\s+(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\)|[a-zA-Z]+)/);ge&&(e.shadowOffsetX=parseInt(ge[1],10),e.shadowOffsetY=parseInt(ge[2],10),e.shadowBlur=parseInt(ge[3],10),e.shadowColor=ge[4])}if(e.fillText(i,le+20,22),W&&ee>0&&(e.lineWidth=ee,e.strokeStyle=W,e.strokeText(i,le+20,22)),e.restore(),v){const ge=J(f||"var(--nice-text-secondary, #6b7280)");e.font=`bold 12px ${se}`;const ke=e.measureText(v).width,We=8,_e=le+10+he+6,Pe=20,Re=7,Oe=ke+We*2,Ge=4;e.beginPath(),e.moveTo(_e+Ge,Re),e.lineTo(_e+Oe-Ge,Re),e.quadraticCurveTo(_e+Oe,Re,_e+Oe,Re+Ge),e.lineTo(_e+Oe,Re+Pe-Ge),e.quadraticCurveTo(_e+Oe,Re+Pe,_e+Oe-Ge,Re+Pe),e.lineTo(_e+Ge,Re+Pe),e.quadraticCurveTo(_e,Re+Pe,_e,Re+Pe-Ge),e.lineTo(_e,Re+Ge),e.quadraticCurveTo(_e,Re,_e+Ge,Re),e.closePath(),e.fillStyle=ge,e.fill(),e.fillStyle=re,e.fillText(v,_e+We,Re+14),e.font=`bold ${oe}px ${se}`}const ue=120;if(e.fillStyle=_,e.fillRect(le+ce-ue-10,5,ue,25),e.fillStyle=re,e.fillText(`${o} pts`,le+ce-ue+15,22),w&&w.currentCombo>=5){const ge=w.currentCombo>=50?"3x":w.currentCombo>=30?"2.5x":w.currentCombo>=20?"2x":w.currentCombo>=10?"1.5x":"",ke=`${w.currentCombo} combo${ge?" "+ge:""}`;e.font=`bold 12px ${se}`;const _e=e.measureText(ke).width+16,Pe=le+ce-ue-10-_e-6;e.fillStyle=J(w.currentCombo>=20?"var(--nice-color-success, #FFD700)":"var(--nice-color-warning, #ff9800)"),e.globalAlpha=.9,sh(e,Pe,7,_e,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=J(w.currentCombo>=20?"var(--nice-text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(ke,Pe+8,22),e.font=`bold 14px ${se}`}if(N&&N.length>0){const ge=N[N.length-1];if(ge.label){const ke=`${N.length}-${ge.label}`;ke!==Ds&&(Ds=ke,Fs=Date.now());const We=Date.now()-Fs;if(We<2500){const _e=We<2e3?1:1-(We-2e3)/500,Pe={Perfect:J("var(--nice-color-success, #00e676)"),Great:J("var(--nice-color-success, #66bb6a)"),Good:J("var(--nice-color-accent, #ffeb3b)"),OK:J("var(--nice-color-warning, #ff9800)"),Bad:J("var(--nice-color-error, #ef5350)"),Awful:J("var(--nice-color-error, #b71c1c)")};e.save(),e.globalAlpha=_e,e.font=`bold ${Math.round(oe*1.2)}px ${se}`;const Re=ge.label,Oe=e.measureText(Re).width,Ge=le+ce/2-Oe/2;e.fillStyle=Pe[Re]||re,e.shadowColor=we.resolveCssColor("var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",e.canvas),e.shadowBlur=6,e.fillText(Re,Ge,58),W&&ee>0&&(e.lineWidth=ee,e.strokeStyle=W,e.strokeText(Re,Ge,58)),e.restore()}}}const xe=s-2,pe=s+5,Se=40;let je=1/0,$e=-1/0;if(a.forEach(ge=>{ge.forEach(ke=>{ke.pitch<je&&(je=ke.pitch),ke.pitch>$e&&($e=ke.pitch)})}),c&&Array.isArray(c)&&c.length>0){let ge=null;isFinite(je)&&isFinite($e)&&(ge=Math.round((je+$e)/2));let ke=1/0,We=-1/0;c.forEach(({t:_e,hz:Pe})=>{if(!Pe||Pe<=0)return;let Re=ge;for(const Ge of a)for(const Je of Ge)_e>=Je.startTime&&_e<=Je.startTime+Je.duration&&(Re=Je.pitch);const Oe=mo(Pe,Re);Oe<ke&&(ke=Oe),Oe>We&&(We=Oe)}),ke!==1/0&&We!==-1/0&&(ke<je&&(je=Math.floor(ke-2)),We>$e&&($e=Math.ceil(We+2)))}(!isFinite(je)||!isFinite($e))&&(je=40,$e=80),je===$e&&(je=Math.max(0,je-6),$e=$e+6);const Te=ge=>{const ke=n-Se-10;return Se+ke-(ge-je)/($e-je)*ke},de=zr(g||"normal"),Ee=(n-Se-10)/Math.max(1,$e-je),Me=Math.max(10,Math.round(Ee*(1+2*de.semitoneTolerance)*.3)),Ie=Math.max(5,Math.round(Me*.45));((ge,ke,We,_e,Pe,Re)=>{ge.lineWidth=1;for(let Oe=Math.ceil(Pe);Oe<=Math.floor(Re);Oe++){const Ge=Te(Oe);ge.strokeStyle=J(Oe%2===0?"var(--guide-line-strong, rgba(255, 255, 255, 0.12))":"var(--guide-line-weak, rgba(255, 255, 255, 0.06))"),ge.beginPath(),ge.moveTo(0,Math.round(Ge)+.5),ge.lineTo(ke,Math.round(Ge)+.5),ge.stroke()}})(e,t,n-Se,Se,je,$e),Et&&Et.clearRect(0,0,t,n);const Ye=(s-xe)/(pe-xe)*t;let Ze=n*.5,Ct=!1,dt=!1;const $t=(ge,ke,We,_e,Pe,Re,Oe=0)=>{const Ge=(Le,Fe,ve,Ne,Ae,Ve)=>{const De=Math.min(Ve,Ne/2,Ae/2);Le.beginPath(),Le.moveTo(Fe+De,ve),Le.lineTo(Fe+Ne-De,ve),Le.quadraticCurveTo(Fe+Ne,ve,Fe+Ne,ve+De),Le.lineTo(Fe+Ne,ve+Ae-De),Le.quadraticCurveTo(Fe+Ne,ve+Ae,Fe+Ne-De,ve+Ae),Le.lineTo(Fe+De,ve+Ae),Le.quadraticCurveTo(Fe,ve+Ae,Fe,ve+Ae-De),Le.lineTo(Fe,ve+De),Le.quadraticCurveTo(Fe,ve,Fe+De,ve),Le.closePath()},Je=Math.max(2,Me/2);_e.forEach(Le=>{if(Le.startTime+Le.duration<Pe||Le.startTime>Re)return;const Fe=(Le.startTime-Pe)/(Re-Pe)*ke,ve=Le.duration/(Re-Pe)*ke,Ne=Te(Le.pitch)-Me/2,Ae=[];if(Array.isArray(p)){const Ve=Le.startTime+Le.duration;p.forEach(De=>{if(De.pitch!==Le.pitch||De.noteStart!=null&&De.noteEnd!=null&&(Math.abs(De.noteStart-Le.startTime)>.01||Math.abs(De.noteEnd-Ve)>.01))return;const rt=Math.max(De.start,Le.startTime),Xe=Math.min(De.end,Ve);if(rt>=Xe)return;const Wt=(rt-Pe)/(Re-Pe)*ke,Qt=(Xe-Pe)/(Re-Pe)*ke;Ae.push({x1:Wt,x2:Qt,frac:De.frac})})}if(Le.isGold){ge.save();const Ve=m&&m.shadowColor?m.shadowColor:_s,De=m&&typeof m.glowBlur=="number"?m.glowBlur:Ls;ge.shadowColor=Ve,ge.shadowBlur=Math.max(4,De-12),ge.fillStyle=J("var(--gold-overlay, rgba(255, 215, 0, 0.15))"),Ge(ge,Fe-1,Ne-1,ve+2,Me+2,Je),ge.fill(),ge.restore();const rt=Qn("var(--gold-base, #b4af9f)");Tn(ge,Fe,Ne,ve,Me,D,z.color??rt,z.highlight,z.glow,z.glass,q,z.patternColor,z.patternOnly,B,S),ge.save(),Ge(ge,Fe,Ne,ve,Me,Je),ge.clip(),ge.globalAlpha=.18,ge.fillStyle=J("var(--nice-color-success, #FFD700)"),ge.fillRect(Fe,Ne,ve,Math.max(1,Me*.25)),ge.globalAlpha=1,ge.restore(),Ae.length>0&&(ge.save(),Ge(ge,Fe,Ne,ve,Me,Je),ge.clip(),Ae.forEach(Xe=>{const Wt=Math.max(1,Xe.x2-Xe.x1);Tn(ge,Xe.x1,Ne,Wt,Me,H,A.color??"var(--nice-warning, #FFD700)",A.highlight,A.glow,A.glass,X,A.patternColor,A.patternOnly,P,T)}),ge.restore()),Ae.length===0&&(ge.lineWidth=1,ge.strokeStyle=J("var(--gold-outline, rgba(255, 215, 0, 0.35))"),Ge(ge,Fe+.5,Ne+.5,ve-1,Math.max(1,Me-1),Je),ge.stroke())}else{const Ve=Qn("var(--note-base, #d1d5db)");Tn(ge,Fe,Ne,ve,Me,Y,L.color??Ve,L.highlight,L.glow,L.glass,Z,L.patternColor,L.patternOnly,K,C),Ae.length>0&&(ge.save(),Ge(ge,Fe,Ne,ve,Me,Je),ge.clip(),Ae.forEach(De=>{const rt=Math.max(1,De.x2-De.x1);Tn(ge,De.x1,Ne,rt,Me,I,R.color??U,R.highlight,R.glow,R.glass,V,R.patternColor,R.patternOnly,F,G)}),ge.restore())}Et&&(Et.fillStyle=we.resolveCssColor("var(--nice-bg, #fff)",Et.canvas),Et.fillRect(Fe,Ne,ve,Me))})};if(a.forEach(ge=>{$t(e,t,n-Se,ge,xe,pe,Se);for(const ke of ge)if(s>=ke.startTime&&s<=ke.startTime+ke.duration){Ze=Te(ke.pitch),Ct=!0,dt=!!ke.isGold;break}}),!Ct){let ge=null,ke=null;for(const We of a)for(const _e of We)_e.startTime>s&&(!ge||_e.startTime<ge.startTime)&&(ge=_e),_e.startTime<=s&&(!ke||_e.startTime>ke.startTime)&&(ke=_e);ge?(Ze=Te(ge.pitch),dt=!!ge.isGold):ke?(Ze=Te(ke.pitch),dt=!!ke.isGold):Ze=n*.5}const pt=_||J("var(--nice-color-accent, #ffcc00)"),Xt=1+Math.sin((s||0)*8)*.06,fe=Ie*Xt,Ce=[];for(const ge of a)for(const ke of ge){if(ke.startTime+ke.duration<xe||ke.startTime>pe)continue;const We=(ke.startTime-xe)/(pe-xe)*t,_e=ke.duration/(pe-xe)*t,Pe=Te(ke.pitch)-Me/2,Re=ke.startTime+ke.duration<=s;Ce.push({x:We,y:Pe,w:_e,h:Me,isGold:ke.isGold,isSung:Re})}if(!Zu($||"ball",{ctx:e,ballX:Ye,ballY:Ze,ballRadius:fe,playerColor:pt,ballIsGold:dt,currentTime:s,height:n,visibleNotes:Ce})){Rt&&e.drawImage(Rt,0,0),xt&&e.drawImage(xt,0,0),e.save(),e.globalCompositeOperation="source-over",e.globalAlpha=.28;const ge=Math.max(18,fe*5),ke=e.createRadialGradient(Ye,Ze,0,Ye,Ze,ge);if(ke.addColorStop(0,pt),ke.addColorStop(1,"transparent"),e.fillStyle=ke,e.beginPath(),e.arc(Ye,Ze,ge,0,Math.PI*2),e.fill(),e.restore(),y&&at&&ft&&(at.save(),at.globalCompositeOperation="source-over",at.globalAlpha=.95,at.fillStyle=pt,at.beginPath(),at.arc(Ye,Ze,fe+4,0,Math.PI*2),at.fill(),at.restore(),at.save(),at.globalCompositeOperation="destination-in",at.drawImage(ft,0,0),at.restore(),e.drawImage(Rt,0,0)),y&&qe&&ft)try{const Pe=Qn(pt),{h:Re,s:Oe,l:Ge}=rh(Pe),Le=ah(Re,Math.max(10,Math.round(Oe*(typeof h=="number"?h:.25))),Ge,.85);qe.save(),qe.globalCompositeOperation="multiply",qe.globalAlpha=.65,qe.fillStyle=Le,qe.beginPath(),qe.arc(Ye,Ze,Math.max(8,fe+6),0,Math.PI*2),qe.fill(),qe.restore(),qe.save(),qe.globalCompositeOperation="destination-out",qe.drawImage(ft,0,0),qe.restore(),e.drawImage(xt,0,0)}catch{qe.save(),qe.globalCompositeOperation="source-over",qe.globalAlpha=.6,qe.fillStyle=pt,qe.beginPath(),qe.arc(Ye,Ze,Math.max(8,fe+6),0,Math.PI*2),qe.fill(),qe.restore(),qe.save(),qe.globalCompositeOperation="destination-out",qe.drawImage(ft,0,0),qe.restore(),e.drawImage(xt,0,0)}const We=m&&m.shadowColor?m.shadowColor:_s,_e=m&&typeof m.glowBlur=="number"?m.glowBlur:Ls;e.save(),dt?(e.shadowColor=We,e.shadowBlur=_e,e.fillStyle=J("var(--gold-light, #FFF0A8)")):(e.shadowColor=pt,e.shadowBlur=10,e.fillStyle=pt),e.globalCompositeOperation="source-over",e.globalAlpha=1,e.beginPath(),e.arc(Ye,Ze,fe,0,Math.PI*2),e.fill(),e.lineWidth=1.5,e.strokeStyle=J("var(--nice-shadow-md, rgba(0,0,0,0.35))"),e.stroke(),e.restore()}try{if(Array.isArray(x)&&x.length>0){const ge=Date.now(),ke=m&&typeof m.lifeMs=="number"?m.lifeMs:Xu,We=(Pe,Re,Oe,Ge=5)=>{const Je=Oe,Le=Oe*.45;e.beginPath();let Fe=Math.PI/2*3,ve=Pe,Ne=Re;const Ae=Math.PI/Ge;e.moveTo(Pe,Re-Je);for(let Ve=0;Ve<Ge;Ve++)ve=Pe+Math.cos(Fe)*Je,Ne=Re+Math.sin(Fe)*Je,e.lineTo(ve,Ne),Fe+=Ae,ve=Pe+Math.cos(Fe)*Le,Ne=Re+Math.sin(Fe)*Le,e.lineTo(ve,Ne),Fe+=Ae;e.lineTo(Pe,Re-Je),e.closePath()},_e=Pe=>{let Re=Pe>>>0;return()=>(Re=Re*1664525+1013904223>>>0,(Re&2147483647)/2147483647)};x.forEach(Pe=>{const Re=ge-Pe.createdAt;if(Re<0||Re>ke)return;const Oe=Re/ke,Ge=(Pe.noteStart-(s-2))/7*t,Je=Te(Pe.notePitch),Le=_e(Pe.seed||Math.floor(Pe.createdAt%1e5)),Fe=m&&typeof m.count=="number"?m.count:Qu,ve=m&&typeof m.baseSpeed=="number"?m.baseSpeed:Ju,Ne=m&&typeof m.baseSize=="number"?m.baseSize:eh;for(let Ae=0;Ae<Fe;Ae++){const Ve=Le(),De=Le(),rt=Ae/Fe*Math.PI*2+Ve*Math.PI*.6+Oe*1.5,Xe=6+ve*(1-Oe)*(.5+De*.8),Wt=Ge+Math.cos(rt)*Xe,Qt=Je+Math.sin(rt)*Xe*(.8+Ve*.6),jt=Math.max(1,Ne*(1-Oe)*(.5+De)),fs=40+Math.round(20*Le()),ms=70+Math.round(20*Le()),Ur=Math.max(0,1-Oe)*(.9-Le()*.3),$c=Math.max(6,jt*2.6),qr=nh(fs,ms,60,Math.round($c),(Pe.seed||0)+Ae);qr&&qr.complete?(e.save(),e.translate(Wt,Qt+4),e.rotate(rt+Oe*4+(Le()-.5)*1.2),e.globalAlpha=Ur,e.drawImage(qr,-jt/2,-jt/2,jt,jt),e.restore()):(e.save(),e.translate(Wt,Qt+4),e.rotate(rt+Oe*4),e.fillStyle=`hsla(${fs}, ${ms}%, 60%, ${Ur})`,e.fillRect(-jt/2,-jt/2,jt,jt),e.restore()),Le()>.85&&(e.save(),e.globalAlpha=Math.max(.35,1-Oe),e.fillStyle=`hsla(${30+Math.round(10*Le())}, ${60+Math.round(30*Le())}%, ${70+Math.round(10*Le())}%, ${Ur})`,e.strokeStyle=`rgba(0,0,0,${.12*(1-Oe)})`,e.lineWidth=.8,We(Wt,Qt+4,jt*(1.4+Le())),e.fill(),e.stroke(),e.restore())}})}}catch{}return{ballX:Ye,ballY:Ze,ballIsGold:dt}},To=({song:e,currentTime:t,playerRef:n,config:a={},userPitch:s,segmentScores:i,goldBursts:o,combo:l,verseRatings:c})=>{const{isPlaying:d=!1,playerName:h="Ziom",score:p=1e4,playerBgColor:g="var(--karaoke-player-bg, #2196f3)",playerCount:y=2,gapDesaturation:m,goldSettings:x,difficultyLevel:v,algorithmLabel:f,algorithmColor:k,latencyMs:b=null,top:w,animationMode:N,karaokeSettings:$=null}=a,M=u.useRef(null),E=u.useRef(null),[R,L]=u.useState({width:600,height:150,top:250,visibleWidth:600}),[A,z]=u.useState(0),j=u.useRef(0),I=u.useRef(null),Y=u.useRef(null),H=u.useRef(null),D=u.useRef(t),V=u.useRef(performance.now()),Z=u.useRef(e),X=u.useRef(R),q=u.useRef(s),G=u.useRef(d),C=u.useRef(0),T=u.useRef(!1),S=u.useRef(null),F=u.useRef(null),K=()=>{const P=(e==null?void 0:e.id)??null;if(P!==F.current||!S.current){F.current=P;const B=e.notes.map(re=>re.noteLine);S.current=Hn(B,e.bpm??void 0);const _=S.current.reduce((re,W)=>re+W.length,0),U=S.current.reduce((re,W)=>re+W.filter(ee=>ee.isGold).length,0),J=S.current.flat().map(re=>re.pitch),se=J.length?Math.min(...J):0,oe=J.length?Math.max(...J):0;ha("BARS",`Parsed notes for "${e.title}" — ${S.current.length} verses, ${_} notes (including ${U} golden), pitch range: ${se}–${oe}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:B.length,verseCount:S.current.length,totalNotes:_,goldCount:U,minPitch:se,maxPitch:oe})}return S.current};return u.useEffect(()=>{const P=(_,U,J)=>_+(U-_)*J,B=_=>{Y.current===null&&(Y.current=_);const U=Math.min(.1,(_-(Y.current||_))/1e3);Y.current=_;const J=C.current,se=j.current,oe=1-Math.exp(-12*U),re=Math.abs(se-J)<.25?se:P(J,se,oe);Math.abs(re-J)>1e-4&&(z(re),C.current=re,M.current&&(M.current.style.transform=`translateX(${re}px)`)),I.current=requestAnimationFrame(B)};return I.current=requestAnimationFrame(B),()=>{I.current&&cancelAnimationFrame(I.current),I.current=null,Y.current=null}},[]),u.useEffect(()=>{const P=()=>{if(!n.current)return;const B=n.current.getBoundingClientRect(),_=2/Math.max(1,y),U=Math.round(B.width*_),J=Math.round(B.width),se=U*(150/600);L({width:U,height:se,top:30,visibleWidth:J})};return P(),window.addEventListener("resize",P),()=>window.removeEventListener("resize",P)},[n,y]),u.useEffect(()=>{var J;if(d||!M.current)return;const P=M.current.getContext("2d");if(!P)return;const B=K(),_=t-(e.gap??0)/1e3,U=ma(P,R.width,R.height,B,_,h,p,g,s,e.id,m??void 0,i,v??void 0,d,x??void 0,o,f,k,C.current,R.visibleWidth,l,c,N,$);if(U&&M.current){const se=R.visibleWidth||(((J=E.current)==null?void 0:J.getBoundingClientRect().width)??R.width),oe=R.width;let re=Math.round(se/2-U.ballX);const W=se-oe;re=Math.max(W,Math.min(0,re)),j.current=re}},[t,e,R,s,d,i,o,N,$]),u.useEffect(()=>{D.current=t,V.current=performance.now()},[t]),u.useEffect(()=>{Z.current=e},[e]),u.useEffect(()=>{X.current=R},[R]),u.useEffect(()=>{q.current=s},[s]),u.useEffect(()=>{G.current=d},[d]),u.useEffect(()=>{const P=()=>{var ae;const B=M.current,_=Z.current,U=X.current;if(!B||!_||!U)return;const J=B.getContext("2d");if(!J)return;const se=K(),oe=Math.min(.5,(performance.now()-V.current)/1e3),W=(G.current?D.current+oe:D.current)-(_.gap??0)/1e3,ee=ma(J,U.width,U.height,se,W,h,p,g,q.current,_.id,m??void 0,i,v??void 0,G.current,x??void 0,o,f,k,C.current,U.visibleWidth,l,c,N,$);if(ee){const le=U.visibleWidth||(((ae=E.current)==null?void 0:ae.getBoundingClientRect().width)??U.width),ce=U.width;let te=Math.round(le/2-ee.ballX);const he=le-ce;te=Math.max(he,Math.min(0,te)),j.current=te}};if(d){T.current||(T.current=!0,ha("BARS",`Drawing bars in RAF loop — canvas: ${X.current.width}×${X.current.height}px, player: ${h}`,{canvasSize:X.current}));const B=()=>{P(),H.current=requestAnimationFrame(B)};return H.current=requestAnimationFrame(B),()=>{H.current&&cancelAnimationFrame(H.current),H.current=null}}T.current=!1},[d,h,p,g,m,i,v,x,o,N,$]),r.jsxs("div",{ref:E,style:{position:"absolute",left:"50%",top:`${w??R.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:R.visibleWidth,height:R.height,overflow:"hidden"},children:[r.jsx("style",{children:"@keyframes av-latency-pulse {0% { transform: scale(1); box-shadow: 0 4px 10px var(--nice-overlay-20, rgba(0, 0, 0, 0.2));} 50% { transform: scale(1.08); box-shadow: 0 8px 18px var(--nice-overlay-30, rgba(0,0,0,0.32));} 100% { transform: scale(1); box-shadow: 0 4px 10px var(--nice-overlay-20, rgba(0, 0, 0, 0.2));} } .av-latency-pulse { animation: av-latency-pulse 1s ease-in-out infinite; }"}),r.jsx("div",{style:{position:"absolute",right:8,top:6,zIndex:40,pointerEvents:"none",display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--nice-text-inverse, #fff)"},children:typeof b<"u"&&b!==null?(()=>{const P=b,B=P<=120?"var(--latency-good, #10b981)":P<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",_=`${P}ms`;return r.jsxs("div",{className:P>250?"av-latency-pulse":"",style:{background:B,padding:"6px 10px",borderRadius:12,boxShadow:"0 4px 10px var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",fontWeight:700,minWidth:56,textAlign:"center",display:"flex",alignItems:"center",gap:6},children:[r.jsx(O.NtdStopwatch,{size:12}),r.jsx("span",{children:_})]})})():r.jsx("div",{style:{background:"var(--latency-none-bg, rgba(75,85,99,0.9))",padding:"6px 8px",borderRadius:12,boxShadow:"0 4px 10px var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",minWidth:44,textAlign:"center"},children:"—"})}),r.jsx("canvas",{ref:M,width:R.width,height:R.height,role:"img","aria-label":`Pitch timeline for ${h??"player"}. Score: ${p??0}`,style:{position:"absolute",left:0,top:0,transform:`translateX(${A}px)`,willChange:"transform"}})]})},Po="/textures/seamless/256x256";function At(e,t,n){return{name:e,icon:n,entries:Array.from({length:t},(a,s)=>{const i=String(s+1).padStart(2,"0");return{label:`${e} ${i}`,url:`${Po}/${e}/Photoreal_${e}_${i}-512x512.png`}})}}function _t(e,t,n){return{name:e,icon:n,entries:Array.from({length:t},(a,s)=>{const i=String(s+1).padStart(2,"0");return{label:`${e} ${i}`,url:`${Po}/${e}/${e}_${i}-256x256.png`}})}}const Ha=[At("Fire",8,"fire"),At("Metal",8,"metal"),At("Ice",8,"ice"),At("Stone",8,"stone"),At("Wood",8,"wood"),At("Tile",8,"tile"),At("Concrete",8,"concrete"),At("Trees",8,"trees"),At("Grass",8,"grass"),_t("Wall",24,"wall"),_t("Rust",24,"rust"),_t("Woven",24,"woven"),_t("Ground",24,"ground"),_t("Pebbles",24,"pebbles"),_t("Plant",24,"plant"),_t("Roof",24,"roof"),_t("Misc",24,"misc")],$o=Ha.flatMap(e=>e.entries);function ch(e){return $o.find(t=>t.url===e)}const dh={fire:O.NtdFire,metal:O.NtdSettings,ice:O.NtdSnowflake,stone:O.NtdMountain,wood:O.NtdTree,tile:O.NtdGrid,concrete:O.NtdLayers,trees:O.NtdTree,grass:O.NtdLeaf,wall:O.NtdHome,rust:O.NtdCircle,woven:O.NtdGrid,ground:O.NtdMountain,pebbles:O.NtdDroplet,plant:O.NtdLeaf,roof:O.NtdHome,misc:O.NtdPalette},uh=({icon:e})=>{const t=dh[e];return t?r.jsx(t,{size:14}):r.jsx(r.Fragment,{children:e})},It=({children:e,inline:t,strong:n})=>r.jsx("div",{style:{fontSize:13,fontWeight:n?600:void 0,color:"var(--nice-text-secondary, #ccc)",marginBottom:t?0:4},children:e}),hh=({fill:e=Gt,onChange:t=()=>{},previewColor:n="var(--nice-primary, #2196f3)",accentColor:a="var(--nice-primary, #0d6efd)",width:s,height:i})=>{const{t:o}=be(),[l,c]=u.useState(null),d=(f,k)=>{t({...e,[f]:k})},h=u.useMemo(()=>{const f=e.color||n||"var(--nice-primary, #2196f3)";return(k,b,w)=>{const N=Wn.find(M=>M.name===k)||Wn[0],$=b?Pr.find(M=>M.name===b)??null:null;return Mo({width:80,height:22,capStyle:N,color:f,highlight:e.highlight,glow:e.glow,glass:e.glass,pattern:$,patternColor:e.patternColor,patternOnly:e.patternOnly,textureUrl:w??null,textureScale:e.textureScale})}},[e,n]),p=`2px solid ${a}`,g=a==="var(--nice-warning-dark, #d4a017)"?"var(--nice-warning-bg, #fff8e1)":"var(--nice-info-bg, #e7f1ff)",y=u.useRef(null),m=u.useRef(null),x=u.useCallback((f,k)=>{f.current&&f.current.scrollBy({left:k*180,behavior:"smooth"})},[]),v={position:"absolute",top:0,width:28,height:"100%",border:"none",cursor:"pointer",zIndex:2,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,fontWeight:700,color:"var(--nice-color-white, #ccc)",background:"linear-gradient(90deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"};return r.jsxs("div",{style:{padding:"4px 0",width:"100%",minWidth:0},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[r.jsx(It,{inline:!0,children:o("playerForm.barColor","Color")}),r.jsx(ie.NiceCheckbox,{label:o("playerForm.auto","Auto"),checked:!e.color,onChange:f=>d("color",f?null:n||"var(--nice-primary, #2196f3)")}),e.color&&r.jsx("input",{type:"color",value:e.color,onChange:f=>d("color",f.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),r.jsx(It,{children:o("playerForm.capShape","Cap shape")}),r.jsxs("div",{style:{position:"relative",marginBottom:10},children:[r.jsx("button",{type:"button",style:{...v,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>x(y,-1),"aria-label":o("playerForm.scrollLeft","Scroll left"),children:r.jsx(O.NtdChevronLeft,{size:16})}),r.jsx("button",{type:"button",style:{...v,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>x(y,1),"aria-label":o("playerForm.scrollRight","Scroll right"),children:r.jsx(O.NtdChevronRight,{size:16})}),r.jsx("div",{ref:y,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:Wn.map(f=>{const k=e.capStyleName===f.name;return r.jsx("div",{title:f.name,onClick:()=>d("capStyleName",f.name),style:{cursor:"pointer",flexShrink:0,border:k?p:"1px solid var(--nice-border-color, #555)",borderRadius:6,padding:3,background:k?g:"var(--nice-bg-secondary, #222)"},dangerouslySetInnerHTML:{__html:h(f.name,null)}},f.name)})})]}),r.jsx(It,{children:o("playerForm.pattern","Pattern")}),r.jsxs("div",{style:{position:"relative",marginBottom:10},children:[r.jsx("button",{type:"button",style:{...v,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>x(m,-1),"aria-label":o("playerForm.scrollLeft","Scroll left"),children:r.jsx(O.NtdChevronLeft,{size:16})}),r.jsx("button",{type:"button",style:{...v,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>x(m,1),"aria-label":o("playerForm.scrollRight","Scroll right"),children:r.jsx(O.NtdChevronRight,{size:16})}),r.jsxs("div",{ref:m,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:[r.jsx("div",{title:o("playerForm.none","None"),onClick:()=>d("patternName",null),style:{cursor:"pointer",flexShrink:0,border:e.patternName?"1px solid var(--nice-border-color, #555)":p,borderRadius:6,padding:"3px 8px",background:e.patternName?"var(--nice-text, #222)":g,fontSize:12,lineHeight:"22px",color:"var(--nice-text-inverse, #ccc)"},children:"—"}),Pr.map(f=>{const k=e.patternName===f.name;return r.jsx("div",{title:f.name,onClick:()=>d("patternName",f.name),style:{cursor:"pointer",flexShrink:0,border:k?p:"1px solid var(--nice-border-color, #555)",borderRadius:6,padding:3,background:k?g:"var(--nice-bg-secondary, #222)"},dangerouslySetInnerHTML:{__html:h(e.capStyleName,f.name)}},f.name)})]})]}),r.jsx("div",{style:{marginBottom:8},children:r.jsx(ie.NiceToggle,{label:o("playerForm.patternOnly","Pattern only (flat, no 3D)"),checked:e.patternOnly,onChange:f=>d("patternOnly",f)})}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[r.jsx(It,{inline:!0,children:o("playerForm.patternColor","Pattern color")}),r.jsx(ie.NiceCheckbox,{label:o("playerForm.auto","Auto"),checked:!e.patternColor,onChange:f=>d("patternColor",f?null:n||"var(--nice-bg, #fff)")}),e.patternColor&&r.jsx("input",{type:"color",value:e.patternColor,onChange:f=>d("patternColor",f.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),!e.patternOnly&&r.jsxs(r.Fragment,{children:[r.jsxs(It,{children:[o("playerForm.highlight","Highlight"),": ",e.highlight,"%"]}),r.jsx("div",{style:{marginBottom:8},children:r.jsx(ie.NiceSlider,{min:0,max:100,value:e.highlight,onChange:f=>d("highlight",f)})}),r.jsxs(It,{children:[o("playerForm.glow","Glow"),": ",e.glow,"%"]}),r.jsx("div",{style:{marginBottom:8},children:r.jsx(ie.NiceSlider,{min:0,max:100,value:e.glow,onChange:f=>d("glow",f)})})]}),r.jsxs(It,{children:[o("playerForm.glass","Transparency (glass)"),": ",e.glass,"%"]}),r.jsx("div",{style:{marginBottom:8},children:r.jsx(ie.NiceSlider,{min:0,max:100,value:e.glass,onChange:f=>d("glass",f)})}),r.jsx("div",{style:{marginTop:4},children:r.jsx(It,{strong:!0,children:o("playerForm.texture","Texture")})}),r.jsxs("div",{style:{marginBottom:6},children:[r.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",marginBottom:6},children:[r.jsx(ie.NiceButton,{size:"sm",variant:e.textureUrl?"outline":"primary",onClick:()=>{d("textureUrl",null),c(null)},children:o("playerForm.texNone","None")}),Ha.map(f=>r.jsx(ie.NiceButton,{size:"sm",variant:(l==null?void 0:l.name)===f.name?"primary":"outline",onClick:()=>c(k=>(k==null?void 0:k.name)===f.name?null:f),title:f.name,ariaLabel:f.name,children:r.jsx(uh,{icon:f.icon})},f.name))]}),l&&r.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap",maxHeight:130,overflowY:"auto",padding:4,border:"1px solid var(--nice-border, #dee2e6)",borderRadius:6,background:"var(--nice-bg-secondary, #f8f9fa)"},children:l.entries.map(f=>{const k=e.textureUrl===f.url;return r.jsx("div",{title:f.label,onClick:()=>d("textureUrl",k?null:f.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:k?`3px solid ${a}`:"1px solid var(--nice-text-muted, #bbb)",backgroundImage:`url(${f.url})`,backgroundSize:"cover",boxShadow:k?`0 0 6px ${a}`:void 0}},f.url)})}),e.textureUrl&&r.jsxs("div",{style:{marginTop:4,display:"flex",alignItems:"center",gap:8},children:[r.jsx("div",{style:{width:80,height:22,borderRadius:6,backgroundImage:`url(${e.textureUrl})`,backgroundSize:`${Math.round(256*e.textureScale)}px`,border:"1px solid var(--nice-border-color, #aaa)"}}),r.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #666)"},children:e.textureUrl.split("/").pop()})]})]}),e.textureUrl&&r.jsxs(r.Fragment,{children:[r.jsxs(It,{children:[o("playerForm.textureScale","Texture scale"),": ",e.textureScale.toFixed(1),"×"]}),r.jsx("div",{style:{marginBottom:8},children:r.jsx(ie.NiceSlider,{min:10,max:200,step:10,value:Math.round(e.textureScale*100),onChange:f=>d("textureScale",f/100)})})]})]})},st=ot.scoped("AudioPitchAnalyzer");function ph({onSegments:e,defaultCompareAll:t=!1,externalFile:n=null,postPitch:a,postLibrosaPitchTrack:s}){const{t:i}=be(),[o,l]=u.useState("pitchy"),[c,d]=u.useState(null),[h,p]=u.useState(t),[g,y]=u.useState({}),[m,x]=u.useState({}),[v,f]=u.useState([]),[k,b]=u.useState([]),[w,N]=u.useState(!1),[$,M]=u.useState(null),[E]=u.useState(null),[R]=u.useState(null),[L,A]=u.useState(null),z=u.useRef(null);function j(q){try{if(q instanceof Error){let C=`${q.message}
|
|
40
|
+
${q.stack??""}`;const T=q;if(T!=null&&T.attemptedUrls)try{C+=`
|
|
41
|
+
Attempted URLs: ${Array.isArray(T.attemptedUrls)?T.attemptedUrls.join(", "):String(T.attemptedUrls)}`}catch{C+=`
|
|
42
|
+
Attempted URLs: ${String(T.attemptedUrls)}`}return C}const G=q;return G!=null&&G.attemptedUrls?`Error: ${String(G.message??G)}
|
|
43
|
+
Attempted URLs: ${Array.isArray(G.attemptedUrls)?G.attemptedUrls.join(", "):String(G.attemptedUrls)}`:String(q)}catch{return"Unknown error"}}function I(q){if(!q||q<=0)return null;const G=12*Math.log2(q/440)+69;return Math.round(G-12)}async function Y(q){var C;const G=(C=q.target.files)==null?void 0:C[0];G&&await H(G,h)}async function H(q,G){M(null),b([]),N(!0);try{const C=await q.arrayBuffer(),T=window.AudioContext??window.webkitAudioContext,F=await new T().decodeAudioData(C),K=F.getChannelData(0);d(K);const P=F.sampleRate,B=Math.floor(P*.1),_=B,U=()=>{const ee=[],ae=la.PitchDetector.forFloat32Array(B);for(let le=0;le<K.length-B;le+=_){const ce=K.slice(le,le+B),[te,he]=ae.findPitch(ce,P),ue=I(te);ue&&te>50&&te<2e3&&he>.7&&ee.push({start:le/P,duration:B/P,pitch:ue,freq:te})}return ee},J=()=>{const ee=[];for(let ae=0;ae<K.length-B;ae+=_){const le=K.slice(ae,ae+B),ce=V(le,P),te=I(ce);te&&ce>50&&ce<2e3&&ee.push({start:ae/P,duration:B/P,pitch:te,freq:ce})}return ee};if(G){N(!0),M(null);const ee={};try{const ae={};try{ee.pitchy=U(),ae.pitchy=null}catch(le){ee.pitchy=[],ae.pitchy=j(le),st.warn("pitchy failed",le)}try{ee["ultrastar-wp"]=J(),ae["ultrastar-wp"]=null}catch(le){ee["ultrastar-wp"]=[],ae["ultrastar-wp"]=j(le),st.warn("ultrastar-wp failed",le)}ee.aubio=[],ae.aubio="disabled";try{if(!a)throw new Error("CREPE backend not configured");const ce=(await a(q)).track??[];ee.crepe=ce.map((te,he)=>{var ue;return{start:te.t,duration:(ue=ce[he+1])!=null&&ue.t?ce[he+1].t-te.t:.1,pitch:I(te.hz)??0,freq:te.hz}}),ae.crepe=null}catch(le){ee.crepe=[],ae.crepe=j(le),st.warn("crepe failed",le)}try{if(!s)throw new Error("Librosa backend not configured");const ce=(await s(new File([q],q.name,{type:q.type}))).track??[];ee.librosa=ce.map((te,he)=>{var ue;return{start:te.t,duration:(ue=ce[he+1])!=null&&ue.t?ce[he+1].t-te.t:.1,pitch:I(te.hz)??0,freq:te.hz}}),ae.librosa=null}catch(le){ee.librosa=[],ae.librosa=j(le),st.warn("librosa failed",le)}x(ae),y(ee),b(ee[o]??[])}catch(ae){st.error("compareAll overall failed",ae);const le=ae instanceof Error?ae.message:String(ae);M(i("audioPitch.errorComparing","Error comparing algorithms: ")+le)}finally{N(!1)}return}const se=[],oe=[];let re=0;if(o==="pitchy"){const ee=la.PitchDetector.forFloat32Array(B);for(let ae=0;ae<K.length-B;ae+=_){const le=K.slice(ae,ae+B);let ce=0;for(let xe=0;xe<le.length;xe++)ce+=le[xe]*le[xe];ce=Math.sqrt(ce/le.length),oe.push(ce);const[te,he]=ee.findPitch(le,P),ue=I(te);ue&&te>50&&te<2e3&&he>.7&&(se.push({start:ae/P,duration:B/P,pitch:ue,freq:te}),re++)}}else if(o==="crepe")try{if(!a)throw new Error("CREPE backend not configured");const ee=await a(q);if(!ee.track||ee.track.length===0)M(i("audioPitch.crepeNoNotes","CREPE detected no notes")),st.warn("Crepe: No notes detected in audio file.");else{const ae=ee.track.map((le,ce)=>{const te=I(le.hz);return te&&le.hz>50&&le.hz<2e3?{start:le.t,duration:ce<ee.track.length-1?ee.track[ce+1].t-le.t:.1,pitch:te,freq:le.hz}:null}).filter(le=>le!==null);if(b(ae),e)try{e(ae)}catch(le){st.error("Error in onSegments:",le)}f([]),d(null);return}}catch(ee){M(i("audioPitch.crepeBackendError","CREPE backend error")),A(j(ee)),st.error("Crepe: Error calling backend:",ee)}else if(o==="librosa")try{await D(q),f([]),d(null);return}catch(ee){M(i("audioPitch.librosaBackendError","Librosa backend error")),A(j(ee)),st.error("Librosa: Error calling backend:",ee)}else if(o==="ultrastar-wp")for(let ee=0;ee<K.length-B;ee+=_){const ae=K.slice(ee,ee+B);let le=0;for(let he=0;he<ae.length;he++)le+=ae[he]*ae[he];le=Math.sqrt(le/ae.length),oe.push(le);const ce=V(ae,P),te=I(ce);te&&ce>50&&ce<2e3&&(se.push({start:ee/P,duration:B/P,pitch:te,freq:ce}),re++)}f(oe);const W=Z(se);if(b(W),e)try{e(W)}catch(ee){st.error("Error in onSegments:",ee)}W.length===0&&o!=="crepe"&&(M(i("audioPitch.noNotesDetected","No notes detected")),st.warn("No notes detected in audio file."))}catch(C){M(i("audioPitch.errorAnalyzing","Error analyzing the file: ")+(C instanceof Error?C.message:String(C))),A(j(C)),st.error("Error analyzing audio file:",C)}finally{N(!1)}}u.useEffect(()=>{n&&H(n,!0)},[n]);async function D(q){try{if(!s)throw new Error("Librosa backend not configured");const G=new File([q],"capture.wav",{type:"audio/wav"}),T=((await s(G)).track??[]).map(S=>({t:S.t,hz:S.hz}));if(e){const S=T.map((F,K)=>{var _;const P=((_=T[K+1])==null?void 0:_.t)??F.t+.1,B=I(F.hz)??0;return{start:F.t,duration:Math.max(.05,P-F.t),pitch:B,freq:F.hz}});e(S),b(S)}}catch(G){st.warn("Librosa analysis failed, falling back to local detectors",G);const T=(typeof G=="object"&&G!==null?G:{}).attemptedUrls;T&&st.error("Librosa attempted URLs:",T);const S=T?Array.isArray(T)?T.join(", "):String(T):null,F=G instanceof Error?G.message:String(G);M(i("audioPitch.librosaBackendError","Librosa backend error")+": "+F+(S?" (attempted: "+S+")":"")),A(j(G))}}function V(q,G){const S=Math.floor(G/50),F=Math.max(2,Math.floor(G/2e3));let K=0;for(let U=0;U<q.length;U++)K+=q[U]*q[U];if(K<=1e-8)return 0;let P=-1,B=0;const _=1e-10;for(let U=F;U<=Math.min(S,q.length-2);U++){let J=0;const se=q.length-U;for(let re=0;re<se;re++)J+=q[re]*q[re+U];const oe=J/(se+_)/(K/q.length+_);oe>B&&(B=oe,P=U)}return P>0&&B>.01?G/P:0}function Z(q){if(q.length===0)return[];const G=[];let C=q[0];for(let T=1;T<q.length;T++){const S=q[T];S.pitch===C.pitch&&Math.abs(S.freq-C.freq)<1?C.duration+=S.duration:(G.push(C),C=S)}return G.push(C),G}function X(){try{const q=Object.keys(g).length>0?Object.keys(g):["pitchy","ultrastar-wp","aubio","crepe","librosa"],G=(()=>{let re=0;for(const W of q){const ee=g[W]??[];for(const ae of ee)re=Math.max(re,ae.start+(ae.duration||0))}return re||0})(),C=(re,W)=>!re||!W?1/0:1200*Math.log2(re/W),T=(re,W)=>{if(!re||!W)return!1;const ee=Math.round(Math.log2(W/re)),ae=re*Math.pow(2,ee),le=Math.abs(C(ae,W));return Math.abs(ee)>=1&&le<50},S=re=>{const W={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!re||re.length===0)return W;W.count=re.length,W.totalDur=re.reduce((ce,te)=>ce+(te.duration||0),0);const ee=re.map(ce=>ce.freq).filter(Boolean);if(ee.length===0)return W;const ae=ee.reduce((ce,te)=>ce+te,0)/ee.length,le=ee.reduce((ce,te)=>ce+(te-ae)*(te-ae),0)/ee.length;return W.meanFreq=ae,W.stdFreq=Math.sqrt(le||0),W.meanDur=W.totalDur/W.count,W.voicedFraction=G>0?W.totalDur/G:null,W},F=(re,W)=>{let ee=0,ae=0;const le=[];for(const te of re){const he=te.start,ue=te.start+(te.duration||.05);let xe=null,pe=0;for(const Se of W){const je=Se.start,$e=Se.start+(Se.duration||.05),Te=Math.max(0,Math.min(ue,$e)-Math.max(he,je));Te>pe&&(pe=Te,xe=Se)}if(xe&&pe>0){const Se=Math.abs(C(te.freq,xe.freq));le.push(Se),Se<50&&ee++,T(te.freq,xe.freq)&&ae++}}const ce=le.length?le.reduce((te,he)=>te+he,0)/le.length:null;return{matches:ee,compared:re.length,meanCents:ce,octaveErrors:ae}},K=[];K.push("# AudioPitchAnalyzer — Comparative Report"),K.push(`Generated: ${new Date().toISOString()}`),K.push(""),K.push("## Summary"),K.push(`- Selected algorithm in UI: **${o}**`),K.push(`- Total analyzed duration (approx): **${G.toFixed(3)} s**`),K.push(""),K.push("## Per-algorithm statistics"),K.push("| Algorithm | Segments | Total voiced (s) | Voiced fraction | Mean freq (Hz) | Std freq (Hz) | Mean dur (s) |"),K.push("|---|---:|---:|---:|---:|---:|---:|");const P={};for(const re of q){const W=g[re]??[],ee=S(W);P[re]=ee,K.push(`| ${re} | ${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"} |`)}K.push(""),K.push("## Pairwise agreement (reference -> test)");const B=q.includes("crepe")?"crepe":q.includes("librosa")?"librosa":q.includes("pitchy")?"pitchy":q[0];K.push(`Reference algorithm: **${B}**`),K.push(""),K.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),K.push("|---|---:|---:|---:|---:|---:|");for(const re of q){if(re===B)continue;const W=F(g[B]??[],g[re]??[]),ee=W.compared?(W.matches/W.compared*100).toFixed(1)+"%":"N/A";K.push(`| ${B} -> ${re} | ${W.matches} | ${W.compared} | ${ee} | ${W.meanCents!==null?W.meanCents.toFixed(1):"N/A"} | ${W.octaveErrors} |`)}K.push(""),K.push("## Observations and analysis"),K.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."),K.push("- Pairwise match rate shows how often algorithms agree on the same regions (within ~50 cents). Octave error counts highlight typical autocorrelation octave mistakes."),K.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."),K.push("");for(const re of q){K.push(`### ${re}`);const W=P[re];K.push(`- Segments: ${W.count||0}`),K.push(`- Total voiced (s): ${(W.totalDur||0).toFixed(3)}`),K.push(`- Voiced fraction: ${W.voicedFraction!==null?(W.voicedFraction*100).toFixed(1)+"%":"N/A"}`),K.push(`- Mean frequency: ${W.meanFreq?W.meanFreq.toFixed(2)+" Hz":"N/A"}`),K.push(`- Std frequency: ${W.stdFreq?W.stdFreq.toFixed(2)+" Hz":"N/A"}`),K.push("")}K.push("## Conclusions & recommendation");const _=[];for(const re of q){if(re===B){_.push({alg:re,score:100});continue}const W=F(g[B]??[],g[re]??[]),ee=W.compared?W.matches/W.compared:0,ae=W.compared?W.octaveErrors/W.compared:0,le=ee-ae*.5;_.push({alg:re,score:le})}_.sort((re,W)=>W.score-re.score),K.push(`- Based on this recording, recommended authoritative detector: **${_[0].alg}** (best agreement with reference).`),K.push("- For live, low-latency feedback use Pitchy (YIN) with smoothing/hysteresis; use Crepe/Librosa for authoritative scoring or post-processing."),K.push("- If octave errors are frequent, consider octave-correction heuristics (prefer lower octave when ambiguity) or combine detectors via voting."),K.push(""),K.push("## Raw data (per-algorithm segments)");for(const re of q){const W=g[re]??[];K.push(`### ${re} — ${W.length} segments`);for(const ae of W)K.push(`- ${ae.start.toFixed(3)} .. ${(ae.start+(ae.duration||0)).toFixed(3)} : ${ae.freq.toFixed(2)} Hz (pitch ${ae.pitch})`);const ee=m[re];ee&&K.push(`- Error: ${ee}`),K.push("")}const U=K.join(`
|
|
44
|
+
`),J=new Blob([U],{type:"text/markdown;charset=utf-8"}),se=URL.createObjectURL(J),oe=document.createElement("a");oe.href=se,oe.download="audiopitch_scientific_report_"+(n?n.name:"capture")+".md",document.body.appendChild(oe),oe.click(),oe.remove(),URL.revokeObjectURL(se)}catch(q){st.error("generateScientificReport error",q),st.warn(i("audioPitch.reportError","Could not generate the report: ")+String(q))}}return r.jsxs("div",{style:{marginTop:32,padding:16,border:"1px solid var(--nice-border, #ccc)",borderRadius:8},children:[r.jsx("h3",{children:i("audioPitch.title","Pitch analysis")}),r.jsxs("div",{style:{marginBottom:12},children:[r.jsx("label",{htmlFor:"pitch-algorithm-select",style:{marginRight:8},children:i("audioPitch.algorithm","Algorithm")}),r.jsxs("select",{id:"pitch-algorithm-select",value:o,onChange:q=>l(q.target.value),style:{marginRight:16},children:[r.jsx("option",{value:"ultrastar-wp",children:i("audioPitch.algorithmUltrastarWp","Ultrastar WP (autocorrelation)")}),r.jsx("option",{value:"crepe",children:"crepe (AI)"}),r.jsx("option",{value:"pitchy",children:"pitchy (YIN)"}),r.jsx("option",{value:"librosa",children:"Librosa (PYIN)"})]}),r.jsxs("label",{style:{marginRight:8},children:[r.jsx("input",{type:"checkbox",checked:h,onChange:q=>p(q.target.checked)})," ",i("audioPitch.compareAll","Compare all algorithms")]}),r.jsx("input",{type:"file",accept:"audio/*",ref:z,onChange:Y,disabled:w})]}),w&&r.jsx("div",{children:i("audioPitch.analyzing","Analyzing...")}),r.jsxs("div",{style:{marginTop:8},children:[r.jsx("b",{children:i("audioPitch.method","Method:")})," ",o]}),$&&r.jsxs("div",{style:{color:"red",marginTop:8},children:[r.jsxs("b",{children:[o,": "]}),r.jsx("div",{children:$}),L&&r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap",marginTop:8},children:L})]}),E&&r.jsxs("div",{style:{marginTop:12},children:[r.jsx("b",{children:i("audioPitch.aubioDiagnostics","Aubio diagnostics")}),r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:E}),R&&r.jsxs("div",{style:{marginTop:8},children:[r.jsx("b",{children:"Probe:"})," ",R]})]}),(Object.keys(g).length>0||Object.keys(m).length>0)&&r.jsxs("div",{style:{marginTop:12},children:[r.jsx("button",{onClick:()=>X(),children:i("audioPitch.downloadReport","Download report")}),Object.entries(m).length>0&&r.jsxs("div",{style:{marginTop:8},children:[r.jsx("b",{children:"Per-algorithm errors:"}),Object.entries(m).filter(([q,G])=>G).map(([q,G])=>r.jsxs("div",{style:{marginTop:6},children:[r.jsxs("b",{children:[q,":"]}),r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:G})]},q))]})]}),k.length>0&&r.jsxs("div",{style:{marginTop:16},children:[r.jsx("b",{children:i("audioPitch.resultUltrastar","Result (UltraStar format):")}),r.jsxs("pre",{style:{background:"var(--nice-text, #222)",color:"var(--nice-bg, #fff)",padding:8,borderRadius:4},children:[k.map(q=>`: ${Math.round(q.start*10)} ${Math.round(q.duration*10)} ${q.pitch} [${q.freq.toFixed(1)} Hz]`).join(`
|
|
45
45
|
`),`
|
|
46
|
-
-`]})]}),c&&c.length>0&&
|
|
47
|
-
`)})]},X))]})]})}const Dt=1e4,Ws=5e3;function Xr(e,t=.35){const r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(!r)return e;const a=Math.min(255,Math.round(parseInt(r[1],16)+(255-parseInt(r[1],16))*t)),s=Math.min(255,Math.round(parseInt(r[2],16)+(255-parseInt(r[2],16))*t)),i=Math.min(255,Math.round(parseInt(r[3],16)+(255-parseInt(r[3],16))*t));return`rgb(${a},${s},${i})`}const gh=["var(--nice-warning, #facc15)","var(--nice-text-secondary, #cbd5e1)","var(--nice-warning, #d97706)"],yh=({entry:e,rank:t,animDelay:r})=>{const[a,s]=u.useState(0),[i,o]=u.useState(0),[l,c]=u.useState(0),[d,h]=u.useState(0),f=Math.min(e.classicScore,Dt),p=Math.min(e.bonusScore,Dt),y=f/Dt*Ws,m=p>0?p/Dt*Ws:0;return u.useEffect(()=>{let x,b=null;const g=Math.max(y,400),S=Math.max(m,m>0?300:0),v=k=>{b===null&&(b=k);const M=k-b-r;if(M<0){x=requestAnimationFrame(v);return}if(M<=g){const T=Math.min(1,M/g),N=1-Math.pow(1-T,3);s(Math.min(N*(f/Dt)*100,100)),c(Math.round(N*e.classicScore)),x=requestAnimationFrame(v);return}if(s(Math.min(f/Dt*100,100)),c(e.classicScore),S>0){const T=M-g;if(T<=S){const N=Math.min(1,T/S),j=1-Math.pow(1-N,3);o(Math.min(j*(p/Dt)*100,100)),h(Math.round(j*e.bonusScore)),x=requestAnimationFrame(v);return}o(Math.min(p/Dt*100,100)),h(e.bonusScore)}};return x=requestAnimationFrame(v),()=>cancelAnimationFrame(x)},[e.classicScore,e.bonusScore,y,m,r]),n.jsxs("div",{className:"karaoke-summary-bar",children:[n.jsx("span",{className:"karaoke-summary-bar-rank",children:t<=3?n.jsx(G.NtdMedal,{size:18,primaryColor:gh[t-1]}):`#${t}`}),n.jsx("span",{className:"karaoke-summary-bar-name",style:{color:e.color},children:e.name}),n.jsxs("div",{className:"karaoke-summary-bar-track",children:[e.bonusScore>0&&n.jsx("div",{className:"karaoke-summary-bar-fill-bonus",style:{width:`${Math.min(a+i,100)}%`,background:Xr(e.color,.45)}}),n.jsx("div",{className:"karaoke-summary-bar-fill-classic",style:{width:`${a}%`,background:`linear-gradient(90deg, ${e.color}, ${Xr(e.color,.15)})`,boxShadow:`0 0 8px ${e.color}55`}}),n.jsxs("div",{className:"karaoke-summary-bar-text",children:[l.toLocaleString(),d>0&&n.jsxs("span",{className:"karaoke-summary-bar-text-bonus",style:{color:Xr(e.color,.5)},children:["+",d.toLocaleString()]})]})]}),n.jsx("span",{className:"karaoke-summary-bar-total",children:(l+d).toLocaleString()})]})},Us=({title:e,entries:t,highlightNames:r,playerColorMap:a})=>n.jsxs("div",{className:"karaoke-summary-rank",children:[n.jsx("h4",{className:"karaoke-summary-rank-title",children:e}),n.jsx("table",{className:"karaoke-summary-rank-table",children:n.jsx("tbody",{children:t.map((s,i)=>{const o=r.has(s.name),l=a.get(s.name);return n.jsxs("tr",{className:o?"karaoke-summary-rank-row karaoke-summary-rank-row--hl":"karaoke-summary-rank-row",children:[n.jsx("td",{className:`karaoke-summary-rank-pos${i<3?" karaoke-summary-rank-pos--top":""}`,children:s.rank}),n.jsxs("td",{className:"karaoke-summary-rank-name",style:l?{color:l}:void 0,children:[o&&n.jsxs(n.Fragment,{children:[n.jsx(G.NtdCircle,{size:8})," "]}),s.name]}),n.jsx("td",{className:"karaoke-summary-rank-score",children:s.score.toLocaleString()})]},`${s.name}-${i}`)})})})]}),Xa=({uploadedSong:e,playerScores:t,topSingings:r,onRestart:a,onContinue:s,t:i,renderReport:o,className:l,style:c,id:d,accessMode:h,"data-testid":f})=>{const[p,y]=u.useState(!1),m=u.useMemo(()=>[...t].sort((k,M)=>M.totalScore-k.totalScore),[t]),x=u.useMemo(()=>{const k=new Map;for(const M of t)k.set(M.name,M.color);return k},[t]),b=u.useMemo(()=>new Set(t.map(k=>k.name)),[t]),g=u.useMemo(()=>m.map((k,M)=>({rank:M+1,name:k.name,score:k.totalScore,color:k.color})),[m]),S=u.useMemo(()=>{const k=r.map(T=>({name:T.playerName,score:T.score})),M=new Set;for(const T of m)M.has(T.id)||(M.add(T.id),k.push({name:T.name,score:T.totalScore}));return k.sort((T,N)=>N.score-T.score),k.slice(0,10).map((T,N)=>({rank:N+1,name:T.name,score:T.score}))},[r,m]),v=e?e.artist?`${e.artist} — ${e.title}`:e.title:i("karaokeSummary.unknownSong","Unknown song");return h==="hidden"?null:n.jsxs("div",{className:`karaoke-summary-overlay${l?` ${l}`:""}`,style:c,id:d,"data-testid":f,children:[n.jsxs("div",{className:"karaoke-summary-card",children:[n.jsx("h1",{className:"karaoke-summary-title",children:v}),n.jsx("div",{className:"karaoke-summary-bars",children:m.length===0?n.jsx("div",{className:"karaoke-summary-empty",children:i("karaokeSummary.noScores","No scores")}):m.map((k,M)=>n.jsx(yh,{entry:k,rank:M+1,animDelay:M*300},k.id))}),(m.length>1||r.length>0)&&n.jsxs("div",{className:"karaoke-summary-ranks",children:[m.length>1&&n.jsx(Us,{title:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[n.jsx(G.NtdHome,{size:14})," ",i("karaokeSummary.localRanking","Session ranking")]}),entries:g,highlightNames:b,playerColorMap:x}),r.length>0&&n.jsx(Us,{title:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[n.jsx(G.NtdTrophy,{size:14})," ",i("karaokeSummary.globalRanking","Top 10")]}),entries:S,highlightNames:b,playerColorMap:x})]}),n.jsxs("div",{className:"karaoke-summary-actions",children:[o&&n.jsxs("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--report",onClick:()=>y(!0),children:[n.jsx(G.NtdBarChart,{size:15})," ",i("karaokeSummary.report","Report")]}),n.jsx("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--restart",onClick:a,children:i("karaokeSummary.restart","Restart")}),n.jsx("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--continue",onClick:s,children:i("karaokeSummary.continue","Continue")})]})]}),p&&(o==null?void 0:o(()=>y(!1)))]})},bh=it.scoped("GenericPlayer"),vh=e=>/youtu(\.be|be\.com)/i.test(e),ko=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),xh=e=>!!e&&/\.(mp3|aac|m4a|flac|wav|ogg)(\?.*)?$/i.test(e),Sh=e=>{var i;if(!((i=e==null?void 0:e.sources)!=null&&i.length))return null;const t=o=>e.sources.find(l=>l.kind===o),r=e.sources.find(o=>o.kind==="youtube"&&(o.videoId||o.url&&vh(o.url)))??null;if(r)return r;const a=t("hls")||e.sources.find(o=>o.url&&ko(o.url))||null;if(a)return a;const s=t("audio")||e.sources.find(o=>o.url&&xh(o.url))||null;return s||(e.sources[0]??null)},Ar=e=>{(!isFinite(e)||e<0)&&(e=0);const t=Math.floor(e/60),r=Math.floor(e%60);return`${t}:${r.toString().padStart(2,"0")}`},kh=[.25,.5,.75,1,1.25,1.5,1.75,2],Qa=({tracks:e=[],initialIndex:t=0,autoPlay:r=!0,countdownSeconds:a=0,height:s=360,onIndexChange:i,onPlayingChange:o,onTimeUpdate:l,externalRef:c,uiMode:d="full",compactNextCount:h=3,progressBarPosition:f="inline",loop:p=!1,onEnded:y,enableKeyboardShortcuts:m=!0,shuffle:x=!1,repeatMode:b="none",playbackSpeed:g=1,abLoop:S=null,onRepeatModeChange:v,onShuffleChange:k,onSpeedChange:M,sleepTimer:T=0,onSleepTimerExpired:N})=>{const{t:j}=Pe(),[R,z]=u.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),A=e[R],$=u.useMemo(()=>Sh(A),[A]),[O,I]=u.useState(!1),[U,J]=u.useState(0),[_,W]=u.useState(0),[K,re]=u.useState(.9),[X,q]=u.useState(null),[E,P]=u.useState(null),C=u.useRef(null),[L,w]=u.useState(x),[D,F]=u.useState(b),[B,V]=u.useState(g),[Y,oe]=u.useState(S),[ie,ne]=u.useState([]),[Z,H]=u.useState(T>0?T*60:null),se=u.useRef(null),[ae,ue]=u.useState(()=>Ai()),ee=u.useRef(null),de=u.useRef(null),fe=u.useRef(null),xe=u.useRef(null);u.useEffect(()=>{if(L&&e.length>0){const pe=e.map((ye,Fe)=>Fe);for(let ye=pe.length-1;ye>0;ye--){const Fe=Math.floor(Math.random()*(ye+1));[pe[ye],pe[Fe]]=[pe[Fe],pe[ye]]}ne(pe)}},[L,e.length]),u.useEffect(()=>(se.current&&(window.clearInterval(se.current),se.current=null),T>0&&O&&(H(T*60),se.current=window.setInterval(()=>{H(pe=>!pe||pe<=1?(se.current&&window.clearInterval(se.current),se.current=null,N==null||N(),null):pe-1)},1e3)),()=>{se.current&&window.clearInterval(se.current)}),[T,O]);const ce=u.useCallback(pe=>{const ye=Math.min(Math.max(0,pe),Math.max(0,e.length-1));z(ye),i==null||i(ye)},[e.length,i]),be=u.useCallback(()=>{if(L&&ie.length>0){const ye=ie.indexOf(R)+1;return ye<ie.length?ie[ye]:D==="all"?ie[0]:-1}return R<e.length-1?R+1:D==="all"?0:-1},[R,e.length,L,ie,D]),Me=u.useCallback(()=>{if(L&&ie.length>0){const pe=ie.indexOf(R);return pe>0?ie[pe-1]:D==="all"?ie[ie.length-1]:-1}return R>0?R-1:D==="all"?e.length-1:-1},[R,e.length,L,ie,D]),Te=u.useCallback(()=>{const pe=be();pe>=0&&ce(pe)},[be,ce]),je=u.useCallback(async()=>{var pe,ye;await Bt(),ue(!0),($==null?void 0:$.kind)==="youtube"?(pe=ee.current)==null||pe.playVideo():(ye=de.current)==null||ye.play(),I(!0),o==null||o(!0)},[$,o]),Xe=u.useCallback(()=>{var pe,ye;($==null?void 0:$.kind)==="youtube"?(pe=ee.current)==null||pe.pauseVideo():(ye=de.current)==null||ye.pause(),I(!1),o==null||o(!1)},[$,o]),le=u.useCallback(()=>O?Xe():je(),[O,je,Xe]),me=u.useCallback(pe=>{var he;const ye=(A==null?void 0:A.startOffset)??0,Fe=pe+ye;($==null?void 0:$.kind)==="youtube"?(he=ee.current)==null||he.seekTo(Fe,!0):de.current&&(de.current.currentTime=Fe);const vt=Math.max(0,pe);W(vt),l==null||l(vt)},[$,l]),De=u.useCallback(()=>{if(_>3){me(0);return}const pe=Me();pe>=0&&ce(pe)},[Me,ce,_,me]),ke=u.useCallback(pe=>{var ye,Fe;re(pe),q(null),($==null?void 0:$.kind)==="youtube"?(Fe=(ye=ee.current)==null?void 0:ye.setVolume)==null||Fe.call(ye,Math.round(pe*100)):de.current&&(de.current.volume=pe)},[$]),ze=u.useCallback(()=>{X!==null?ke(X):(q(K),ke(0))},[K,X,ke]),tt=u.useCallback(pe=>{var ye,Fe;V(pe),de.current&&(de.current.playbackRate=pe),($==null?void 0:$.kind)==="youtube"&&((Fe=(ye=ee.current)==null?void 0:ye.setPlaybackRate)==null||Fe.call(ye,pe)),M==null||M(pe)},[$,M]),Ye=u.useCallback(()=>{const pe=["none","all","one"],ye=pe[(pe.indexOf(D)+1)%pe.length];F(ye),v==null||v(ye)},[D,v]),He=u.useCallback(()=>{const pe=!L;w(pe),k==null||k(pe)},[L,k]),At=u.useCallback(pe=>{oe(pe)},[]);u.useImperativeHandle(c,()=>({play:je,pause:Xe,toggle:le,seekTo:me,setVolume:ke,setSpeed:tt,setRepeatMode:pe=>{F(pe),v==null||v(pe)},toggleShuffle:He,setABLoop:At,getUnderlyingPlayer:()=>($==null?void 0:$.kind)==="youtube"?ee.current:($==null?void 0:$.kind)==="hls"||($==null?void 0:$.kind)==="audio"?de.current:null}),[je,Xe,le,me,ke,tt,He,At,$==null?void 0:$.kind]),u.useEffect(()=>{const pe=window.setInterval(()=>{let ye=0,Fe=0;($==null?void 0:$.kind)==="youtube"&&ee.current?(ye=ee.current.getCurrentTime()||0,Fe=ee.current.getDuration()||0):de.current&&(ye=de.current.currentTime||0,Fe=de.current.duration||0);const vt=(A==null?void 0:A.startOffset)??0,he=Math.max(0,ye-vt);W(he),J(Fe),l==null||l(he),Y&&he>=Y.b&&me(Y.a)},250);return()=>window.clearInterval(pe)},[$==null?void 0:$.kind,l,Y]),u.useEffect(()=>()=>{C.current&&(window.clearInterval(C.current),C.current=null)},[]),u.useEffect(()=>{if(fe.current){try{fe.current.destroy()}catch{}fe.current=null}if(de.current&&(de.current.volume=K,de.current.crossOrigin=$!=null&&$.withCredentials?"use-credentials":"anonymous"),($==null?void 0:$.kind)==="hls"&&ko($.url)){const pe=de.current;if(!pe)return;const ye=()=>{pe.src=$.url,pe.load();const Fe=(A==null?void 0:A.startOffset)??0;try{Fe&&!isNaN(Fe)&&(pe.currentTime=Fe)}catch{}r&&pe.play().catch(()=>{})};pe.canPlayType("application/vnd.apple.mpegurl")?ye():(async()=>{var Fe;try{const he=(await import("hls.js")).default;if((Fe=he==null?void 0:he.isSupported)!=null&&Fe.call(he)){const Se=new he({xhrSetup:Ve=>{if($!=null&&$.withCredentials&&(Ve.withCredentials=!0),$!=null&&$.headers)for(const[Ie,Re]of Object.entries($.headers))try{Ve.setRequestHeader(Ie,Re)}catch{}}});fe.current=Se,Se.loadSource($.url),Se.attachMedia(pe),Se.on(he.Events.MANIFEST_PARSED,()=>{r&&pe.play().catch(()=>{})})}else ye()}catch(vt){bh.debug("HLS.js setup failed, falling back to native playback",vt),ye()}})()}else if(($==null?void 0:$.kind)==="audio"&&$.url&&de.current){const pe=de.current;pe.src=$.url,pe.load();const ye=(A==null?void 0:A.startOffset)??0;try{ye&&!isNaN(ye)&&(pe.currentTime=ye)}catch{}r&&pe.play().catch(()=>{})}C.current&&(window.clearInterval(C.current),C.current=null),P(null),W(0),J(0),r&&($==null?void 0:$.kind)==="youtube"&&a>0?(P(a),C.current=window.setInterval(()=>{P(pe=>{var ye;if(!pe)return null;if(pe<=1){C.current&&(window.clearInterval(C.current),C.current=null);try{(ye=ee.current)==null||ye.playVideo()}catch{}return I(!0),o==null||o(!0),null}return pe-1})},1e3)):I(!!r)},[$==null?void 0:$.url,$==null?void 0:$.kind,$==null?void 0:$.withCredentials,JSON.stringify($==null?void 0:$.headers),r,K]);const ht=u.useCallback(()=>{if(D==="one"){me(0),je();return}const pe=be();pe>=0?ce(pe):(I(!1),o==null||o(!1),me(0),y==null||y())},[D,be,ce,o,me,y,je]);u.useEffect(()=>{if(!m)return;const pe=ye=>{const Fe=ye.target;if(!(Fe.tagName==="INPUT"||Fe.tagName==="TEXTAREA"||Fe.isContentEditable))switch(ye.key){case" ":ye.preventDefault(),le();break;case"ArrowRight":ye.preventDefault(),me(Math.min(_+5,U));break;case"ArrowLeft":ye.preventDefault(),me(Math.max(0,_-5));break;case"ArrowUp":ye.preventDefault(),ke(Math.min(1,K+.05));break;case"ArrowDown":ye.preventDefault(),ke(Math.max(0,K-.05));break;case"m":case"M":ze();break;case"n":case"N":Te();break;case"p":case"P":De();break;case"r":case"R":Ye();break;case"s":case"S":He();break}};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[m,le,me,_,U,ke,K,ze,Te,De,Ye,He]);const It=($==null?void 0:$.kind)==="youtube"||d==="full"||d==="nobuttons",ct=h>0?e.slice(R+1,R+1+h):[];return n.jsxs("div",{ref:xe,className:"gp-player",style:{display:"grid",gap:12},tabIndex:-1,children:[r&&!ae&&n.jsx("div",{className:"gp-audio-activation",onClick:()=>{ue(!0),je()},style:{position:"fixed",inset:0,zIndex:200,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",cursor:"pointer"},children:n.jsx("span",{style:{color:"#fff",fontSize:24},children:"Click to activate audio"})}),It&&n.jsxs("div",{className:"gp-stage",style:{width:"100%",height:s,background:($==null?void 0:$.kind)==="youtube"?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[($==null?void 0:$.kind)==="youtube"&&n.jsx(Ta,{videoId:$.videoId??Nh($.url),onReady:pe=>{ee.current=pe.target,ke(K);const ye=(A==null?void 0:A.startOffset)??0;try{ye&&pe.target.seekTo(ye,!0)}catch{}if(d==="nobuttons"){try{pe.target.playVideo()}catch{}I(!0)}},onEnd:ht,opts:{width:"100%",height:"100%",playerVars:{autoplay:r||d==="nobuttons"?1:0,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,loop:p?1:0}},style:{width:"100%",height:"100%"}}),E!==null&&n.jsx("div",{style:{position:"absolute",inset:0,zIndex:120,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-70, rgba(0, 0, 0, 0.7))"},children:n.jsx("span",{style:{color:"#fff",fontSize:72,fontWeight:"bold"},children:E})}),d==="nobuttons"&&n.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"auto",zIndex:100,cursor:"default"}}),(($==null?void 0:$.kind)==="audio"||($==null?void 0:$.kind)==="hls")&&n.jsxs(n.Fragment,{children:[d==="full"&&n.jsx("div",{style:{textAlign:"center",color:"var(--nice-overlay-light-90, rgba(255, 255, 255, 0.9))"},children:A!=null&&A.coverUrl?n.jsx("img",{alt:"cover",src:A.coverUrl,style:{height:s-24,objectFit:"contain"}}):n.jsxs("div",{style:{opacity:.8},children:[n.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[A==null?void 0:A.artist," — ",A==null?void 0:A.title]}),n.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--nice-text-secondary, #64748b)"},children:($==null?void 0:$.label)??`${($==null?void 0:$.codec)??""} ${($==null?void 0:$.quality)??""}`.trim()})]})}),n.jsx("audio",{ref:de,onEnded:ht,onLoadedMetadata:()=>{const pe=de.current;pe&&J(pe.duration||0)},crossOrigin:$!=null&&$.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]})]}),(d==="minimal"||d==="compact")&&n.jsx("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:(A==null?void 0:A.title)??""}),n.jsx("div",{style:{color:"var(--nice-text-secondary, #64748b)",fontSize:13},children:(A==null?void 0:A.artist)??""})]})}),d==="full"&&n.jsxs(n.Fragment,{children:[n.jsx(wo,{currentTime:_,duration:U}),n.jsx(wh,{isPlaying:O,index:R,count:e.length,currentTime:_,duration:U,volume:K,onPrev:De,onNext:Te,onToggle:le,onSeek:me,onVolume:ke}),n.jsx(Rh,{shuffleOn:L,repeatMode:D,speed:B,abLoop:Y,currentTime:_,sleepRemaining:Z,onToggleShuffle:He,onCycleRepeat:Ye,onSpeedChange:tt,onSetABLoop:At,onMuteToggle:ze,isMuted:X!==null})]}),d==="progressOnly"&&n.jsx("div",{style:f==="fixedBottom"?{position:"fixed",left:0,right:0,bottom:0,padding:"8px 12px",background:"var(--nice-overlay-90, rgba(15, 23, 42, 0.9))",backdropFilter:"blur(2px)",zIndex:1e3}:{},children:n.jsx(Ch,{currentTime:_,duration:U,onSeek:me})}),(d==="minimal"||d==="compact")&&n.jsx(jh,{isPlaying:O,canPrev:R>0,canNext:R<e.length-1,onPrev:De,onNext:Te,onToggle:le}),d==="compact"&&ct.length>0&&n.jsx(Mh,{items:ct,onSelect:pe=>ce(R+1+pe)}),d==="nobuttons"&&n.jsx(n.Fragment,{}),d==="full"&&e.length>0&&n.jsx("div",{className:"gp-list",style:{display:"grid",gap:4},children:e.map((pe,ye)=>n.jsxs("button",{onClick:()=>ce(ye),style:{textAlign:"left",border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"8px 10px",background:ye===R?"color-mix(in srgb, var(--nice-color-primary) 14%, transparent)":"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},title:pe.sources.map(Fe=>Fe.kind).join(", "),children:[n.jsx("div",{style:{fontWeight:600},children:pe.title}),n.jsx("div",{style:{color:"var(--nice-text-secondary)",fontSize:12},children:pe.artist})]},pe.id))})]})},yt={border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},wo=({currentTime:e,duration:t})=>n.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[n.jsx("div",{}),n.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-secondary, #64748b)"},children:[Ar(e)," / ",Ar(t)]})]}),wh=({isPlaying:e,index:t,count:r,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek:d,onVolume:h})=>{const{t:f}=Pe();return n.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[n.jsxs("div",{style:{display:"flex",gap:8},children:[n.jsx("button",{onClick:o,disabled:t<=0,title:f("player.previousTrack","Previous track"),"aria-label":f("player.previousTrack","Previous track"),style:yt,children:n.jsx(G.NtdSkipBack,{size:16})}),n.jsx("button",{onClick:c,title:e?f("player.pause","Pause"):f("player.play","Play"),"aria-label":e?f("player.pause","Pause"):f("player.play","Play"),style:yt,children:e?n.jsx(G.NtdPause,{size:16}):n.jsx(G.NtdPlay,{size:16})}),n.jsx("button",{onClick:l,disabled:t>=r-1,title:f("player.nextTrack","Next track"),"aria-label":f("player.nextTrack","Next track"),style:yt,children:n.jsx(G.NtdSkipForward,{size:16})})]}),n.jsx("input",{type:"range",min:0,max:Math.max(1,s),step:.1,value:a,onChange:p=>d(parseFloat(p.target.value)),"aria-label":"Seek position"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[n.jsx(G.NtdVolume,{size:16}),n.jsx("input",{type:"range",min:0,max:1,step:.01,value:i,onChange:p=>h(parseFloat(p.target.value)),"aria-label":"Volume"})]})]})},Ch=({currentTime:e,duration:t,onSeek:r})=>n.jsxs(n.Fragment,{children:[n.jsx(wo,{currentTime:e,duration:t}),n.jsx("input",{type:"range",min:0,max:Math.max(1,t),step:.1,value:e,onChange:a=>r(parseFloat(a.target.value)),"aria-label":"Seek position"})]}),jh=({isPlaying:e,canPrev:t,canNext:r,onPrev:a,onNext:s,onToggle:i})=>{const{t:o}=Pe();return n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[n.jsx("button",{onClick:a,disabled:!t,title:o("player.previousTrack","Previous track"),"aria-label":o("player.previousTrack","Previous track"),style:yt,children:n.jsx(G.NtdSkipBack,{size:16})}),n.jsx("button",{onClick:i,title:e?o("player.pause","Pause"):o("player.play","Play"),"aria-label":e?o("player.pause","Pause"):o("player.play","Play"),style:yt,children:e?n.jsx(G.NtdPause,{size:16}):n.jsx(G.NtdPlay,{size:16})}),n.jsx("button",{onClick:s,disabled:!r,title:o("player.nextTrack","Next track"),"aria-label":o("player.nextTrack","Next track"),style:yt,children:n.jsx(G.NtdSkipForward,{size:16})})]})},Mh=({items:e,onSelect:t})=>{const{t:r}=Pe();return n.jsxs("div",{style:{border:"1px solid var(--nice-border-color)",borderRadius:8,padding:10,background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)"},children:[n.jsx("div",{style:{fontWeight:600,marginBottom:6},children:r("player.upNext","Up next")}),n.jsx("ol",{style:{margin:0,paddingLeft:18},children:e.map((a,s)=>n.jsx("li",{style:{marginBottom:4},children:n.jsxs("button",{type:"button",onClick:()=>t(s),style:{border:"none",padding:0,background:"transparent",cursor:"pointer",color:"var(--nice-text-primary, #0f172a)"},title:a.sources.map(i=>i.kind).join(", "),children:[n.jsx("span",{style:{fontWeight:600},children:a.artist})," — ",a.title]})},a.id))})]})},Rh=({shuffleOn:e,repeatMode:t,speed:r,abLoop:a,currentTime:s,sleepRemaining:i,onToggleShuffle:o,onCycleRepeat:l,onSpeedChange:c,onSetABLoop:d,onMuteToggle:h,isMuted:f})=>{const{t:p}=Pe(),y={none:"Off",all:"All",one:"One"},m=t==="one"?n.jsxs("span",{style:{position:"relative",display:"inline-flex"},children:[n.jsx(G.NtdRepeat,{size:16}),n.jsx("span",{style:{position:"absolute",right:-3,bottom:-3,fontSize:8,fontWeight:700},children:"1"})]}):t==="all"?n.jsx(G.NtdRepeat,{size:16}):n.jsx(G.NtdArrowRight,{size:16});return n.jsxs("div",{className:"gp-pro-controls",style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap",fontSize:13},children:[n.jsx("button",{onClick:o,title:p("player.shuffle","Shuffle"),"aria-label":p("player.shuffle","Shuffle"),style:{...yt,opacity:e?1:.4,fontWeight:e?700:400},children:n.jsx(G.NtdShuffle,{size:16})}),n.jsx("button",{onClick:l,title:`${p("player.repeat","Repeat")}: ${y[t]}`,"aria-label":`${p("player.repeat","Repeat")}: ${y[t]}`,style:{...yt,opacity:t==="none"?.4:1},children:m}),n.jsx("select",{value:r,onChange:x=>c(parseFloat(x.target.value)),title:p("player.speed","Speed"),"aria-label":p("player.speed","Speed"),style:{...yt,minWidth:56,fontSize:12},children:kh.map(x=>n.jsxs("option",{value:x,children:[x,"x"]},x))}),n.jsx("button",{onClick:h,title:p("player.mute","Mute"),"aria-label":p("player.mute","Mute"),style:{...yt,opacity:f?1:.6},children:f?n.jsx(G.NtdVolumeMute,{size:16}):n.jsx(G.NtdVolume,{size:16})}),a?n.jsxs("span",{style:{display:"flex",gap:4,alignItems:"center"},children:[n.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #64748b)"},children:["A: ",Ar(a.a)," — B: ",Ar(a.b)]}),n.jsx("button",{onClick:()=>d(null),title:p("player.clearLoop","Clear loop"),style:{...yt,fontSize:11,padding:"2px 6px"},children:n.jsx(G.NtdClose,{size:12})})]}):n.jsx("button",{onClick:()=>d({a:s,b:s+10}),title:p("player.abLoop","A-B Loop"),"aria-label":p("player.abLoop","Set A-B Loop"),style:{...yt,opacity:.4},children:"A-B"}),i!==null&&i>0&&n.jsxs("span",{style:{marginLeft:"auto",fontSize:11,color:"var(--nice-text-secondary, #64748b)",display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(G.NtdMoon,{size:12})," ",Math.floor(i/60),":",(i%60).toString().padStart(2,"0")]})]})};function Nh(e){if(!e)return;const t=e.match(/youtu\.be\/([A-Za-z0-9_-]{6,})/);if(t)return t[1];const r=e.match(/[?&]v=([A-Za-z0-9_-]{6,})/);if(r)return r[1]}function Co(e){const t={};if(!e)return t;const r=e.split(",");for(const a of r){const s=a.trim();s.startsWith("v=")?t.youtubeId=s.substring(2):s.startsWith("co=")?t.coverImage=s.substring(3):s.startsWith("bg=")&&(t.backgroundImage=s.substring(3))}return t}function Th(e,t="/api/karaoke/cover"){var a,s;const r=((a=e.coverImage)==null?void 0:a.startsWith("http://"))||((s=e.coverImage)==null?void 0:s.startsWith("https://"));return e.coverImage&&r?e.coverImage:e.youtubeId?`https://img.youtube.com/vi/${e.youtubeId}/hqdefault.jpg`:e.coverImage?`${t}?filePath=${encodeURIComponent(e.coverImage)}`:"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='320' height='180'%3E%3Crect width='320' height='180' fill='%23333'/%3E%3Ctext x='160' y='95' text-anchor='middle' fill='%23999' font-size='16'%3ENo Cover%3C/text%3E%3C/svg%3E"}function $h(e,t="/backgrounds"){return e.backgroundImage?`${t}/${e.backgroundImage}`:""}function jo(e,t,r=.01){let a=0;for(let o=0;o<e.length;o++)a+=e[o]*e[o];if(a=Math.sqrt(a/e.length),a<r)return 0;let s=-1,i=0;for(let o=20;o<e.length/2;o++){let l=0;for(let c=0;c<e.length/2;c++)l+=e[c]*e[c+o];l/=e.length/2,l>i&&(i=l,s=o)}return s>0?t/s:0}function Ja(e,t){const r=[];return e.forEach((a,s)=>{a.forEach((i,o)=>{r.push({startTime:i.startTime+t,duration:i.duration,pitch:i.pitch,isGold:i.isGold,line:s,idx:o})})}),r}function Mo(e,t,r){const a=[];return e.forEach(s=>{var c;const[i,o]=s.noteKey.split("-").map(Number),l=(c=t[i])==null?void 0:c[o];l&&s.segments.forEach(d=>{a.push({start:d.visualStart-r,end:d.visualEnd-r,pitch:l.pitch,frac:d.frac,isGold:l.isGold,noteStart:l.startTime,noteEnd:l.startTime+l.duration})})}),a}function Ro(e,t=120){let r=e;if(e.length>t){const a=e.length/t,s=[];for(let i=0;i<t;i++)s.push(e[Math.floor(i*a)]);r=s}return r.map(a=>({t:Math.round(a.t*1e3)/1e3,hz:Math.round(a.hz)}))}function No(e,t,r){const s=Date.parse(e)-r;return Math.max(0,Math.round(t-s))}const To={crepe:"var(--nice-accent, #a78bfa)",librosa:"var(--nice-success-light, #34d399)",pitchy:"var(--nice-primary-light, #60a5fa)",autocorr:"var(--nice-text-secondary, #555555)"};function Ph(e){return e==="autocorr"?"Ultrastar":e.charAt(0).toUpperCase()+e.slice(1)}function Eh(e){return To[e]??"var(--nice-text-secondary, #555555)"}function Ah(e){const t=To[e]??"var(--nice-text-secondary, #555555)";return`var(--algo-${e}, ${t})`}function $o(e,t){const r=!(t!=null&&t.includes("no-music")),a=t==null?void 0:t.includes("instrumental"),s=[];if(r){if(e.videoPath){let i=e.videoPath;if(i.startsWith("v=")){const o=Co(i);o.youtubeId&&(i=`https://www.youtube.com/watch?v=${o.youtubeId}`)}/youtu(\.be|be\.com)/i.test(i)?s.push({kind:"youtube",url:i}):/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(e.videoPath)&&s.push({kind:"audio",url:e.videoPath})}if(s.length===0){const i=a?e.instrumentalPath:e.audioPath;i&&/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(i)&&s.push({kind:"audio",url:i})}s.length===0&&e.youtubeId&&s.push({kind:"youtube",url:`https://www.youtube.com/watch?v=${e.youtubeId}`})}return{id:String(e.id??e.title??"song"),title:e.title??"—",artist:e.artist??"—",coverUrl:e.coverPath??void 0,sources:s}}function Ih(e){const t=e.videoPath??e.video??void 0;return{id:e.id,title:e.title??"",artist:e.artist??"",year:e.year,genre:e.genre,language:e.language,filePath:e.filePath,coverPath:e.coverPath,audioPath:e.audioPath??e.audio??void 0,videoPath:t,format:0,notes:e.notes??[],gap:e.gap,bpm:e.bpm,videoGap:e.videoGap,start:e.start,end:e.end,youtubeId:e.youtubeId,instrumentalPath:e.instrumentalPath,isVerified:e.isVerified,coverImage:e.coverImage,backgroundImage:e.backgroundImage}}var es=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(es||{});function Po(e,t="song.txt"){const r=e.split(/\r?\n/),a={},s=[];for(const o of r){const l=o.replace(/\uFEFF/g,"");if(l.trim()){if(l.startsWith("#")){const c=l.indexOf(":");c>0&&(a[l.slice(1,c).trim().toUpperCase()]=l.slice(c+1).trim())}else if(/^[:*\-FG]/.test(l))s.push({noteLine:l});else if(l.trim()==="E")break}}const i=o=>{if(!o)return;const l=parseFloat(o.replace(",","."));return Number.isFinite(l)?l:void 0};return{title:a.TITLE||t.replace(/\.txt$/i,""),artist:a.ARTIST||"",format:es.Ultrastar,bpm:i(a.BPM),gap:i(a.GAP),genre:a.GENRE||void 0,language:a.LANGUAGE||void 0,year:a.YEAR||void 0,audioPath:a.MP3||void 0,videoPath:a.VIDEO||a.MP3||void 0,notes:s}}const Lh=e=>window.btoa(unescape(encodeURIComponent(e))),Eo=({onSongUpload:e,parseSong:t,onError:r,accept:a=".txt",maxFileSize:s=5*1024*1024,t:i})=>{const{t:o}=Pe(),l=i??o,c=h=>{const f=new FileReader;f.onload=async p=>{var m;if(!((m=p.target)!=null&&m.result))return;const y=p.target.result;try{const x=t?await t({fileName:h.name,data:Lh(y)}):Po(y,h.name);e(x)}catch(x){r==null||r(x)}},f.readAsText(h,"UTF-8")},d=h=>/\.txt$/i.test(h.name)?h.size===0?l("karaokeUploader.empty","The file is empty."):null:l("karaokeUploader.notTxt","Please choose an UltraStar .txt file.");return n.jsx("div",{className:"nice-karaoke-uploader",children:n.jsx(ve.NiceUpload,{accept:a,maxFileSize:s,validateFile:d,multiple:!1,text:l("karaokeUploader.dropPrompt","Click or drag & drop an UltraStar file (.txt)"),onFilesSelected:h=>{const f=h[0];f&&c(f)}})})};function Dh(e,t,r,a,s){const o=a*.45;e.beginPath();for(let l=0;l<10;l++){const c=l%2===0?a:o,d=Math.PI/5*l-Math.PI/2,h=t+Math.cos(d)*c,f=r+Math.sin(d)*c;l===0?e.moveTo(h,f):e.lineTo(h,f)}e.closePath(),e.fillStyle=s,e.fill()}const Ut=60,Vs=4,qs=["A","B","X","Y","LB","RB","LT","RT"],Ao=({lanes:e,events:t,currentTime:r,activeLanes:a,difficulty:s,feedbackQueue:i,isPlaying:o,height:l=300})=>{const c=e.length,d=u.useRef(null),h=u.useRef([]);return u.useEffect(()=>{h.current=i},[i]),u.useEffect(()=>{var v,k,M,T;const f=d.current;if(!f)return;const p=f.getContext("2d");if(!p)return;const y=window.devicePixelRatio||1,m=f.clientWidth,x=f.clientHeight;if(f.width=m*y,f.height=x*y,p.scale(y,y),p.clearRect(0,0,m,x),c===0)return;const b=m/c;for(let N=0;N<c;N++){const j=N*b;p.fillStyle=N%2===0?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",p.fillRect(j,0,b,x),N>0&&(p.strokeStyle="rgba(255,255,255,0.1)",p.lineWidth=1,p.beginPath(),p.moveTo(j,0),p.lineTo(j,x),p.stroke())}const g=x-Ut-10;p.strokeStyle="rgba(255,255,255,0.4)",p.lineWidth=2,p.setLineDash([8,4]),p.beginPath(),p.moveTo(0,g),p.lineTo(m,g),p.stroke(),p.setLineDash([]);const S=(x-Ut-20)/Vs;for(const N of t){const j=N.note.startTime,R=j+N.note.duration,z=j-r;if(z>Vs||R<r-.5)continue;const A=N.lane,$=A*b+4,O=b-8,I=g-z*S,U=N.note.duration*S,J=r>=j-.15&&r<=R+.15,_=r>R+.15,W=((v=e[A])==null?void 0:v.color)??"#888";_?p.fillStyle="rgba(100,100,100,0.3)":J?(p.fillStyle=W,p.shadowColor=W,p.shadowBlur=12):p.fillStyle=W+"99";const K=Math.max(U,8),re=6;p.beginPath(),p.moveTo($+re,I),p.lineTo($+O-re,I),p.quadraticCurveTo($+O,I,$+O,I+re),p.lineTo($+O,I+K-re),p.quadraticCurveTo($+O,I+K,$+O-re,I+K),p.lineTo($+re,I+K),p.quadraticCurveTo($,I+K,$,I+K-re),p.lineTo($,I+re),p.quadraticCurveTo($,I,$+re,I),p.fill(),p.shadowBlur=0,N.note.isGold&&Dh(p,$+O/2,I+K/2,Math.min(7,O/4),"#fbbf24")}for(let N=0;N<c;N++){const j=N*b,R=x-Ut,z=a[N],A=((k=e[N])==null?void 0:k.color)??"#888";p.fillStyle=z?A:"rgba(30,30,30,0.9)",p.fillRect(j+2,R+2,b-4,Ut-4),p.strokeStyle=z?"#fff":A,p.lineWidth=z?3:1,p.strokeRect(j+2,R+2,b-4,Ut-4),p.fillStyle=z?"#000":"#fff",p.font=`bold ${Math.min(24,b*.3)}px monospace`,p.textAlign="center",p.textBaseline="middle",p.fillText(((M=e[N])==null?void 0:M.label)??"",j+b/2,R+Ut/2);const $=((T=e[N])==null?void 0:T.gamepadButton)??-1;$>=0&&$<qs.length&&(p.fillStyle=z?"rgba(0,0,0,0.6)":"rgba(255,255,255,0.4)",p.font="10px sans-serif",p.fillText(qs[$],j+b/2,R+Ut-8))}for(const N of h.current){const j=r-N.time;if(j<0||j>.8)continue;const R=Math.max(0,1-j/.8),z=N.lane*b;p.save(),p.globalAlpha=R,p.font="bold 20px sans-serif",p.textAlign="center",p.textBaseline="bottom",p.fillStyle=N.type==="perfect"?"#10b981":N.type==="good"?"#f59e0b":"#ef4444";const A=N.type==="perfect"?"PERFECT":N.type==="good"?"GOOD":"MISS";p.fillText(A,z+b/2,g-10-j*40),p.restore()}},[r,e,t,a,c,o]),!o||c===0?null:n.jsxs("div",{className:"nice-pad-karaoke-overlay",style:{position:"absolute",top:0,left:0,right:0,height:l,zIndex:35,pointerEvents:"none"},children:[n.jsx("canvas",{ref:d,role:"img","aria-label":"Pad karaoke note highway — hit notes in time with the music",style:{width:"100%",height:"100%",display:"block"}}),n.jsxs("div",{style:{position:"absolute",top:8,right:12,background:"var(--nice-overlay-60, rgba(0,0,0,0.6))",color:"#fff",padding:"4px 12px",borderRadius:8,fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:1,display:"flex",alignItems:"center",gap:6},children:[n.jsx(G.NtdGamepad,{size:14})," PAD — ",s]})]})},In=["var(--player-color-1, #ef4444)","var(--player-color-2, #f59e0b)","var(--player-color-3, #10b981)","var(--player-color-4, #3b82f6)","var(--player-color-5, #8b5cf6)","var(--player-color-6, #ec4899)"],Io={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 fa(e){return 440*Math.pow(2,(e-69)/12)}function Lo(e,t){const r=Io[t],a=r.keys.length,s=[];for(const d of e)for(const h of d)s.includes(h.pitch)||s.push(h.pitch);if(s.sort((d,h)=>d-h),s.length===0)return r.keys.map((d,h)=>({index:h,key:d,gamepadButton:r.buttons[h],label:r.labels[h],minPitch:-999,maxPitch:999,color:In[h%In.length]}));const i=s[0],l=s[s.length-1]-i+1,c=[];for(let d=0;d<a;d++){const h=i+Math.floor(l*d/a),f=i+Math.floor(l*(d+1)/a)-1;c.push({index:d,key:r.keys[d],gamepadButton:r.buttons[d],label:r.labels[d],minPitch:d===0?-999:h,maxPitch:d===a-1?999:f,color:In[d%In.length]})}return c}function Do(e,t){for(const s of t)if(e>=s.minPitch&&e<=s.maxPitch)return s.index;let r=0,a=1/0;for(const s of t){const i=(s.minPitch+s.maxPitch)/2,o=Math.abs(e-i);o<a&&(a=o,r=s.index)}return r}function zo(e,t,r){const a=[];for(let s=0;s<e.length;s++)for(let i=0;i<e[s].length;i++){const o={...e[s][i]};o.startTime+=r,a.push({note:o,lane:Do(o.pitch,t),lineIndex:s,noteIndex:i})}return a.sort((s,i)=>s.note.startTime-i.note.startTime),a}class _o{constructor(t){this.lanes=[],this.events=[],this.raf=null,this.keysDown=new Set,this.gamepadButtonsDown=new Set,this.running=!1,this.getCurrentTime=()=>0,this.lastFeedbackTime=0,this.lastActiveNote=null,this.preWindow=.15,this.postWindow=.15,this.loop=()=>{var c,d,h,f,p,y,m,x;if(!this.running)return;const s=this.getCurrentTime();this.pollGamepad();const i=this.getActiveLanes();(d=(c=this.config).onLaneActive)==null||d.call(c,i);const o=this.findActiveNote(s);if(o!==this.lastActiveNote&&(this.lastActiveNote=o,(f=(h=this.config).onCurrentNote)==null||f.call(h,o)),i.some(Boolean)&&o){const b=o.lane,g=i.indexOf(!0);if(i[b]){const S=fa(o.note.pitch);this.config.onPitch(S),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(y=(p=this.config).onHitFeedback)==null||y.call(p,{type:"perfect",lane:b,time:s}))}else if(g>=0){const v=Math.abs(g-b)*3,k=fa(o.note.pitch+v);this.config.onPitch(k),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(x=(m=this.config).onHitFeedback)==null||x.call(m,{type:"miss",lane:g,time:s}))}}this.raf=requestAnimationFrame(this.loop)},this.config=t;const r=Hn(t.noteLines,t.bpm),a=(t.gap??0)/1e3;switch(this.lanes=Lo(r,t.difficulty),this.events=zo(r,this.lanes,a),t.difficulty){case"easy":this.preWindow=.25,this.postWindow=.25;break;case"normal":this.preWindow=.15,this.postWindow=.15;break;case"hard":this.preWindow=.08,this.postWindow=.08;break}}getLanes(){return this.lanes}getEvents(){return this.events}start(t){this.running||(this.running=!0,this.getCurrentTime=t,this.handleKeyDown=this.handleKeyDown.bind(this),this.handleKeyUp=this.handleKeyUp.bind(this),window.addEventListener("keydown",this.handleKeyDown),window.addEventListener("keyup",this.handleKeyUp),this.loop())}stop(){this.running=!1,this.raf&&(cancelAnimationFrame(this.raf),this.raf=null),window.removeEventListener("keydown",this.handleKeyDown),window.removeEventListener("keyup",this.handleKeyUp),this.keysDown.clear(),this.gamepadButtonsDown.clear()}handleKeyDown(t){var a;const r=(a=t.target)==null?void 0:a.tagName;r&&["INPUT","TEXTAREA","SELECT"].includes(r)||this.keysDown.add(t.key.toLowerCase())}handleKeyUp(t){this.keysDown.delete(t.key.toLowerCase())}pollGamepad(){var a;const t=navigator.getGamepads?Array.from(navigator.getGamepads()).filter(Boolean):[];if(!t.length)return;const r=t[0];if(r){this.gamepadButtonsDown.clear();for(let s=0;s<r.buttons.length;s++)(a=r.buttons[s])!=null&&a.pressed&&this.gamepadButtonsDown.add(s)}}getActiveLanes(){const t=new Array(this.lanes.length).fill(!1);for(const r of this.lanes)(this.keysDown.has(r.key)||this.gamepadButtonsDown.has(r.gamepadButton))&&(t[r.index]=!0);return t}findActiveNote(t){for(const r of this.events){const a=r.note.startTime-this.preWindow,s=r.note.startTime+r.note.duration+this.postWindow;if(t>=a&&t<=s)return r}return null}}const ft=it.scoped("BaseStreamClient");function Hs(e,t,r){if(t===r)return e.slice();const a=Math.round(e.length*r/t),s=new Float32Array(a),i=e.length/a;for(let o=0;o<a;o++){const l=o*i,c=Math.floor(l),d=Math.min(e.length-1,c+1),h=l-c;s[o]=e[c]*(1-h)+e[d]*h}return s}function zh(e){const t=new Int16Array(e.length);for(let r=0;r<e.length;r++){const a=Math.max(-1,Math.min(1,e[r]));t[r]=a<0?Math.round(a*32768):Math.round(a*32767)}return t}const Sn=16e3,_h="/scripts/pitch-worklet.js";class Fo{constructor(t){this.sendQueue=[],this.maxQueue=20,this.reconnectAttempts=0,this.maxReconnectAttempts=3,this.buffer=new Float32Array(0),this.externalStream=!1,this.usingWorklet=!1,this.closed=!1,this.started=!1,this.chunksSent=0,this.chunksDropped=0,this.responsesReceived=0,this.lastStatusLog=0,this.opts=t}onMaxReconnect(){var t,r;try{(r=(t=this.opts).onMaxReconnect)==null||r.call(t)}catch{}this.stopAudioNodes()}get useWorklet(){return!0}get workletPath(){return _h}ts(){return new Date().toISOString().slice(11,23)}connectWs(){this.ws&&this.ws.readyState!==WebSocket.CLOSING&&this.ws.readyState!==WebSocket.CLOSED||(ft.info(`[${this.ts()}] connecting to ${this.opts.wsUrl}`),this.ws=new WebSocket(this.opts.wsUrl),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{var t,r,a,s,i,o;try{(r=(t=this.opts).onOpen)==null||r.call(t)}catch{}if(this.reconnectAttempts=0,this.chunksSent=0,this.chunksDropped=0,this.responsesReceived=0,ft.info(`[${this.ts()}] ws OPEN | worklet=${this.usingWorklet}`),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.sendQueue.length){const l=this.sendQueue.length;try{for(const c of this.sendQueue)try{this.ws.send(c),this.chunksSent++,(s=(a=this.opts).onSend)==null||s.call(a,c.byteLength)}catch(d){(o=(i=this.opts).onError)==null||o.call(i,d);break}}finally{this.sendQueue=[]}ft.info(`[${this.ts()}] flushed ${l} queued chunks`)}},this.ws.onclose=t=>{var r,a;try{(a=(r=this.opts).onClose)==null||a.call(r,t)}catch{}if(ft.info(`[${this.ts()}] ws CLOSE code=${t.code} clean=${t.wasClean} | sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived}`),this.sendQueue=[],this.ws=void 0,!this.closed&&this.started)if(this.reconnectAttempts++,this.reconnectAttempts<=this.maxReconnectAttempts){const s=Math.min(300*Math.pow(1.5,this.reconnectAttempts-1),5e3);ft.info(`[${this.ts()}] auto-reconnect #${this.reconnectAttempts} in ${s.toFixed(0)}ms`),this.reconnectTimer=setTimeout(()=>{this.closed||this.connectWs()},s)}else ft.warn(`[${this.ts()}] max reconnect attempts reached`),this.onMaxReconnect();else this.stopAudioNodes()},this.ws.onerror=t=>{var r,a;ft.warn(`[${this.ts()}] ws ERROR`,t);try{(a=(r=this.opts).onError)==null||a.call(r,t)}catch{}},this.ws.onmessage=t=>{var r,a;this.responsesReceived++;try{const s=typeof t.data=="string"?t.data:new TextDecoder().decode(t.data);this.handleWsMessage(s)}catch(s){(a=(r=this.opts).onError)==null||a.call(r,s)}})}handleAudioFrame(t){var p,y,m,x,b,g,S,v;const r=new Float32Array(this.buffer.length+t.length);r.set(this.buffer,0),r.set(t,this.buffer.length),this.buffer=r;const a=this.audioCtx.sampleRate,s=Math.round((this.opts.chunkMs??200)*Sn/1e3),i=Math.floor(this.buffer.length*Sn/a),o=Math.floor(i/s);if(o<=0)return;const l=o*s,c=Math.floor(l*a/Sn),d=this.buffer.slice(0,c);this.buffer=this.buffer.slice(c);const h=Hs(d,a,Sn);let f=0;for(;f+s<=h.length;){const k=h.subarray(f,f+s),T=zh(k).buffer,N=this.ws;if(N&&N.readyState===WebSocket.OPEN)try{N.send(T),this.chunksSent++,(y=(p=this.opts).onSend)==null||y.call(p,T.byteLength)}catch(R){(x=(m=this.opts).onError)==null||x.call(m,R)}else N&&N.readyState===WebSocket.CONNECTING?this.sendQueue.length<this.maxQueue&&(this.sendQueue.push(T),(g=(b=this.opts).onSend)==null||g.call(b,0)):(this.chunksDropped++,(v=(S=this.opts).onSend)==null||v.call(S,0));const j=Date.now();j-this.lastStatusLog>5e3&&(this.lastStatusLog=j,ft.info(`[${this.ts()}] STATUS: sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived} ws=${(N==null?void 0:N.readyState)??"none"} worklet=${this.usingWorklet}`)),f+=s}if(f<h.length){const k=h.subarray(f),M=Hs(k,Sn,a),T=new Float32Array(M.length+this.buffer.length);T.set(M,0),T.set(this.buffer,M.length),this.buffer=T}}async setupAudioNodes(t){if(this.useWorklet)try{await this.audioCtx.audioWorklet.addModule(this.workletPath);const a=new AudioWorkletNode(this.audioCtx,"pitch-processor");a.port.onmessage=s=>{this.handleAudioFrame(s.data)},t.connect(a),a.connect(this.audioCtx.destination),this.workletNode=a,this.usingWorklet=!0,ft.info(`[${this.ts()}] using AudioWorklet (pitch-processor)`);return}catch(a){ft.warn(`[${this.ts()}] AudioWorklet unavailable, falling back to ScriptProcessorNode`,a)}const r=4096;this.proc=this.audioCtx.createScriptProcessor(r,1,1),t.connect(this.proc),this.proc.connect(this.audioCtx.destination),this.proc.onaudioprocess=a=>{this.handleAudioFrame(a.inputBuffer.getChannelData(0))},this.usingWorklet=!1,ft.info(`[${this.ts()}] using ScriptProcessorNode fallback`)}stopAudioNodes(){try{this.workletNode&&(this.workletNode.port.close(),this.workletNode.disconnect(),this.workletNode=void 0)}catch{}try{this.proc&&(this.proc.onaudioprocess=null,this.proc.disconnect(),this.proc=void 0)}catch{}}async start(){if(this.closed)throw new Error("client closed");if(this.started)return;this.started=!0,(!this.ws||this.ws.readyState===WebSocket.CLOSED)&&this.connectWs(),this.mediaStream||(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:!0})),this.audioCtx=new AudioContext;const t=this.audioCtx.createMediaStreamSource(this.mediaStream);await this.setupAudioNodes(t)}async startWithMediaStream(t){if(this.closed)throw new Error("client closed");if(this.started)return;this.started=!0,this.externalStream=!0,(!this.ws||this.ws.readyState===WebSocket.CLOSED)&&this.connectWs(),this.mediaStream=t,this.audioCtx=new AudioContext;const r=this.audioCtx.createMediaStreamSource(this.mediaStream);await this.setupAudioNodes(r)}stop(){var t,r;if(ft.info(`[${this.ts()}] stop() called | closed=${this.closed} started=${this.started} sent=${this.chunksSent} responses=${this.responsesReceived}`),this.closed=!0,this.started=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.stopAudioNodes(),this.audioCtx&&this.audioCtx.state!=="closed"&&this.audioCtx.close().catch(()=>{}),!this.externalStream)try{(t=this.mediaStream)==null||t.getTracks().forEach(a=>a.stop())}catch{}try{(r=this.ws)==null||r.close()}catch{}this.ws=void 0,this.sendQueue=[]}}const Fh=it.scoped("CrepeStreaming");class Oh extends Fo{constructor(t){super({...t,chunkMs:t.chunkMs??200}),this.crepeOpts=t}get tag(){return"CrepeStreamClient"}handleWsMessage(t){var a,s;const r=JSON.parse(t);(s=(a=this.crepeOpts).onMessage)==null||s.call(a,r)}onMaxReconnect(){var t,r;Fh.warn(`[${this.tag}] [${this.ts()}] triggering fallback`),this.stopAudioNodes();try{(r=(t=this.crepeOpts).onFallback)==null||r.call(t)}catch{}}}class Bh extends Fo{constructor(t){super({...t,chunkMs:t.chunkMs??100}),this.librosaOpts=t}get tag(){return"LibrosaStreamClient"}handleWsMessage(t){var a,s;const r=JSON.parse(t);(s=(a=this.librosaOpts).onMessage)==null||s.call(a,r)}get useWorklet(){return!1}}const Et={debug:(...e)=>{},warn:(...e)=>{typeof console<"u"&&console.warn("[KaraokePitch]",...e)}};function Gh(e){const t=new Float32Array(e);for(let r=0;r<e;r++)t[r]=.5*(1-Math.cos(2*Math.PI*r/(e-1)));return t}function Wh(e,t){const r=new Float32Array(e.length);for(let a=0;a<e.length;a++)r[a]=e[a]*t[a];return r}function Oo({isPlaying:e,gameMode:t,players:r,playersMicKey:a,micAlgorithms:s={},defaultPitchAlgorithm:i="pitchy",micRmsThresholds:o={},micOffsets:l={},micGains:c={},micPitchThresholds:d={},micSmoothingWindows:h={},micHysteresisFrames:f={},micUseHanning:p={},micMonitorEnabled:y={},micMonitorVolumes:m={},currentTimeRef:x,isPadMode:b,clockOffsetMsRef:g,currentPartyIdRef:S,rtc:v}){const[k,M]=u.useState({}),T=u.useRef({}),N=u.useRef({}),[j,R]=u.useState({}),z=u.useRef({}),A=u.useRef([]),$=u.useRef(null),O=u.useRef(null),[,I]=u.useState({}),[,U]=u.useState({}),[,J]=u.useState({}),[_,W]=u.useState({}),[K,re]=u.useState(!0),[X,q]=u.useState(!1),E=u.useRef(r);E.current=r;const P=u.useRef(0),C=u.useRef(performance.now());return u.useEffect(()=>{A.current.forEach(B=>B()),A.current=[];const L={current:!1};function w(B,V,Y=0){x.current!==P.current&&(P.current=x.current,C.current=performance.now());const oe=Math.min(.25,(performance.now()-C.current)/1e3),ie=x.current+oe-Y/1e3;M(Z=>{const H=Z[B]||[];return{...Z,[B]:[...H,{t:ie,hz:V}]}}),T.current[B]=(T.current[B]||[]).concat({t:ie,hz:V});const ne=T.current[B];ne.length>500&&(T.current[B]=ne.slice(-500))}function D(B,V,Y,oe=.02,ie=0,ne=.6,Z=0,H=0,se=0,ae=!1){let ue=null,ee=null,de=null;return(async()=>{try{ue=new AudioContext;let ce=ue.createMediaStreamSource(V);if(Z>0){const me=ue.createGain();me.gain.value=Z,ce.connect(me),ce=me}const be=ue.createAnalyser();be.fftSize=2048,ce.connect(be);const Me=new Float32Array(be.fftSize),Te=ae?Gh(be.fftSize):null,je=[];let Xe=0;if(Y==="pitchy")try{const{PitchDetector:me}=await import("pitchy");de=me.forFloat32Array(be.fftSize)}catch(me){Et.warn("pitchy import failed, falling back to autocorrelation",me)}const le=()=>{try{be.getFloatTimeDomainData(Me)}catch{}const me=Te?Wh(Me,Te):Me;let De=0;for(let ze=0;ze<me.length;ze++)De+=me[ze]*me[ze];De=Math.sqrt(De/me.length);let ke=0;if(De>=oe)if(de)try{const[ze,tt]=de.findPitch(me,ue.sampleRate);ze>50&&ze<3e3&&tt>ne&&(ke=ze)}catch{}else ke=jo(me,ue.sampleRate,oe),(ke<50||ke>3e3)&&(ke=0);if(ke>0&&H>1&&(je.push(ke),je.length>H&&je.shift(),ke=je.reduce((ze,tt)=>ze+tt,0)/je.length),ke>0)Xe=0,w(B,ke,ie);else if(Xe++,se>0&&Xe<=se&&je.length>0){const ze=je[je.length-1];ze>0&&w(B,ze,ie)}ee=requestAnimationFrame(le),z.current[B]=ee};le()}catch(xe){Et.warn("startLocalPitch error",xe)}})(),()=>{ee&&cancelAnimationFrame(ee),ue&&ue.close().catch(()=>{})}}function F(B,V,Y,oe=0){Y==="crepe"&&O.current?(O.current.stop(),O.current=null):Y==="librosa"&&$.current&&($.current.stop(),$.current=null);const ie=window.location,ne=ie.protocol==="https:"?"wss:":"ws:",Z=Y==="librosa"?`${ne}//${ie.host}/api/librosa/ws/pyin`:`${ne}//${ie.host}/api/ai/audio/pitch/ws/pitch_server`,H=Y==="librosa"?I:U;H(de=>({...de,[B]:"connecting"}));const se=[],ae=de=>{if(de>0){for(se.push(x.current);se.length>200;)se.shift();Y==="crepe"&&J(fe=>({...fe,[B]:(fe[B]||0)+1}))}},ue=()=>{H(de=>({...de,[B]:"closed"})),se.length=0},ee=de=>{if(typeof de.hz=="number"&&de.hz>0){const fe=de.hz,ce=(se.length>0?se.shift():x.current)-oe/1e3;M(be=>{const Me=be[B]||[];return{...be,[B]:[...Me,{t:ce,hz:fe}]}})}else se.length>0&&se.shift()};if(Y==="librosa"){const de=new Bh({wsUrl:Z,onOpen:()=>H(fe=>({...fe,[B]:"connected"})),onClose:ue,onError:fe=>{H(xe=>({...xe,[B]:"error"})),Et.warn("Librosa WS error",fe)},onMessage:ee,onSend:ae});return $.current=de,de.startWithMediaStream(V).catch(fe=>{Et.warn("Librosa client start failed",fe),H(xe=>({...xe,[B]:"failed"}))}),()=>{de.stop(),$.current=null,H(fe=>({...fe,[B]:""}))}}else{const de=new Oh({wsUrl:Z,onOpen:()=>H(fe=>({...fe,[B]:"connected"})),onClose:ue,onError:fe=>{H(xe=>({...xe,[B]:"error"})),Et.warn("Crepe WS error",fe)},onMessage:ee,onSend:ae,onFallback:()=>{H(xe=>({...xe,[B]:"fallback-pitchy"})),O.current=null;const fe=D(B,V,"pitchy",.02,oe);A.current.push(fe)}});return O.current=de,de.startWithMediaStream(V).catch(fe=>{Et.warn("Crepe client start failed",fe),H(xe=>({...xe,[B]:"failed"}))}),()=>{de.stop(),O.current=null,H(fe=>({...fe,[B]:""}))}}}if(e){if(M({}),t!=="pad"){const B={};E.current.forEach(V=>{if(!V.micId)return;const Y=s[V.id]||i,oe=V.micId&&o[V.micId]||.02,ie=V.micId&&l[V.micId]||0,ne=V.micId&&c[V.micId]||0,Z=V.micId&&d[V.micId]||.6,H=V.micId&&h[V.micId]||0,se=V.micId&&f[V.micId]||0,ae=V.micId&&p[V.micId]||!1,ue=V.micId&&y[V.micId]||!1,ee=(V.micId?m[V.micId]:void 0)??100,de=new Da;de.startRecording({deviceId:V.micId,onLevel:()=>{},gain:ne,monitorEnabled:ue,monitorVolume:ee}).then(()=>{if(L.current){de.stopRecording().catch(()=>{});return}B[V.id]=de;const fe=de.getStream();if(!fe){Et.warn(`No stream from recorder for player ${V.id}`);return}if(Y==="librosa"||Y==="crepe"){const xe=F(V.id,fe,Y,ie);A.current.push(xe)}else{const xe=D(V.id,fe,Y,oe,ie,Z,ne,H,se,ae);A.current.push(xe)}}).catch(fe=>Et.warn(`recorder start failed for player ${V.id}`,fe))}),N.current=B}}else{const B=N.current,V=Object.keys(B).map(Number);Promise.allSettled(V.map(async Y=>{const oe=await B[Y].stopRecording();return{pid:Y,blob:oe}})).then(Y=>{const oe={};for(const ie of Y)ie.status==="fulfilled"&&ie.value.blob&&(oe[ie.value.pid]=ie.value.blob);Object.keys(oe).length>0&&R(ie=>({...ie,...oe}))}),N.current={},Object.values(z.current).forEach(Y=>Y&&cancelAnimationFrame(Y)),z.current={}}return()=>{L.current=!0,A.current.forEach(B=>B()),A.current=[],Object.values(N.current).forEach(B=>B.stopRecording().catch(()=>{})),N.current={},Object.values(z.current).forEach(B=>B&&cancelAnimationFrame(B)),z.current={}}},[e,t,a,s,i,o,l,c,d,h,f,p,y,m]),u.useEffect(()=>{if(!v)return;const L=300,w=async()=>{try{const F={...T.current};for(const B of Object.keys(F)){const V=Number(B),Y=F[V]||[];if(!Y||Y.length===0)continue;T.current[V]=[];const oe=Ro(Y,120),ie={playerId:V,points:oe,clientNowUtc:new Date().toISOString(),quantized:!0};S!=null&&S.current&&(ie.EventId=S.current);try{v.isConnected()&&await v.publishTimelineUpdate(ie)}catch(ne){Et.warn("failed to publish timeline update, will retry",ne),T.current[V]=(T.current[V]||[]).concat(Y).slice(-1e3)}}}catch{}},D=window.setInterval(w,L);return()=>{D&&window.clearInterval(D)}},[v,S]),u.useEffect(()=>{if(!v)return;const L=w=>{try{const D=w;if(!D||typeof D.playerId>"u"||!Array.isArray(D.points))return;const F=Number(D.playerId),B=D.points.map(V=>({t:V.t,hz:V.hz}));if(!B.length)return;if(D.serverTimeUtc){const V=No(D.serverTimeUtc,Date.now(),(g==null?void 0:g.current)||0);W(Y=>({...Y,[F]:V}))}M(V=>{const Y=V[F]||[];return{...V,[F]:[...Y,...B]}})}catch{}};return v.onTimelineUpdate(L),()=>v.offTimelineUpdate(L)},[v,g]),{livePitch:k,setLivePitch:M,recordings:j,recordersRef:N,unsentPitchRef:T,pitchCleanupsRef:A,remoteLatencyMs:_,showRemoteTimelines:K,setShowRemoteTimelines:re,compactTimelines:X,setCompactTimelines:q}}function Bo(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function Go(e){return e>=50?3:e>=30?2.5:e>=20?2:e>=10?1.5:1}function Wo(e,t,r){const{semitoneTolerance:a,preWindow:s,postExtra:i}=r,o=r.segMs??.25,l=typeof r.completionBonusFactor=="number"?r.completionBonusFactor:.15,c=typeof r.goldFullBonusFactor=="number"?r.goldFullBonusFactor:.3,d=typeof r.difficultyMult=="number"?r.difficultyMult:1,h=!!r.disableGoldNotes;let f=0,p=0,y=0;const m=[];let x=0,b=0,g=0;const S=new Map;e.forEach((R,z)=>{const A=R.startTime,$=R.startTime+R.duration,O=A-s,I=$+i,U=t.filter(E=>E.t>=O&&E.t<=I&&E.hz>0);if(!U||U.length===0)return;const J=Math.max(1,Math.ceil((R.duration||.25)/o)),_=Math.max(10,Math.round(100*(R.duration||1))),W=Math.max(1,Math.round(_/J));let K=0;const re=[];for(let E=0;E<J;E++){const P=A+E*(R.duration/J),C=A+(E+1)*(R.duration/J),L=Math.min(.06,R.duration/J*.2),w=P-L,D=C+L,F=t.filter(ne=>ne.t>=w&&ne.t<=D&&ne.hz>0);if(!F||F.length===0)continue;let B=0;F.forEach(ne=>{let H=((12*Math.log2(ne.hz/440)+69)%12+12)%12;for(;H-R.pitch>6;)H-=12;for(;H-R.pitch<-6;)H+=12;const se=Math.abs(H-R.pitch);B+=se});const V=B/F.length;let Y=0;if(a<=0)Y=V===0?1:0;else{const ne=a*2;Y=Math.max(0,1-Math.min(V/ne,1))}if(Y<=0)continue;const oe=!h&&R.isGold?2:1,ie=Math.round(W*oe*Y);ie>0&&(f+=ie,K+=ie,re.push({segIndex:E,frac:Y,add:ie,segStart:w,segEnd:D,visualStart:P,visualEnd:C}))}const X=R.line??0;S.has(X)||S.set(X,{total:0,hit:0,comboBonus:0});const q=S.get(X);if(q.total++,K>0){x++,x>b&&(b=x),q.hit++;const E=Go(x),P=E>1?Math.round(K*(E-1)):0;g+=P,q.comboBonus+=P;const C=Math.max(1,Math.ceil((R.duration||.25)/o)),w=re.length>=C,D=w?Math.round(Math.max(10,Math.round(100*(R.duration||1)))*l*(!h&&R.isGold?1.5:1)*d):0,F=w&&!h&&R.isGold?Math.round(Math.max(10,Math.round(100*(R.duration||1)))*c*d):0;p+=D,y+=F,m.push({noteKey:`${R.line??0}-${R.idx??0}`,segments:re,totalAdded:K,completed:w,completionBonus:D,goldFullBonus:F})}else x=0});const v=[];for(const[R,z]of S.entries()){const A=z.total>0?z.hit/z.total:0;v.push({verseIndex:R,hitFraction:A,label:Bo(A),comboBonus:z.comboBonus})}const k={maxCombo:b,currentCombo:0,totalComboBonus:g},M=g+p+y,T=m.length,N=m.filter(R=>R.completed).length,j={hits:T,misses:e.length-T,good:T-N,perfect:N,maxCombo:b};return{classicScore:f,bonusScore:M,totalScore:f+M,total:f,perNote:m,combo:k,verseRatings:v,noteStats:j}}function Uo(e,t){let r=0;for(const a of e){const s=Math.max(10,Math.round(100*(a.duration||1))),i=!t&&a.isGold?2:1;r+=s*i}return r}function Vo(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function qo(e,t,r){const a=Uo(t,r);if(a<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0,total:0};const s=Vo(e.classicScore,a),i=Math.round(e.bonusScore/a*1e4);return{...e,classicScore:s,bonusScore:i,totalScore:s+i,total:s}}const kn={maxCombo:0,currentCombo:0,totalComboBonus:0},Ks={hits:0,misses:0,good:0,perfect:0,maxCombo:0};function Ho({livePitch:e,uploadedSong:t,isPlaying:r,difficulty:a,players:s,isPadMode:i}){const[o,l]=u.useState(0),[c,d]=u.useState(0),[h,f]=u.useState(0),[p,y]=u.useState([]),[m,x]=u.useState(kn),[b,g]=u.useState([]),[S,v]=u.useState([]),[k,M]=u.useState({}),[T,N]=u.useState({}),[j,R]=u.useState({}),[z,A]=u.useState({}),[$,O]=u.useState({});return u.useEffect(()=>{if(!t||!r)return;const I=Hn(t.notes.map(F=>F.noteLine),t.bpm??void 0),U=(t.gap??0)/1e3,J=Ja(I,U),_=zr(a),W=[];let K=null,re=null,X=null,q=[];const E={},P={},C={},L={},w={},D=i?s[0]:s.find(F=>!!F.micId)||s[0];for(let F=0;F<s.length;F++){const B=s[F],V=(B==null?void 0:B.id)!=null?e[B.id]||[]:[];if(V.length===0){W.push({id:B.id,name:B.name||`Player ${B.id}`,color:B.color||et[F%et.length],classicScore:0,bonusScore:0,totalScore:0}),E[B.id]=[],P[B.id]={...kn},C[B.id]=[],L[B.id]=0,w[B.id]={...Ks};continue}const Y=Ha(B.id),oe=!!(Y!=null&&Y.disableGoldNotes),ie=Wo(J,V,{semitoneTolerance:_.semitoneTolerance,preWindow:_.preWindow,postExtra:_.postExtra,difficultyMult:_.difficultyMult,disableGoldNotes:oe}),ne=qo(ie,J,oe);W.push({id:B.id,name:B.name||`Player ${B.id}`,color:B.color||et[F%et.length],classicScore:ne.classicScore,bonusScore:ne.bonusScore,totalScore:ne.totalScore}),E[B.id]=Mo(ie.perNote,I,U),P[B.id]=ie.combo??{...kn},C[B.id]=ie.verseRatings??[],L[B.id]=ne.totalScore,w[B.id]=ie.noteStats??{...Ks},B.id===(D==null?void 0:D.id)&&(K=ne,re=ie.combo??null,X=ie.verseRatings??null,q=E[B.id])}v(W),M(E),N(P),R(C),A(L),O(w),K?(l(K.classicScore),d(K.bonusScore),f(K.totalScore),y(q),x(re??kn),g(X??[])):(l(0),d(0),f(0),y([]),x(kn),g([]))},[e,t,r,a,s,i]),{liveScore:o,liveBonusScore:c,liveTotalScore:h,liveSegmentScores:p,liveCombo:m,liveVerseRatings:b,perPlayerScores:S,perPlayerSegmentScores:k,perPlayerCombo:T,perPlayerVerseRatings:j,perPlayerTotalScores:z,perPlayerNoteStats:$}}const Uh=e=>!!e&&/youtu(\.be|be\.com)/i.test(e),Vh=({players:e,song:t,initialSong:r=null,difficulty:a="normal",gameMode:s="normal",height:i=480,showTimelines:o=!0,showLyrics:l=!0,singleTimeline:c=!1,requestMicPermission:d=!0,initiallyActivated:h=!1,showUploader:f=!1,parseSong:p,micAlgorithms:y,defaultPitchAlgorithm:m="pitchy",micRmsThresholds:x,micOffsets:b,micGains:g,micPitchThresholds:S,micSmoothingWindows:v,micHysteresisFrames:k,micUseHanning:M,micMonitorEnabled:T,micMonitorVolumes:N,searchYouTubeByArtistTitle:j,fetchTopSingings:R,onSaveResults:z,rtc:A,onSongChange:$,onPlayingChange:O,onTimeUpdate:I,onEnded:U,onContinue:J,renderReport:_,t:W,className:K,style:re,id:X,accessMode:q,"data-testid":E})=>{var Oe;const{t:P}=Pe(),C=W??P,[L,w]=u.useState(t??r??null),[D,F]=u.useState(!1),[B,V]=u.useState(0),[Y,oe]=u.useState(h),[ie,ne]=u.useState(!1),[Z,H]=u.useState([]),[se,ae]=u.useState(""),[ue,ee]=u.useState(null),[de,fe]=u.useState(0),xe=s==="pad",[ce,be]=u.useState([]),[Me,Te]=u.useState([]),[je,Xe]=u.useState([]),[le,me]=u.useState([]),De=u.useRef(null),ke=u.useRef(null),ze=u.useRef(null),tt=u.useRef(!1),Ye=u.useRef(0);u.useEffect(()=>{Ye.current=B},[B]);const He=u.useRef(t);u.useEffect(()=>{t!==void 0&&t!==He.current&&(He.current=t,w(t),ne(!1),V(0),fe(ge=>ge+1))},[t]);const At=u.useMemo(()=>JSON.stringify(e.map(ge=>({id:ge.id,micId:ge.micId}))),[e]),{livePitch:ht,setLivePitch:It,recordings:ct,remoteLatencyMs:pe}=Oo({isPlaying:D,gameMode:s,players:e,playersMicKey:At,micAlgorithms:y,defaultPitchAlgorithm:m,micRmsThresholds:x,micOffsets:b,micGains:g,micPitchThresholds:S,micSmoothingWindows:v,micHysteresisFrames:k,micUseHanning:M,micMonitorEnabled:T,micMonitorVolumes:N,currentTimeRef:Ye,isPadMode:xe,rtc:A}),ye=Ho({livePitch:ht,uploadedSong:L,isPlaying:D,difficulty:a,players:e,isPadMode:xe}),Fe=u.useRef(ye);Fe.current=ye;const vt=u.useMemo(()=>L?$o(L,s):null,[L,s]),he=((Oe=e[0])==null?void 0:Oe.id)??1;u.useEffect(()=>{var Ne;if(!xe||!D||!L){(Ne=De.current)==null||Ne.stop(),De.current=null,be([]),Te([]),Xe([]),me([]);return}const ge=new _o({difficulty:a,noteLines:L.notes.map(Ee=>Ee.noteLine),bpm:L.bpm??void 0,gap:L.gap??0,onPitch:Ee=>{const We=Ye.current;It(_e=>{const rt=_e[he]||[];return{..._e,[he]:[...rt,{t:We,hz:Ee}]}})},onHitFeedback:Ee=>me(We=>[...We.slice(-20),Ee]),onLaneActive:Ee=>Xe(Ee)});return be(ge.getLanes()),Te(ge.getEvents()),Xe(new Array(ge.getLanes().length).fill(!1)),ge.start(()=>Ye.current),De.current=ge,()=>{ge.stop(),De.current=null}},[xe,D,L,a,he,It]);const Se=u.useCallback(ge=>{F(ge),O==null||O(ge)},[O]),Ve=u.useCallback(ge=>{V(ge),I==null||I(ge)},[I]),Ie=u.useCallback(()=>{var Ne;try{Bt()}catch{}const ge=()=>{oe(!0),tt.current=!0};!xe&&d&&((Ne=navigator.mediaDevices)!=null&&Ne.getUserMedia)?navigator.mediaDevices.getUserMedia({audio:!0}).then(Ee=>Ee.getTracks().forEach(We=>We.stop())).catch(()=>{}).finally(ge):ge()},[xe,d]);u.useEffect(()=>{if(!Y||!tt.current)return;tt.current=!1;const ge=window.setInterval(()=>{ke.current&&(window.clearInterval(ge),ke.current.play())},100),Ne=window.setTimeout(()=>window.clearInterval(ge),3e3);return()=>{window.clearInterval(ge),window.clearTimeout(Ne)}},[Y]);const Re=u.useCallback(()=>{ne(!0),U==null||U();const ge=(L==null?void 0:L.id)??0,Ne=Fe.current,Ee=[];for(const _e of e){const rt=Ne.perPlayerTotalScores[_e.id]??0;if(rt<=0)continue;const Ze=Ne.perPlayerNoteStats[_e.id];Ee.push({playerId:_e.id,songId:ge,score:rt,hits:(Ze==null?void 0:Ze.hits)??0,misses:(Ze==null?void 0:Ze.misses)??0,good:(Ze==null?void 0:Ze.good)??0,perfect:(Ze==null?void 0:Ze.perfect)??0,combo:(Ze==null?void 0:Ze.maxCombo)??0})}const We=()=>{R&&ge>0&&Promise.resolve(R(ge)).then(H).catch(()=>{})};z&&Ee.length>0?Promise.resolve(z(Ee)).then(We).catch(We):We()},[e,L,z,R,U]);u.useEffect(()=>{var ge;s==="demo"&&D&&B>=12&&((ge=ke.current)==null||ge.pause(),Re())},[s,D,B,Re]),u.useEffect(()=>{if(!L||de===0||!j||Uh(L.videoPath))return;if(L.youtubeId){const Ne=`https://www.youtube.com/watch?v=${L.youtubeId}`;w(Ee=>Ee&&{...Ee,videoPath:Ne});return}if(!L.artist||!L.title)return;let ge=!1;return ae(C("karaokeManager.ytSearching","Searching YouTube…")),ee("searching"),Promise.resolve(j(L.artist,L.title)).then(Ne=>{if(!ge)if(Ne){const Ee=`https://www.youtube.com/watch?v=${Ne}`;w(We=>We&&{...We,videoPath:Ee}),ae(""),ee(null)}else ae(C("karaokeManager.ytNotFound","Not found on YouTube")),ee("error"),window.setTimeout(()=>{ge||(ae(""),ee(null))},4e3)}).catch(()=>{ge||(ae(C("karaokeManager.ytSearchError","Search error")),ee("error"))}),()=>{ge=!0}},[de,L,j,C]);const $e=u.useCallback(()=>{var ge,Ne;ne(!1),It({}),(ge=ke.current)==null||ge.seekTo(0),(Ne=ke.current)==null||Ne.play()},[It]),Be=u.useCallback(()=>{ne(!1),J==null||J()},[J]),Ge=u.useCallback(ge=>{w(ge),ne(!1),V(0),fe(Ne=>Ne+1),$==null||$(ge)},[$]),Je=u.useMemo(()=>{if(!c)return e;const ge=e.find(Ne=>!!Ne.micId)||e[0];return ge?[ge]:[]},[e,c]),Ae=((L==null?void 0:L.gap)??0)/1e3;return q==="hidden"?null:n.jsxs("div",{className:`nice-karaoke-manager${K?` ${K}`:""}`,style:{position:"relative",textAlign:"center",minHeight:i,...re},id:X,"data-testid":E,children:[se&&n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,margin:"10px auto",padding:"8px 16px",maxWidth:420,borderRadius:8,fontSize:14,fontWeight:500,background:"var(--nice-accent, #3b82f6)",color:"var(--nice-text-on-primary, #fff)"},children:[ue==="error"?n.jsx(G.NtdClose,{size:16}):n.jsx(G.NtdSearch,{size:16}),se]}),!L&&f&&n.jsx(Eo,{onSongUpload:Ge,parseSong:p,t:C}),L&&!Y&&n.jsxs("button",{type:"button",className:"nice-karaoke-manager__activate",onClick:Ie,style:{position:"absolute",inset:0,zIndex:30,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:16,border:"none",cursor:"pointer",background:"var(--nice-overlay-80, rgba(0,0,0,0.82))",color:"#fff"},children:[n.jsx("div",{style:{fontSize:56,lineHeight:0},children:xe?n.jsx(G.NtdGamepad,{size:56}):n.jsx(G.NtdMicrophone,{size:56})}),n.jsx("h2",{style:{margin:0,fontSize:22,fontWeight:700,color:"#fff"},children:C("karaokeManager.activateAudio","Tap to start")}),n.jsx("p",{style:{margin:0,maxWidth:360,fontSize:14,color:"var(--nice-text-muted, #94a3b8)"},children:xe?C("karaokeManager.padHint","Hit the notes with your keys or pad!"):C("karaokeManager.micHint","Your browser needs a tap to unlock the microphone and audio.")})]}),L&&n.jsxs("div",{ref:ze,style:{position:"relative",width:"100%",maxWidth:1200,margin:"0 auto"},children:[n.jsx("div",{style:{width:"100%",position:"relative",zIndex:10},children:n.jsx(Qa,{tracks:vt?[vt]:[],autoPlay:!1,uiMode:"nobuttons",height:i,externalRef:ke,onPlayingChange:Se,onTimeUpdate:Ve,onEnded:Re})}),o&&Y&&n.jsx("div",{style:{position:"absolute",inset:0,zIndex:20,pointerEvents:"none"},children:Je.map((ge,Ne)=>{const Ee=ht[ge.id]||[],We=Ae?Ee.map(_e=>({t:_e.t-Ae,hz:_e.hz})):Ee;return n.jsx(Ya,{song:L,currentTime:B,playerRef:ze,userPitch:We,segmentScores:ye.perPlayerSegmentScores[ge.id],combo:ye.perPlayerCombo[ge.id],verseRatings:ye.perPlayerVerseRatings[ge.id],config:{playerName:ge.name,score:ye.perPlayerTotalScores[ge.id]??0,playerBgColor:ge.color||et[Ne%et.length],difficultyLevel:a,isPlaying:D,playerCount:Je.length,latencyMs:pe[ge.id]??null,top:30+Ne*160}},ge.id)})}),xe&&ce.length>0&&n.jsx(Ao,{lanes:ce,events:Me,currentTime:B,activeLanes:je,difficulty:a,feedbackQueue:le,isPlaying:D}),l&&Y&&n.jsx("div",{style:{position:"absolute",bottom:20,left:0,right:0,zIndex:25,pointerEvents:"none"},children:n.jsx(Fa,{song:L,currentTime:B})})]}),ie&&Object.keys(ct).length>0&&n.jsx(qh,{recordings:ct,players:e,t:C}),ie&&n.jsx(Xa,{uploadedSong:L,playerScores:ye.perPlayerScores,topSingings:Z,onRestart:$e,onContinue:Be,t:C,renderReport:_})]})},qh=({recordings:e,players:t,t:r})=>{const a=u.useMemo(()=>{const s={};for(const[i,o]of Object.entries(e))o&&(s[Number(i)]=URL.createObjectURL(o));return s},[e]);return u.useEffect(()=>()=>{for(const s of Object.values(a))URL.revokeObjectURL(s)},[a]),n.jsxs("div",{style:{margin:"24px auto",maxWidth:640,background:"var(--nice-bg-tertiary)",borderRadius:12,padding:16,textAlign:"left"},children:[n.jsxs("h4",{style:{marginTop:0,color:"var(--nice-text-primary, #fff)"},children:[n.jsx(G.NtdMicrophone,{size:16})," ",r("karaokeManager.playerRecordings","Player recordings")]}),n.jsx("ul",{style:{listStyle:"none",padding:0,margin:0,color:"var(--nice-text-primary, #fff)"},children:t.map(s=>n.jsxs("li",{style:{marginBottom:12,display:"flex",alignItems:"center",gap:10},children:[n.jsx("b",{children:s.name||`Player ${s.id}`}),a[s.id]?n.jsxs(n.Fragment,{children:[n.jsx("audio",{controls:!0,src:a[s.id],style:{flex:1,maxWidth:300}}),n.jsxs("a",{href:a[s.id],download:`${s.name||`player-${s.id}`}-recording.webm`,style:{color:"var(--nice-accent-light, #4fc3f7)",whiteSpace:"nowrap"},children:[n.jsx(G.NtdDownload,{size:13})," ",r("karaokeManager.download","Download")]})]}):n.jsx("span",{style:{opacity:.6},children:r("karaokeManager.noRecording","No recording")})]},s.id))})]})},Ko=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function an(e){return 12*Math.log2(e/440)+69}function Jn(e){const t=Ko[Math.round(e)%12],r=Math.floor(Math.round(e)/12)-1;return`${t}${r}`}function Qr(e,t){const r=e-t;return r-12*Math.round(r/12)}function er(e,t){if(e.length===0)return 0;const r=t/100*(e.length-1),a=Math.floor(r),s=Math.ceil(r);return a===s?e[a]:e[a]+(e[s]-e[a])*(r-a)}function Yo(e){const{playerName:t,playerColor:r,songTitle:a,songArtist:s,songBpm:i,difficulty:o,pitchPoints:l,notes:c,verseRatings:d,combo:h,classicScore:f,bonusScore:p,totalScore:y,micSettings:m}=e,x=l.filter(le=>le.hz>0),b=x.map(le=>an(le.hz)),g=[],S=[],v=[...c].sort((le,me)=>le.startTime-me.startTime);function k(le){let me=0,De=v.length-1;for(;me<=De;){const ke=me+De>>>1,ze=v[ke];if(le<ze.startTime)De=ke-1;else if(le>ze.startTime+ze.duration)me=ke+1;else return ze.pitch}return null}const M=[];for(const le of l){const me=le.hz>0?an(le.hz):0,De=k(le.t);M.push({t:le.t,sung:me,expected:De}),me>0&&De!==null&&g.push(Qr(me,De)*100)}const T=M.flatMap(le=>le.sung>0&&le.expected!==null?[le.sung-le.expected]:[]).sort((le,me)=>le-me),N=T.length>0?12*Math.round(er(T,50)/12):0,j=M.map(le=>({t:le.t,sung:le.sung,expected:le.expected===null?0:le.expected+N}));let R=0;for(const le of v){const me=le.startTime-.3,De=le.startTime+le.duration;for(;R<x.length&&x[R].t<me;)R++;R<x.length&&x[R].t<=De&&S.push((x[R].t-le.startTime)*1e3)}const z=g.map(Math.abs),A=[...z].sort((le,me)=>le-me),$=z.length>0?z.reduce((le,me)=>le+me,0)/z.length:0,O=er(A,50),I=z.length>1?Math.sqrt(z.reduce((le,me)=>le+(me-$)**2,0)/(z.length-1)):0,U=z.filter(le=>le<=50).length,J=z.filter(le=>le<=15).length,_=z.length>0?U/z.length*100:0,W=z.length>0?J/z.length*100:0,K=["< −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"],re=new Array(10).fill(0);for(const le of g){const me=le<-100?0:le<-50?1:le<-25?2:le<-15?3:le<0?4:le<15?5:le<25?6:le<50?7:le<100?8:9;re[me]++}const X=K.map((le,me)=>({centRange:le,count:re[me],pct:g.length>0?re[me]/g.length*100:0})),q=x.map(le=>le.hz).sort((le,me)=>le-me),E=q.length>0?q[0]:0,P=q.length>0?q[q.length-1]:0,C=E>0?an(E):0,L=P>0?an(P):0,w=L-C,D=[...b].sort((le,me)=>le-me),F=er(D,10),B=er(D,90),V=new Array(12).fill(0);for(const le of b){const me=Math.round(le)%12;me>=0&&me<12&&V[me]++}const Y=V.reduce((le,me)=>le+me,0),oe=Ko.map((le,me)=>({note:le,count:V[me],pct:Y>0?V[me]/Y*100:0})),ie=Hh(x),ne=S.length>0?S.reduce((le,me)=>le+me,0)/S.length:0,Z=S.length>1?Math.sqrt(S.reduce((le,me)=>le+(me-ne)**2,0)/(S.length-1)):0,H=Z>0?Math.max(0,Math.min(100,100-Z/2)):100;let se=0,ae=0;for(let le=1;le<b.length;le++){const me=Math.abs(b[le]-b[le-1]);se+=me,ae++}const ue=ae>0?se/ae*100/12:0,ee=l.filter(le=>le.hz<=0).length,de=l.length>0?(1-ee/l.length)*100:0,fe=new Map;for(const le of c){const me=le.line??0;fe.has(me)||fe.set(me,[]),fe.get(me).push(le)}const xe=new Map;for(const le of x){const me=k(le.t);if(me===null)continue;let De=0,ke=v.length-1,ze=-1;for(;De<=ke;){const Ye=De+ke>>>1,He=v[Ye];if(le.t<He.startTime)ke=Ye-1;else if(le.t>He.startTime+He.duration)De=Ye+1;else{ze=He.line??0;break}}if(ze<0)continue;const tt=Math.abs(Qr(an(le.hz),me)*100);xe.has(ze)||xe.set(ze,[]),xe.get(ze).push(tt)}const ce=d.map(le=>{const me=fe.get(le.verseIndex)??[],De=xe.get(le.verseIndex)??[],ke=De.length>0?De.reduce((ze,tt)=>ze+tt,0)/De.length:0;return{verseIndex:le.verseIndex,label:le.label,hitFraction:le.hitFraction,avgCentDeviation:Math.round(ke*10)/10,noteCount:me.length,notesHit:Math.round(le.hitFraction*me.length),comboBonus:le.comboBonus}}),be=2,Me=.5,Te=l.length>0?l[l.length-1].t:0,je=[],Xe=M.flatMap(le=>le.sung>0&&le.expected!==null?[{t:le.t,hit:Math.abs(Qr(le.sung,le.expected))<=.5}]:[]);if(Xe.length>0){let le=0,me=0,De=0;for(let ke=0;ke<=Te;ke+=Me){const ze=ke-be/2,tt=ke+be/2;for(;me<Xe.length&&Xe[me].t<tt;)Xe[me].hit&&De++,me++;for(;le<me&&Xe[le].t<ze;)Xe[le].hit&&De--,le++;const Ye=me-le;je.push({t:ke,accuracy:Ye>0?De/Ye*100:0})}}else for(let le=0;le<=Te;le+=Me)je.push({t:le,accuracy:0});return{playerName:t,playerColor:r,songTitle:a,songArtist:s,songBpm:i,difficulty:o,timestamp:new Date().toISOString(),classicScore:f,bonusScore:p,totalScore:y,maxCombo:(h==null?void 0:h.maxCombo)??0,totalComboBonus:(h==null?void 0:h.totalComboBonus)??0,totalPitchPoints:l.length,avgCentDeviation:Math.round($*10)/10,medianCentDeviation:Math.round(O*10)/10,stdDevCents:Math.round(I*10)/10,intonationAccuracyPct:Math.round(_*10)/10,perfectHitPct:Math.round(W*10)/10,pitchDeviationHistogram:X,lowestHz:Math.round(E*10)/10,highestHz:Math.round(P*10)/10,lowestNote:C>0?Jn(C):"—",highestNote:L>0?Jn(L):"—",rangeInSemitones:Math.round(w*10)/10,tessituraLow:F>0?Jn(F):"—",tessituraHigh:B>0?Jn(B):"—",pitchClassDistribution:oe,vibrato:ie,avgOnsetDeviationMs:Math.round(ne*10)/10,rhythmStabilityPct:Math.round(H*10)/10,jitterPct:Math.round(ue*100)/100,shimmerProxy:Math.round(de*10)/10,verseMetrics:ce,micSettings:m,pitchOverTime:j,accuracyOverTime:je}}function Hh(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(y=>an(y.hz)),r=e.map(y=>y.t),a=.5,s=[],i=[];let o=0,l=0,c=0;for(let y=0;y<e.length;y++){for(l+=t[y],c++;o<y&&r[y]-r[o]>=a;)l-=t[o],c--,o++;if(c<6||(y-o)%10!==0)continue;const m=l/c;let x=0,b=t[o]-m,g=Math.abs(b);for(let k=o+1;k<=y;k++){const M=t[k]-m;M*b<0&&x++,b=M;const T=Math.abs(M);T>g&&(g=T)}const S=r[y]-r[o];if(S<=0)continue;const v=x/2/S;v>=3&&v<=12&&(s.push(v),i.push(g*100))}if(s.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const d=s.reduce((y,m)=>y+m,0)/s.length,h=i.reduce((y,m)=>y+m,0)/i.length,f=Math.sqrt(s.reduce((y,m)=>y+(m-d)**2,0)/s.length),p=Math.max(0,Math.min(100,100-f*20));return{detected:!0,avgRateHz:Math.round(d*10)/10,avgExtentCents:Math.round(h*10)/10,regularityPct:Math.round(p)}}const Q={overlay:{position:"fixed",inset:0,background:"var(--nice-overlay-90, rgba(0,0,0,0.92))",display:"flex",alignItems:"flex-start",justifyContent:"center",zIndex:250,color:"var(--nice-text, #e2e8f0)",overflowY:"auto",padding:"24px 12px"},container:{background:"var(--nice-bg, #0f172a)",borderRadius:16,padding:32,width:"min(960px, 95vw)",boxShadow:"0 16px 48px var(--nice-overlay-60, rgba(0,0,0,0.6))",fontFamily:"'Segoe UI', system-ui, -apple-system, sans-serif"},header:{textAlign:"center",marginBottom:24,borderBottom:"2px solid var(--nice-border, #334155)",paddingBottom:20},title:{fontSize:28,fontWeight:800,color:"var(--nice-text, #f1f5f9)",margin:"0 0 4px"},subtitle:{fontSize:14,color:"var(--nice-text-muted, #64748b)",margin:0},sectionTitle:{fontSize:18,fontWeight:700,color:"var(--nice-accent, #38bdf8)",margin:"28px 0 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",paddingBottom:6,display:"flex",alignItems:"center",gap:8},table:{width:"100%",borderCollapse:"collapse",fontSize:13,margin:"8px 0"},th:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"left",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},thRight:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"right",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},td:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-secondary, #cbd5e1)"},tdRight:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",textAlign:"right",color:"var(--nice-text, #e2e8f0)",fontWeight:500},tdBold:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text, #f1f5f9)",fontWeight:700},kpiGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:12,margin:"12px 0"},kpiCard:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:"14px 16px",textAlign:"center",border:"1px solid var(--nice-border, #334155)"},kpiValue:{fontSize:26,fontWeight:800,color:"var(--nice-warning, #fbbf24)"},kpiLabel:{fontSize:11,color:"var(--nice-text-muted, #64748b)",marginTop:2,textTransform:"uppercase",letterSpacing:.8},kpiUnit:{fontSize:13,fontWeight:400,color:"var(--nice-text-muted, #94a3b8)",marginLeft:2},chartWrap:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:16,margin:"12px 0",border:"1px solid var(--nice-border, #334155)"},chartTitle:{fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:8,textAlign:"center"},badge:e=>({display:"inline-block",padding:"2px 10px",borderRadius:20,background:e,color:"#fff",fontSize:12,fontWeight:700}),btnPrimary:{background:"var(--nice-info, #3b82f6)",color:"#fff",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:700,cursor:"pointer"},btnSecondary:{background:"var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:600,cursor:"pointer"},row:{display:"flex",gap:16,flexWrap:"wrap"},half:{flex:"1 1 45%",minWidth:280},footer:{textAlign:"center",marginTop:24,paddingTop:16,borderTop:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #475569)",fontSize:11}};function mt(e){return e>=90?"#22c55e":e>=70?"#84cc16":e>=50?"#eab308":e>=30?"#f97316":"#ef4444"}function Ys(e){switch(e){case"Perfect":return"#22c55e";case"Great":return"#84cc16";case"Good":return"#eab308";case"OK":return"#f97316";default:return"#ef4444"}}function Kh(e){return e.includes("−15 to 0")||e.includes("0 to +15")?"var(--nice-success, #22c55e)":e.includes("25")?"var(--nice-warning, #eab308)":"var(--nice-danger, #ef4444)"}const Vt=e=>Math.round(e*10)/10;function Zs(e,t,r){return e.map((a,s)=>({name:a,color:r[s],data:t.map((i,o)=>o===s?Vt(i):0)}))}function Xs(e,t){if(e.length<=t)return e;const r=Math.ceil(e.length/t);return e.filter((a,s)=>s%r===0)}function Qs(e){const t=e.length>1?e[e.length-1]-e[0]:0,r=[1,2,5,10,15,30,60,120,300].find(s=>t/s<=10)??600;let a=Math.ceil((e[0]??0)/r)*r;return e.map(s=>{if(s+1e-9<a)return"";for(;a<=s+1e-9;)a+=r;return`${Math.round(s)}s`})}const Js=240,Yh=({reports:e,noteCount:t,uploadedSong:r=null,playerScores:a,livePitch:s,liveVerseRatings:i,liveCombo:o,difficulty:l="normal",micSettings:c,onClose:d,t:h,className:f,style:p,id:y,accessMode:m,"data-testid":x})=>{const{t:b}=Pe(),g=h??b,S=u.useRef(null),v=u.useMemo(()=>{if(e||!r)return[];const C=Hn(r.notes.map(w=>w.noteLine),r.bpm??void 0),L=(r.gap??0)/1e3;return Ja(C,L)},[e,r]),k=u.useMemo(()=>e||(!r||!a||!o?[]:a.map(C=>{const L=(s==null?void 0:s[C.id])||[];return Yo({playerName:C.name,playerColor:C.color,songTitle:r.title,songArtist:r.artist,songBpm:r.bpm??0,difficulty:l,pitchPoints:L,notes:v,verseRatings:i??[],combo:o,classicScore:C.classicScore,bonusScore:C.bonusScore,totalScore:C.totalScore,micSettings:(c==null?void 0:c[C.id])??null})})),[e,r,a,s,i,o,l,v,c]),M=u.useCallback(()=>{var F,B;if(!S.current)return;const C=`<!DOCTYPE html>
|
|
46
|
+
-`]})]}),c&&c.length>0&&r.jsxs("div",{style:{marginTop:24},children:[r.jsx("b",{children:i("audioPitch.waveformRms","Waveform and RMS:")}),r.jsx("canvas",{width:600,height:100,style:{background:"var(--nice-bg-secondary, #222)",borderRadius:4,width:"100%",maxWidth:600,display:"block"},role:"img","aria-label":i("audioPitch.waveformAndRmsVisualizationCanvas","Waveform and RMS visualization canvas"),ref:q=>{if(!q)return;const G=q.getContext("2d");if(G){G.clearRect(0,0,600,100),G.strokeStyle=we.resolveCssColor("var(--nice-info, #0ff)",G.canvas),G.beginPath();for(let C=0;C<c.length;C+=Math.ceil(c.length/600)){const T=C/c.length*600,S=50-c[C]*48;C===0?G.moveTo(T,S):G.lineTo(T,S)}if(G.stroke(),v.length>0){G.strokeStyle=we.resolveCssColor("var(--nice-warning, #ff0)",G.canvas),G.beginPath();for(let C=0;C<v.length;C++){const T=C/v.length*600,S=100-v[C]*90;C===0?G.moveTo(T,S):G.lineTo(T,S)}G.stroke()}}}}),r.jsxs("div",{style:{color:"var(--nice-text-muted, #aaa)",fontSize:12,marginTop:4},children:[r.jsx("span",{style:{color:"var(--nice-info, #0ff)"},children:i("audioPitch.waveform","Waveform")})," "," | ",r.jsx("span",{style:{color:"var(--nice-warning, #ff0)"},children:"RMS"})]})]}),!w&&k.length===0&&!$&&r.jsx("div",{style:{marginTop:16,color:"var(--nice-text-muted, #aaa)"},children:r.jsx("i",{children:i("audioPitch.noNotesDetected","No notes detected")})}),h&&Object.keys(g).length>0&&r.jsxs("div",{style:{marginTop:16},children:[r.jsx("h4",{children:i("audioPitch.algorithmComparison","Algorithm comparison")}),Object.entries(g).map(([q,G])=>r.jsxs("div",{style:{marginBottom:12},children:[r.jsx("b",{children:q}),": ",i("audioPitch.detectedSegments","detected segments:")," ",G.length,r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-text-inverse, #ddd)",padding:8,borderRadius:4,marginTop:8},children:G.map(C=>`: ${Math.round(C.start*10)} ${Math.round(C.duration*10)} ${C.pitch} [${C.freq.toFixed(1)} Hz]`).join(`
|
|
47
|
+
`)})]},q))]})]})}const zt=1e4,Bs=5e3;function Xr(e,t=.35){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(!n)return e;const a=Math.min(255,Math.round(parseInt(n[1],16)+(255-parseInt(n[1],16))*t)),s=Math.min(255,Math.round(parseInt(n[2],16)+(255-parseInt(n[2],16))*t)),i=Math.min(255,Math.round(parseInt(n[3],16)+(255-parseInt(n[3],16))*t));return`rgb(${a},${s},${i})`}const fh=["var(--nice-warning, #facc15)","var(--nice-text-secondary, #cbd5e1)","var(--nice-warning, #d97706)"],mh=({entry:e,rank:t,animDelay:n})=>{const[a,s]=u.useState(0),[i,o]=u.useState(0),[l,c]=u.useState(0),[d,h]=u.useState(0),p=Math.min(e.classicScore,zt),g=Math.min(e.bonusScore,zt),y=p/zt*Bs,m=g>0?g/zt*Bs:0;return u.useEffect(()=>{let x,v=null;const f=Math.max(y,400),k=Math.max(m,m>0?300:0),b=w=>{v===null&&(v=w);const N=w-v-n;if(N<0){x=requestAnimationFrame(b);return}if(N<=f){const $=Math.min(1,N/f),M=1-Math.pow(1-$,3);s(Math.min(M*(p/zt)*100,100)),c(Math.round(M*e.classicScore)),x=requestAnimationFrame(b);return}if(s(Math.min(p/zt*100,100)),c(e.classicScore),k>0){const $=N-f;if($<=k){const M=Math.min(1,$/k),E=1-Math.pow(1-M,3);o(Math.min(E*(g/zt)*100,100)),h(Math.round(E*e.bonusScore)),x=requestAnimationFrame(b);return}o(Math.min(g/zt*100,100)),h(e.bonusScore)}};return x=requestAnimationFrame(b),()=>cancelAnimationFrame(x)},[e.classicScore,e.bonusScore,y,m,n]),r.jsxs("div",{className:"nice-karaoke-summary__bar",children:[r.jsx("span",{className:"nice-karaoke-summary__bar-rank",children:t<=3?r.jsx(O.NtdMedal,{size:18,primaryColor:fh[t-1]}):`#${t}`}),r.jsx("span",{className:"nice-karaoke-summary__bar-name",style:{color:e.color},children:e.name}),r.jsxs("div",{className:"nice-karaoke-summary__bar-track",children:[e.bonusScore>0&&r.jsx("div",{className:"nice-karaoke-summary__bar-fill-bonus",style:{width:`${Math.min(a+i,100)}%`,background:Xr(e.color,.45)}}),r.jsx("div",{className:"nice-karaoke-summary__bar-fill-classic",style:{width:`${a}%`,background:`linear-gradient(90deg, ${e.color}, ${Xr(e.color,.15)})`,boxShadow:`0 0 8px ${e.color}55`}}),r.jsxs("div",{className:"nice-karaoke-summary__bar-text",children:[l.toLocaleString(),d>0&&r.jsxs("span",{className:"nice-karaoke-summary__bar-text-bonus",style:{color:Xr(e.color,.5)},children:["+",d.toLocaleString()]})]})]}),r.jsx("span",{className:"nice-karaoke-summary__bar-total",children:(l+d).toLocaleString()})]})},Gs=({title:e,entries:t,highlightNames:n,playerColorMap:a})=>r.jsxs("div",{className:"nice-karaoke-summary__rank",children:[r.jsx("h4",{className:"nice-karaoke-summary__rank-title",children:e}),r.jsx("table",{className:"nice-karaoke-summary__rank-table",children:r.jsx("tbody",{children:t.map((s,i)=>{const o=n.has(s.name),l=a.get(s.name);return r.jsxs("tr",{className:`nice-karaoke-summary__rank-row ${o?"nice-karaoke-summary__rank-row--hl":""}`,children:[r.jsx("td",{className:`nice-karaoke-summary__rank-pos ${i<3?"nice-karaoke-summary__rank-pos--top":""}`,children:s.rank}),r.jsxs("td",{className:"nice-karaoke-summary__rank-name",style:l?{color:l}:void 0,children:[o&&r.jsxs(r.Fragment,{children:[r.jsx(O.NtdCircle,{size:8})," "]}),s.name]}),r.jsx("td",{className:"nice-karaoke-summary__rank-score",children:s.score.toLocaleString()})]},`${s.name}-${i}`)})})})]}),Eo=({uploadedSong:e,playerScores:t,topSingings:n,onRestart:a,onContinue:s,t:i,renderReport:o,className:l,style:c,id:d,accessMode:h,"data-testid":p})=>{const[g,y]=u.useState(!1),m=u.useMemo(()=>[...t].sort((w,N)=>N.totalScore-w.totalScore),[t]),x=u.useMemo(()=>{const w=new Map;for(const N of t)w.set(N.name,N.color);return w},[t]),v=u.useMemo(()=>new Set(t.map(w=>w.name)),[t]),f=u.useMemo(()=>m.map((w,N)=>({rank:N+1,name:w.name,score:w.totalScore,color:w.color})),[m]),k=u.useMemo(()=>{const w=n.map($=>({name:$.playerName,score:$.score})),N=new Set;for(const $ of m)N.has($.id)||(N.add($.id),w.push({name:$.name,score:$.totalScore}));return w.sort(($,M)=>M.score-$.score),w.slice(0,10).map(($,M)=>({rank:M+1,name:$.name,score:$.score}))},[n,m]),b=e?e.artist?`${e.artist} — ${e.title}`:e.title:i("karaokeSummary.unknownSong","Unknown song");return h==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-summary ${l??""}`,style:c,id:d,"data-testid":p,children:[r.jsxs("div",{className:"nice-karaoke-summary__card",children:[r.jsx("h1",{className:"nice-karaoke-summary__title",children:b}),r.jsx("div",{className:"nice-karaoke-summary__bars",children:m.length===0?r.jsx("div",{className:"nice-karaoke-summary__empty",children:i("karaokeSummary.noScores","No scores")}):m.map((w,N)=>r.jsx(mh,{entry:w,rank:N+1,animDelay:N*300},w.id))}),(m.length>1||n.length>0)&&r.jsxs("div",{className:"nice-karaoke-summary__ranks",children:[m.length>1&&r.jsx(Gs,{title:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(O.NtdHome,{size:14})," ",i("karaokeSummary.localRanking","Session ranking")]}),entries:f,highlightNames:v,playerColorMap:x}),n.length>0&&r.jsx(Gs,{title:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(O.NtdTrophy,{size:14})," ",i("karaokeSummary.globalRanking","Top 10")]}),entries:k,highlightNames:v,playerColorMap:x})]}),r.jsxs("div",{className:"nice-karaoke-summary__actions",children:[o&&r.jsxs("button",{type:"button",className:"nice-karaoke-summary__btn nice-karaoke-summary__btn--report",onClick:()=>y(!0),children:[r.jsx(O.NtdBarChart,{size:15})," ",i("karaokeSummary.report","Report")]}),r.jsx("button",{type:"button",className:"nice-karaoke-summary__btn nice-karaoke-summary__btn--restart",onClick:a,children:i("karaokeSummary.restart","Restart")}),r.jsx("button",{type:"button",className:"nice-karaoke-summary__btn nice-karaoke-summary__btn--continue",onClick:s,children:i("karaokeSummary.continue","Continue")})]})]}),g&&(o==null?void 0:o(()=>y(!1)))]})},gh=ot.scoped("GenericPlayer"),yh=e=>/youtu(\.be|be\.com)/i.test(e),Ao=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),vh=e=>!!e&&/\.(mp3|aac|m4a|flac|wav|ogg)(\?.*)?$/i.test(e),bh=e=>{var i;if(!((i=e==null?void 0:e.sources)!=null&&i.length))return null;const t=o=>e.sources.find(l=>l.kind===o),n=e.sources.find(o=>o.kind==="youtube"&&(o.videoId||o.url&&yh(o.url)))??null;if(n)return n;const a=t("hls")||e.sources.find(o=>o.url&&Ao(o.url))||null;if(a)return a;const s=t("audio")||e.sources.find(o=>o.url&&vh(o.url))||null;return s||(e.sources[0]??null)},Ar=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")}`},xh=[.25,.5,.75,1,1.25,1.5,1.75,2],Io=({tracks:e=[],initialIndex:t=0,autoPlay:n=!0,countdownSeconds:a=0,height:s=360,onIndexChange:i,onPlayingChange:o,onTimeUpdate:l,externalRef:c,uiMode:d="full",compactNextCount:h=3,progressBarPosition:p="inline",loop:g=!1,onEnded:y,enableKeyboardShortcuts:m=!0,shuffle:x=!1,repeatMode:v="none",playbackSpeed:f=1,abLoop:k=null,onRepeatModeChange:b,onShuffleChange:w,onSpeedChange:N,sleepTimer:$=0,onSleepTimerExpired:M})=>{const{t:E}=be(),{t:R}=be(),[L,A]=u.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),z=e[L],j=u.useMemo(()=>bh(z),[z]),[I,Y]=u.useState(!1),[H,D]=u.useState(0),[V,Z]=u.useState(0),[X,q]=u.useState(.9),[G,C]=u.useState(null),[T,S]=u.useState(null),F=u.useRef(null),[K,P]=u.useState(x),[B,_]=u.useState(v),[U,J]=u.useState(f),[se,oe]=u.useState(k),[re,W]=u.useState([]),[ee,ae]=u.useState($>0?$*60:null),le=u.useRef(null),[ce,te]=u.useState(()=>$i()),he=u.useRef(null),ue=u.useRef(null),xe=u.useRef(null),pe=u.useRef(null);u.useEffect(()=>{if(K&&e.length>0){const fe=e.map((Ce,Be)=>Be);for(let Ce=fe.length-1;Ce>0;Ce--){const Be=Math.floor(Math.random()*(Ce+1));[fe[Ce],fe[Be]]=[fe[Be],fe[Ce]]}W(fe)}},[K,e.length]),u.useEffect(()=>(le.current&&(window.clearInterval(le.current),le.current=null),$>0&&I&&(ae($*60),le.current=window.setInterval(()=>{ae(fe=>!fe||fe<=1?(le.current&&window.clearInterval(le.current),le.current=null,M==null||M(),null):fe-1)},1e3)),()=>{le.current&&window.clearInterval(le.current)}),[$,I]);const Se=u.useCallback(fe=>{const Ce=Math.min(Math.max(0,fe),Math.max(0,e.length-1));A(Ce),i==null||i(Ce)},[e.length,i]),je=u.useCallback(()=>{if(K&&re.length>0){const Ce=re.indexOf(L)+1;return Ce<re.length?re[Ce]:B==="all"?re[0]:-1}return L<e.length-1?L+1:B==="all"?0:-1},[L,e.length,K,re,B]),$e=u.useCallback(()=>{if(K&&re.length>0){const fe=re.indexOf(L);return fe>0?re[fe-1]:B==="all"?re[re.length-1]:-1}return L>0?L-1:B==="all"?e.length-1:-1},[L,e.length,K,re,B]),Te=u.useCallback(()=>{const fe=je();fe>=0&&Se(fe)},[je,Se]),He=u.useCallback(async()=>{var fe,Ce;await Yt(),te(!0),(j==null?void 0:j.kind)==="youtube"?(fe=he.current)==null||fe.playVideo():(Ce=ue.current)==null||Ce.play(),Y(!0),o==null||o(!0)},[j,o]),de=u.useCallback(()=>{var fe,Ce;(j==null?void 0:j.kind)==="youtube"?(fe=he.current)==null||fe.pauseVideo():(Ce=ue.current)==null||Ce.pause(),Y(!1),o==null||o(!1)},[j,o]),ye=u.useCallback(()=>I?de():He(),[I,He,de]),Ee=u.useCallback(fe=>{var ke;const Ce=(z==null?void 0:z.startOffset)??0,Be=fe+Ce;(j==null?void 0:j.kind)==="youtube"?(ke=he.current)==null||ke.seekTo(Be,!0):ue.current&&(ue.current.currentTime=Be);const ge=Math.max(0,fe);Z(ge),l==null||l(ge)},[j,l]),Me=u.useCallback(()=>{if(V>3){Ee(0);return}const fe=$e();fe>=0&&Se(fe)},[$e,Se,V,Ee]),Ie=u.useCallback(fe=>{var Ce,Be;q(fe),C(null),(j==null?void 0:j.kind)==="youtube"?(Be=(Ce=he.current)==null?void 0:Ce.setVolume)==null||Be.call(Ce,Math.round(fe*100)):ue.current&&(ue.current.volume=fe)},[j]),tt=u.useCallback(()=>{G!==null?Ie(G):(C(X),Ie(0))},[X,G,Ie]),Ye=u.useCallback(fe=>{var Ce,Be;J(fe),ue.current&&(ue.current.playbackRate=fe),(j==null?void 0:j.kind)==="youtube"&&((Be=(Ce=he.current)==null?void 0:Ce.setPlaybackRate)==null||Be.call(Ce,fe)),N==null||N(fe)},[j,N]),Ze=u.useCallback(()=>{const fe=["none","all","one"],Ce=fe[(fe.indexOf(B)+1)%fe.length];_(Ce),b==null||b(Ce)},[B,b]),Ct=u.useCallback(()=>{const fe=!K;P(fe),w==null||w(fe)},[K,w]),dt=u.useCallback(fe=>{oe(fe)},[]);u.useImperativeHandle(c,()=>({play:He,pause:de,toggle:ye,seekTo:Ee,setVolume:Ie,setSpeed:Ye,setRepeatMode:fe=>{_(fe),b==null||b(fe)},toggleShuffle:Ct,setABLoop:dt,getUnderlyingPlayer:()=>(j==null?void 0:j.kind)==="youtube"?he.current:(j==null?void 0:j.kind)==="hls"||(j==null?void 0:j.kind)==="audio"?ue.current:null}),[He,de,ye,Ee,Ie,Ye,Ct,dt,j==null?void 0:j.kind]),u.useEffect(()=>{const fe=window.setInterval(()=>{let Ce=0,Be=0;(j==null?void 0:j.kind)==="youtube"&&he.current?(Ce=he.current.getCurrentTime()||0,Be=he.current.getDuration()||0):ue.current&&(Ce=ue.current.currentTime||0,Be=ue.current.duration||0);const ge=(z==null?void 0:z.startOffset)??0,ke=Math.max(0,Ce-ge);Z(ke),D(Be),l==null||l(ke),se&&ke>=se.b&&Ee(se.a)},250);return()=>window.clearInterval(fe)},[j==null?void 0:j.kind,l,se]),u.useEffect(()=>()=>{F.current&&(window.clearInterval(F.current),F.current=null)},[]),u.useEffect(()=>{if(xe.current){try{xe.current.destroy()}catch{}xe.current=null}if(ue.current&&(ue.current.volume=X,ue.current.crossOrigin=j!=null&&j.withCredentials?"use-credentials":"anonymous"),(j==null?void 0:j.kind)==="hls"&&Ao(j.url)){const fe=ue.current;if(!fe)return;const Ce=()=>{fe.src=j.url,fe.load();const Be=(z==null?void 0:z.startOffset)??0;try{Be&&!isNaN(Be)&&(fe.currentTime=Be)}catch{}n&&fe.play().catch(()=>{})};fe.canPlayType("application/vnd.apple.mpegurl")?Ce():(async()=>{var Be;try{const ke=(await import("hls.js")).default;if((Be=ke==null?void 0:ke.isSupported)!=null&&Be.call(ke)){const We=new ke({xhrSetup:_e=>{if(j!=null&&j.withCredentials&&(_e.withCredentials=!0),j!=null&&j.headers)for(const[Pe,Re]of Object.entries(j.headers))try{_e.setRequestHeader(Pe,Re)}catch{}}});xe.current=We,We.loadSource(j.url),We.attachMedia(fe),We.on(ke.Events.MANIFEST_PARSED,()=>{n&&fe.play().catch(()=>{})})}else Ce()}catch(ge){gh.debug("HLS.js setup failed, falling back to native playback",ge),Ce()}})()}else if((j==null?void 0:j.kind)==="audio"&&j.url&&ue.current){const fe=ue.current;fe.src=j.url,fe.load();const Ce=(z==null?void 0:z.startOffset)??0;try{Ce&&!isNaN(Ce)&&(fe.currentTime=Ce)}catch{}n&&fe.play().catch(()=>{})}F.current&&(window.clearInterval(F.current),F.current=null),S(null),Z(0),D(0),n&&(j==null?void 0:j.kind)==="youtube"&&a>0?(S(a),F.current=window.setInterval(()=>{S(fe=>{var Ce;if(!fe)return null;if(fe<=1){F.current&&(window.clearInterval(F.current),F.current=null);try{(Ce=he.current)==null||Ce.playVideo()}catch{}return Y(!0),o==null||o(!0),null}return fe-1})},1e3)):Y(!!n)},[j==null?void 0:j.url,j==null?void 0:j.kind,j==null?void 0:j.withCredentials,JSON.stringify(j==null?void 0:j.headers),n,X]);const $t=u.useCallback(()=>{if(B==="one"){Ee(0),He();return}const fe=je();fe>=0?Se(fe):(Y(!1),o==null||o(!1),Ee(0),y==null||y())},[B,je,Se,o,Ee,y,He]);u.useEffect(()=>{if(!m)return;const fe=Ce=>{const Be=Ce.target;if(!(Be.tagName==="INPUT"||Be.tagName==="TEXTAREA"||Be.isContentEditable))switch(Ce.key){case" ":Ce.preventDefault(),ye();break;case"ArrowRight":Ce.preventDefault(),Ee(Math.min(V+5,H));break;case"ArrowLeft":Ce.preventDefault(),Ee(Math.max(0,V-5));break;case"ArrowUp":Ce.preventDefault(),Ie(Math.min(1,X+.05));break;case"ArrowDown":Ce.preventDefault(),Ie(Math.max(0,X-.05));break;case"m":case"M":tt();break;case"n":case"N":Te();break;case"p":case"P":Me();break;case"r":case"R":Ze();break;case"s":case"S":Ct();break}};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[m,ye,Ee,V,H,Ie,X,tt,Te,Me,Ze,Ct]);const pt=(j==null?void 0:j.kind)==="youtube"||d==="full"||d==="nobuttons",Xt=h>0?e.slice(L+1,L+1+h):[];return r.jsxs("div",{ref:pe,className:"gp-player",style:{display:"grid",gap:12},tabIndex:-1,children:[n&&!ce&&r.jsx("div",{className:"gp-audio-activation",onClick:()=>{te(!0),He()},style:{position:"fixed",inset:0,zIndex:200,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",cursor:"pointer"},children:r.jsx("span",{style:{color:"#fff",fontSize:24},children:E("player.clickToActivateAudio","Click to activate audio")})}),pt&&r.jsxs("div",{className:"gp-stage",style:{width:"100%",height:s,background:(j==null?void 0:j.kind)==="youtube"?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(j==null?void 0:j.kind)==="youtube"&&r.jsx(Pa,{videoId:j.videoId??Mh(j.url),onReady:fe=>{he.current=fe.target,Ie(X);const Ce=(z==null?void 0:z.startOffset)??0;try{Ce&&fe.target.seekTo(Ce,!0)}catch{}if(d==="nobuttons"){try{fe.target.playVideo()}catch{}Y(!0)}},onEnd:$t,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%"}}),T!==null&&r.jsx("div",{style:{position:"absolute",inset:0,zIndex:120,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-70, rgba(0, 0, 0, 0.7))"},children:r.jsx("span",{style:{color:"#fff",fontSize:72,fontWeight:"bold"},children:T})}),d==="nobuttons"&&r.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"auto",zIndex:100,cursor:"default"}}),((j==null?void 0:j.kind)==="audio"||(j==null?void 0:j.kind)==="hls")&&r.jsxs(r.Fragment,{children:[d==="full"&&r.jsx("div",{style:{textAlign:"center",color:"var(--nice-overlay-light-90, rgba(255, 255, 255, 0.9))"},children:z!=null&&z.coverUrl?r.jsx("img",{alt:"cover",src:z.coverUrl,style:{height:s-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[z==null?void 0:z.artist," — ",z==null?void 0:z.title]}),r.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--nice-text-secondary, #64748b)"},children:(j==null?void 0:j.label)??`${(j==null?void 0:j.codec)??""} ${(j==null?void 0:j.quality)??""}`.trim()})]})}),r.jsx("audio",{ref:ue,onEnded:$t,onLoadedMetadata:()=>{const fe=ue.current;fe&&D(fe.duration||0)},crossOrigin:j!=null&&j.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]})]}),(d==="minimal"||d==="compact")&&r.jsx("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:r.jsxs("div",{children:[r.jsx("div",{style:{fontWeight:600},children:(z==null?void 0:z.title)??""}),r.jsx("div",{style:{color:"var(--nice-text-secondary, #64748b)",fontSize:13},children:(z==null?void 0:z.artist)??""})]})}),d==="full"&&r.jsxs(r.Fragment,{children:[r.jsx(Lo,{currentTime:V,duration:H}),r.jsx(Sh,{isPlaying:I,index:L,count:e.length,currentTime:V,duration:H,volume:X,onPrev:Me,onNext:Te,onToggle:ye,onSeek:Ee,onVolume:Ie}),r.jsx(jh,{shuffleOn:K,repeatMode:B,speed:U,abLoop:se,currentTime:V,sleepRemaining:ee,onToggleShuffle:Ct,onCycleRepeat:Ze,onSpeedChange:Ye,onSetABLoop:dt,onMuteToggle:tt,isMuted:G!==null})]}),d==="progressOnly"&&r.jsx("div",{style:p==="fixedBottom"?{position:"fixed",left:0,right:0,bottom:0,padding:"8px 12px",background:"var(--nice-overlay-90, rgba(15, 23, 42, 0.9))",backdropFilter:"blur(2px)",zIndex:1e3}:{},children:r.jsx(kh,{currentTime:V,duration:H,onSeek:Ee})}),(d==="minimal"||d==="compact")&&r.jsx(wh,{isPlaying:I,canPrev:L>0,canNext:L<e.length-1,onPrev:Me,onNext:Te,onToggle:ye}),d==="compact"&&Xt.length>0&&r.jsx(Ch,{items:Xt,onSelect:fe=>Se(L+1+fe)}),d==="nobuttons"&&r.jsx(r.Fragment,{}),d==="full"&&e.length>0&&r.jsx("div",{className:"gp-list",style:{display:"grid",gap:4},children:e.map((fe,Ce)=>r.jsxs("button",{onClick:()=>Se(Ce),style:{textAlign:"left",border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"8px 10px",background:Ce===L?"color-mix(in srgb, var(--nice-color-primary) 14%, transparent)":"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},title:fe.sources.map(Be=>Be.kind).join(", "),children:[r.jsx("div",{style:{fontWeight:600},children:fe.title}),r.jsx("div",{style:{color:"var(--nice-text-secondary)",fontSize:12},children:fe.artist})]},fe.id))})]})},vt={border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},Lo=({currentTime:e,duration:t})=>r.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[r.jsx("div",{}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-secondary, #64748b)"},children:[Ar(e)," / ",Ar(t)]})]}),Sh=({isPlaying:e,index:t,count:n,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek:d,onVolume:h})=>{const{t:p}=be();return r.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("button",{onClick:o,disabled:t<=0,title:p("player.previousTrack","Previous track"),"aria-label":p("player.previousTrack","Previous track"),style:vt,children:r.jsx(O.NtdSkipBack,{size:16})}),r.jsx("button",{onClick:c,title:e?p("player.pause","Pause"):p("player.play","Play"),"aria-label":e?p("player.pause","Pause"):p("player.play","Play"),style:vt,children:e?r.jsx(O.NtdPause,{size:16}):r.jsx(O.NtdPlay,{size:16})}),r.jsx("button",{onClick:l,disabled:t>=n-1,title:p("player.nextTrack","Next track"),"aria-label":p("player.nextTrack","Next track"),style:vt,children:r.jsx(O.NtdSkipForward,{size:16})})]}),r.jsx("input",{type:"range",min:0,max:Math.max(1,s),step:.1,value:a,onChange:g=>d(parseFloat(g.target.value)),"aria-label":p("player.seekPosition","Seek position")}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx(O.NtdVolume,{size:16}),r.jsx("input",{type:"range",min:0,max:1,step:.01,value:i,onChange:g=>h(parseFloat(g.target.value)),"aria-label":p("player.volume","Volume")})]})]})},kh=({currentTime:e,duration:t,onSeek:n})=>{const{t:a}=be();return r.jsxs(r.Fragment,{children:[r.jsx(Lo,{currentTime:e,duration:t}),r.jsx("input",{type:"range",min:0,max:Math.max(1,t),step:.1,value:e,onChange:s=>n(parseFloat(s.target.value)),"aria-label":a("player.seekPosition","Seek position")})]})},wh=({isPlaying:e,canPrev:t,canNext:n,onPrev:a,onNext:s,onToggle:i})=>{const{t:o}=be();return r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[r.jsx("button",{onClick:a,disabled:!t,title:o("player.previousTrack","Previous track"),"aria-label":o("player.previousTrack","Previous track"),style:vt,children:r.jsx(O.NtdSkipBack,{size:16})}),r.jsx("button",{onClick:i,title:e?o("player.pause","Pause"):o("player.play","Play"),"aria-label":e?o("player.pause","Pause"):o("player.play","Play"),style:vt,children:e?r.jsx(O.NtdPause,{size:16}):r.jsx(O.NtdPlay,{size:16})}),r.jsx("button",{onClick:s,disabled:!n,title:o("player.nextTrack","Next track"),"aria-label":o("player.nextTrack","Next track"),style:vt,children:r.jsx(O.NtdSkipForward,{size:16})})]})},Ch=({items:e,onSelect:t})=>{const{t:n}=be();return r.jsxs("div",{style:{border:"1px solid var(--nice-border-color)",borderRadius:8,padding:10,background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)"},children:[r.jsx("div",{style:{fontWeight:600,marginBottom:6},children:n("player.upNext","Up next")}),r.jsx("ol",{style:{margin:0,paddingLeft:18},children:e.map((a,s)=>r.jsx("li",{style:{marginBottom:4},children:r.jsxs("button",{type:"button",onClick:()=>t(s),style:{border:"none",padding:0,background:"transparent",cursor:"pointer",color:"var(--nice-text-primary, #0f172a)"},title:a.sources.map(i=>i.kind).join(", "),children:[r.jsx("span",{style:{fontWeight:600},children:a.artist})," — ",a.title]})},a.id))})]})},jh=({shuffleOn:e,repeatMode:t,speed:n,abLoop:a,currentTime:s,sleepRemaining:i,onToggleShuffle:o,onCycleRepeat:l,onSpeedChange:c,onSetABLoop:d,onMuteToggle:h,isMuted:p})=>{const{t:g}=be(),y={none:"Off",all:"All",one:"One"},m=t==="one"?r.jsxs("span",{style:{position:"relative",display:"inline-flex"},children:[r.jsx(O.NtdRepeat,{size:16}),r.jsx("span",{style:{position:"absolute",right:-3,bottom:-3,fontSize:8,fontWeight:700},children:"1"})]}):t==="all"?r.jsx(O.NtdRepeat,{size:16}):r.jsx(O.NtdArrowRight,{size:16});return r.jsxs("div",{className:"gp-pro-controls",style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap",fontSize:13},children:[r.jsx("button",{onClick:o,title:g("player.shuffle","Shuffle"),"aria-label":g("player.shuffle","Shuffle"),style:{...vt,opacity:e?1:.4,fontWeight:e?700:400},children:r.jsx(O.NtdShuffle,{size:16})}),r.jsx("button",{onClick:l,title:`${g("player.repeat","Repeat")}: ${y[t]}`,"aria-label":`${g("player.repeat","Repeat")}: ${y[t]}`,style:{...vt,opacity:t==="none"?.4:1},children:m}),r.jsx("select",{value:n,onChange:x=>c(parseFloat(x.target.value)),title:g("player.speed","Speed"),"aria-label":g("player.speed","Speed"),style:{...vt,minWidth:56,fontSize:12},children:xh.map(x=>r.jsxs("option",{value:x,children:[x,"x"]},x))}),r.jsx("button",{onClick:h,title:g("player.mute","Mute"),"aria-label":g("player.mute","Mute"),style:{...vt,opacity:p?1:.6},children:p?r.jsx(O.NtdVolumeMute,{size:16}):r.jsx(O.NtdVolume,{size:16})}),a?r.jsxs("span",{style:{display:"flex",gap:4,alignItems:"center"},children:[r.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #64748b)"},children:["A: ",Ar(a.a)," — B: ",Ar(a.b)]}),r.jsx("button",{onClick:()=>d(null),title:g("player.clearLoop","Clear loop"),style:{...vt,fontSize:11,padding:"2px 6px"},children:r.jsx(O.NtdClose,{size:12})})]}):r.jsx("button",{onClick:()=>d({a:s,b:s+10}),title:g("player.abLoop","A-B Loop"),"aria-label":g("player.setAbLoop","Set A-B Loop"),style:{...vt,opacity:.4},children:"A-B"}),i!==null&&i>0&&r.jsxs("span",{style:{marginLeft:"auto",fontSize:11,color:"var(--nice-text-secondary, #64748b)",display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(O.NtdMoon,{size:12})," ",Math.floor(i/60),":",(i%60).toString().padStart(2,"0")]})]})};function Mh(e){if(!e)return;const t=e.match(/youtu\.be\/([A-Za-z0-9_-]{6,})/);if(t)return t[1];const n=e.match(/[?&]v=([A-Za-z0-9_-]{6,})/);if(n)return n[1]}function _o(e){const t={};if(!e)return t;const n=e.split(",");for(const a of n){const s=a.trim();s.startsWith("v=")?t.youtubeId=s.substring(2):s.startsWith("co=")?t.coverImage=s.substring(3):s.startsWith("bg=")&&(t.backgroundImage=s.substring(3))}return t}function Rh(e,t="/api/karaoke/cover"){var a,s;const n=((a=e.coverImage)==null?void 0:a.startsWith("http://"))||((s=e.coverImage)==null?void 0:s.startsWith("https://"));return e.coverImage&&n?e.coverImage:e.youtubeId?`https://img.youtube.com/vi/${e.youtubeId}/hqdefault.jpg`:e.coverImage?`${t}?filePath=${encodeURIComponent(e.coverImage)}`:"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='320' height='180'%3E%3Crect width='320' height='180' fill='%23333'/%3E%3Ctext x='160' y='95' text-anchor='middle' fill='%23999' font-size='16'%3ENo Cover%3C/text%3E%3C/svg%3E"}function Nh(e,t="/backgrounds"){return e.backgroundImage?`${t}/${e.backgroundImage}`:""}function zo(e,t,n=.01){let a=0;for(let o=0;o<e.length;o++)a+=e[o]*e[o];if(a=Math.sqrt(a/e.length),a<n)return 0;let s=-1,i=0;for(let o=20;o<e.length/2;o++){let l=0;for(let c=0;c<e.length/2;c++)l+=e[c]*e[c+o];l/=e.length/2,l>i&&(i=l,s=o)}return s>0?t/s:0}function Ka(e,t){const n=[];return e.forEach((a,s)=>{a.forEach((i,o)=>{n.push({startTime:i.startTime+t,duration:i.duration,pitch:i.pitch,isGold:i.isGold,line:s,idx:o})})}),n}function Do(e,t,n){const a=[];return e.forEach(s=>{var c;const[i,o]=s.noteKey.split("-").map(Number),l=(c=t[i])==null?void 0:c[o];l&&s.segments.forEach(d=>{a.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})})}),a}function Fo(e,t=120){let n=e;if(e.length>t){const a=e.length/t,s=[];for(let i=0;i<t;i++)s.push(e[Math.floor(i*a)]);n=s}return n.map(a=>({t:Math.round(a.t*1e3)/1e3,hz:Math.round(a.hz)}))}function Oo(e,t,n){const s=Date.parse(e)-n;return Math.max(0,Math.round(t-s))}const Bo={crepe:"var(--nice-accent, #a78bfa)",librosa:"var(--nice-success-light, #34d399)",pitchy:"var(--nice-primary-light, #60a5fa)",autocorr:"var(--nice-text-secondary, #555555)"};function Th(e){return e==="autocorr"?"Ultrastar":e.charAt(0).toUpperCase()+e.slice(1)}function Ph(e){return Bo[e]??"var(--nice-text-secondary, #555555)"}function $h(e){const t=Bo[e]??"var(--nice-text-secondary, #555555)";return`var(--algo-${e}, ${t})`}function Go(e,t){const n=!(t!=null&&t.includes("no-music")),a=t==null?void 0:t.includes("instrumental"),s=[];if(n){if(e.videoPath){let i=e.videoPath;if(i.startsWith("v=")){const o=_o(i);o.youtubeId&&(i=`https://www.youtube.com/watch?v=${o.youtubeId}`)}/youtu(\.be|be\.com)/i.test(i)?s.push({kind:"youtube",url:i}):/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(e.videoPath)&&s.push({kind:"audio",url:e.videoPath})}if(s.length===0){const i=a?e.instrumentalPath:e.audioPath;i&&/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(i)&&s.push({kind:"audio",url:i})}s.length===0&&e.youtubeId&&s.push({kind:"youtube",url:`https://www.youtube.com/watch?v=${e.youtubeId}`})}return{id:String(e.id??e.title??"song"),title:e.title??"—",artist:e.artist??"—",coverUrl:e.coverPath??void 0,sources:s}}function Eh(e){const t=e.videoPath??e.video??void 0;return{id:e.id,title:e.title??"",artist:e.artist??"",year:e.year,genre:e.genre,language:e.language,filePath:e.filePath,coverPath:e.coverPath,audioPath:e.audioPath??e.audio??void 0,videoPath:t,format:0,notes:e.notes??[],gap:e.gap,bpm:e.bpm,videoGap:e.videoGap,start:e.start,end:e.end,youtubeId:e.youtubeId,instrumentalPath:e.instrumentalPath,isVerified:e.isVerified,coverImage:e.coverImage,backgroundImage:e.backgroundImage}}var Ya=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(Ya||{});function Wo(e,t="song.txt"){const n=e.split(/\r?\n/),a={},s=[];for(const o of n){const l=o.replace(/\uFEFF/g,"");if(l.trim()){if(l.startsWith("#")){const c=l.indexOf(":");c>0&&(a[l.slice(1,c).trim().toUpperCase()]=l.slice(c+1).trim())}else if(/^[:*\-FG]/.test(l))s.push({noteLine:l});else if(l.trim()==="E")break}}const i=o=>{if(!o)return;const l=parseFloat(o.replace(",","."));return Number.isFinite(l)?l:void 0};return{title:a.TITLE||t.replace(/\.txt$/i,""),artist:a.ARTIST||"",format:Ya.Ultrastar,bpm:i(a.BPM),gap:i(a.GAP),genre:a.GENRE||void 0,language:a.LANGUAGE||void 0,year:a.YEAR||void 0,audioPath:a.MP3||void 0,videoPath:a.VIDEO||a.MP3||void 0,notes:s}}const Ah=e=>window.btoa(unescape(encodeURIComponent(e))),Vo=({onSongUpload:e,parseSong:t,onError:n,accept:a=".txt",maxFileSize:s=5*1024*1024,t:i})=>{const{t:o}=be(),l=i??o,c=h=>{const p=new FileReader;p.onload=async g=>{var m;if(!((m=g.target)!=null&&m.result))return;const y=g.target.result;try{const x=t?await t({fileName:h.name,data:Ah(y)}):Wo(y,h.name);e(x)}catch(x){n==null||n(x)}},p.readAsText(h,"UTF-8")},d=h=>/\.txt$/i.test(h.name)?h.size===0?l("karaokeUploader.empty","The file is empty."):null:l("karaokeUploader.notTxt","Please choose an UltraStar .txt file.");return r.jsx("div",{className:"nice-karaoke-uploader",children:r.jsx(ie.NiceUpload,{accept:a,maxFileSize:s,validateFile:d,multiple:!1,text:l("karaokeUploader.dropPrompt","Click or drag & drop an UltraStar file (.txt)"),onFilesSelected:h=>{const p=h[0];p&&c(p)}})})},Ih=[],Lh=[],_h=[],zh=[];function Dh(e,t,n,a,s){const o=a*.45;e.beginPath();for(let l=0;l<10;l++){const c=l%2===0?a:o,d=Math.PI/5*l-Math.PI/2,h=t+Math.cos(d)*c,p=n+Math.sin(d)*c;l===0?e.moveTo(h,p):e.lineTo(h,p)}e.closePath(),e.fillStyle=s,e.fill()}const Vt=60,Ws=4,Qr="#888",Vs=["A","B","X","Y","LB","RB","LT","RT"],Uo=({lanes:e=Ih,events:t=Lh,currentTime:n,activeLanes:a=_h,difficulty:s,feedbackQueue:i=zh,isPlaying:o,height:l=300})=>{const{t:c}=be(),d=e.length,h=u.useRef(null),p=u.useRef([]);return u.useEffect(()=>{p.current=i},[i]),u.useEffect(()=>{var N,$;const g=h.current;if(!g)return;const y=g.getContext("2d");if(!y)return;const m=window.devicePixelRatio||1,x=g.clientWidth,v=g.clientHeight;if(g.width=x*m,g.height=v*m,y.scale(m,m),y.clearRect(0,0,x,v),d===0)return;const f=x/d;for(let M=0;M<d;M++){const E=M*f;y.fillStyle=M%2===0?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",y.fillRect(E,0,f,v),M>0&&(y.strokeStyle="rgba(255,255,255,0.1)",y.lineWidth=1,y.beginPath(),y.moveTo(E,0),y.lineTo(E,v),y.stroke())}const k=v-Vt-10;y.strokeStyle="rgba(255,255,255,0.4)",y.lineWidth=2,y.setLineDash([8,4]),y.beginPath(),y.moveTo(0,k),y.lineTo(x,k),y.stroke(),y.setLineDash([]);const b=e.map(M=>we.resolveCssColor((M==null?void 0:M.color)??Qr,g)),w=(v-Vt-20)/Ws;for(const M of t){const E=M.note.startTime,R=E+M.note.duration,L=E-n;if(L>Ws||R<n-.5)continue;const A=M.lane,z=A*f+4,j=f-8,I=k-L*w,Y=M.note.duration*w,H=n>=E-.15&&n<=R+.15,D=n>R+.15,V=b[A]??Qr;D?y.fillStyle="rgba(100,100,100,0.3)":H?(y.fillStyle=V,y.shadowColor=V,y.shadowBlur=12):(y.fillStyle=V,y.globalAlpha=.6);const Z=Math.max(Y,8),X=6;y.beginPath(),y.moveTo(z+X,I),y.lineTo(z+j-X,I),y.quadraticCurveTo(z+j,I,z+j,I+X),y.lineTo(z+j,I+Z-X),y.quadraticCurveTo(z+j,I+Z,z+j-X,I+Z),y.lineTo(z+X,I+Z),y.quadraticCurveTo(z,I+Z,z,I+Z-X),y.lineTo(z,I+X),y.quadraticCurveTo(z,I,z+X,I),y.fill(),y.globalAlpha=1,y.shadowBlur=0,M.note.isGold&&Dh(y,z+j/2,I+Z/2,Math.min(7,j/4),"#fbbf24")}for(let M=0;M<d;M++){const E=M*f,R=v-Vt,L=a[M],A=b[M]??Qr;y.fillStyle=L?A:"rgba(30,30,30,0.9)",y.fillRect(E+2,R+2,f-4,Vt-4),y.strokeStyle=L?"#fff":A,y.lineWidth=L?3:1,y.strokeRect(E+2,R+2,f-4,Vt-4),y.fillStyle=L?"#000":"#fff",y.font=`bold ${Math.min(24,f*.3)}px monospace`,y.textAlign="center",y.textBaseline="middle",y.fillText(((N=e[M])==null?void 0:N.label)??"",E+f/2,R+Vt/2);const z=(($=e[M])==null?void 0:$.gamepadButton)??-1;z>=0&&z<Vs.length&&(y.fillStyle=L?"rgba(0,0,0,0.6)":"rgba(255,255,255,0.4)",y.font="10px sans-serif",y.fillText(Vs[z],E+f/2,R+Vt-8))}for(const M of p.current){const E=n-M.time;if(E<0||E>.8)continue;const R=Math.max(0,1-E/.8),L=M.lane*f;y.save(),y.globalAlpha=R,y.font="bold 20px sans-serif",y.textAlign="center",y.textBaseline="bottom",y.fillStyle=M.type==="perfect"?"#10b981":M.type==="good"?"#f59e0b":"#ef4444";const A=M.type==="perfect"?"PERFECT":M.type==="good"?"GOOD":"MISS";y.fillText(A,L+f/2,k-10-E*40),y.restore()}},[n,e,t,a,d,o]),!o||d===0?null:r.jsxs("div",{className:"nice-pad-karaoke-overlay",style:{position:"absolute",top:0,left:0,right:0,height:l,zIndex:35,pointerEvents:"none"},children:[r.jsx("canvas",{ref:h,role:"img","aria-label":c("padKaraokeOverlay.padKaraokeNoteHighwayHit","Pad karaoke note highway — hit notes in time with the music"),style:{width:"100%",height:"100%",display:"block"}}),r.jsxs("div",{style:{position:"absolute",top:8,right:12,background:"var(--nice-overlay-60, rgba(0,0,0,0.6))",color:"#fff",padding:"4px 12px",borderRadius:8,fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:1,display:"flex",alignItems:"center",gap:6},children:[r.jsx(O.NtdGamepad,{size:14})," PAD — ",s]})]})},In=["var(--player-color-1, #ef4444)","var(--player-color-2, #f59e0b)","var(--player-color-3, #10b981)","var(--player-color-4, #3b82f6)","var(--player-color-5, #8b5cf6)","var(--player-color-6, #ec4899)"],qo={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 ga(e){return 440*Math.pow(2,(e-69)/12)}function Ho(e,t){const n=qo[t],a=n.keys.length,s=[];for(const d of e)for(const h of d)s.includes(h.pitch)||s.push(h.pitch);if(s.sort((d,h)=>d-h),s.length===0)return n.keys.map((d,h)=>({index:h,key:d,gamepadButton:n.buttons[h],label:n.labels[h],minPitch:-999,maxPitch:999,color:In[h%In.length]}));const i=s[0],l=s[s.length-1]-i+1,c=[];for(let d=0;d<a;d++){const h=i+Math.floor(l*d/a),p=i+Math.floor(l*(d+1)/a)-1;c.push({index:d,key:n.keys[d],gamepadButton:n.buttons[d],label:n.labels[d],minPitch:d===0?-999:h,maxPitch:d===a-1?999:p,color:In[d%In.length]})}return c}function Ko(e,t){for(const s of t)if(e>=s.minPitch&&e<=s.maxPitch)return s.index;let n=0,a=1/0;for(const s of t){const i=(s.minPitch+s.maxPitch)/2,o=Math.abs(e-i);o<a&&(a=o,n=s.index)}return n}function Yo(e,t,n){const a=[];for(let s=0;s<e.length;s++)for(let i=0;i<e[s].length;i++){const o={...e[s][i]};o.startTime+=n,a.push({note:o,lane:Ko(o.pitch,t),lineIndex:s,noteIndex:i})}return a.sort((s,i)=>s.note.startTime-i.note.startTime),a}class Zo{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,p,g,y,m,x;if(!this.running)return;const s=this.getCurrentTime();this.pollGamepad();const i=this.getActiveLanes();(d=(c=this.config).onLaneActive)==null||d.call(c,i);const o=this.findActiveNote(s);if(o!==this.lastActiveNote&&(this.lastActiveNote=o,(p=(h=this.config).onCurrentNote)==null||p.call(h,o)),i.some(Boolean)&&o){const v=o.lane,f=i.indexOf(!0);if(i[v]){const k=ga(o.note.pitch);this.config.onPitch(k),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(y=(g=this.config).onHitFeedback)==null||y.call(g,{type:"perfect",lane:v,time:s}))}else if(f>=0){const b=Math.abs(f-v)*3,w=ga(o.note.pitch+b);this.config.onPitch(w),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(x=(m=this.config).onHitFeedback)==null||x.call(m,{type:"miss",lane:f,time:s}))}}this.raf=requestAnimationFrame(this.loop)},this.config=t;const n=Hn(t.noteLines,t.bpm),a=(t.gap??0)/1e3;switch(this.lanes=Ho(n,t.difficulty),this.events=Yo(n,this.lanes,a),t.difficulty){case"easy":this.preWindow=.25,this.postWindow=.25;break;case"normal":this.preWindow=.15,this.postWindow=.15;break;case"hard":this.preWindow=.08,this.postWindow=.08;break}}getLanes(){return this.lanes}getEvents(){return this.events}start(t){this.running||(this.running=!0,this.getCurrentTime=t,this.handleKeyDown=this.handleKeyDown.bind(this),this.handleKeyUp=this.handleKeyUp.bind(this),window.addEventListener("keydown",this.handleKeyDown),window.addEventListener("keyup",this.handleKeyUp),this.loop())}stop(){this.running=!1,this.raf&&(cancelAnimationFrame(this.raf),this.raf=null),window.removeEventListener("keydown",this.handleKeyDown),window.removeEventListener("keyup",this.handleKeyUp),this.keysDown.clear(),this.gamepadButtonsDown.clear()}handleKeyDown(t){var a;const n=(a=t.target)==null?void 0:a.tagName;n&&["INPUT","TEXTAREA","SELECT"].includes(n)||this.keysDown.add(t.key.toLowerCase())}handleKeyUp(t){this.keysDown.delete(t.key.toLowerCase())}pollGamepad(){var a;const t=navigator.getGamepads?Array.from(navigator.getGamepads()).filter(Boolean):[];if(!t.length)return;const n=t[0];if(n){this.gamepadButtonsDown.clear();for(let s=0;s<n.buttons.length;s++)(a=n.buttons[s])!=null&&a.pressed&&this.gamepadButtonsDown.add(s)}}getActiveLanes(){const t=new Array(this.lanes.length).fill(!1);for(const n of this.lanes)(this.keysDown.has(n.key)||this.gamepadButtonsDown.has(n.gamepadButton))&&(t[n.index]=!0);return t}findActiveNote(t){for(const n of this.events){const a=n.note.startTime-this.preWindow,s=n.note.startTime+n.note.duration+this.postWindow;if(t>=a&&t<=s)return n}return null}}const mt=ot.scoped("BaseStreamClient");function Us(e,t,n){if(t===n)return e.slice();const a=Math.round(e.length*n/t),s=new Float32Array(a),i=e.length/a;for(let o=0;o<a;o++){const l=o*i,c=Math.floor(l),d=Math.min(e.length-1,c+1),h=l-c;s[o]=e[c]*(1-h)+e[d]*h}return s}function Fh(e){const t=new Int16Array(e.length);for(let n=0;n<e.length;n++){const a=Math.max(-1,Math.min(1,e[n]));t[n]=a<0?Math.round(a*32768):Math.round(a*32767)}return t}const Sn=16e3,Oh="/scripts/pitch-worklet.js";class Xo{constructor(t){this.sendQueue=[],this.maxQueue=20,this.reconnectAttempts=0,this.maxReconnectAttempts=3,this.buffer=new Float32Array(0),this.externalStream=!1,this.usingWorklet=!1,this.closed=!1,this.started=!1,this.chunksSent=0,this.chunksDropped=0,this.responsesReceived=0,this.lastStatusLog=0,this.opts=t}onMaxReconnect(){var t,n;try{(n=(t=this.opts).onMaxReconnect)==null||n.call(t)}catch{}this.stopAudioNodes()}get useWorklet(){return!0}get workletPath(){return Oh}ts(){return new Date().toISOString().slice(11,23)}connectWs(){this.ws&&this.ws.readyState!==WebSocket.CLOSING&&this.ws.readyState!==WebSocket.CLOSED||(mt.info(`[${this.ts()}] connecting to ${this.opts.wsUrl}`),this.ws=new WebSocket(this.opts.wsUrl),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{var t,n,a,s,i,o;try{(n=(t=this.opts).onOpen)==null||n.call(t)}catch{}if(this.reconnectAttempts=0,this.chunksSent=0,this.chunksDropped=0,this.responsesReceived=0,mt.info(`[${this.ts()}] ws OPEN | worklet=${this.usingWorklet}`),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.sendQueue.length){const l=this.sendQueue.length;try{for(const c of this.sendQueue)try{this.ws.send(c),this.chunksSent++,(s=(a=this.opts).onSend)==null||s.call(a,c.byteLength)}catch(d){(o=(i=this.opts).onError)==null||o.call(i,d);break}}finally{this.sendQueue=[]}mt.info(`[${this.ts()}] flushed ${l} queued chunks`)}},this.ws.onclose=t=>{var n,a;try{(a=(n=this.opts).onClose)==null||a.call(n,t)}catch{}if(mt.info(`[${this.ts()}] ws CLOSE code=${t.code} clean=${t.wasClean} | sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived}`),this.sendQueue=[],this.ws=void 0,!this.closed&&this.started)if(this.reconnectAttempts++,this.reconnectAttempts<=this.maxReconnectAttempts){const s=Math.min(300*Math.pow(1.5,this.reconnectAttempts-1),5e3);mt.info(`[${this.ts()}] auto-reconnect #${this.reconnectAttempts} in ${s.toFixed(0)}ms`),this.reconnectTimer=setTimeout(()=>{this.closed||this.connectWs()},s)}else mt.warn(`[${this.ts()}] max reconnect attempts reached`),this.onMaxReconnect();else this.stopAudioNodes()},this.ws.onerror=t=>{var n,a;mt.warn(`[${this.ts()}] ws ERROR`,t);try{(a=(n=this.opts).onError)==null||a.call(n,t)}catch{}},this.ws.onmessage=t=>{var n,a;this.responsesReceived++;try{const s=typeof t.data=="string"?t.data:new TextDecoder().decode(t.data);this.handleWsMessage(s)}catch(s){(a=(n=this.opts).onError)==null||a.call(n,s)}})}handleAudioFrame(t){var g,y,m,x,v,f,k,b;const n=new Float32Array(this.buffer.length+t.length);n.set(this.buffer,0),n.set(t,this.buffer.length),this.buffer=n;const a=this.audioCtx.sampleRate,s=Math.round((this.opts.chunkMs??200)*Sn/1e3),i=Math.floor(this.buffer.length*Sn/a),o=Math.floor(i/s);if(o<=0)return;const l=o*s,c=Math.floor(l*a/Sn),d=this.buffer.slice(0,c);this.buffer=this.buffer.slice(c);const h=Us(d,a,Sn);let p=0;for(;p+s<=h.length;){const w=h.subarray(p,p+s),$=Fh(w).buffer,M=this.ws;if(M&&M.readyState===WebSocket.OPEN)try{M.send($),this.chunksSent++,(y=(g=this.opts).onSend)==null||y.call(g,$.byteLength)}catch(R){(x=(m=this.opts).onError)==null||x.call(m,R)}else M&&M.readyState===WebSocket.CONNECTING?this.sendQueue.length<this.maxQueue&&(this.sendQueue.push($),(f=(v=this.opts).onSend)==null||f.call(v,0)):(this.chunksDropped++,(b=(k=this.opts).onSend)==null||b.call(k,0));const E=Date.now();E-this.lastStatusLog>5e3&&(this.lastStatusLog=E,mt.info(`[${this.ts()}] STATUS: sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived} ws=${(M==null?void 0:M.readyState)??"none"} worklet=${this.usingWorklet}`)),p+=s}if(p<h.length){const w=h.subarray(p),N=Us(w,Sn,a),$=new Float32Array(N.length+this.buffer.length);$.set(N,0),$.set(this.buffer,N.length),this.buffer=$}}async setupAudioNodes(t){if(this.useWorklet)try{await this.audioCtx.audioWorklet.addModule(this.workletPath);const a=new AudioWorkletNode(this.audioCtx,"pitch-processor");a.port.onmessage=s=>{this.handleAudioFrame(s.data)},t.connect(a),a.connect(this.audioCtx.destination),this.workletNode=a,this.usingWorklet=!0,mt.info(`[${this.ts()}] using AudioWorklet (pitch-processor)`);return}catch(a){mt.warn(`[${this.ts()}] AudioWorklet unavailable, falling back to ScriptProcessorNode`,a)}const n=4096;this.proc=this.audioCtx.createScriptProcessor(n,1,1),t.connect(this.proc),this.proc.connect(this.audioCtx.destination),this.proc.onaudioprocess=a=>{this.handleAudioFrame(a.inputBuffer.getChannelData(0))},this.usingWorklet=!1,mt.info(`[${this.ts()}] using ScriptProcessorNode fallback`)}stopAudioNodes(){try{this.workletNode&&(this.workletNode.port.close(),this.workletNode.disconnect(),this.workletNode=void 0)}catch{}try{this.proc&&(this.proc.onaudioprocess=null,this.proc.disconnect(),this.proc=void 0)}catch{}}async start(){if(this.closed)throw new Error("client closed");if(this.started)return;this.started=!0,(!this.ws||this.ws.readyState===WebSocket.CLOSED)&&this.connectWs(),this.mediaStream||(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:!0})),this.audioCtx=new AudioContext;const t=this.audioCtx.createMediaStreamSource(this.mediaStream);await this.setupAudioNodes(t)}async startWithMediaStream(t){if(this.closed)throw new Error("client closed");if(this.started)return;this.started=!0,this.externalStream=!0,(!this.ws||this.ws.readyState===WebSocket.CLOSED)&&this.connectWs(),this.mediaStream=t,this.audioCtx=new AudioContext;const n=this.audioCtx.createMediaStreamSource(this.mediaStream);await this.setupAudioNodes(n)}stop(){var t,n;if(mt.info(`[${this.ts()}] stop() called | closed=${this.closed} started=${this.started} sent=${this.chunksSent} responses=${this.responsesReceived}`),this.closed=!0,this.started=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.stopAudioNodes(),this.audioCtx&&this.audioCtx.state!=="closed"&&this.audioCtx.close().catch(()=>{}),!this.externalStream)try{(t=this.mediaStream)==null||t.getTracks().forEach(a=>a.stop())}catch{}try{(n=this.ws)==null||n.close()}catch{}this.ws=void 0,this.sendQueue=[]}}const Bh=ot.scoped("CrepeStreaming");class Gh extends Xo{constructor(t){super({...t,chunkMs:t.chunkMs??200}),this.crepeOpts=t}get tag(){return"CrepeStreamClient"}handleWsMessage(t){var a,s;const n=JSON.parse(t);(s=(a=this.crepeOpts).onMessage)==null||s.call(a,n)}onMaxReconnect(){var t,n;Bh.warn(`[${this.tag}] [${this.ts()}] triggering fallback`),this.stopAudioNodes();try{(n=(t=this.crepeOpts).onFallback)==null||n.call(t)}catch{}}}class Wh extends Xo{constructor(t){super({...t,chunkMs:t.chunkMs??100}),this.librosaOpts=t}get tag(){return"LibrosaStreamClient"}handleWsMessage(t){var a,s;const n=JSON.parse(t);(s=(a=this.librosaOpts).onMessage)==null||s.call(a,n)}get useWorklet(){return!1}}const Lt={debug:(...e)=>{},warn:(...e)=>{typeof console<"u"&&console.warn("[KaraokePitch]",...e)}};function Vh(e){const t=new Float32Array(e);for(let n=0;n<e;n++)t[n]=.5*(1-Math.cos(2*Math.PI*n/(e-1)));return t}function Uh(e,t){const n=new Float32Array(e.length);for(let a=0;a<e.length;a++)n[a]=e[a]*t[a];return n}function Qo({isPlaying:e,gameMode:t,players:n,playersMicKey:a,micAlgorithms:s={},defaultPitchAlgorithm:i="pitchy",micRmsThresholds:o={},micOffsets:l={},micGains:c={},micPitchThresholds:d={},micSmoothingWindows:h={},micHysteresisFrames:p={},micUseHanning:g={},micMonitorEnabled:y={},micMonitorVolumes:m={},currentTimeRef:x,isPadMode:v,clockOffsetMsRef:f,currentPartyIdRef:k,rtc:b}){const[w,N]=u.useState({}),$=u.useRef({}),M=u.useRef({}),[E,R]=u.useState({}),L=u.useRef({}),A=u.useRef([]),z=u.useRef(null),j=u.useRef(null),[,I]=u.useState({}),[,Y]=u.useState({}),[,H]=u.useState({}),[D,V]=u.useState({}),[Z,X]=u.useState(!0),[q,G]=u.useState(!1),C=u.useRef(n);C.current=n;const T=u.useRef(0),S=u.useRef(performance.now());return u.useEffect(()=>{A.current.forEach(_=>_()),A.current=[];const F={current:!1};function K(_,U,J=0){x.current!==T.current&&(T.current=x.current,S.current=performance.now());const se=Math.min(.25,(performance.now()-S.current)/1e3),oe=x.current+se-J/1e3;N(W=>{const ee=W[_]||[];return{...W,[_]:[...ee,{t:oe,hz:U}]}}),$.current[_]=($.current[_]||[]).concat({t:oe,hz:U});const re=$.current[_];re.length>500&&($.current[_]=re.slice(-500))}function P(_,U,J,se=.02,oe=0,re=.6,W=0,ee=0,ae=0,le=!1){let ce=null,te=null,he=null;return(async()=>{try{ce=new AudioContext;let pe=ce.createMediaStreamSource(U);if(W>0){const ye=ce.createGain();ye.gain.value=W,pe.connect(ye),pe=ye}const Se=ce.createAnalyser();Se.fftSize=2048,pe.connect(Se);const je=new Float32Array(Se.fftSize),$e=le?Vh(Se.fftSize):null,Te=[];let He=0;if(J==="pitchy")try{const{PitchDetector:ye}=await import("pitchy");he=ye.forFloat32Array(Se.fftSize)}catch(ye){Lt.warn("pitchy import failed, falling back to autocorrelation",ye)}const de=()=>{try{Se.getFloatTimeDomainData(je)}catch{}const ye=$e?Uh(je,$e):je;let Ee=0;for(let Ie=0;Ie<ye.length;Ie++)Ee+=ye[Ie]*ye[Ie];Ee=Math.sqrt(Ee/ye.length);let Me=0;if(Ee>=se)if(he)try{const[Ie,tt]=he.findPitch(ye,ce.sampleRate);Ie>50&&Ie<3e3&&tt>re&&(Me=Ie)}catch{}else Me=zo(ye,ce.sampleRate,se),(Me<50||Me>3e3)&&(Me=0);if(Me>0&&ee>1&&(Te.push(Me),Te.length>ee&&Te.shift(),Me=Te.reduce((Ie,tt)=>Ie+tt,0)/Te.length),Me>0)He=0,K(_,Me,oe);else if(He++,ae>0&&He<=ae&&Te.length>0){const Ie=Te[Te.length-1];Ie>0&&K(_,Ie,oe)}te=requestAnimationFrame(de),L.current[_]=te};de()}catch(xe){Lt.warn("startLocalPitch error",xe)}})(),()=>{te&&cancelAnimationFrame(te),ce&&ce.close().catch(()=>{})}}function B(_,U,J,se=0){J==="crepe"&&j.current?(j.current.stop(),j.current=null):J==="librosa"&&z.current&&(z.current.stop(),z.current=null);const oe=window.location,re=oe.protocol==="https:"?"wss:":"ws:",W=J==="librosa"?`${re}//${oe.host}/api/librosa/ws/pyin`:`${re}//${oe.host}/api/ai/audio/pitch/ws/pitch_server`,ee=J==="librosa"?I:Y;ee(he=>({...he,[_]:"connecting"}));const ae=[],le=he=>{if(he>0){for(ae.push(x.current);ae.length>200;)ae.shift();J==="crepe"&&H(ue=>({...ue,[_]:(ue[_]||0)+1}))}},ce=()=>{ee(he=>({...he,[_]:"closed"})),ae.length=0},te=he=>{if(typeof he.hz=="number"&&he.hz>0){const ue=he.hz,pe=(ae.length>0?ae.shift():x.current)-se/1e3;N(Se=>{const je=Se[_]||[];return{...Se,[_]:[...je,{t:pe,hz:ue}]}})}else ae.length>0&&ae.shift()};if(J==="librosa"){const he=new Wh({wsUrl:W,onOpen:()=>ee(ue=>({...ue,[_]:"connected"})),onClose:ce,onError:ue=>{ee(xe=>({...xe,[_]:"error"})),Lt.warn("Librosa WS error",ue)},onMessage:te,onSend:le});return z.current=he,he.startWithMediaStream(U).catch(ue=>{Lt.warn("Librosa client start failed",ue),ee(xe=>({...xe,[_]:"failed"}))}),()=>{he.stop(),z.current=null,ee(ue=>({...ue,[_]:""}))}}else{const he=new Gh({wsUrl:W,onOpen:()=>ee(ue=>({...ue,[_]:"connected"})),onClose:ce,onError:ue=>{ee(xe=>({...xe,[_]:"error"})),Lt.warn("Crepe WS error",ue)},onMessage:te,onSend:le,onFallback:()=>{ee(xe=>({...xe,[_]:"fallback-pitchy"})),j.current=null;const ue=P(_,U,"pitchy",.02,se);A.current.push(ue)}});return j.current=he,he.startWithMediaStream(U).catch(ue=>{Lt.warn("Crepe client start failed",ue),ee(xe=>({...xe,[_]:"failed"}))}),()=>{he.stop(),j.current=null,ee(ue=>({...ue,[_]:""}))}}}if(e){if(N({}),t!=="pad"){const _={};C.current.forEach(U=>{if(!U.micId)return;const J=s[U.id]||i,se=U.micId&&o[U.micId]||.02,oe=U.micId&&l[U.micId]||0,re=U.micId&&c[U.micId]||0,W=U.micId&&d[U.micId]||.6,ee=U.micId&&h[U.micId]||0,ae=U.micId&&p[U.micId]||0,le=U.micId&&g[U.micId]||!1,ce=U.micId&&y[U.micId]||!1,te=(U.micId?m[U.micId]:void 0)??100,he=new La;he.startRecording({deviceId:U.micId,onLevel:()=>{},gain:re,monitorEnabled:ce,monitorVolume:te}).then(()=>{if(F.current){he.stopRecording().catch(()=>{});return}_[U.id]=he;const ue=he.getStream();if(!ue){Lt.warn(`No stream from recorder for player ${U.id}`);return}if(J==="librosa"||J==="crepe"){const xe=B(U.id,ue,J,oe);A.current.push(xe)}else{const xe=P(U.id,ue,J,se,oe,W,re,ee,ae,le);A.current.push(xe)}}).catch(ue=>Lt.warn(`recorder start failed for player ${U.id}`,ue))}),M.current=_}}else{const _=M.current,U=Object.keys(_).map(Number);Promise.allSettled(U.map(async J=>{const se=await _[J].stopRecording();return{pid:J,blob:se}})).then(J=>{const se={};for(const oe of J)oe.status==="fulfilled"&&oe.value.blob&&(se[oe.value.pid]=oe.value.blob);Object.keys(se).length>0&&R(oe=>({...oe,...se}))}),M.current={},Object.values(L.current).forEach(J=>J&&cancelAnimationFrame(J)),L.current={}}return()=>{F.current=!0,A.current.forEach(_=>_()),A.current=[],Object.values(M.current).forEach(_=>_.stopRecording().catch(()=>{})),M.current={},Object.values(L.current).forEach(_=>_&&cancelAnimationFrame(_)),L.current={}}},[e,t,a,s,i,o,l,c,d,h,p,g,y,m]),u.useEffect(()=>{if(!b)return;const F=300,K=async()=>{try{const B={...$.current};for(const _ of Object.keys(B)){const U=Number(_),J=B[U]||[];if(!J||J.length===0)continue;$.current[U]=[];const se=Fo(J,120),oe={playerId:U,points:se,clientNowUtc:new Date().toISOString(),quantized:!0};k!=null&&k.current&&(oe.EventId=k.current);try{b.isConnected()&&await b.publishTimelineUpdate(oe)}catch(re){Lt.warn("failed to publish timeline update, will retry",re),$.current[U]=($.current[U]||[]).concat(J).slice(-1e3)}}}catch{}},P=window.setInterval(K,F);return()=>{P&&window.clearInterval(P)}},[b,k]),u.useEffect(()=>{if(!b)return;const F=K=>{try{const P=K;if(!P||typeof P.playerId>"u"||!Array.isArray(P.points))return;const B=Number(P.playerId),_=P.points.map(U=>({t:U.t,hz:U.hz}));if(!_.length)return;if(P.serverTimeUtc){const U=Oo(P.serverTimeUtc,Date.now(),(f==null?void 0:f.current)||0);V(J=>({...J,[B]:U}))}N(U=>{const J=U[B]||[];return{...U,[B]:[...J,..._]}})}catch{}};return b.onTimelineUpdate(F),()=>b.offTimelineUpdate(F)},[b,f]),{livePitch:w,setLivePitch:N,recordings:E,recordersRef:M,unsentPitchRef:$,pitchCleanupsRef:A,remoteLatencyMs:D,showRemoteTimelines:Z,setShowRemoteTimelines:X,compactTimelines:q,setCompactTimelines:G}}function Jo(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function el(e){return e>=50?3:e>=30?2.5:e>=20?2:e>=10?1.5:1}function tl(e,t,n){const{semitoneTolerance:a,preWindow:s,postExtra:i}=n,o=n.segMs??.25,l=typeof n.completionBonusFactor=="number"?n.completionBonusFactor:.15,c=typeof n.goldFullBonusFactor=="number"?n.goldFullBonusFactor:.3,d=typeof n.difficultyMult=="number"?n.difficultyMult:1,h=!!n.disableGoldNotes;let p=0,g=0,y=0;const m=[];let x=0,v=0,f=0;const k=new Map;e.forEach((R,L)=>{const A=R.startTime,z=R.startTime+R.duration,j=A-s,I=z+i,Y=t.filter(C=>C.t>=j&&C.t<=I&&C.hz>0);if(!Y||Y.length===0)return;const H=Math.max(1,Math.ceil((R.duration||.25)/o)),D=Math.max(10,Math.round(100*(R.duration||1))),V=Math.max(1,Math.round(D/H));let Z=0;const X=[];for(let C=0;C<H;C++){const T=A+C*(R.duration/H),S=A+(C+1)*(R.duration/H),F=Math.min(.06,R.duration/H*.2),K=T-F,P=S+F,B=t.filter(re=>re.t>=K&&re.t<=P&&re.hz>0);if(!B||B.length===0)continue;let _=0;B.forEach(re=>{let ee=((12*Math.log2(re.hz/440)+69)%12+12)%12;for(;ee-R.pitch>6;)ee-=12;for(;ee-R.pitch<-6;)ee+=12;const ae=Math.abs(ee-R.pitch);_+=ae});const U=_/B.length;let J=0;if(a<=0)J=U===0?1:0;else{const re=a*2;J=Math.max(0,1-Math.min(U/re,1))}if(J<=0)continue;const se=!h&&R.isGold?2:1,oe=Math.round(V*se*J);oe>0&&(p+=oe,Z+=oe,X.push({segIndex:C,frac:J,add:oe,segStart:K,segEnd:P,visualStart:T,visualEnd:S}))}const q=R.line??0;k.has(q)||k.set(q,{total:0,hit:0,comboBonus:0});const G=k.get(q);if(G.total++,Z>0){x++,x>v&&(v=x),G.hit++;const C=el(x),T=C>1?Math.round(Z*(C-1)):0;f+=T,G.comboBonus+=T;const S=Math.max(1,Math.ceil((R.duration||.25)/o)),K=X.length>=S,P=K?Math.round(Math.max(10,Math.round(100*(R.duration||1)))*l*(!h&&R.isGold?1.5:1)*d):0,B=K&&!h&&R.isGold?Math.round(Math.max(10,Math.round(100*(R.duration||1)))*c*d):0;g+=P,y+=B,m.push({noteKey:`${R.line??0}-${R.idx??0}`,segments:X,totalAdded:Z,completed:K,completionBonus:P,goldFullBonus:B})}else x=0});const b=[];for(const[R,L]of k.entries()){const A=L.total>0?L.hit/L.total:0;b.push({verseIndex:R,hitFraction:A,label:Jo(A),comboBonus:L.comboBonus})}const w={maxCombo:v,currentCombo:0,totalComboBonus:f},N=f+g+y,$=m.length,M=m.filter(R=>R.completed).length,E={hits:$,misses:e.length-$,good:$-M,perfect:M,maxCombo:v};return{classicScore:p,bonusScore:N,totalScore:p+N,perNote:m,combo:w,verseRatings:b,noteStats:E}}function nl(e,t){let n=0;for(const a of e){const s=Math.max(10,Math.round(100*(a.duration||1))),i=!t&&a.isGold?2:1;n+=s*i}return n}function rl(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function al(e,t,n){const a=nl(t,n);if(a<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0};const s=rl(e.classicScore,a),i=Math.round(e.bonusScore/a*1e4);return{...e,classicScore:s,bonusScore:i,totalScore:s+i}}const kn={maxCombo:0,currentCombo:0,totalComboBonus:0},qs={hits:0,misses:0,good:0,perfect:0,maxCombo:0};function sl({livePitch:e,uploadedSong:t,isPlaying:n,difficulty:a,players:s,isPadMode:i}){const[o,l]=u.useState(0),[c,d]=u.useState(0),[h,p]=u.useState(0),[g,y]=u.useState([]),[m,x]=u.useState(kn),[v,f]=u.useState([]),[k,b]=u.useState([]),[w,N]=u.useState({}),[$,M]=u.useState({}),[E,R]=u.useState({}),[L,A]=u.useState({}),[z,j]=u.useState({});return u.useEffect(()=>{if(!t||!n)return;const I=Hn(t.notes.map(B=>B.noteLine),t.bpm??void 0),Y=(t.gap??0)/1e3,H=Ka(I,Y),D=zr(a),V=[];let Z=null,X=null,q=null,G=[];const C={},T={},S={},F={},K={},P=i?s[0]:s.find(B=>!!B.micId)||s[0];for(let B=0;B<s.length;B++){const _=s[B],U=(_==null?void 0:_.id)!=null?e[_.id]||[]:[];if(U.length===0){V.push({id:_.id,name:_.name||`Player ${_.id}`,color:_.color||et[B%et.length],classicScore:0,bonusScore:0,totalScore:0}),C[_.id]=[],T[_.id]={...kn},S[_.id]=[],F[_.id]=0,K[_.id]={...qs};continue}const J=Ua(_.id),se=!!(J!=null&&J.disableGoldNotes),oe=tl(H,U,{semitoneTolerance:D.semitoneTolerance,preWindow:D.preWindow,postExtra:D.postExtra,difficultyMult:D.difficultyMult,disableGoldNotes:se}),re=al(oe,H,se);V.push({id:_.id,name:_.name||`Player ${_.id}`,color:_.color||et[B%et.length],classicScore:re.classicScore,bonusScore:re.bonusScore,totalScore:re.totalScore}),C[_.id]=Do(oe.perNote,I,Y),T[_.id]=oe.combo??{...kn},S[_.id]=oe.verseRatings??[],F[_.id]=re.totalScore,K[_.id]=oe.noteStats??{...qs},_.id===(P==null?void 0:P.id)&&(Z=re,X=oe.combo??null,q=oe.verseRatings??null,G=C[_.id])}b(V),N(C),M(T),R(S),A(F),j(K),Z?(l(Z.classicScore),d(Z.bonusScore),p(Z.totalScore),y(G),x(X??kn),f(q??[])):(l(0),d(0),p(0),y([]),x(kn),f([]))},[e,t,n,a,s,i]),{liveScore:o,liveBonusScore:c,liveTotalScore:h,liveSegmentScores:g,liveCombo:m,liveVerseRatings:v,perPlayerScores:k,perPlayerSegmentScores:w,perPlayerCombo:$,perPlayerVerseRatings:E,perPlayerTotalScores:L,perPlayerNoteStats:z}}const qh=[],Hh=e=>!!e&&/youtu(\.be|be\.com)/i.test(e),Kh=({players:e=qh,song:t,initialSong:n=null,difficulty:a="normal",gameMode:s="normal",height:i=480,showTimelines:o=!0,showLyrics:l=!0,singleTimeline:c=!1,requestMicPermission:d=!0,initiallyActivated:h=!1,showUploader:p=!1,parseSong:g,micAlgorithms:y,defaultPitchAlgorithm:m="pitchy",micRmsThresholds:x,micOffsets:v,micGains:f,micPitchThresholds:k,micSmoothingWindows:b,micHysteresisFrames:w,micUseHanning:N,micMonitorEnabled:$,micMonitorVolumes:M,searchYouTubeByArtistTitle:E,fetchTopSingings:R,onSaveResults:L,rtc:A,onSongChange:z,onPlayingChange:j,onTimeUpdate:I,onEnded:Y,onContinue:H,renderReport:D,t:V,className:Z,style:X,id:q,accessMode:G,"data-testid":C})=>{var Fe;const{t:T}=be(),S=V??T,[F,K]=u.useState(t??n??null),[P,B]=u.useState(!1),[_,U]=u.useState(0),[J,se]=u.useState(h),[oe,re]=u.useState(!1),[W,ee]=u.useState([]),[ae,le]=u.useState(""),[ce,te]=u.useState(null),[he,ue]=u.useState(0),xe=s==="pad",[pe,Se]=u.useState([]),[je,$e]=u.useState([]),[Te,He]=u.useState([]),[de,ye]=u.useState([]),Ee=u.useRef(null),Me=u.useRef(null),Ie=u.useRef(null),tt=u.useRef(!1),Ye=u.useRef(0);u.useEffect(()=>{Ye.current=_},[_]);const Ze=u.useRef(t);u.useEffect(()=>{t!==void 0&&t!==Ze.current&&(Ze.current=t,K(t),re(!1),U(0),ue(ve=>ve+1))},[t]);const Ct=u.useMemo(()=>JSON.stringify(e.map(ve=>({id:ve.id,micId:ve.micId}))),[e]),{livePitch:dt,setLivePitch:$t,recordings:pt,remoteLatencyMs:Xt}=Qo({isPlaying:P,gameMode:s,players:e,playersMicKey:Ct,micAlgorithms:y,defaultPitchAlgorithm:m,micRmsThresholds:x,micOffsets:v,micGains:f,micPitchThresholds:k,micSmoothingWindows:b,micHysteresisFrames:w,micUseHanning:N,micMonitorEnabled:$,micMonitorVolumes:M,currentTimeRef:Ye,isPadMode:xe,rtc:A}),fe=sl({livePitch:dt,uploadedSong:F,isPlaying:P,difficulty:a,players:e,isPadMode:xe}),Ce=u.useRef(fe);Ce.current=fe;const Be=u.useMemo(()=>F?Go(F,s):null,[F,s]),ge=((Fe=e[0])==null?void 0:Fe.id)??1;u.useEffect(()=>{var Ne;if(!xe||!P||!F){(Ne=Ee.current)==null||Ne.stop(),Ee.current=null,Se([]),$e([]),He([]),ye([]);return}const ve=new Zo({difficulty:a,noteLines:F.notes.map(Ae=>Ae.noteLine),bpm:F.bpm??void 0,gap:F.gap??0,onPitch:Ae=>{const Ve=Ye.current;$t(De=>{const rt=De[ge]||[];return{...De,[ge]:[...rt,{t:Ve,hz:Ae}]}})},onHitFeedback:Ae=>ye(Ve=>[...Ve.slice(-20),Ae]),onLaneActive:Ae=>He(Ae)});return Se(ve.getLanes()),$e(ve.getEvents()),He(new Array(ve.getLanes().length).fill(!1)),ve.start(()=>Ye.current),Ee.current=ve,()=>{ve.stop(),Ee.current=null}},[xe,P,F,a,ge,$t]);const ke=u.useCallback(ve=>{B(ve),j==null||j(ve)},[j]),We=u.useCallback(ve=>{U(ve),I==null||I(ve)},[I]),_e=u.useCallback(()=>{var Ne;try{Yt()}catch{}const ve=()=>{se(!0),tt.current=!0};!xe&&d&&((Ne=navigator.mediaDevices)!=null&&Ne.getUserMedia)?navigator.mediaDevices.getUserMedia({audio:!0}).then(Ae=>Ae.getTracks().forEach(Ve=>Ve.stop())).catch(()=>{}).finally(ve):ve()},[xe,d]);u.useEffect(()=>{if(!J||!tt.current)return;tt.current=!1;const ve=window.setInterval(()=>{Me.current&&(window.clearInterval(ve),Me.current.play())},100),Ne=window.setTimeout(()=>window.clearInterval(ve),3e3);return()=>{window.clearInterval(ve),window.clearTimeout(Ne)}},[J]);const Pe=u.useCallback(()=>{re(!0),Y==null||Y();const ve=(F==null?void 0:F.id)??0,Ne=Ce.current,Ae=[];for(const De of e){const rt=Ne.perPlayerTotalScores[De.id]??0;if(rt<=0)continue;const Xe=Ne.perPlayerNoteStats[De.id];Ae.push({playerId:De.id,songId:ve,score:rt,hits:(Xe==null?void 0:Xe.hits)??0,misses:(Xe==null?void 0:Xe.misses)??0,good:(Xe==null?void 0:Xe.good)??0,perfect:(Xe==null?void 0:Xe.perfect)??0,combo:(Xe==null?void 0:Xe.maxCombo)??0})}const Ve=()=>{R&&ve>0&&Promise.resolve(R(ve)).then(ee).catch(()=>{})};L&&Ae.length>0?Promise.resolve(L(Ae)).then(Ve).catch(Ve):Ve()},[e,F,L,R,Y]);u.useEffect(()=>{var ve;s==="demo"&&P&&_>=12&&((ve=Me.current)==null||ve.pause(),Pe())},[s,P,_,Pe]),u.useEffect(()=>{if(!F||he===0||!E||Hh(F.videoPath))return;if(F.youtubeId){const Ne=`https://www.youtube.com/watch?v=${F.youtubeId}`;K(Ae=>Ae&&{...Ae,videoPath:Ne});return}if(!F.artist||!F.title)return;let ve=!1;return le(S("karaokeManager.ytSearching","Searching YouTube…")),te("searching"),Promise.resolve(E(F.artist,F.title)).then(Ne=>{if(!ve)if(Ne){const Ae=`https://www.youtube.com/watch?v=${Ne}`;K(Ve=>Ve&&{...Ve,videoPath:Ae}),le(""),te(null)}else le(S("karaokeManager.ytNotFound","Not found on YouTube")),te("error"),window.setTimeout(()=>{ve||(le(""),te(null))},4e3)}).catch(()=>{ve||(le(S("karaokeManager.ytSearchError","Search error")),te("error"))}),()=>{ve=!0}},[he,F,E,S]);const Re=u.useCallback(()=>{var ve,Ne;re(!1),$t({}),(ve=Me.current)==null||ve.seekTo(0),(Ne=Me.current)==null||Ne.play()},[$t]),Oe=u.useCallback(()=>{re(!1),H==null||H()},[H]),Ge=u.useCallback(ve=>{K(ve),re(!1),U(0),ue(Ne=>Ne+1),z==null||z(ve)},[z]),Je=u.useMemo(()=>{if(!c)return e;const ve=e.find(Ne=>!!Ne.micId)||e[0];return ve?[ve]:[]},[e,c]),Le=((F==null?void 0:F.gap)??0)/1e3;return G==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-manager${Z?` ${Z}`:""}`,style:{position:"relative",textAlign:"center",minHeight:i,...X},id:q,"data-testid":C,children:[ae&&r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,margin:"10px auto",padding:"8px 16px",maxWidth:420,borderRadius:8,fontSize:14,fontWeight:500,background:"var(--nice-accent, #3b82f6)",color:"var(--nice-text-on-primary, #fff)"},children:[ce==="error"?r.jsx(O.NtdClose,{size:16}):r.jsx(O.NtdSearch,{size:16}),ae]}),!F&&p&&r.jsx(Vo,{onSongUpload:Ge,parseSong:g,t:S}),F&&!J&&r.jsxs("button",{type:"button",className:"nice-karaoke-manager__activate",onClick:_e,style:{position:"absolute",inset:0,zIndex:30,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:16,border:"none",cursor:"pointer",background:"var(--nice-overlay-80, rgba(0,0,0,0.82))",color:"#fff"},children:[r.jsx("div",{style:{fontSize:56,lineHeight:0},children:xe?r.jsx(O.NtdGamepad,{size:56}):r.jsx(O.NtdMicrophone,{size:56})}),r.jsx("h2",{style:{margin:0,fontSize:22,fontWeight:700,color:"#fff"},children:S("karaokeManager.activateAudio","Tap to start")}),r.jsx("p",{style:{margin:0,maxWidth:360,fontSize:14,color:"var(--nice-text-muted, #94a3b8)"},children:xe?S("karaokeManager.padHint","Hit the notes with your keys or pad!"):S("karaokeManager.micHint","Your browser needs a tap to unlock the microphone and audio.")})]}),F&&r.jsxs("div",{ref:Ie,style:{position:"relative",width:"100%",maxWidth:1200,margin:"0 auto"},children:[r.jsx("div",{style:{width:"100%",position:"relative",zIndex:10},children:r.jsx(Io,{tracks:Be?[Be]:[],autoPlay:!1,uiMode:"nobuttons",height:i,externalRef:Me,onPlayingChange:ke,onTimeUpdate:We,onEnded:Pe})}),o&&J&&r.jsx("div",{style:{position:"absolute",inset:0,zIndex:20,pointerEvents:"none"},children:Je.map((ve,Ne)=>{const Ae=dt[ve.id]||[],Ve=Le?Ae.map(De=>({t:De.t-Le,hz:De.hz})):Ae;return r.jsx(To,{song:F,currentTime:_,playerRef:Ie,userPitch:Ve,segmentScores:fe.perPlayerSegmentScores[ve.id],combo:fe.perPlayerCombo[ve.id],verseRatings:fe.perPlayerVerseRatings[ve.id],config:{playerName:ve.name,score:fe.perPlayerTotalScores[ve.id]??0,playerBgColor:ve.color||et[Ne%et.length],difficultyLevel:a,isPlaying:P,playerCount:Je.length,latencyMs:Xt[ve.id]??null,top:30+Ne*160}},ve.id)})}),xe&&pe.length>0&&r.jsx(Uo,{lanes:pe,events:je,currentTime:_,activeLanes:Te,difficulty:a,feedbackQueue:de,isPlaying:P}),l&&J&&r.jsx("div",{style:{position:"absolute",bottom:20,left:0,right:0,zIndex:25,pointerEvents:"none"},children:r.jsx(po,{song:F,currentTime:_})})]}),oe&&Object.keys(pt).length>0&&r.jsx(Yh,{recordings:pt,players:e,t:S}),oe&&r.jsx(Eo,{uploadedSong:F,playerScores:fe.perPlayerScores,topSingings:W,onRestart:Re,onContinue:Oe,t:S,renderReport:D})]})},Yh=({recordings:e,players:t,t:n})=>{const a=u.useMemo(()=>{const s={};for(const[i,o]of Object.entries(e))o&&(s[Number(i)]=URL.createObjectURL(o));return s},[e]);return u.useEffect(()=>()=>{for(const s of Object.values(a))URL.revokeObjectURL(s)},[a]),r.jsxs("div",{style:{margin:"24px auto",maxWidth:640,background:"var(--nice-bg-tertiary)",borderRadius:12,padding:16,textAlign:"left"},children:[r.jsxs("h4",{style:{marginTop:0,color:"var(--nice-text-primary, #fff)"},children:[r.jsx(O.NtdMicrophone,{size:16})," ",n("karaokeManager.playerRecordings","Player recordings")]}),r.jsx("ul",{style:{listStyle:"none",padding:0,margin:0,color:"var(--nice-text-primary, #fff)"},children:t.map(s=>r.jsxs("li",{style:{marginBottom:12,display:"flex",alignItems:"center",gap:10},children:[r.jsx("b",{children:s.name||`Player ${s.id}`}),a[s.id]?r.jsxs(r.Fragment,{children:[r.jsx("audio",{controls:!0,src:a[s.id],style:{flex:1,maxWidth:300}}),r.jsxs("a",{href:a[s.id],download:`${s.name||`player-${s.id}`}-recording.webm`,style:{color:"var(--nice-accent-light, #4fc3f7)",whiteSpace:"nowrap"},children:[r.jsx(O.NtdDownload,{size:13})," ",n("karaokeManager.download","Download")]})]}):r.jsx("span",{style:{opacity:.6},children:n("karaokeManager.noRecording","No recording")})]},s.id))})]})},il=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function on(e){return 12*Math.log2(e/440)+69}function Jn(e){const t=il[Math.round(e)%12],n=Math.floor(Math.round(e)/12)-1;return`${t}${n}`}function Jr(e,t){const n=e-t;return n-12*Math.round(n/12)}function er(e,t){if(e.length===0)return 0;const n=t/100*(e.length-1),a=Math.floor(n),s=Math.ceil(n);return a===s?e[a]:e[a]+(e[s]-e[a])*(n-a)}function ol(e){const{playerName:t,playerColor:n,songTitle:a,songArtist:s,songBpm:i,difficulty:o,pitchPoints:l,notes:c,verseRatings:d,combo:h,classicScore:p,bonusScore:g,totalScore:y,micSettings:m}=e,x=l.filter(de=>de.hz>0),v=x.map(de=>on(de.hz)),f=[],k=[],b=[...c].sort((de,ye)=>de.startTime-ye.startTime);function w(de){let ye=0,Ee=b.length-1;for(;ye<=Ee;){const Me=ye+Ee>>>1,Ie=b[Me];if(de<Ie.startTime)Ee=Me-1;else if(de>Ie.startTime+Ie.duration)ye=Me+1;else return Ie.pitch}return null}const N=[];for(const de of l){const ye=de.hz>0?on(de.hz):0,Ee=w(de.t);N.push({t:de.t,sung:ye,expected:Ee}),ye>0&&Ee!==null&&f.push(Jr(ye,Ee)*100)}const $=N.flatMap(de=>de.sung>0&&de.expected!==null?[de.sung-de.expected]:[]).sort((de,ye)=>de-ye),M=$.length>0?12*Math.round(er($,50)/12):0,E=N.map(de=>({t:de.t,sung:de.sung,expected:de.expected===null?0:de.expected+M}));let R=0;for(const de of b){const ye=de.startTime-.3,Ee=de.startTime+de.duration;for(;R<x.length&&x[R].t<ye;)R++;R<x.length&&x[R].t<=Ee&&k.push((x[R].t-de.startTime)*1e3)}const L=f.map(Math.abs),A=[...L].sort((de,ye)=>de-ye),z=L.length>0?L.reduce((de,ye)=>de+ye,0)/L.length:0,j=er(A,50),I=L.length>1?Math.sqrt(L.reduce((de,ye)=>de+(ye-z)**2,0)/(L.length-1)):0,Y=L.filter(de=>de<=50).length,H=L.filter(de=>de<=15).length,D=L.length>0?Y/L.length*100:0,V=L.length>0?H/L.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"],X=new Array(10).fill(0);for(const de of f){const ye=de<-100?0:de<-50?1:de<-25?2:de<-15?3:de<0?4:de<15?5:de<25?6:de<50?7:de<100?8:9;X[ye]++}const q=Z.map((de,ye)=>({centRange:de,count:X[ye],pct:f.length>0?X[ye]/f.length*100:0})),G=x.map(de=>de.hz).sort((de,ye)=>de-ye),C=G.length>0?G[0]:0,T=G.length>0?G[G.length-1]:0,S=C>0?on(C):0,F=T>0?on(T):0,K=F-S,P=[...v].sort((de,ye)=>de-ye),B=er(P,10),_=er(P,90),U=new Array(12).fill(0);for(const de of v){const ye=Math.round(de)%12;ye>=0&&ye<12&&U[ye]++}const J=U.reduce((de,ye)=>de+ye,0),se=il.map((de,ye)=>({note:de,count:U[ye],pct:J>0?U[ye]/J*100:0})),oe=Zh(x),re=k.length>0?k.reduce((de,ye)=>de+ye,0)/k.length:0,W=k.length>1?Math.sqrt(k.reduce((de,ye)=>de+(ye-re)**2,0)/(k.length-1)):0,ee=W>0?Math.max(0,Math.min(100,100-W/2)):100;let ae=0,le=0;for(let de=1;de<v.length;de++){const ye=Math.abs(v[de]-v[de-1]);ae+=ye,le++}const ce=le>0?ae/le*100/12:0,te=l.filter(de=>de.hz<=0).length,he=l.length>0?(1-te/l.length)*100:0,ue=new Map;for(const de of c){const ye=de.line??0;ue.has(ye)||ue.set(ye,[]),ue.get(ye).push(de)}const xe=new Map;for(const de of x){const ye=w(de.t);if(ye===null)continue;let Ee=0,Me=b.length-1,Ie=-1;for(;Ee<=Me;){const Ye=Ee+Me>>>1,Ze=b[Ye];if(de.t<Ze.startTime)Me=Ye-1;else if(de.t>Ze.startTime+Ze.duration)Ee=Ye+1;else{Ie=Ze.line??0;break}}if(Ie<0)continue;const tt=Math.abs(Jr(on(de.hz),ye)*100);xe.has(Ie)||xe.set(Ie,[]),xe.get(Ie).push(tt)}const pe=d.map(de=>{const ye=ue.get(de.verseIndex)??[],Ee=xe.get(de.verseIndex)??[],Me=Ee.length>0?Ee.reduce((Ie,tt)=>Ie+tt,0)/Ee.length:0;return{verseIndex:de.verseIndex,label:de.label,hitFraction:de.hitFraction,avgCentDeviation:Math.round(Me*10)/10,noteCount:ye.length,notesHit:Math.round(de.hitFraction*ye.length),comboBonus:de.comboBonus}}),Se=2,je=.5,$e=l.length>0?l[l.length-1].t:0,Te=[],He=N.flatMap(de=>de.sung>0&&de.expected!==null?[{t:de.t,hit:Math.abs(Jr(de.sung,de.expected))<=.5}]:[]);if(He.length>0){let de=0,ye=0,Ee=0;for(let Me=0;Me<=$e;Me+=je){const Ie=Me-Se/2,tt=Me+Se/2;for(;ye<He.length&&He[ye].t<tt;)He[ye].hit&&Ee++,ye++;for(;de<ye&&He[de].t<Ie;)He[de].hit&&Ee--,de++;const Ye=ye-de;Te.push({t:Me,accuracy:Ye>0?Ee/Ye*100:0})}}else for(let de=0;de<=$e;de+=je)Te.push({t:de,accuracy:0});return{playerName:t,playerColor:n,songTitle:a,songArtist:s,songBpm:i,difficulty:o,timestamp:new Date().toISOString(),classicScore:p,bonusScore:g,totalScore:y,maxCombo:(h==null?void 0:h.maxCombo)??0,totalComboBonus:(h==null?void 0:h.totalComboBonus)??0,totalPitchPoints:l.length,avgCentDeviation:Math.round(z*10)/10,medianCentDeviation:Math.round(j*10)/10,stdDevCents:Math.round(I*10)/10,intonationAccuracyPct:Math.round(D*10)/10,perfectHitPct:Math.round(V*10)/10,pitchDeviationHistogram:q,lowestHz:Math.round(C*10)/10,highestHz:Math.round(T*10)/10,lowestNote:S>0?Jn(S):"—",highestNote:F>0?Jn(F):"—",rangeInSemitones:Math.round(K*10)/10,tessituraLow:B>0?Jn(B):"—",tessituraHigh:_>0?Jn(_):"—",pitchClassDistribution:se,vibrato:oe,avgOnsetDeviationMs:Math.round(re*10)/10,rhythmStabilityPct:Math.round(ee*10)/10,jitterPct:Math.round(ce*100)/100,shimmerProxy:Math.round(he*10)/10,verseMetrics:pe,micSettings:m,pitchOverTime:E,accuracyOverTime:Te}}function Zh(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(y=>on(y.hz)),n=e.map(y=>y.t),a=.5,s=[],i=[];let o=0,l=0,c=0;for(let y=0;y<e.length;y++){for(l+=t[y],c++;o<y&&n[y]-n[o]>=a;)l-=t[o],c--,o++;if(c<6||(y-o)%10!==0)continue;const m=l/c;let x=0,v=t[o]-m,f=Math.abs(v);for(let w=o+1;w<=y;w++){const N=t[w]-m;N*v<0&&x++,v=N;const $=Math.abs(N);$>f&&(f=$)}const k=n[y]-n[o];if(k<=0)continue;const b=x/2/k;b>=3&&b<=12&&(s.push(b),i.push(f*100))}if(s.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const d=s.reduce((y,m)=>y+m,0)/s.length,h=i.reduce((y,m)=>y+m,0)/i.length,p=Math.sqrt(s.reduce((y,m)=>y+(m-d)**2,0)/s.length),g=Math.max(0,Math.min(100,100-p*20));return{detected:!0,avgRateHz:Math.round(d*10)/10,avgExtentCents:Math.round(h*10)/10,regularityPct:Math.round(g)}}const Q={overlay:{position:"fixed",inset:0,background:"var(--nice-overlay-90, rgba(0,0,0,0.92))",display:"flex",alignItems:"flex-start",justifyContent:"center",zIndex:250,color:"var(--nice-text, #e2e8f0)",overflowY:"auto",padding:"24px 12px"},container:{background:"var(--nice-bg, #0f172a)",borderRadius:16,padding:32,width:"min(960px, 95vw)",boxShadow:"0 16px 48px var(--nice-overlay-60, rgba(0,0,0,0.6))",fontFamily:"'Segoe UI', system-ui, -apple-system, sans-serif"},header:{textAlign:"center",marginBottom:24,borderBottom:"2px solid var(--nice-border, #334155)",paddingBottom:20},title:{fontSize:28,fontWeight:800,color:"var(--nice-text, #f1f5f9)",margin:"0 0 4px"},subtitle:{fontSize:14,color:"var(--nice-text-muted, #64748b)",margin:0},sectionTitle:{fontSize:18,fontWeight:700,color:"var(--nice-accent, #38bdf8)",margin:"28px 0 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",paddingBottom:6,display:"flex",alignItems:"center",gap:8},table:{width:"100%",borderCollapse:"collapse",fontSize:13,margin:"8px 0"},th:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"left",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},thRight:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"right",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},td:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-secondary, #cbd5e1)"},tdRight:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",textAlign:"right",color:"var(--nice-text, #e2e8f0)",fontWeight:500},tdBold:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text, #f1f5f9)",fontWeight:700},kpiGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:12,margin:"12px 0"},kpiCard:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:"14px 16px",textAlign:"center",border:"1px solid var(--nice-border, #334155)"},kpiValue:{fontSize:26,fontWeight:800,color:"var(--nice-warning, #fbbf24)"},kpiLabel:{fontSize:11,color:"var(--nice-text-muted, #64748b)",marginTop:2,textTransform:"uppercase",letterSpacing:.8},kpiUnit:{fontSize:13,fontWeight:400,color:"var(--nice-text-muted, #94a3b8)",marginLeft:2},chartWrap:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:16,margin:"12px 0",border:"1px solid var(--nice-border, #334155)"},chartTitle:{fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:8,textAlign:"center"},badge:e=>({display:"inline-block",padding:"2px 10px",borderRadius:20,background:e,color:"#fff",fontSize:12,fontWeight:700}),btnPrimary:{background:"var(--nice-info, #3b82f6)",color:"#fff",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:700,cursor:"pointer"},btnSecondary:{background:"var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:600,cursor:"pointer"},row:{display:"flex",gap:16,flexWrap:"wrap"},half:{flex:"1 1 45%",minWidth:280},footer:{textAlign:"center",marginTop:24,paddingTop:16,borderTop:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #475569)",fontSize:11}};function gt(e){return e>=90?"#22c55e":e>=70?"#84cc16":e>=50?"#eab308":e>=30?"#f97316":"#ef4444"}function Hs(e){switch(e){case"Perfect":return"#22c55e";case"Great":return"#84cc16";case"Good":return"#eab308";case"OK":return"#f97316";default:return"#ef4444"}}function Xh(e){return e.includes("−15 to 0")||e.includes("0 to +15")?"var(--nice-success, #22c55e)":e.includes("25")?"var(--nice-warning, #eab308)":"var(--nice-danger, #ef4444)"}const Ut=e=>Math.round(e*10)/10;function Ks(e,t,n){return e.map((a,s)=>({name:a,color:n[s],data:t.map((i,o)=>o===s?Ut(i):0)}))}function Ys(e,t){if(e.length<=t)return e;const n=Math.ceil(e.length/t);return e.filter((a,s)=>s%n===0)}function Zs(e){const t=e.length>1?e[e.length-1]-e[0]:0,n=[1,2,5,10,15,30,60,120,300].find(s=>t/s<=10)??600;let a=Math.ceil((e[0]??0)/n)*n;return e.map(s=>{if(s+1e-9<a)return"";for(;a<=s+1e-9;)a+=n;return`${Math.round(s)}s`})}const Xs=240,Qh=({reports:e,noteCount:t,uploadedSong:n=null,playerScores:a,livePitch:s,liveVerseRatings:i,liveCombo:o,difficulty:l="normal",micSettings:c,onClose:d,t:h,className:p,style:g,id:y,accessMode:m,"data-testid":x})=>{const{t:v}=be(),f=h??v,k=u.useRef(null),b=u.useMemo(()=>{if(e||!n)return[];const S=Hn(n.notes.map(K=>K.noteLine),n.bpm??void 0),F=(n.gap??0)/1e3;return Ka(S,F)},[e,n]),w=u.useMemo(()=>e||(!n||!a||!o?[]:a.map(S=>{const F=(s==null?void 0:s[S.id])||[];return ol({playerName:S.name,playerColor:S.color,songTitle:n.title,songArtist:n.artist,songBpm:n.bpm??0,difficulty:l,pitchPoints:F,notes:b,verseRatings:i??[],combo:o,classicScore:S.classicScore,bonusScore:S.bonusScore,totalScore:S.totalScore,micSettings:(c==null?void 0:c[S.id])??null})})),[e,n,a,s,i,o,l,b,c]),N=u.useCallback(()=>{var B,_;if(!k.current)return;const S=`<!DOCTYPE html>
|
|
48
48
|
<html lang="en"><head><meta charset="utf-8">
|
|
49
|
-
<title>Vocal Performance Report — ${((
|
|
49
|
+
<title>Vocal Performance Report — ${((B=w[0])==null?void 0:B.songTitle)??"Karaoke"}</title>
|
|
50
50
|
<style>
|
|
51
51
|
body{margin:0;padding:24px;background:var(--nice-bg, #0f172a);color:var(--nice-text, #e2e8f0);font-family:'Segoe UI',system-ui,sans-serif}
|
|
52
52
|
table{border-collapse:collapse;width:100%}th,td{padding:6px 10px;border-bottom:1px solid var(--nice-bg-secondary, #1e293b);text-align:left}
|
|
@@ -56,19 +56,19 @@ th{background:var(--nice-bg-secondary, #1e293b);color:var(--nice-text-muted, #94
|
|
|
56
56
|
.nice-chart__grid-line,.nice-chart__axis{stroke:var(--nice-border, #334155)}.nice-chart__axis-label,.nice-chart__legend-text{fill:var(--nice-text-muted, #94a3b8);font-size:11px}
|
|
57
57
|
@media print{body{background:#fff;color:#000}th{background:var(--nice-bg-secondary, #f0f0f0);color:var(--nice-text-muted, #333)}td{color:var(--nice-text-muted, #333);border-color:var(--nice-border, #ddd)}}
|
|
58
58
|
</style></head><body>
|
|
59
|
-
${
|
|
60
|
-
</body></html>`,
|
|
59
|
+
${k.current.innerHTML}
|
|
60
|
+
</body></html>`,F=new Blob([S],{type:"text/html"}),K=URL.createObjectURL(F),P=document.createElement("a");P.href=K,P.download=`vocal-report-${(((_=w[0])==null?void 0:_.songTitle)??"karaoke").replace(/[^a-z0-9]/gi,"_")}.html`,P.click(),URL.revokeObjectURL(K)},[w]),$=u.useCallback(()=>window.print(),[]),M=u.useCallback(()=>{var B;const S=JSON.stringify(w,null,2),F=new Blob([S],{type:"application/json"}),K=URL.createObjectURL(F),P=document.createElement("a");P.href=K,P.download=`vocal-data-${(((B=w[0])==null?void 0:B.songTitle)??"karaoke").replace(/[^a-z0-9]/gi,"_")}.json`,P.click(),URL.revokeObjectURL(K)},[w]);if(m==="hidden")return null;if(w.length===0)return r.jsx("div",{className:p,style:{...Q.overlay,...g},id:y,"data-testid":x,onClick:S=>S.target===S.currentTarget&&(d==null?void 0:d()),onKeyDown:S=>S.key==="Escape"&&(d==null?void 0:d()),children:r.jsxs("div",{style:{...Q.container,textAlign:"center"},children:[r.jsxs("div",{style:Q.header,children:[r.jsxs("h2",{style:Q.title,children:[r.jsx(O.NtdBarChart,{size:24})," ",f("karaoke.report.title","Vocal Performance Report")]}),r.jsx("p",{style:Q.subtitle,children:f("karaoke.report.empty","No performance data yet — sing a song to see the report.")})]}),d&&r.jsxs("button",{style:Q.btnSecondary,onClick:d,children:[r.jsx(O.NtdClose,{size:16})," ",f("common.close","Close")]})]})});const E=w[0],R=t??b.length,L=zr(l),A=E.intonationAccuracyPct*.3+E.perfectHitPct*.2+E.rhythmStabilityPct*.15+E.shimmerProxy*.1+Math.min(100,E.maxCombo/Math.max(R,1)*100)*.1+Math.min(100,E.totalScore/1e4*100)*.15,z=A>=95?"A+":A>=90?"A":A>=85?"A−":A>=80?"B+":A>=75?"B":A>=70?"B−":A>=65?"C+":A>=60?"C":A>=55?"C−":A>=50?"D+":A>=45?"D":A>=40?"D−":"F",j={"A+":f("vocalReport.gradeAPlus","Outstanding — professional-level control."),A:f("vocalReport.gradeA","Excellent intonation and timing."),"A−":f("vocalReport.gradeAMinus","Very strong performance."),"B+":f("vocalReport.gradeBPlus","Great, with minor pitch slips."),B:f("vocalReport.gradeB","Solid and consistent."),"B−":f("vocalReport.gradeBMinus","Good, room to tighten timing."),"C+":f("vocalReport.gradeCPlus","Decent — practice pitch accuracy."),C:f("vocalReport.gradeC","Average; work on intonation."),"C−":f("vocalReport.gradeCMinus","Passable; needs steadier pitch."),"D+":f("vocalReport.gradeDPlus","Below average — keep practising."),D:f("vocalReport.gradeD","Weak intonation throughout."),"D−":f("vocalReport.gradeDMinus","Struggling with pitch and timing."),F:f("vocalReport.gradeF","Off-pitch for most notes.")};let I=0;const Y=[{metric:f("vocalReport.radarIntonation","Intonation"),value:E.intonationAccuracyPct,max:100},{metric:f("vocalReport.radarPerfectHits","Perfect hits"),value:E.perfectHitPct,max:100},{metric:f("vocalReport.radarRhythm","Rhythm"),value:E.rhythmStabilityPct,max:100},{metric:f("vocalReport.radarVocalRange","Range"),value:Math.min(100,E.rangeInSemitones/24*100),max:100},{metric:f("vocalReport.radarStability","Stability"),value:E.shimmerProxy,max:100},{metric:f("vocalReport.radarCombo","Combo"),value:Math.min(100,E.maxCombo/Math.max(R,1)*100),max:100}],H=[{name:f("vocalReport.perfLabel","Perfect"),value:E.perfectHitPct,fill:"var(--nice-success, #22c55e)"},{name:f("vocalReport.goodLabel","Good"),value:E.intonationAccuracyPct-E.perfectHitPct,fill:"var(--nice-success, #84cc16)"},{name:f("vocalReport.offPitch","Off-pitch"),value:100-E.intonationAccuracyPct,fill:"var(--nice-danger, #ef4444)"}].filter(S=>S.value>0),D=E.pitchClassDistribution.filter(S=>S.count>0).sort((S,F)=>F.pct-S.pct),V=E.verseMetrics.map(S=>({verse:`V${S.verseIndex+1}`,accuracy:Math.round(S.hitFraction*100),label:S.label})),Z=Ys(E.pitchOverTime,Xs),X=Ys(E.accuracyOverTime,Xs),q=E.pitchDeviationHistogram,G=f("vocalReport.samples","Samples"),C=f("vocalReport.hitPct","Hit %"),T=f("vocalReport.cents","cents");return r.jsxs("div",{className:p,style:{...Q.overlay,...g},id:y,"data-testid":x,onClick:S=>S.target===S.currentTarget&&(d==null?void 0:d()),onKeyDown:S=>S.key==="Escape"&&(d==null?void 0:d()),children:[r.jsx("style",{children:`
|
|
61
61
|
@media print {
|
|
62
62
|
body { background: #fff !important; color: #000 !important; }
|
|
63
63
|
* { color-adjust: exact !important; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
|
|
64
64
|
}
|
|
65
|
-
`}),n.jsxs("div",{ref:S,style:Q.container,children:[n.jsxs("div",{style:Q.header,children:[n.jsxs("h1",{style:{...Q.title,display:"inline-flex",alignItems:"center",gap:8},children:[n.jsx(G.NtdBarChart,{size:26})," ",g("vocalReport.title","Vocal Performance Report")]}),n.jsxs("p",{style:Q.subtitle,children:[j.songArtist," — ",j.songTitle," | ",g("vocalReport.difficulty","Difficulty"),": ",n.jsx("strong",{children:j.difficulty})," "," | ",new Date(j.timestamp).toLocaleString()]}),n.jsxs("div",{style:{marginTop:16,display:"flex",justifyContent:"center",alignItems:"center",gap:16},children:[n.jsx("div",{style:{width:72,height:72,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:`linear-gradient(135deg, ${mt(A)}44, ${mt(A)})`,border:`3px solid ${mt(A)}`,boxShadow:`0 0 20px ${mt(A)}44`},children:n.jsx("span",{style:{fontSize:28,fontWeight:900,color:"#fff"},children:$})}),n.jsxs("div",{style:{textAlign:"left"},children:[n.jsxs("div",{style:{fontSize:14,fontWeight:700,color:mt(A)},children:[g("vocalReport.overallGrade","Overall grade"),": ",A.toFixed(1),"%"]}),n.jsx("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",maxWidth:360},children:O[$]??""})]})]})]}),n.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end",marginBottom:16,flexWrap:"wrap"},children:[n.jsxs("button",{style:Q.btnPrimary,onClick:M,children:[n.jsx(G.NtdDownload,{size:14})," ",g("vocalReport.downloadHtml","Download HTML")]}),n.jsxs("button",{style:Q.btnSecondary,onClick:T,children:[n.jsx(G.NtdPrint,{size:14})," ",g("vocalReport.printPdf","Print / PDF")]}),n.jsxs("button",{style:Q.btnSecondary,onClick:N,children:[n.jsx(G.NtdCode,{size:14})," ",g("vocalReport.exportJson","Export JSON")]}),n.jsxs("button",{style:Q.btnSecondary,onClick:d,children:[n.jsx(G.NtdClose,{size:14})," ",g("vocalReport.close","Close")]})]}),n.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",g("vocalReport.scoreOverview","Score overview")]}),n.jsxs("div",{style:Q.kpiGrid,children:[n.jsxs("div",{style:Q.kpiCard,children:[n.jsx("div",{style:Q.kpiValue,children:j.totalScore.toLocaleString()}),n.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.totalScore","Total score")})]}),n.jsxs("div",{style:Q.kpiCard,children:[n.jsx("div",{style:Q.kpiValue,children:j.classicScore.toLocaleString()}),n.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.classicScore","Classic score")})]}),n.jsxs("div",{style:Q.kpiCard,children:[n.jsx("div",{style:Q.kpiValue,children:j.bonusScore.toLocaleString()}),n.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.bonusScore","Bonus score")})]}),n.jsxs("div",{style:Q.kpiCard,children:[n.jsxs("div",{style:Q.kpiValue,children:[j.maxCombo,"×"]}),n.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.maxCombo","Max combo")})]}),n.jsxs("div",{style:Q.kpiCard,children:[n.jsxs("div",{style:{...Q.kpiValue,color:mt(j.intonationAccuracyPct)},children:[j.intonationAccuracyPct,"%"]}),n.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.intonationAccuracy","Intonation accuracy")})]}),n.jsxs("div",{style:Q.kpiCard,children:[n.jsxs("div",{style:{...Q.kpiValue,color:mt(j.perfectHitPct)},children:[j.perfectHitPct,"%"]}),n.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.perfectHits","Perfect hits")})]})]}),k.length>1&&n.jsxs(n.Fragment,{children:[n.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",g("vocalReport.playerComparison","Player comparison")]}),n.jsxs("table",{style:Q.table,children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{style:Q.th,children:"#"}),n.jsx("th",{style:Q.th,children:g("vocalReport.player","Player")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.classic","Classic")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.bonus","Bonus")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.total","Total")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.intonation","Intonation")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.perfect","Perfect")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.range","Range")})]})}),n.jsx("tbody",{children:k.map((C,L)=>n.jsxs("tr",{children:[n.jsx("td",{style:Q.td,children:L+1}),n.jsx("td",{style:{...Q.tdBold,color:C.playerColor},children:C.playerName}),n.jsx("td",{style:Q.tdRight,children:C.classicScore.toLocaleString()}),n.jsx("td",{style:Q.tdRight,children:C.bonusScore.toLocaleString()}),n.jsx("td",{style:{...Q.tdRight,fontWeight:700,color:"var(--nice-warning, #fbbf24)"},children:C.totalScore.toLocaleString()}),n.jsx("td",{style:Q.tdRight,children:n.jsxs("span",{style:Q.badge(mt(C.intonationAccuracyPct)),children:[C.intonationAccuracyPct,"%"]})}),n.jsx("td",{style:Q.tdRight,children:n.jsxs("span",{style:Q.badge(mt(C.perfectHitPct)),children:[C.perfectHitPct,"%"]})}),n.jsxs("td",{style:Q.tdRight,children:[C.lowestNote,"–",C.highestNote]})]},L))})]})]}),n.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",g("vocalReport.pitchAccuracy","Pitch accuracy")]}),n.jsxs("table",{style:Q.table,children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{style:Q.th,children:g("vocalReport.metric","Metric")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.value","Value")}),n.jsx("th",{style:Q.th,children:g("vocalReport.description","Description")})]})}),n.jsxs("tbody",{children:[n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.meanAbsDev","Mean abs. deviation")}),n.jsxs("td",{style:Q.tdRight,children:[j.avgCentDeviation,n.jsxs("span",{style:Q.kpiUnit,children:[" ",P]})]}),n.jsx("td",{style:Q.td,children:g("vocalReport.meanAbsDevDesc","Average distance from the target pitch.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.medianDev","Median deviation")}),n.jsxs("td",{style:Q.tdRight,children:[j.medianCentDeviation,n.jsxs("span",{style:Q.kpiUnit,children:[" ",P]})]}),n.jsx("td",{style:Q.td,children:g("vocalReport.medianDevDesc","Typical deviation, robust to outliers.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.stdDev","Std. deviation")}),n.jsxs("td",{style:Q.tdRight,children:[j.stdDevCents,n.jsxs("span",{style:Q.kpiUnit,children:[" ",P]})]}),n.jsx("td",{style:Q.td,children:g("vocalReport.stdDevDesc","Consistency of pitch (lower = steadier).")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.intonationAccuracyLabel","Intonation accuracy")}),n.jsxs("td",{style:{...Q.tdRight,color:mt(j.intonationAccuracyPct)},children:[j.intonationAccuracyPct,"%"]}),n.jsx("td",{style:Q.td,children:g("vocalReport.intonationAccuracyDesc","Share of frames within tolerance.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.perfectHitRate","Perfect-hit rate")}),n.jsxs("td",{style:{...Q.tdRight,color:mt(j.perfectHitPct)},children:[j.perfectHitPct,"%"]}),n.jsx("td",{style:Q.td,children:g("vocalReport.perfectHitRateDesc","Notes hit dead-on.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.totalPitchSamples","Total pitch samples")}),n.jsx("td",{style:Q.tdRight,children:j.totalPitchPoints.toLocaleString()}),n.jsx("td",{style:Q.td,children:g("vocalReport.totalPitchSamplesDesc","Number of analysed pitch frames.")})]})]})]}),n.jsxs("div",{style:Q.chartWrap,children:[n.jsx("div",{style:Q.chartTitle,children:g("vocalReport.deviationDistribution","Deviation distribution")}),n.jsx("div",{style:{height:220},children:n.jsx(ve.NiceChart,{width:860,height:220,stacked:!0,showLegend:!1,categories:X.map(C=>C.centRange),series:Zs(X.map(C=>`${q} (${C.centRange})`),X.map(C=>C.count),X.map(C=>Kh(C.centRange)))})})]}),n.jsxs("div",{style:Q.row,children:[n.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[n.jsx("div",{style:Q.chartTitle,children:g("vocalReport.hitClassification","Hit classification")}),n.jsx("div",{style:{height:220},children:n.jsx(ve.NicePieChart,{width:400,height:260,data:J.map(C=>({label:C.name,value:Vt(C.value),color:C.fill}))})})]}),n.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[n.jsx("div",{style:Q.chartTitle,children:g("vocalReport.performanceProfile","Performance profile")}),n.jsx("div",{style:{height:220},children:n.jsx(ve.NiceChart,{width:400,height:220,showLegend:!1,categories:U.map(C=>C.metric),series:[{name:g("vocalReport.performanceProfile","Performance profile"),type:"radar",color:"var(--nice-info, #3b82f6)",data:U.map(C=>Vt(C.value))},{name:"100%",type:"radar",color:"transparent",data:U.map(C=>C.max)}]})})]})]}),n.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",g("vocalReport.pitchTracking","Pitch tracking")]}),n.jsxs("div",{style:Q.chartWrap,children:[n.jsx("div",{style:Q.chartTitle,children:g("vocalReport.sungVsExpected","Sung vs expected")}),n.jsx("div",{style:{height:260},children:n.jsx(ve.NiceChart,{width:860,height:230,categories:Qs(K.map(C=>C.t)),series:[{name:g("vocalReport.expected","Expected"),type:"line",color:"var(--nice-success, #22c55e)",data:K.map(C=>Vt(C.expected))},{name:g("vocalReport.sung","Sung"),type:"line",color:"var(--nice-info, #3b82f6)",data:K.map(C=>Vt(C.sung))}]})})]}),n.jsxs("div",{style:Q.chartWrap,children:[n.jsx("div",{style:Q.chartTitle,children:g("vocalReport.rollingAccuracy","Rolling accuracy")}),n.jsx("div",{style:{height:180},children:n.jsx(ve.NiceChart,{width:860,height:180,showLegend:!1,categories:Qs(re.map(C=>C.t)),series:[{name:g("vocalReport.rollingAccuracy","Rolling accuracy"),type:"area",color:"var(--nice-accent, #8b5cf6)",data:re.map(C=>Vt(C.accuracy))}]})})]}),n.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",g("vocalReport.vocalRange","Vocal range")]}),n.jsxs("div",{style:Q.row,children:[n.jsx("div",{style:Q.half,children:n.jsx("table",{style:Q.table,children:n.jsxs("tbody",{children:[n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.lowestNote","Lowest note")}),n.jsxs("td",{style:Q.tdRight,children:[j.lowestNote," (",j.lowestHz," Hz)"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.highestNote","Highest note")}),n.jsxs("td",{style:Q.tdRight,children:[j.highestNote," (",j.highestHz," Hz)"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.rangeLabel","Range")}),n.jsxs("td",{style:Q.tdRight,children:[j.rangeInSemitones," ",g("vocalReport.semitones","semitones")]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.tessitura","Tessitura")}),n.jsxs("td",{style:Q.tdRight,children:[j.tessituraLow," — ",j.tessituraHigh]})]})]})})}),n.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[n.jsx("div",{style:Q.chartTitle,children:g("vocalReport.chromagram","Chromagram")}),n.jsx("div",{style:{height:180},children:n.jsx(ve.NiceChart,{width:400,height:180,showLegend:!1,categories:_.map(C=>C.note),series:[{name:g("vocalReport.usagePct","Usage %"),type:"bar",color:"var(--nice-primary, #6366f1)",data:_.map(C=>Vt(C.pct))}]})})]})]}),n.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",g("vocalReport.vibratoStability","Vibrato & stability")]}),n.jsxs("div",{style:Q.row,children:[n.jsx("div",{style:Q.half,children:n.jsx("table",{style:Q.table,children:n.jsxs("tbody",{children:[n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.vibratoDetected","Vibrato detected")}),n.jsx("td",{style:Q.tdRight,children:n.jsx("span",{style:Q.badge(j.vibrato.detected?"var(--nice-success, #22c55e)":"var(--nice-text-muted, #64748b)"),children:j.vibrato.detected?g("vocalReport.yes","Yes"):g("vocalReport.no","No")})})]}),j.vibrato.detected&&n.jsxs(n.Fragment,{children:[n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.avgRate","Avg. rate")}),n.jsxs("td",{style:Q.tdRight,children:[j.vibrato.avgRateHz," Hz"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.avgExtent","Avg. extent")}),n.jsxs("td",{style:Q.tdRight,children:["±",j.vibrato.avgExtentCents," ",P]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.regularity","Regularity")}),n.jsxs("td",{style:Q.tdRight,children:[j.vibrato.regularityPct,"%"]})]})]})]})})}),n.jsx("div",{style:Q.half,children:n.jsx("table",{style:Q.table,children:n.jsxs("tbody",{children:[n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.jitter","Jitter")}),n.jsxs("td",{style:Q.tdRight,children:[j.jitterPct,"%"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.vocalPresence","Vocal presence")}),n.jsxs("td",{style:Q.tdRight,children:[j.shimmerProxy,"%"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.avgOnsetDev","Avg. onset deviation")}),n.jsxs("td",{style:Q.tdRight,children:[j.avgOnsetDeviationMs," ms"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.rhythmStability","Rhythm stability")}),n.jsx("td",{style:Q.tdRight,children:n.jsxs("span",{style:Q.badge(mt(j.rhythmStabilityPct)),children:[j.rhythmStabilityPct,"%"]})})]})]})})})]}),j.verseMetrics.length>0&&n.jsxs(n.Fragment,{children:[n.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",g("vocalReport.verseBreakdown","Per-verse breakdown")]}),n.jsxs("div",{style:Q.chartWrap,children:[n.jsx("div",{style:Q.chartTitle,children:g("vocalReport.accuracyByVerse","Accuracy by verse")}),n.jsx("div",{style:{height:200},children:n.jsx(ve.NiceChart,{width:860,height:200,stacked:!0,showLegend:!1,categories:W.map(C=>C.verse),series:Zs(W.map(C=>`${E} (${C.verse})`),W.map(C=>C.accuracy),W.map(C=>Ys(C.label)))})})]}),n.jsxs("table",{style:Q.table,children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{style:Q.th,children:g("vocalReport.verse","Verse")}),n.jsx("th",{style:Q.th,children:g("vocalReport.rating","Rating")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.hitPct","Hit %")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.avgDeviation","Avg. dev.")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.notes","Notes")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.notesHit","Hit")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.comboBonus","Combo bonus")})]})}),n.jsx("tbody",{children:j.verseMetrics.map((C,L)=>n.jsxs("tr",{children:[n.jsxs("td",{style:Q.td,children:[g("vocalReport.verse","Verse")," ",C.verseIndex+1]}),n.jsx("td",{style:Q.td,children:n.jsx("span",{style:Q.badge(Ys(C.label)),children:C.label})}),n.jsxs("td",{style:Q.tdRight,children:[(C.hitFraction*100).toFixed(1),"%"]}),n.jsxs("td",{style:Q.tdRight,children:[C.avgCentDeviation," ¢"]}),n.jsx("td",{style:Q.tdRight,children:C.noteCount}),n.jsx("td",{style:Q.tdRight,children:C.notesHit}),n.jsxs("td",{style:Q.tdRight,children:["+",C.comboBonus]})]},L))})]})]}),n.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",g("vocalReport.scoringConfig","Scoring configuration")]}),n.jsxs("table",{style:Q.table,children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{style:Q.th,children:g("vocalReport.parameter","Parameter")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.value","Value")}),n.jsx("th",{style:Q.th,children:g("vocalReport.description","Description")})]})}),n.jsxs("tbody",{children:[n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.difficultyLevel","Difficulty level")}),n.jsx("td",{style:Q.tdRight,children:j.difficulty}),n.jsx("td",{style:Q.td,children:g("vocalReport.difficultyLevelDesc","Affects tolerance and multiplier.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.semitoneTolerance","Semitone tolerance")}),n.jsx("td",{style:Q.tdRight,children:z.semitoneTolerance}),n.jsx("td",{style:Q.td,children:g("vocalReport.semitoneToleranceDesc","Pitch window counted as a hit.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.preWindow","Pre window")}),n.jsxs("td",{style:Q.tdRight,children:[z.preWindow," s"]}),n.jsx("td",{style:Q.td,children:g("vocalReport.preWindowDesc","Lead-in time before a note.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.postExtra","Post extra")}),n.jsxs("td",{style:Q.tdRight,children:[z.postExtra," s"]}),n.jsx("td",{style:Q.td,children:g("vocalReport.postExtraDesc","Grace time after a note.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.difficultyMultiplier","Difficulty multiplier")}),n.jsxs("td",{style:Q.tdRight,children:[z.difficultyMult,"×"]}),n.jsx("td",{style:Q.td,children:g("vocalReport.difficultyMultiplierDesc","Score scaling for difficulty.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.songBpm","Song BPM")}),n.jsx("td",{style:Q.tdRight,children:j.songBpm}),n.jsx("td",{style:Q.td,children:g("vocalReport.songBpmDesc","Tempo used for note timing.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.totalNotes","Total notes")}),n.jsx("td",{style:Q.tdRight,children:R}),n.jsx("td",{style:Q.td,children:g("vocalReport.totalNotesDesc","Number of scored notes in the song.")})]})]})]}),k.some(C=>C.micSettings)&&n.jsxs(n.Fragment,{children:[n.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",g("vocalReport.micConfig","Microphone configuration")]}),k.map((C,L)=>C.micSettings&&n.jsxs("div",{style:{marginBottom:16},children:[k.length>1&&n.jsx("h4",{style:{color:C.playerColor,margin:"0 0 8px",fontSize:14},children:C.playerName}),n.jsxs("table",{style:Q.table,children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{style:Q.th,children:g("vocalReport.setting","Setting")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.value","Value")})]})}),n.jsxs("tbody",{children:[n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.device","Device")}),n.jsx("td",{style:Q.tdRight,children:C.micSettings.deviceLabel||C.micSettings.deviceId})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.pitchAlgorithm","Pitch algorithm")}),n.jsx("td",{style:Q.tdRight,children:C.micSettings.algorithm})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.inputGain","Input gain")}),n.jsxs("td",{style:Q.tdRight,children:[C.micSettings.gain,"×"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.rmsThreshold","RMS threshold")}),n.jsx("td",{style:Q.tdRight,children:C.micSettings.rmsThreshold})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.pitchThreshold","Pitch threshold")}),n.jsx("td",{style:Q.tdRight,children:C.micSettings.pitchThreshold})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.smoothingWindow","Smoothing window")}),n.jsxs("td",{style:Q.tdRight,children:[C.micSettings.smoothingWindow," ",g("vocalReport.frames","frames")]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.hysteresisFrames","Hysteresis frames")}),n.jsx("td",{style:Q.tdRight,children:C.micSettings.hysteresisFrames})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.hanningWindow","Hanning window")}),n.jsx("td",{style:Q.tdRight,children:C.micSettings.useHanning?g("vocalReport.enabled","Enabled"):g("vocalReport.disabled","Disabled")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.latencyOffset","Latency offset")}),n.jsxs("td",{style:Q.tdRight,children:[C.micSettings.latencyOffsetMs," ms"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.monitor","Monitor")}),n.jsx("td",{style:Q.tdRight,children:C.micSettings.monitorEnabled?`${g("vocalReport.on","On")} (${Math.round(C.micSettings.monitorVolume*100)}%)`:g("vocalReport.off","Off")})]})]})]})]},L))]}),n.jsx("div",{style:Q.footer,children:n.jsxs("p",{children:[g("vocalReport.footerGenerated","Report generated")," ·"," ",j.timestamp.replace(/[-:T.Z]/g,"").slice(0,14)]})})]})]})},Zh="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100'%3E%3Crect width='100' height='100' fill='%23334155'/%3E%3Ccircle cx='42' cy='64' r='8' fill='%2394a3b8'/%3E%3Crect x='48' y='34' width='3' height='32' fill='%2394a3b8'/%3E%3C/svg%3E";function Xh(e){if(!e)return"";const t=Math.floor(e/60),r=Math.round(e%60);return`${t}:${r.toString().padStart(2,"0")}`}function ei(e){return Array.from(new Set(e.filter(t=>!!t))).sort((t,r)=>t.localeCompare(r))}const Zo=u.memo(({song:e,index:t,active:r,coverUrl:a,topScore:s,selected:i,multiSelect:o,disabled:l,t:c,onPlay:d,onToggleSelect:h,onFocusRow:f})=>{const p=()=>{o?h(e.id):l||d==null||d(e)};return n.jsxs("div",{className:`nice-ksb-row${i?" nice-ksb-row--selected":""}${r?" nice-ksb-row--active":""}`,role:"option","aria-selected":i,"data-ksb-index":t,tabIndex:r?0:-1,onClick:p,onFocus:()=>f(t),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),p())},children:[o&&n.jsx("input",{type:"checkbox",className:"nice-ksb-row__check",checked:i,onChange:()=>h(e.id),onClick:y=>y.stopPropagation(),"aria-label":e.title}),n.jsx("img",{className:"nice-ksb-row__cover",src:a,alt:"",loading:"lazy"}),n.jsxs("div",{className:"nice-ksb-row__main",children:[n.jsx("div",{className:"nice-ksb-row__title",children:e.title}),n.jsx("div",{className:"nice-ksb-row__artist",children:e.artist||"—"})]}),n.jsxs("div",{className:"nice-ksb-row__meta",children:[e.genre&&n.jsx("span",{className:"nice-ksb-badge",children:e.genre}),e.year&&n.jsx("span",{className:"nice-ksb-badge",children:e.year}),e.durationSec?n.jsx("span",{className:"nice-ksb-badge",children:Xh(e.durationSec)}):null,e.externalSource&&n.jsx("span",{className:"nice-ksb-badge nice-ksb-badge--src",children:e.externalSource}),s&&n.jsxs("span",{className:"nice-ksb-badge nice-ksb-badge--score",title:s.playerName,children:[n.jsx(G.NtdTrophy,{size:11})," ",s.score.toLocaleString()]})]}),!o&&n.jsxs("button",{type:"button",className:"nice-ksb-row__play",disabled:l,onClick:y=>{y.stopPropagation(),d==null||d(e)},children:[n.jsx(G.NtdPlay,{size:13})," ",c("karaokeBrowser.play","Play")]})]})});Zo.displayName="NiceKaraokeSongRow";const Qh=({songs:e,fetchSongs:t,loading:r=!1,getCover:a,getTopScore:s,onPlay:i,onSelect:o,multiSelect:l=!1,maxSelections:c=0,showSidebar:d=!0,enableGamepad:h=!0,disabled:f=!1,disabledReason:p,t:y,className:m,style:x,id:b,accessMode:g,"data-testid":S})=>{const{t:v}=Pe(),k=y??v,[M,T]=u.useState(""),[N,j]=u.useState(""),[R,z]=u.useState(""),[A,$]=u.useState(""),[O,I]=u.useState("artist"),[U,J]=u.useState("asc"),[_,W]=u.useState({type:"all"}),[K,re]=u.useState(new Set),[X,q]=u.useState([]),[E,P]=u.useState(!1);u.useEffect(()=>{const ce=setTimeout(()=>j(M),300);return()=>clearTimeout(ce)},[M]),u.useEffect(()=>{if(e||!t)return;let ce=!1;return P(!0),Promise.resolve(t({searchQuery:N.trim()||void 0,genres:R?[R]:void 0,languages:A?[A]:void 0})).then(be=>!ce&&q(be)).catch(()=>!ce&&q([])).finally(()=>!ce&&P(!1)),()=>{ce=!0}},[e,t,N,R,A]);const C=e??X,L=u.useMemo(()=>ei(C.map(ce=>ce.genre)),[C]),w=u.useMemo(()=>ei(C.map(ce=>ce.language)),[C]),D=u.useMemo(()=>{let ce=C;const be=N.trim().toLowerCase();be&&(ce=ce.filter(Te=>`${Te.title} ${Te.artist}`.toLowerCase().includes(be))),R&&(ce=ce.filter(Te=>Te.genre===R)),A&&(ce=ce.filter(Te=>Te.language===A)),_.type==="genre"&&(ce=ce.filter(Te=>Te.genre===_.value)),_.type==="language"&&(ce=ce.filter(Te=>Te.language===_.value));const Me=U==="asc"?1:-1;return[...ce].sort((Te,je)=>{const Xe=Te[O]??"",le=je[O]??"";return typeof Xe=="number"&&typeof le=="number"?(Xe-le)*Me:String(Xe).localeCompare(String(le))*Me})},[C,N,R,A,_,O,U]),F=ce=>{re(be=>{const Me=new Set(be);return Me.has(ce)?Me.delete(ce):(c===0||Me.size<c)&&Me.add(ce),Me})},B=()=>{const ce=C.filter(be=>K.has(be.id));o==null||o({songs:ce})},V=r||E,Y=ce=>{ce===O?J(be=>be==="asc"?"desc":"asc"):(I(ce),J("asc"))},oe=u.useRef(null),[ie,ne]=u.useState(0),Z=u.useRef(0),H=u.useRef(D);H.current=D,u.useEffect(()=>{ne(ce=>{const be=Math.min(Math.max(0,ce),Math.max(0,D.length-1));return Z.current=be,be})},[D.length]);const se=u.useCallback(ce=>{var Me;const be=(Me=oe.current)==null?void 0:Me.querySelector(`[data-ksb-index="${ce}"]`);be==null||be.focus(),be==null||be.scrollIntoView({block:"nearest"})},[]),ae=u.useCallback(ce=>{Z.current=ce,ne(ce)},[]),ue=u.useCallback((ce,be=!0)=>{const Me=H.current.length;if(Me===0)return;const Te=Math.min(Me-1,Math.max(0,ce));Z.current=Te,ne(Te),be&&requestAnimationFrame(()=>se(Te))},[se]),ee=u.useCallback(ce=>ue(Z.current+ce),[ue]),de=ce=>{const be=H.current[ce];be&&(l?F(be.id):f||i==null||i(be))},fe=ce=>{switch(ce.key){case"ArrowDown":ce.preventDefault(),ee(1);break;case"ArrowUp":ce.preventDefault(),ee(-1);break;case"Home":ce.preventDefault(),ue(0);break;case"End":ce.preventDefault(),ue(H.current.length-1);break;case"PageDown":ce.preventDefault(),ee(5);break;case"PageUp":ce.preventDefault(),ee(-5);break}},xe=we.useGamepad({enabled:h,actions:{navUp:{button:"DpadUp",onPress:()=>ee(-1),repeatDelay:350,repeatRate:110},navDown:{button:"DpadDown",onPress:()=>ee(1),repeatDelay:350,repeatRate:110},stickUp:{axis:"LeftY",axisDirection:"negative",onPress:()=>ee(-1),repeatDelay:350,repeatRate:130},stickDown:{axis:"LeftY",axisDirection:"positive",onPress:()=>ee(1),repeatDelay:350,repeatRate:130},select:{button:"A",onPress:()=>de(Z.current)},confirm:{button:"Start",onPress:()=>{l&&B()}}}});return g==="hidden"?null:n.jsxs("div",{className:`nice-ksb${m?` ${m}`:""}`,style:x,id:b,"data-testid":S,children:[d&&n.jsxs("aside",{className:"nice-ksb__sidebar",children:[n.jsxs("button",{type:"button",className:`nice-ksb__node${_.type==="all"?" nice-ksb__node--active":""}`,onClick:()=>W({type:"all"}),children:[n.jsx(G.NtdMusic,{size:14})," ",k("karaokeBrowser.allSongs","All songs")," (",C.length,")"]}),L.length>0&&n.jsxs("div",{className:"nice-ksb__facet",children:[n.jsx("div",{className:"nice-ksb__facet-title",children:k("karaokeBrowser.genres","Genres")}),L.map(ce=>n.jsx("button",{type:"button",className:`nice-ksb__node${_.type==="genre"&&_.value===ce?" nice-ksb__node--active":""}`,onClick:()=>W({type:"genre",value:ce}),children:ce},ce))]}),w.length>0&&n.jsxs("div",{className:"nice-ksb__facet",children:[n.jsx("div",{className:"nice-ksb__facet-title",children:k("karaokeBrowser.languages","Languages")}),w.map(ce=>n.jsx("button",{type:"button",className:`nice-ksb__node${_.type==="language"&&_.value===ce?" nice-ksb__node--active":""}`,onClick:()=>W({type:"language",value:ce}),children:ce},ce))]})]}),n.jsxs("div",{className:"nice-ksb__main",children:[n.jsxs("div",{className:"nice-ksb__toolbar",children:[n.jsx("input",{className:"nice-ksb__search",type:"search",value:M,placeholder:k("karaokeBrowser.search","Search title or artist…"),onChange:ce=>T(ce.target.value)}),n.jsx("div",{className:"nice-ksb__sort",children:["artist","title","year","genre"].map(ce=>n.jsxs("button",{type:"button",className:`nice-ksb__sort-btn${O===ce?" nice-ksb__sort-btn--active":""}`,onClick:()=>Y(ce),children:[k(`karaokeBrowser.sort.${ce}`,ce),O===ce&&(U==="asc"?n.jsx(G.NtdChevronUp,{size:12}):n.jsx(G.NtdChevronDown,{size:12}))]},ce))}),n.jsxs("span",{className:`nice-ksb__navhint${xe.connected?" nice-ksb__navhint--pad":""}`,title:k("karaokeBrowser.navHint","Navigate with ↑ ↓ or the D-pad · Enter / A to play"),children:[xe.connected?n.jsx(G.NtdGamepad,{size:14}):n.jsx(G.NtdMove,{size:14}),n.jsx("span",{className:"nice-ksb__navhint-keys",children:xe.connected?"D-pad · A":"↑ ↓ · Enter"})]})]}),f&&p&&n.jsx("div",{className:"nice-ksb__disabled",children:p}),n.jsx("div",{className:"nice-ksb__list",role:"listbox","aria-multiselectable":l,"aria-label":k("karaokeBrowser.songs","Songs"),ref:oe,onKeyDown:fe,children:V?n.jsx("div",{className:"nice-ksb__empty",children:k("karaokeBrowser.loading","Loading…")}):D.length===0?n.jsx("div",{className:"nice-ksb__empty",children:k("karaokeBrowser.noResults","No songs found")}):D.map((ce,be)=>n.jsx(Zo,{song:ce,index:be,active:be===ie,coverUrl:(a==null?void 0:a(ce))||ce.coverImage||ce.externalCoverUrl||ce.coverPath||Zh,topScore:s==null?void 0:s(ce),selected:K.has(ce.id),multiSelect:l,disabled:f,t:k,onPlay:i,onToggleSelect:F,onFocusRow:ae},ce.id))}),l&&n.jsxs("div",{className:"nice-ksb__footer",children:[n.jsxs("span",{children:[K.size,c>0?` / ${c}`:""," ",k("karaokeBrowser.selected","selected")]}),n.jsx("button",{type:"button",className:"nice-ksb__confirm",disabled:K.size===0,onClick:B,children:k("karaokeBrowser.confirm","Add selected")})]})]})]})};function Xo(e,t,r=50,a=30){const s=Math.round(e/1e3*t),i=Math.round(r/1e3*t),o=Math.max(1,Math.round(a/1e3*t)),l=new Float32Array(s);for(let c=0;c<o;c++){const d=.5*(1-Math.cos(2*Math.PI*c/(o-1))),h=i+c-Math.floor(o/2);h>=0&&h<s&&(l[h]=d)}return l}function ti(e,t,r=1e3){const a=Math.max(1,Math.round(t/r)),s=Math.ceil(e.length/a),i=new Float32Array(s);for(let l=0;l<s;l++){const c=l*a,d=Math.min(e.length,c+a);let h=0;for(let f=c;f<d;f++)h+=Math.abs(e[f]);i[l]=h/(d-c||1)}let o=0;for(let l=0;l<i.length;l++)i[l]>o&&(o=i[l]);if(o>0)for(let l=0;l<i.length;l++)i[l]=i[l]/o;return{env:i,factor:a}}function Jh(e,t){const r=e.length,a=t.length;if(r===0||a===0)return 0;let s={lag:0,score:-1/0};const i=Math.min(2e3,a);for(let o=-i;o<=i;o++){let l=0,c=0,d=0;for(let p=0;p<r;p++){const y=p+o+Math.floor((a-r)/2);if(y<0||y>=a)continue;const m=e[p],x=t[y];l+=m*x,c+=m*m,d+=x*x}const h=Math.sqrt(Math.max(1e-9,c*d)),f=l/h;f>s.score&&(s={lag:o,score:f})}return s.lag}function Qo(e,t,r=50,a=30){try{const s=Math.max(300,Math.round(e.length/t*1e3)),i=Xo(s,t,r,a),o=ti(e,t,1e3),l=ti(i,t,1e3),d=Jh(l.env,o.env)*1e3/1e3;return Math.round(d)}catch{return null}}const ep=({deviceId:e,initialOffsetMs:t=null,onSave:r,onClose:a,rounds:s=3,t:i,className:o,style:l,id:c,accessMode:d,"data-testid":h})=>{const{t:f}=Pe(),p=i??f,[y,m]=u.useState(null),[x,b]=u.useState(t),[g,S]=u.useState(!1),[v,k]=u.useState([]),[M,T]=u.useState(0),[N,j]=u.useState(!1),R=u.useRef(!1);u.useEffect(()=>{b(t??null)},[t,e]);const z=async()=>{const I=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),U=new AudioContext,J=U.sampleRate,_=U.createMediaStreamSource(I),W=U.createScriptProcessor(2048,1,1);_.connect(W),W.connect(U.destination);const K=1200,re=Math.round(K/1e3*J),X=new Float32Array(re);let q=0,E=!1;W.onaudioprocess=F=>{if(E)return;const B=F.inputBuffer.getChannelData(0),V=Math.min(B.length,re-q);V>0&&(X.set(B.subarray(0,V),q),q+=V),q>=re&&(E=!0)},await new Promise(F=>setTimeout(F,80));const P=new AudioContext,C=P.createOscillator(),L=P.createGain();C.type="sine",C.frequency.value=1e3,L.gain.value=1e-4,C.connect(L),L.connect(P.destination);const w=P.currentTime+.05;L.gain.setValueAtTime(1e-4,w-.01),L.gain.linearRampToValueAtTime(1,w),L.gain.linearRampToValueAtTime(1e-4,w+.06),C.start(w-.02),C.stop(w+.1),await new Promise(F=>{const B=()=>{if(E||q>=re){F();return}setTimeout(B,50)};setTimeout(()=>{E=!0,F()},K+500),B()}),W.onaudioprocess=null;try{W.disconnect()}catch{}try{_.disconnect()}catch{}try{await P.close()}catch{}try{await U.close()}catch{}I.getTracks().forEach(F=>F.stop());const D=X.subarray(0,q);return Qo(D,J,130,30)},A=async()=>{if(!R.current){R.current=!0,j(!0),m(p("latencyCalibrator.requestingMic","Requesting microphone — click allow if prompted")),b(null),k([]),T(0);try{const I=[];for(let J=0;J<s;J++){m(`${p("latencyCalibrator.playingTone","Playing test tone and recording…")} (${J+1}/${s})`),T(Math.round(J/s*100));const _=await z();_!==null&&(I.push(Math.max(-500,Math.min(2e3,Math.round(_)))),k([...I])),J<s-1&&await new Promise(W=>setTimeout(W,400))}if(T(100),I.length===0){m(p("latencyCalibrator.noSignal","No signal detected — try louder or check the microphone"));return}let U;if(I.length>=3){const _=[...I].sort((W,K)=>W-K).slice(1,-1);U=Math.round(_.reduce((W,K)=>W+K,0)/_.length)}else U=Math.round(I.reduce((J,_)=>J+_,0)/I.length);b(U),m(`${p("latencyCalibrator.measured","Measured")} ~${U} ms (${I.length}: ${I.join(", ")} ms)`)}catch(I){m(`${p("latencyCalibrator.calibrationError","Calibration error: ")}${I instanceof Error?I.message:String(I)}`)}finally{R.current=!1,j(!1)}}},$=async()=>{if(!(x===null||!r)){S(!0);try{await r(Math.round(x)),m(p("latencyCalibrator.saved","Saved"))}catch(I){m(`${p("latencyCalibrator.saveError","Save error: ")}${String(I)}`)}finally{S(!1)}}},O={padding:"7px 16px",border:"none",borderRadius:8,cursor:"pointer",fontWeight:600};return d==="hidden"?null:n.jsxs("div",{className:`nice-latency-calibrator${o?` ${o}`:""}`,style:{padding:12,color:"var(--nice-text, inherit)",...l},id:c,"data-testid":h,children:[n.jsxs("h5",{style:{margin:"0 0 8px",display:"flex",alignItems:"center",gap:6},children:[n.jsx(G.NtdSettings,{size:16})," ",p("latencyCalibrator.title","Latency calibrator — microphone")]}),n.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:[p("latencyCalibrator.device","Device"),": ",n.jsx("small",{children:e||"—"})]}),n.jsxs("div",{style:{marginTop:8,display:"flex",gap:8},children:[n.jsx("button",{type:"button",onClick:A,disabled:N,style:{...O,background:"var(--nice-accent, #3b82f6)",color:"var(--nice-text-on-primary, #fff)"},children:p("latencyCalibrator.calibrate","Calibrate")}),n.jsx("button",{type:"button",onClick:()=>{b(null),m(null),k([]),T(0)},style:{...O,background:"var(--nice-bg-tertiary)",color:"var(--nice-text, #e2e8f0)"},children:p("latencyCalibrator.clear","Clear")})]}),N&&n.jsx("div",{style:{marginTop:8,height:6,borderRadius:3,background:"var(--nice-bg-tertiary)",overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:`${M}%`,background:"var(--nice-accent, #3b82f6)",transition:"width 0.2s"}})}),v.length>0&&n.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:[p("latencyCalibrator.rounds","Rounds"),": ",v.join(", ")," ms"]}),n.jsxs("div",{style:{marginTop:8,fontSize:13},children:[n.jsxs("div",{children:[p("latencyCalibrator.status","Status"),": ",y??p("latencyCalibrator.none","none")]}),n.jsxs("div",{children:[p("latencyCalibrator.measuredOffset","Measured offset"),":"," ",x!==null?n.jsxs("strong",{children:[x," ms"]}):"—"]})]}),n.jsxs("div",{style:{marginTop:12,display:"flex",gap:8},children:[r&&n.jsx("button",{type:"button",onClick:$,disabled:x===null||g,style:{...O,background:"var(--nice-success, #22c55e)",color:"var(--nice-text-on-primary, #fff)",opacity:x===null||g?.5:1},children:p("latencyCalibrator.save","Save")}),a&&n.jsx("button",{type:"button",onClick:a,style:{...O,background:"transparent",border:"1px solid var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)"},children:p("latencyCalibrator.close","Close")})]})]})},tp=[{value:"normal",label:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(G.NtdMicrophone,{size:14})," Mic"]})},{value:"pad",label:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(G.NtdGamepad,{size:14})," Pad"]})},{value:"demo",label:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(G.NtdStopwatch,{size:14})," Demo"]})}],Jo=({players:e,defaultPlayers:t,onPlayersChange:r,gameMode:a="normal",onGameModeChange:s,gameModes:i=tp,difficulty:o="normal",onDifficultyChange:l,audioInputs:c,maxPlayers:d=4,onCalibrate:h,t:f,className:p,style:y,id:m,accessMode:x,"data-testid":b})=>{const{t:g}=Pe(),S=f??g,[v,k]=we.useControllableState({value:e,defaultValue:t,fallbackValue:[],onChange:r,componentName:"NiceKaraokeSetupPanel"}),[M,T]=u.useState([]);u.useEffect(()=>{var I,U,J;if(c||!((I=navigator.mediaDevices)!=null&&I.enumerateDevices))return;let $=!1;const O=()=>navigator.mediaDevices.enumerateDevices().then(_=>!$&&T(_.filter(W=>W.kind==="audioinput"))).catch(()=>{});return O(),(J=(U=navigator.mediaDevices).addEventListener)==null||J.call(U,"devicechange",O),()=>{var _,W;$=!0,(W=(_=navigator.mediaDevices).removeEventListener)==null||W.call(_,"devicechange",O)}},[c]);const N=c??M,j=u.useMemo(()=>[{value:"",label:S("karaokeSetup.noMic","No microphone")},...N.map(($,O)=>({value:$.deviceId,label:$.label||`${S("karaokeSetup.microphone","Microphone")} ${O+1}`}))],[N,S]),R=($,O)=>k(v.map(I=>I.id===$?{...I,...O}:I)),z=()=>{if(v.length>=d)return;const $=v.reduce((O,I)=>Math.max(O,I.id),0)+1;k([...v,{id:$,name:`${S("karaokeSetup.player","Player")} ${v.length+1}`,color:et[v.length%et.length],micId:null}])},A=$=>k(v.filter(O=>O.id!==$));return x==="hidden"?null:n.jsxs("div",{className:`nice-karaoke-setup${p?` ${p}`:""}`,style:{display:"flex",flexDirection:"column",gap:16,...y},id:m,"data-testid":b,children:[n.jsxs("div",{style:{display:"flex",gap:24,flexWrap:"wrap"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:12,fontWeight:600,marginBottom:6,color:"var(--nice-text-muted, #94a3b8)"},children:S("karaokeSetup.mode","Game mode")}),n.jsx(ve.NiceSegmentedControl,{options:i,value:a,onChange:$=>s==null?void 0:s($)})]}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:12,fontWeight:600,marginBottom:6,color:"var(--nice-text-muted, #94a3b8)"},children:S("karaokeSetup.difficulty","Difficulty")}),n.jsx(ve.NiceSegmentedControl,{options:[{value:"easy",label:S("karaokeSetup.easy","Easy")},{value:"normal",label:S("karaokeSetup.normal","Normal")},{value:"hard",label:S("karaokeSetup.hard","Hard")}],value:o,onChange:$=>l==null?void 0:l($)})]})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[n.jsxs("div",{style:{fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:[S("karaokeSetup.players","Players")," (",v.length,"/",d,")"]}),v.map($=>n.jsx(ve.NiceCard,{children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[n.jsx(ve.NiceColorPicker,{value:$.color||et[0],onChange:O=>R($.id,{color:O})}),n.jsx("div",{style:{flex:"1 1 160px",minWidth:140},children:n.jsx(ve.NiceTextInput,{value:$.name,onChange:O=>R($.id,{name:O}),placeholder:S("karaokeSetup.playerName","Player name"),size:"sm"})}),n.jsx("div",{style:{flex:"1 1 180px",minWidth:150},children:n.jsx(ve.NiceSelect,{options:j,value:$.micId??"",onChange:O=>R($.id,{micId:(typeof O=="string"?O:O[0])||null}),placeholder:S("karaokeSetup.selectMic","Microphone"),size:"sm"})}),h&&$.micId&&n.jsxs(ve.NiceButton,{variant:"ghost",size:"sm",onClick:()=>h($.micId),children:[n.jsx(G.NtdSettings,{size:14})," ",S("karaokeSetup.calibrate","Calibrate")]}),n.jsx(ve.NiceButton,{variant:"danger",size:"sm",onClick:()=>A($.id),"aria-label":S("karaokeSetup.remove","Remove"),children:n.jsx(G.NtdClose,{size:14})})]})},$.id)),n.jsx("div",{children:n.jsxs(ve.NiceButton,{variant:"primary",onClick:z,disabled:v.length>=d,children:[n.jsx(G.NtdPlus,{size:14})," ",S("karaokeSetup.addPlayer","Add player")]})})]})]})},np=["freeForAll","roundRobin","hostOnly","firstCome"],rp={freeForAll:G.NtdDice,roundRobin:G.NtdRepeat,hostOnly:G.NtdCrown,firstCome:G.NtdLightning},ap={freeForAll:"success",roundRobin:"warning",hostOnly:"info",firstCome:"danger"},el=({players:e,mode:t,defaultMode:r,onModeChange:a,turnTimeSec:s=30,hostIndex:i=0,onActivePlayerChange:o,myPlayerIndex:l,t:c,className:d,style:h,id:f,accessMode:p,"data-testid":y})=>{const{t:m}=Pe(),x=c??m,[b,g]=we.useControllableState({value:t,defaultValue:r,fallbackValue:"freeForAll",onChange:a,componentName:"NiceKaraokeSelectionMode"}),S={freeForAll:x("songSelection.freeForAll","Free for all"),roundRobin:x("songSelection.roundRobin","Round robin"),hostOnly:x("songSelection.hostOnly","Host only"),firstCome:x("songSelection.firstCome","First come")},[v,k]=u.useState(0),[M,T]=u.useState(s),N=u.useRef(null),[j,R]=u.useState(null),[z,A]=u.useState(!1),[$,O]=u.useState(null),I=u.useRef(null),U=u.useMemo(()=>b==="hostOnly"?i:b==="roundRobin"?v%Math.max(1,e.length):b==="firstCome"?z?-1:$??-1:-1,[b,v,e.length,i,z,$]);u.useEffect(()=>{o==null||o(U)},[U,o]),u.useEffect(()=>{if(b!=="roundRobin"||s<=0){N.current&&clearInterval(N.current);return}return T(s),N.current=setInterval(()=>{T(re=>re<=1?(k(X=>X+1),s):re-1)},1e3),()=>{N.current&&clearInterval(N.current)}},[b,s,v]);const J=u.useCallback(()=>{O(null),A(!1),R(3),I.current&&clearInterval(I.current),I.current=setInterval(()=>{R(re=>re===null||re<=1?(I.current&&clearInterval(I.current),A(!0),null):re-1)},1e3)},[]);u.useEffect(()=>()=>{I.current&&clearInterval(I.current)},[]),u.useEffect(()=>{b!=="firstCome"&&(R(null),A(!1),O(null))},[b]);const _=u.useCallback(()=>{k(re=>re+1),T(s)},[s]),W=re=>{var X;return((X=e[re])==null?void 0:X.name)||`${x("songSelection.player","Player")} ${re+1}`},K=U>=0&&U<e.length?e[U]:null;return p==="hidden"?null:n.jsxs("div",{className:`nice-karaoke-selection-mode${d?` ${d}`:""}`,style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,padding:"8px 12px",background:"var(--nice-bg-secondary)",borderRadius:10,border:"1px solid var(--nice-border, #333)",...h},id:f,"data-testid":y,children:[n.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:np.map(re=>n.jsxs(ve.NiceButton,{size:"sm",variant:b===re?ap[re]:"outline",onClick:()=>g(re),children:[u.createElement(rp[re],{size:14})," ",S[re]]},re))}),b!=="freeForAll"&&b!=="firstCome"&&K&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[n.jsxs(ve.NiceBadge,{variant:U===l?"success":"secondary",children:[n.jsx(G.NtdMicrophone,{size:12})," ",W(U)]}),U===l&&n.jsx("span",{style:{color:"var(--nice-success, #4caf50)",fontSize:12,fontWeight:600},children:x("songSelection.yourTurn","Your turn!")})]}),b==="roundRobin"&&s>0&&n.jsx("div",{style:{flex:1,minWidth:120,maxWidth:200},children:n.jsx(ve.NiceProgress,{value:M,max:s,variant:M<=5?"error":M<=10?"warning":"info",showLabel:!0,formatValue:re=>`${re}s`})}),b==="roundRobin"&&n.jsxs(ve.NiceButton,{size:"sm",variant:"ghost",onClick:_,children:[x("songSelection.next","Next")," ",n.jsx(G.NtdPlay,{size:12})]}),b==="firstCome"&&n.jsxs(n.Fragment,{children:[j!==null&&n.jsx("div",{style:{fontSize:32,fontWeight:900,color:"var(--nice-error, #f44336)",minWidth:60,textAlign:"center"},children:j}),z&&$===null&&n.jsxs(ve.NiceBadge,{variant:"danger",children:[n.jsx(G.NtdLightning,{size:12})," ",x("songSelection.raceGo","GO! Pick a song!")]}),$!==null&&$<e.length&&n.jsxs(ve.NiceBadge,{variant:"success",children:[n.jsx(G.NtdTrophy,{size:12})," ",W($)," ",x("songSelection.raceWon","picks!")]}),n.jsx(ve.NiceButton,{size:"sm",variant:j!==null?"secondary":"danger",onClick:J,disabled:j!==null,children:$!==null?n.jsxs(n.Fragment,{children:[n.jsx(G.NtdRepeat,{size:12})," ",x("songSelection.raceAgain","New race")]}):n.jsxs(n.Fragment,{children:[n.jsx(G.NtdLightning,{size:12})," ",x("songSelection.raceStart","Start race")]})})]})]})};function sp(e,t,r,a){return u.useMemo(()=>e==="freeForAll"?!0:e==="firstCome"?t===-1:e==="hostOnly"?a===r:e==="roundRobin"?a===t:!1,[e,t,r,a])}const ip=({players:e,defaultPlayers:t,onPlayersChange:r,gameMode:a,onGameModeChange:s,gameModes:i,difficulty:o,onDifficultyChange:l,audioInputs:c,maxPlayers:d=4,onCalibrate:h,initialSelectionMode:f="freeForAll",turnTimeSec:p=30,hostIndex:y=0,myPlayerIndex:m,onChange:x,variant:b="bar",t:g,className:S,style:v,id:k,accessMode:M,"data-testid":T})=>{const{t:N}=Pe(),j=g??N,[R,z]=we.useControllableState({value:e,defaultValue:t,fallbackValue:[],onChange:r,componentName:"NiceKaraokeSessionJoin"}),[A,$]=u.useState([]);u.useEffect(()=>{var w,D,F;if(c||!((w=navigator.mediaDevices)!=null&&w.enumerateDevices))return;let C=!1;const L=()=>navigator.mediaDevices.enumerateDevices().then(B=>!C&&$(B.filter(V=>V.kind==="audioinput"))).catch(()=>{});return L(),(F=(D=navigator.mediaDevices).addEventListener)==null||F.call(D,"devicechange",L),()=>{var B,V;C=!0,(V=(B=navigator.mediaDevices).removeEventListener)==null||V.call(B,"devicechange",L)}},[c]);const O=c??A,I=O.length===0,U=R.some(C=>!C.micId),J=!U,[_,W]=u.useState(f),[K,re]=u.useState(-1),X=u.useCallback((C,L)=>{x==null||x({selectionMode:C,activePickerIndex:L,allMicsAssigned:J,noInputDevices:I})},[x,J,I]),q=u.useCallback(C=>{W(C),X(C,K)},[X,K]),E=u.useCallback(C=>{re(C),X(_,C)},[X,_]),P=u.useMemo(()=>({padding:10,borderRadius:8,fontWeight:700,marginTop:8,textAlign:"center"}),[]);return M==="hidden"?null:n.jsxs("div",{className:`nice-karaoke-session-join${S?` ${S}`:""}`,style:b==="card"?{background:"var(--nice-bg-secondary)",borderRadius:12,padding:16,...v}:v,id:k,"data-testid":T,children:[n.jsx(Jo,{players:R,onPlayersChange:z,gameMode:a,onGameModeChange:s,gameModes:i,difficulty:o,onDifficultyChange:l,audioInputs:O,maxPlayers:d,onCalibrate:h,t:j}),I&&n.jsxs("div",{style:{...P,background:"var(--nice-error, #ef4444)",color:"#fff"},children:[j("karaokeSessionJoin.noInputDevices","No microphone detected"),n.jsx("br",{}),n.jsx("span",{style:{fontWeight:400,fontSize:13},children:j("karaokeSessionJoin.noInputDevicesHint","Connect a microphone to sing.")})]}),!I&&U&&n.jsx("div",{style:{...P,background:"var(--nice-warning, #f59e0b)",color:"var(--nice-text-on-primary, #222)",fontSize:14},children:j("karaokeSessionJoin.assignMicWarning","Assign a microphone to each player.")}),R.length>1&&n.jsx("div",{style:{marginTop:12},children:n.jsx(el,{players:R,mode:_,onModeChange:q,onActivePlayerChange:E,turnTimeSec:p,hostIndex:y,myPlayerIndex:m,t:j})})]})};function Ue(e,t){var s;const r=((s=t.split(".").pop())==null?void 0:s.toLowerCase())??"",a=r==="otf"?"opentype":r==="woff2"?"woff2":r==="woff"?"woff":"truetype";return{family:e,url:`/fonts/${t}`,format:a}}const op=[Ue("Belagak","BelagakRegular-dr1zE.otf"),Ue("Big Scratch Brush","BigScratchBrush-PVY9g.ttf"),Ue("Gerhaus","Gerhaus-PK69E.ttf"),Ue("Gerhaus Italic","GerhausItalic-d96l7.ttf"),Ue("Handone Medium","HandoneMedium-nAevO.otf"),Ue("Handson Bold","HandsonBold-9MnrL.otf"),Ue("Kineks Round Bold","KineksRoundBold-7OR34.ttf"),Ue("Kineks Round Light","KineksRoundLight-m2r35.ttf"),Ue("Kineks Round Medium","KineksRoundMedium-drejZ.ttf"),Ue("Kineks Round","KineksRoundRegular-PVRl7.ttf"),Ue("Kineks Round SemiBold","KineksRoundSemiBold-LVWG3.ttf"),Ue("Lemon Jelly","LemonJellyPersonalUse-dEqR.ttf"),Ue("Lemon Milk Bold","LemonMilkBold-gx2B3.otf"),Ue("Lemon Milk Bold Italic","LemonMilkBoldItalic-PKZ3P.otf"),Ue("Lemon Milk Light","LemonMilkLight-owxMq.otf"),Ue("Lemon Milk Light Italic","LemonMilkLightItalic-7BjPE.otf"),Ue("Lemon Milk Medium","LemonMilkMedium-mLZYV.otf"),Ue("Lemon Milk Medium Italic","LemonMilkMediumItalic-d95nl.otf"),Ue("Lemon Milk","LemonMilkRegular-X3XE2.otf"),Ue("Lemon Milk Italic","LemonMilkRegularItalic-L3AEy.otf"),Ue("Pemage","PemageRegular-YqrdO.otf"),Ue("Rosmatika","RosmatikaRegular-BWA45.ttf"),Ue("Scabber","Scabber-q2Mn0.ttf"),Ue("Stylish Calligraphy","StylishCalligraphyDemo-XPZZ.ttf"),Ue("Super Adorable","SuperAdorable-MAvyp.ttf"),Ue("Super Chiby","SuperChiby-BL62V.ttf"),Ue("Super Joyful","SuperJoyful-lxwPq.ttf"),Ue("Super Kindly","SuperKindly-drE8E.ttf"),Ue("Super Meatball","SuperMeatball-Yq1Gy.ttf")],ts="nice2dev-karaoke-display",lp=[{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"},...op.map(e=>({value:e.family,label:e.family}))],tl=[{id:"default",name:"Cyan ? Yellow ? Amber",sungGradient:["#00e5ff","#ffe600","#ffab00"],goldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,229,255,0.6)"},{id:"neon-pink",name:"Neon Pink ? Violet ? Blue",sungGradient:["#ff1493","#9b59b6","var(--nice-primary, #3498db)"],goldGradient:["var(--nice-warning, #FFD700)","#FF69B4","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,20,147,0.6)"},{id:"fire",name:"Red ? Orange ? Yellow",sungGradient:["#ff1744","#ff9100","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#FF6D00","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,23,68,0.6)"},{id:"ocean",name:"Deep Blue ? Teal ? Aqua",sungGradient:["#1a237e","#00897b","#00e5ff"],goldGradient:["var(--nice-warning, #FFD700)","#00BCD4","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,137,123,0.6)"},{id:"forest",name:"Green ? Lime ? Yellow",sungGradient:["#1b5e20","#76ff03","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#76ff03","var(--nice-warning, #FFD700)"],glowColor:"rgba(118,255,3,0.6)"},{id:"retro",name:"Orange ? Pink ? Purple",sungGradient:["#ff6d00","var(--nice-color-accent-pink, #e91e63)","#7b1fa2"],goldGradient:["var(--nice-warning, #FFD700)","var(--nice-color-accent-pink, #e91e63)","var(--nice-warning, #FFD700)"],glowColor:"rgba(233,30,99,0.6)"}],mn={presetId:"default",customSungGradient:["#00e5ff","#ffe600","#ffab00"],customGoldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],customGlowColor:"rgba(0,229,255,0.6)",animationMode:"ball",fontFamily:"Arial",transitionEffect:"none",curtainPrimaryColor:"#8b0000",curtainSecondaryColor:"#1a0000",curtainDurationMs:900,immersiveMode:!1};let ni=!1;function nl(){try{const e=localStorage.getItem(ts);if(e){const t=JSON.parse(e);return{...mn,...t}}}catch{}return{...mn}}async function cp(e){if(ni||(ni=!0,!e))return;const t=await e();if(t)try{const r=JSON.parse(t),a={...mn,...r};localStorage.setItem(ts,JSON.stringify(a))}catch{}}function dp(e){const t=JSON.stringify(e);localStorage.setItem(ts,t),ns(e)}function rl(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=tl.find(r=>r.id===e.presetId);return t?{sungGradient:t.sungGradient,goldGradient:t.goldGradient,glowColor:t.glowColor}:{sungGradient:mn.customSungGradient,goldGradient:mn.customGoldGradient,glowColor:mn.customGlowColor}}function ns(e){const{sungGradient:t,goldGradient:r,glowColor:a}=rl(e),s=document.documentElement;s.style.setProperty("--karaoke-sung-gradient",`linear-gradient(90deg, ${t[0]} 0%, ${t[1]} 60%, ${t[2]} 100%)`),s.style.setProperty("--karaoke-gold-gradient",`linear-gradient(90deg, ${r[0]}, ${r[1]}, ${r[2]})`),s.style.setProperty("--karaoke-gold-glow-first",`0 0 12px ${r[0]}`),s.style.setProperty("--karaoke-active-glow",`0 0 10px ${a}, 0 0 4px ${t[1]}80`),s.style.setProperty("--karaoke-active-drop-first",`0 0 6px ${a}`),s.style.setProperty("--karaoke-active-bg",`linear-gradient(90deg, transparent 0%, ${t[0]}14 20%, ${t[1]}10 80%, transparent 100%)`),s.style.setProperty("--karaoke-font-family",e.fontFamily||"Arial")}function up(){const e=nl();ns(e)}function hp(e){const t=(e||"").split(/\r?\n/),r=[];for(let a=0;a<t.length;a++){const s=t[a].trim();if(s&&/^[:*F]\s/.test(s)){const i=s.slice(1).trim().split(/\s+/),o=parseInt(i[0]||"0",10),l=parseInt(i[1]||"0",10),c=isNaN(o)?0:o/10,d=isNaN(l)?0:l/10;r.push({lineIndex:a,start:c,duration:d,raw:t[a]})}}return r}const pp=({index:e,data:t})=>{const{lines:r,notes:a,currentIndex:s,animationConfig:i}=t,o=r[e]??"",l=a.findIndex(g=>g.lineIndex===e),c=l>=0&&l===s,d=(i==null?void 0:i.enabled)??!0,h=(i==null?void 0:i.durationMs)??300,f=(i==null?void 0:i.translateX)??8,p=(i==null?void 0:i.scale)??1.01,y=(i==null?void 0:i.easing)??"cubic-bezier(.22,1,.36,1)",m=(i==null?void 0:i.opacityInactive)??.9,x=(i==null?void 0:i.boxShadow)??"0 6px 18px var(--nice-primary-tint-8, rgba(3,102,214,0.08))",b={transition:d?`transform ${h}ms ${y}, opacity ${h}ms ${y}`:"none",transform:c?`translateX(${f}px) scale(${p})`:"translateX(0px) scale(1)",opacity:c?1:m,boxShadow:c?x:"none"};return n.jsx("div",{style:{height:"100%",padding:"4px 6px",borderRadius:4},"data-note-idx":l>=0?l:void 0,children:n.jsx("div",{style:{...b,background:c?"var(--nice-primary-tint-12, rgba(0,130,200,0.12))":"transparent",padding:"4px 6px",borderRadius:4},children:n.jsx("code",{style:{fontFamily:"monospace",whiteSpace:"pre-wrap"},children:o})})})},al=({ultrastarText:e,audioUrl:t,audioRef:r,animationConfig:a})=>{const{t:s}=Pe(),i=u.useRef(null),o=r??i,[l,c]=u.useState(!1),d=u.useMemo(()=>hp(e),[e]),h=u.useRef(null),f=u.useRef(null),p=u.useRef(0),y=u.useRef(0),[m,x]=u.useState(-1),b=u.useMemo(()=>(e||"").split(/\r?\n/),[e]),g=28,S=b.length*g,v=u.useMemo(()=>({lines:b,notes:d,currentIndex:m,animationConfig:a}),[b,d,m,a]),k=u.useCallback((M,T)=>n.jsx(pp,{index:T,data:v}),[v]);return u.useEffect(()=>{const M=o.current;M&&(l?M.play().catch(()=>c(!1)):M.pause())},[l,o]),u.useEffect(()=>{const M=o.current;if(!M)return;let T=-1;const N=a??null,j=N&&typeof N.scrollSmooth=="number"?N.scrollSmooth:.18;let R=performance.now();const z=()=>{var X,q;const A=performance.now(),$=Math.max(0,Math.min(.2,(A-R)/1e3));R=A;const O=M.currentTime||0;p.current=O;let I=-1;for(let E=0;E<d.length;E++){const P=d[E];if(O>=P.start&&O<P.start+Math.max(.001,P.duration)){I=E;break}}I!==T&&(T=I,x(I));let U=0;if(T>=0){const E=((X=d[T])==null?void 0:X.lineIndex)??0,P=((q=h.current)==null?void 0:q.clientHeight)??220;U=E*g-P/2+g/2;const C=Math.max(0,S-P);(isNaN(U)||!isFinite(U))&&(U=0),U=Math.max(0,Math.min(U,C))}const J=1-Math.pow(Math.max(0,1-j),Math.min(4,$*60)),re=(((a==null?void 0:a.scrollEasing)||"easeOutCubic")==="linear"?E=>E:E=>1-Math.pow(1-E,3))(J);y.current=y.current+(U-y.current)*re;try{const E=h.current;E&&typeof E.scrollTop=="number"&&(E.scrollTop=Math.round(y.current))}catch{}f.current=requestAnimationFrame(z)};return f.current=requestAnimationFrame(z),()=>{f.current&&cancelAnimationFrame(f.current)}},[o,d,S,a]),n.jsxs("div",{children:[n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[n.jsx("button",{onClick:()=>c(M=>!M),disabled:!t,children:l?"Pause":"Play"}),n.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-secondary, #666)"},children:[(p.current||0).toFixed(2),"s"]}),n.jsxs("div",{style:{marginLeft:"auto",fontSize:13,color:"var(--nice-text-secondary, #666)"},children:["Notes: ",d.length]})]}),n.jsx("div",{style:{border:"1px solid var(--nice-border, #ddd)",height:220,overflow:"hidden",padding:8,position:"relative"},children:e?n.jsx(ve.NiceVirtualScroller,{ref:h,items:b,itemHeight:g,height:220,renderItem:k,style:{border:"none",borderRadius:0,background:"transparent",fontSize:"inherit"}}):n.jsx("div",{style:{color:"var(--nice-text-secondary, #888)"},children:s("karaokeEditor.noText","No text")})}),!r&&n.jsx("audio",{ref:i,src:t||void 0,preload:"metadata",style:{display:"none"}})]})};function fp(e){const t=(e||"").split(/\r?\n/).map(a=>a.replace(/\s+$/,"")),r=[];for(let a=0;a<t.length;a++){const s=t[a].trim();if(/^[:*F]\s/.test(s)){const i=s.slice(1).trim().split(/\s+/),o=parseInt(i[0]||"0",10)/10||0,l=parseInt(i[1]||"0",10)/10||.1;r.push({lineIndex:a,start:o,duration:l})}}return{lines:t,notes:r}}const mp=new Set;function sl({ultrastarText:e,audioUrl:t,audioRef:r,ytRef:a}){const{lines:s,notes:i}=u.useMemo(()=>fp(e),[e]),[o,l]=u.useState(mp),c=u.useRef(i);c.current=i;const d=u.useRef(t);return d.current=t,u.useEffect(()=>{let h=null,f=null;if(!(a!=null&&a.current))if(r!=null&&r.current)h=r.current;else{const x=document.querySelector("audio");x instanceof HTMLAudioElement?h=x:d.current&&(f=document.createElement("audio"),f.src=d.current,f.preload="metadata",f.style.display="none",document.body.appendChild(f),h=f)}let p=0,y="";const m=()=>{let x=0;const b=a==null?void 0:a.current;if(b&&typeof b.getCurrentTime=="function")try{x=b.getCurrentTime()||0}catch{x=0}else x=h&&h.currentTime||0;const g=new Set;for(const v of c.current)x>=v.start&&x<v.start+Math.max(.001,v.duration)&&g.add(v.lineIndex);const S=[...g].join(",");S!==y&&(y=S,l(g)),p=requestAnimationFrame(m)};return p=requestAnimationFrame(m),()=>{cancelAnimationFrame(p),f==null||f.remove()}},[]),n.jsx("div",{style:{width:"100%",height:340,overflow:"hidden",background:"#101010",padding:"20px 0",boxSizing:"border-box"},children:s.map((h,f)=>{const p=o.has(f);return n.jsx("div",{"aria-current":p||void 0,style:{font:"18px monospace",lineHeight:"22px",whiteSpace:"pre",padding:"0 10px",color:p?"var(--nice-info, #00aaff)":"var(--nice-overlay-light-90, #e2e8f0)",background:p?"rgba(0,130,200,0.16)":void 0},children:h||" "},f)})})}const gp=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),ri=e=>{(!isFinite(e)||e<0)&&(e=0);const t=Math.floor(e/60),r=Math.floor(e%60);return`${t}:${r.toString().padStart(2,"0")}`},Jr={border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},yp=({isPlaying:e,index:t,count:r,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek:d,onVolume:h})=>{const{t:f}=Pe();return n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[n.jsx("div",{}),n.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-secondary)"},children:[ri(a)," / ",ri(s)]})]}),n.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[n.jsxs("div",{style:{display:"flex",gap:8},children:[n.jsx("button",{onClick:o,disabled:t<=0,title:f("playerControls.prev","Prev"),"aria-label":f("playerControls.previousTrack","Previous track"),style:Jr,children:n.jsx(G.NtdSkipBack,{size:16})}),n.jsx("button",{onClick:c,title:e?f("playerControls.pause","Pause"):f("playerControls.play","Play"),"aria-label":e?f("playerControls.pause","Pause"):f("playerControls.play","Play"),style:Jr,children:e?n.jsx(G.NtdPause,{size:16}):n.jsx(G.NtdPlay,{size:16})}),n.jsx("button",{onClick:l,disabled:t>=r-1,title:f("playerControls.next","Next"),"aria-label":f("playerControls.nextTrack","Next track"),style:Jr,children:n.jsx(G.NtdSkipForward,{size:16})})]}),n.jsx("input",{type:"range",min:0,max:Math.max(1,s),step:.1,value:a,"aria-label":f("playerControls.seekPosition","Seek position"),onChange:p=>d(parseFloat(p.target.value))}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[n.jsx(G.NtdVolume,{size:16}),n.jsx("input",{type:"range",min:0,max:1,step:.01,value:i,"aria-label":f("playerControls.volume","Volume"),onChange:p=>h(parseFloat(p.target.value))})]})]})]})},il=u.memo(yp);function bp(e,t,r,a,s){const o=Math.max(1,Math.floor(a.length/48)),l=t/48;for(let c=0;c<48;c++){const d=a[c*o]/255,h=d*(r-6),f=c*l,p=r-h,y=c/48*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(f+1,p,l-2,h)}}function vp(e,t,r,a,s,i){if(!i.current){const f=[];for(let y=0;y<24;y++)f.push({ang:y/24*Math.PI*2,phase:Math.random()*Math.PI*2,baseR:Math.min(t,r)*.22+Math.random()*30});i.current={nodes:f}}const o=i.current,l=t/2,c=r/2,d=26+a*80,h=[];for(const f of o.nodes){f.phase+=.02+a*.06;const p=f.baseR+Math.sin(f.phase)*d,y=l+Math.cos(f.ang)*p,m=c+Math.sin(f.ang)*p;h.push([y,m])}e.fillStyle=`hsla(${s}, 70%, 55%, .22)`,e.strokeStyle=`hsla(${(s+40)%360}, 90%, 65%, .9)`,e.lineWidth=2,e.beginPath();for(let f=0;f<h.length;f++){const[p,y]=h[f],[m,x]=h[(f+1)%h.length],b=(p+m)/2,g=(y+x)/2;f===0?e.moveTo(b,g):e.quadraticCurveTo(p,y,b,g)}e.closePath(),e.fill(),e.stroke()}function xp(e,t,r,a,s,i){i.current||(i.current={items:[]});const o=i.current;Math.random()<.06+a*.25&&o.items.push({x:Math.random()*t,y:Math.random()*r,r:8+Math.random()*24,life:1,hue:(s+Math.random()*120)%360});const l=[];for(const c of o.items){c.r+=2+a*14,c.life*=.975-a*.02,c.life>.04&&l.push(c);const d=e.createRadialGradient(c.x,c.y,1,c.x,c.y,c.r);d.addColorStop(0,`hsla(${c.hue}, 90%, 60%, ${.35*c.life})`),d.addColorStop(.6,`hsla(${(c.hue+40)%360}, 80%, 55%, ${.18*c.life})`),d.addColorStop(1,`hsla(${(c.hue+80)%360}, 70%, 50%, 0)`),e.fillStyle=d,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}o.items=l}const Sp="var(--nice-text-muted, #94a3b8)",kp=({height:e,coverUrl:t,title:r,subtitle:a,label:s})=>n.jsx("div",{style:{textAlign:"center",color:"var(--nice-text-secondary, #e2e8f0)"},children:t?n.jsx("img",{alt:"cover",src:t,style:{height:e-24,objectFit:"contain"}}):n.jsxs("div",{style:{opacity:.8},children:[n.jsx("div",{style:{fontSize:18,fontWeight:600},children:r??"—"}),n.jsx("div",{style:{marginTop:8,fontSize:12,color:Sp},children:s??a??"—"})]})});function Jt(e,t){return e+Math.random()*(t-e)}function wp(e,t,r,a,s,i,o){o.current||(o.current={embers:[],t:0});const l=o.current,c=e.createLinearGradient(0,r,0,r*.4);c.addColorStop(0,`hsla(${(i+30)%360}, 90%, 50%, .35)`),c.addColorStop(1,`hsla(${(i+10)%360}, 90%, 50%, 0)`),e.fillStyle=c,e.fillRect(0,0,t,r);const d=6;for(let f=0;f<d;f++){const p=(f+.5)/d*t,y=(a[Math.floor((f+1)/(d+1)*a.length)]||0)/255,m=r*.18+(.25+s*.6+y*.7)*r*.55,x=e.createLinearGradient(p,r,p,r-m);x.addColorStop(0,`hsla(${(i+40)%360},100%,55%,.9)`),x.addColorStop(.5,`hsla(${(i+10)%360},100%,60%,.75)`),x.addColorStop(1,`hsla(${(i-20)%360},100%,80%,.05)`);const b=Math.sin(l.t*1.2+f*.8)*(15+s*30);e.fillStyle=x,e.beginPath(),e.moveTo(p-20,r),e.bezierCurveTo(p-35,r-m*.45,p-25+b,r-m*.75,p+b,r-m),e.bezierCurveTo(p+25+b*.3,r-m*.65,p+35,r-m*.35,p+20,r),e.closePath(),e.fill()}const h=Math.floor(1+s*6);for(let f=0;f<h;f++)l.embers.push({x:Jt(t*.25,t*.75),y:r-Jt(4,14),r:Jt(1,3),vx:Jt(-.15,.15),vy:-Jt(.6,1.8)-s*1.2,life:Jt(.8,1.6)});e.save(),e.globalCompositeOperation="lighter";for(let f=l.embers.length-1;f>=0;f--){const p=l.embers[f];if(p.x+=p.vx,p.y+=p.vy,p.vy-=.01,p.life-=.015+s*.02,p.life<=0||p.y<-10){l.embers.splice(f,1);continue}const y=e.createRadialGradient(p.x,p.y,0,p.x,p.y,p.r*3);y.addColorStop(0,`hsla(${(i+25)%360},100%,65%,.9)`),y.addColorStop(1,`hsla(${(i+25)%360},100%,65%,0)`),e.fillStyle=y,e.beginPath(),e.arc(p.x,p.y,p.r*3,0,Math.PI*2),e.fill()}e.restore(),e.fillStyle="rgba(60,36,22,.9)",e.fillRect(t*.2,r-10,t*.6,6),l.t+=.02+s*.08}function Cp(e,t,r,a,s){const i=t/2,o=r/2,l=Math.min(t,r)*.28,c=96,d=Math.max(1,Math.floor(a.length/c));for(let h=0;h<c;h++){const f=(a[h*d]??0)/255,p=h/c*Math.PI*2,y=f*(Math.min(t,r)*.22)+6,m=i+Math.cos(p)*l,x=o+Math.sin(p)*l,b=i+Math.cos(p)*(l+y),g=o+Math.sin(p)*(l+y);e.strokeStyle=`hsl(${(s+h*3)%360}, 90%, ${40+f*40}%)`,e.lineWidth=3,e.beginPath(),e.moveTo(m,x),e.lineTo(b,g),e.stroke()}e.fillStyle=`hsla(${(s+180)%360}, 60%, 15%, .4)`,e.beginPath(),e.arc(i,o,l-8,0,Math.PI*2),e.fill()}function jp(e,t,r,a,s){const l=t/14,c=r/8;for(let d=0;d<8;d++)for(let h=0;h<14;h++){const f=Math.min(a.length-1,d*14+h),p=a[f]/255,y=(s+h/14*210+d/8*90)%360,m=65+p*30,x=20+p*40,b=(1-p)*4;e.fillStyle=`hsl(${y}, ${m}%, ${x}%)`,e.fillRect(h*l+b,d*c+b,Math.max(1,l-2*b),Math.max(1,c-2*b))}}function Mp(e){const r=Array.from(new Set(e.filter(Boolean))).map(a=>new Promise(s=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>s(i),i.onerror=()=>s(i),i.src=a}));return Promise.all(r)}async function Rp(e,t,r,a,s){e.current||(e.current={sprites:[],loadedUrls:[],ready:!1});const i=e.current,o=t.join("|")!==i.loadedUrls.join("|");if(!i.ready||o){const l=await Mp(t.length?t:[]);i.loadedUrls=t,i.sprites=[],i.ready=!0;const c=d=>l[d%Math.max(1,l.length)]??new Image;for(let d=0;d<r;d++){const h=Math.random()*Math.min(a,s)*.38+40;i.sprites.push({img:c(d),x:(Math.random()-.5)*h*.4,y:(Math.random()-.5)*h*.4,z:Math.random()*600+100,ang:Math.random()*Math.PI*2,spin:(Math.random()*.03+.01)*(Math.random()<.5?-1:1),vz:Math.random()*1.2+.2,size:Math.random()*.35+.65})}}}function Np(e,t,r,a,s,i,o,l){const c=i.current;if(!(c!=null&&c.ready))return;const d=t/2,h=r/2,f=900,p=1+a*2;for(const m of c.sprites){m.ang+=m.spin*p,m.z-=m.vz*(.8+a*2.4),m.z<40&&(m.z=f);const x=Math.min(t,r)*.32+Math.sin(m.ang*.8)*18;m.x=Math.cos(m.ang)*x,m.y=Math.sin(m.ang*1.1)*x*.6}const y=[...c.sprites].sort((m,x)=>x.z-m.z);for(const m of y){const x=f/(f-m.z)*.6*m.size,b=d+m.x*x,g=h+m.y*x,S=64*x,v=64*x;e.save(),e.globalAlpha=.12+(1-m.z/f)*.2,e.fillStyle=`hsl(${(s+(1-m.z/f)*60)%360}, 90%, 60%)`,e.beginPath(),e.ellipse(b,g,S*.7,v*.7,0,0,Math.PI*2),e.fill(),e.restore(),m.img&&m.img.width?e.drawImage(m.img,b-S/2,g-v/2,S,v):(e.save(),e.fillStyle=`hsl(${(s+180)%360}, 40%, 55%)`,e.fillRect(b-S/2,g-v/2,S,v),e.restore())}}function wn(e,t){return e+Math.random()*(t-e)}function Tp(e,t,r,a,s,i){i.current||(i.current={blobs:Array.from({length:7},(d,h)=>({x:wn(t*.2,t*.8),y:wn(r*.2,r*.8),r:wn(Math.min(t,r)*.05,Math.min(t,r)*.12),vx:wn(-.6,.6),vy:wn(-.6,.6),hue:(s+h*10)%360}))});const o=i.current,l=.6+a*2.2;e.save(),e.globalCompositeOperation="lighter";for(const c of o.blobs){c.x+=c.vx*l,c.y+=c.vy*l,c.vy-=.01-a*.015,c.x<c.r&&(c.x=c.r,c.vx=Math.abs(c.vx)),c.x>t-c.r&&(c.x=t-c.r,c.vx=-Math.abs(c.vx)),c.y<c.r&&(c.y=c.r,c.vy=Math.abs(c.vy)),c.y>r-c.r&&(c.y=r-c.r,c.vy=-Math.abs(c.vy));const d=(c.hue+a*120)%360,h=e.createRadialGradient(c.x,c.y,c.r*.2,c.x,c.y,c.r);h.addColorStop(0,`hsla(${d}, 95%, 70%, .8)`),h.addColorStop(1,`hsla(${(d+40)%360}, 90%, 30%, 0)`),e.fillStyle=h,e.shadowBlur=18,e.shadowColor=`hsl(${d}, 100%, 60%)`,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}e.restore(),e.strokeStyle=we.resolveCssColor("var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",e.canvas),e.lineWidth=2,e.strokeRect(1,1,t-2,r-2)}function $p(e,t,r,a,s,i){i.current||(i.current={tris:[]});const o=i.current,l=6;for(;o.tris.length<l;)o.tris.push({a:Math.random()*Math.PI*2,r:30+Math.random()*Math.min(t,r)*.35,dr:(Math.random()*.6+.2)*(Math.random()<.5?-1:1)});const c=t/2,d=r/2;for(const h of o.tris){h.a+=.002+a*.02*(h.dr>0?1:-1),h.r+=Math.sin(h.a*2)*(.3+a*1.4);const f=Math.max(40,Math.min(h.r,Math.min(t,r)*.48));e.save(),e.translate(c,d),e.rotate(h.a),e.strokeStyle=`hsla(${(s+f*.2)%360}, 90%, 60%, .9)`,e.lineWidth=2.5,e.beginPath(),e.moveTo(f,0);for(let p=1;p<3;p++){const y=p*Math.PI*2/3;e.lineTo(Math.cos(y)*f,Math.sin(y)*f)}e.closePath(),e.shadowBlur=12,e.shadowColor=e.strokeStyle,e.stroke(),e.restore()}}function Pp(e,t,r,a,s,i){const o=t/2,l=r/2,c=5,d=Math.min(t,r)*.42;i.current+=.01;for(let h=0;h<c;h++){const f=(h+1)/(c+1),p=f*d;e.strokeStyle=`hsla(${(s+h*30)%360}, 70%, 45%, 0.35)`,e.lineWidth=1,e.beginPath(),e.arc(o,l,p,0,Math.PI*2),e.stroke();const y=Math.floor(a.length*f|0),m=(a[y]??0)/255,x=6+h*2;for(let b=0;b<x;b++){const g=i.current*(1+h*.15)+b/x*Math.PI*2,S=p+Math.sin(g*2)*6*m,v=o+Math.cos(g)*S,k=l+Math.sin(g)*S;e.fillStyle=`hsla(${(s+h*30+b*6)%360}, 90%, ${55+m*30}%, ${.6+m*.3})`,e.beginPath(),e.arc(v,k,2+m*4,0,Math.PI*2),e.fill()}}}function Ep(e,t,r,a,s){const l=t/12,c=r/6;for(let d=0;d<6;d++)for(let h=0;h<12;h++){const f=(d*12+h)%a.length,p=a[f]/255,y=(s+h/12*180+d/6*90)%360,m=70+p*25,x=25+p*35;e.fillStyle=`hsl(${y}, ${m}%, ${x}%)`,e.fillRect(h*l,d*c,Math.ceil(l),Math.ceil(c))}}function Ap(e,t,r,a,s,i){const o=t/2,l=r/2,c=2+Math.floor(a*14);for(let h=0;h<c;h++){const f=Math.random()*Math.PI*2,p=.5+Math.random()*(2.5+a*4);i.current.push({x:o,y:l,vx:Math.cos(f)*p,vy:Math.sin(f)*p,life:0,max:40+Math.random()*60,hue:(s+Math.random()*60)%360})}e.fillStyle="rgba(2,6,23,0.2)",e.fillRect(0,0,t,r);const d=i.current;for(let h=d.length-1;h>=0;h--){const f=d[h];f.x+=f.vx,f.y+=f.vy,f.life+=1;const p=1-f.life/f.max;e.fillStyle=`hsla(${f.hue},85%,60%,${Math.max(0,p)})`,e.beginPath(),e.arc(f.x,f.y,2+p*3,0,Math.PI*2),e.fill(),(f.life>=f.max||f.x<-20||f.y<-20||f.x>t+20||f.y>r+20)&&d.splice(h,1)}d.length>1200&&d.splice(0,d.length-1200)}function Ip(e,t,r,a,s,i){e.fillStyle="rgba(10,16,28,0.25)",e.fillRect(0,0,t,r);const o=t/2,l=r/2,c=Math.min(t,r)*(.38+s*.12),d=e.createRadialGradient(o,l,c*.1,o,l,c);d.addColorStop(0,`hsla(${(i+200)%360},90%,70%,0.95)`),d.addColorStop(.5,`hsla(${(i+260)%360},80%,55%,0.6)`),d.addColorStop(1,"transparent"),e.fillStyle=d,e.beginPath(),e.arc(o,l,c,0,Math.PI*2),e.fill();const h=18+Math.floor(s*50);for(let f=0;f<h;f++){const p=f/h*Math.PI*2+a*(.6+s*1.4),y=(Math.sin(a*2+f*1.7)+Math.cos(a*1.3+f*2.1))*.15,m=c*(.4+.55*Math.abs(Math.sin(a*1.2+f))),x=6;e.save(),e.translate(o,l),e.rotate(p+y),e.beginPath(),e.moveTo(0,0);for(let g=1;g<=x;g++){const S=m/x*g,v=(Math.sin(a*3+f*.8+g)*.6+Math.cos(a*2+f+g*.7))*(8+24*s),k=S,M=v;e.lineTo(M,k)}e.globalCompositeOperation="lighter";const b=(i+f*(240/h))%360;e.strokeStyle=`hsla(${b}, 90%, ${60+s*20}%, ${.35+s*.4})`,e.lineWidth=2+s*2,e.stroke(),e.restore()}e.beginPath(),e.arc(o,l,c*(.98+.02*Math.sin(a*2)),0,Math.PI*2),e.strokeStyle=`hsla(${(i+40)%360},90%,70%,${.25+s*.25})`,e.lineWidth=1.5,e.stroke(),e.globalCompositeOperation="source-over"}function Lp(e,t,r,a,s){const o=Math.max(1,Math.floor(a.length/96)),l=t/2,c=r/2,d=Math.min(t,r)*.22,h=Math.min(t,r)*.48;for(let f=0;f<96;f++){const p=a[f*o]/255,y=f/96*Math.PI*2,m=d,x=d+p*(h-d),b=l+Math.cos(y)*m,g=c+Math.sin(y)*m,S=l+Math.cos(y)*x,v=c+Math.sin(y)*x;e.strokeStyle=`hsl(${f/96*360+s},85%,60%)`,e.lineWidth=3,e.beginPath(),e.moveTo(b,g),e.lineTo(S,v),e.stroke()}e.fillStyle=we.resolveCssColor("var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.canvas),e.beginPath(),e.arc(l,c,d*.85,0,Math.PI*2),e.fill()}function Dp(e,t,r,a,s,i){const o=t/2,l=r/2,c=Math.min(t,r)*.5,d=ai(a,0,Math.floor(a.length*.1))/255,h=ai(a,Math.floor(a.length*.6),a.length)/255;i.current+=.01+h*.03;const f=24;for(let p=0;p<f;p++){const y=i.current+p/f*Math.PI*2,m=(.35+d*.55)*c,x=o+Math.cos(y)*m,b=l+Math.sin(y)*m,g=e.createRadialGradient(o,l,0,o,l,m),S=p/f*360+s;g.addColorStop(0,`hsla(${S},85%,65%,0.0)`),g.addColorStop(1,`hsla(${S},85%,65%,0.9)`),e.strokeStyle=g,e.lineWidth=6+h*8,e.beginPath(),e.moveTo(o,l),e.lineTo(x,b),e.stroke()}e.fillStyle="rgba(2,6,23,0.25)",e.fillRect(0,0,t,r)}function ai(e,t,r){let a=0,s=0;for(let i=t;i<r;i++)a+=e[i],s++;return s?a/s:0}function zp(e,t,r,a,s,i){e.fillStyle="rgba(10,16,28,0.35)",e.fillRect(0,0,t,r);const o=r/2,l=Math.max(8,18-s*10),c=r*.35*(.6+s*.7),d=a.length,h=t/(d-1);e.beginPath();for(let y=0;y<d;y++){const m=(a[y]-128)/128,x=Math.sin(i*1.5+y*.03)*.12,b=y*h,g=o-l-(m+x)*c;y===0?e.moveTo(b,g):e.lineTo(b,g)}const f=e.createLinearGradient(0,0,0,o-l);f.addColorStop(0,"hsla(260,90%,75%,0.9)"),f.addColorStop(1,"hsla(220,85%,60%,0.4)"),e.strokeStyle=f,e.lineWidth=2,e.stroke(),e.beginPath();for(let y=0;y<d;y++){const m=(a[y]-128)/128,x=Math.cos(i*1.3+y*.035)*.12,b=y*h,g=o+l+(m+x)*c;y===0?e.moveTo(b,g):e.lineTo(b,g)}const p=e.createLinearGradient(0,o+l,0,r);p.addColorStop(0,"hsla(190,90%,65%,0.9)"),p.addColorStop(1,"hsla(160,85%,55%,0.4)"),e.strokeStyle=p,e.lineWidth=2,e.stroke(),e.globalCompositeOperation="lighter",e.strokeStyle=we.resolveCssColor("var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.canvas),e.lineWidth=6,e.beginPath(),e.moveTo(0,o-l),e.lineTo(t,o-l),e.stroke(),e.beginPath(),e.moveTo(0,o+l),e.lineTo(t,o+l),e.stroke(),e.globalCompositeOperation="source-over"}function _p(e,t,r,a,s,i){const o=t/2,l=r/2,c=5,d=Math.min(t,r)*.12;for(let h=0;h<c;h++){const f=Math.floor(h/c*a.length),p=a[f]/255,y=d+h*d*.55+p*d*.5,m=(i+h*40)%360;e.lineWidth=3+p*6,e.strokeStyle=`hsla(${m},80%,60%,${.5+.5*s})`,e.beginPath(),e.arc(o,l,y,0,Math.PI*2),e.stroke()}}function Fp(e,t,r,a,s){const i=Math.min(a.length,256),o=Math.max(1,Math.floor(a.length/i)),l=t/i;for(let c=0;c<i;c++){const d=a[c*o]/255,h=d*(r-6),f=c*l,p=r-h,y=c/i*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(f+1,p,l-2,h)}}function Op(e,t,r,a){e.current||(e.current={stars:[],ready:!1});const s=e.current;if(!s.ready||s.stars.length!==t){const i=[];for(let o=0;o<t;o++){const l={x:(Math.random()-.5)*r,y:(Math.random()-.5)*a,z:Math.random()*800+100,pz:0};i.push(l)}s.stars=i,s.ready=!0}}function Bp(e,t,r,a,s,i){const o=i.current,l=t/2,c=r/2,d=4+a*18;e.save(),e.translate(l,c);for(const h of o.stars){h.z-=d,h.z<20&&(h.x=(Math.random()-.5)*t,h.y=(Math.random()-.5)*r,h.z=900,h.pz=h.z);const f=h.x/h.z*600,p=h.y/h.z*600,y=h.x/h.pz*600,m=h.y/h.pz*600;h.pz=h.z,e.strokeStyle=`hsla(${(s+200)%360}, 90%, 70%, 0.7)`,e.lineWidth=Math.max(1,(1-h.z/900)*2),e.beginPath(),e.moveTo(y,m),e.lineTo(f,p),e.stroke()}e.restore()}function Gp(e,t,r,a){e.lineWidth=2,e.strokeStyle=we.resolveCssColor("var(--nice-primary-light, #c7d2fe)",e.canvas),e.beginPath();const s=t/a.length;for(let i=0;i<a.length;i++){const o=(a[i]-128)/128,l=i*s,c=r/2+o*(r*.45);i===0?e.moveTo(l,c):e.lineTo(l,c)}e.stroke()}const Wp=({active:e,onClick:t,title:r,children:a})=>n.jsx("button",{type:"button",onClick:t,title:r,"aria-pressed":e,style:{padding:"4px 8px",borderRadius:6,fontSize:12,border:`1px solid ${e?"var(--nice-info, #6366f1)":"var(--nice-border-color, #334155)"}`,background:e?"rgba(99,102,241,.12)":"var(--nice-overlay-60, rgba(15,23,42,.6))",color:e?"var(--nice-text-on-primary, #e2e8f0)":"var(--nice-text-on-primary, #cbd5e1)",cursor:"pointer",whiteSpace:"nowrap",lineHeight:1.2},children:a}),rs=({modes:e=[],active:t,setActive:r,rows:a=2})=>{const{t:s}=Pe(),i=Math.max(1,a);return!e||e.length===0?null:n.jsx("div",{style:{position:"absolute",top:10,right:10,pointerEvents:"auto",zIndex:9999},children:n.jsx("div",{style:{display:"grid",gridAutoFlow:"column",gridTemplateRows:`repeat(${i}, auto)`,gridAutoColumns:"max-content",gap:6,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:6,borderRadius:10,border:"1px solid var(--nice-border-color, #334155)",backdropFilter:"blur(2px)",justifyItems:"end",alignItems:"start"},children:e.map(o=>n.jsx(Wp,{active:t===o,onClick:()=>r(o),title:`${s("visualizer.mode","Mode")}: ${o}`,children:o},o))})})};function Up(e,t){const[r,a]=u.useState(()=>{try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}});return u.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(r))}catch{}},[e,r]),[r,a]}const Vp=({vu:e,hide:t})=>{if(t)return null;const r=12,a=Math.round(e*r);return n.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px 8px",borderRadius:8,border:"1px solid var(--nice-border-color, #334155)",backdropFilter:"blur(2px)",pointerEvents:"none",zIndex:9998},children:Array.from({length:r}).map((s,i)=>{const o=120*(i/r);return n.jsx("div",{style:{width:6,height:18,borderRadius:2,background:i<a?`hsl(${o}, 80%, 50%)`:"var(--nice-text, #1f2937)"}},i)})})},qp="var(--player-bg, #0f172a)";function Hp(e,t){const r=e.length;for(let a=0;a<r;a++){const s=a/r,i=.55*Math.exp(-Math.pow((s-(.12+.08*Math.sin(t*.7)))*7,2))+.45*Math.exp(-Math.pow((s-(.4+.15*Math.sin(t*1.1+1)))*9,2))+.3*(1-s)*(.55+.45*Math.sin(t*2+a*.06));e[a]=Math.max(0,Math.min(255,Math.floor(i*255)))}}function Kp(e,t){const r=e.length;for(let a=0;a<r;a++){const s=a/r*Math.PI*2,i=Math.sin(s*3+t*3)*.5+Math.sin(s*7+t*2)*.28;e[a]=Math.max(0,Math.min(255,Math.floor(128+i*110)))}}const as=({kind:e,audioRef:t,width:r="100%",height:a=360,coverUrl:s,title:i,subtitle:o,label:l,defaultMode:c="cover",storageKey:d="gp-stage:mode",allowedModes:h,imageUrls:f,imageCount:p=14,autoAnimate:y=!1})=>{const m=u.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette","radial","rays","particles","rings","grid","imageTornado","colorRipples","starfield","orbitals","eqcircle","triangles","blob","plasma","lavaLamp","cozyFire","rift"],[e,h]),x=u.useMemo(()=>{const X=m.includes(c)?c:m[0];try{const q=localStorage.getItem(d);if(!q)return X;const E=JSON.parse(q);return m.includes(E)?E:X}catch{return X}},[m,c,d]),[b,g]=Up(d,x),S=u.useRef(null),v=u.useRef(null),k=u.useRef(null),M=u.useRef(null),T=u.useRef(null),N=u.useRef(null),j=u.useRef(0),R=u.useRef(0),z=u.useRef([]),[A,$]=u.useState(0),O=u.useRef(null),I=u.useRef(null),U=u.useRef(null),J=u.useRef(null),_=u.useRef(null),W=u.useRef(null),K=u.useRef(null),re=b!=="cover"&&b!=="video";return u.useEffect(()=>{var w;if(e==="youtube"||(v.current&&(cancelAnimationFrame(v.current),v.current=null),!re))return;Bt();const X=yn(),q=t.current;if(!q&&!y)return;if(q&&!k.current)try{k.current=X.createMediaElementSource(q)}catch{}if(q&&!M.current){const D=X.createAnalyser();D.fftSize=2048,D.smoothingTimeConstant=.85,M.current=D;try{(w=k.current)==null||w.connect(D)}catch{}try{D.connect(X.destination)}catch{}}const E=M.current;T.current=new Uint8Array(E?E.frequencyBinCount:1024),N.current=new Uint8Array(E?E.fftSize:2048);const P=()=>{const D=S.current,F=Math.max(1,Math.floor(window.devicePixelRatio||1));D.width=Math.floor(D.clientWidth*F),D.height=Math.floor(D.clientHeight*F);const B=D.getContext("2d");B==null||B.setTransform(1,0,0,1,0,0),B==null||B.scale(F,F)};P();const C=()=>P();window.addEventListener("resize",C),Op(U,220,S.current.width,S.current.height);const L=async()=>{const D=S.current;if(!D)return;const F=D.getContext("2d");if(!F)return;const B=Math.max(1,Math.floor(window.devicePixelRatio||1)),V=D.width/B,Y=D.height/B,oe=performance.now()*.001,ie=b==="waveform"||b==="rift";E&&(ie?E.getByteTimeDomainData(N.current):E.getByteFrequencyData(T.current)),y&&(Hp(T.current,oe),Kp(N.current,oe));let ne=0;const Z=ie?N.current:T.current;for(let H=0;H<Z.length;H++){const se=ie?(Z[H]-128)/128:Z[H]/255;ne+=se*se}if(ne=Math.sqrt(ne/Z.length),$(Math.min(1,ne)),F.clearRect(0,0,V,Y),b==="spectrum")Fp(F,V,Y,T.current,j.current);else if(b==="bars")bp(F,V,Y,T.current,j.current);else if(b==="waveform")Gp(F,V,Y,N.current);else if(b==="palette"){const H=(j.current+ne*120)%360;Ep(F,V,Y,T.current,H)}else if(b==="radial")Lp(F,V,Y,T.current,j.current);else if(b==="rays")Dp(F,V,Y,T.current,j.current,R);else if(b==="particles")Ap(F,V,Y,ne,j.current,z);else if(b==="rings")_p(F,V,Y,T.current,ne,j.current);else if(b==="grid"){const H=(j.current+ne*160)%360;jp(F,V,Y,T.current,H)}else if(b==="imageTornado"){const H=f!=null&&f.length?f:s?[s]:[];await Rp(O,H,p,V,Y);const se=(j.current+ne*100)%360;Np(F,V,Y,ne,se,O)}else if(b==="colorRipples"){const H=(j.current+ne*120)%360;xp(F,V,Y,ne,H,I)}else if(b==="starfield"){const H=(j.current+60)%360;Bp(F,V,Y,ne,H,U)}else if(b==="orbitals"){const H=(j.current+ne*180)%360;Pp(F,V,Y,T.current,H,R)}else if(b==="eqcircle"){const H=(j.current+120)%360;Cp(F,V,Y,T.current,H)}else if(b==="triangles"){const H=(j.current+40)%360;$p(F,V,Y,ne,H,J)}else if(b==="blob"){const H=(j.current+90)%360;vp(F,V,Y,ne,H,_)}else if(b==="plasma"){const H=(j.current+ne*200)%360;Ip(F,V,Y,oe,ne,H)}else if(b==="rift")zp(F,V,Y,N.current,ne,oe);else if(b==="lavaLamp"){const H=(j.current+ne*80)%360;Tp(F,V,Y,ne,H,W)}else if(b==="cozyFire"){const H=(j.current+ne*140)%360;wp(F,V,Y,T.current,ne,H,K)}j.current=(j.current+.4)%360,v.current=requestAnimationFrame(L)};return v.current=requestAnimationFrame(L),()=>{window.removeEventListener("resize",C),v.current&&cancelAnimationFrame(v.current)}},[re,e,t,b,f,p,s,y]),n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none",background:b==="cover"?"transparent":qp},children:b==="cover"?n.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:n.jsx(kp,{height:a,coverUrl:s,title:i,subtitle:o,label:l})}):n.jsx("canvas",{ref:S,style:{width:typeof r=="number"?`${r}px`:r,height:a,borderRadius:8},role:"img","aria-label":"Stage visualizer canvas"})}),n.jsxs("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:[n.jsx(rs,{modes:m,active:b,setActive:g,rows:2}),n.jsx(Vp,{vu:A,hide:e==="youtube"})]})]})},ol=({height:e,autoPlay:t,track:r,source:a,ytRef:s,audioRef:i,hlsRef:o,setVol:l,onEnd:c,volume:d,extractVideoId:h})=>{u.useEffect(()=>{const m=i.current;if(m){if(m.volume=d,m.crossOrigin=a!=null&&a.withCredentials?"use-credentials":"anonymous",(a==null?void 0:a.kind)==="hls"&&gp(a.url)){const x=()=>{m.src=a.url,m.load(),t&&m.play().catch(()=>{})};if(m.canPlayType("application/vnd.apple.mpegurl")){x();return}(async()=>{const g=(await import("hls.js")).default;if(g.isSupported()){const S=new g({xhrSetup:v=>{if(a!=null&&a.withCredentials&&(v.withCredentials=!0),a!=null&&a.headers)for(const[k,M]of Object.entries(a.headers))v.setRequestHeader(k,String(M))}});o.current=S,S.loadSource(a.url),S.attachMedia(m),S.on(g.Events.MANIFEST_PARSED,()=>t&&m.play().catch(()=>{}))}else x()})()}(a==null?void 0:a.kind)==="audio"&&a.url&&(m.src=a.url,m.load(),t&&m.play().catch(()=>{}))}},[a==null?void 0:a.url,a==null?void 0:a.kind,a==null?void 0:a.withCredentials,d,t]);const f=(a==null?void 0:a.kind)==="youtube",p=f?"video":"cover",y=`gp-stage:mode:${(a==null?void 0:a.kind)??"none"}`;return n.jsxs("div",{className:"gp-stage",style:{width:"100%",height:e,background:f?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(a==null?void 0:a.kind)==="youtube"&&n.jsx(Ta,{videoId:a.videoId??h(a.url),onReady:m=>{s.current=m.target,l(d),t&&m.target.playVideo()},onEnd:c,opts:{width:"100%",height:"100%",playerVars:{autoplay:t?1:0,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3}},style:{width:"100%",height:"100%"}}),((a==null?void 0:a.kind)==="audio"||(a==null?void 0:a.kind)==="hls")&&n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{textAlign:"center",color:"var(--nice-overlay-light-90, #e2e8f0)"},children:r!=null&&r.coverUrl?n.jsx("img",{alt:"cover",src:r.coverUrl,style:{height:e-24,objectFit:"contain"}}):n.jsxs("div",{style:{opacity:.8},children:[n.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[r==null?void 0:r.artist," — ",r==null?void 0:r.title]}),n.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--nice-text-dim, #94a3b8)"},children:(a==null?void 0:a.label)??`${(a==null?void 0:a.codec)??""} ${(a==null?void 0:a.quality)??""}`.trim()})]})}),n.jsx("audio",{ref:i,onEnded:c,onLoadedMetadata:()=>{},crossOrigin:a!=null&&a.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]}),n.jsx(as,{kind:(a==null?void 0:a.kind)==="hls"?"hls":(a==null?void 0:a.kind)??"audio",audioRef:i,hlsRef:o,height:e,coverUrl:r==null?void 0:r.coverUrl,title:r==null?void 0:r.title,subtitle:r==null?void 0:r.artist,label:(a==null?void 0:a.label)??`${(a==null?void 0:a.codec)??""} ${(a==null?void 0:a.quality)??""}`.trim(),defaultMode:p,storageKey:y},`vis-${y}`)]})};function Yp(e,t){const[r,a]=u.useState(()=>{try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}});return u.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(r))}catch{}},[e,r]),[r,a]}const Zp="var(--nice-text-dim, #94a3b8)",Xp=({active:e,onClick:t,title:r,children:a})=>n.jsx("button",{type:"button",onClick:t,title:r,style:{padding:"4px 8px",borderRadius:6,fontSize:12,border:`1px solid ${e?"var(--nice-color-accent, #6366f1)":"var(--nice-border-muted, #334155)"}`,background:e?"var(--nice-accent-tint-10, rgba(99,102,241,.12))":"var(--nice-overlay-60, rgba(15,23,42,.6))",color:e?"var(--nice-text-on-primary, #e2e8f0)":"var(--nice-overlay-light-80, rgba(255, 255, 255, 0.8))",cursor:"pointer"},children:a}),ll=({kind:e,audioRef:t,width:r="100%",height:a=360,coverUrl:s,title:i,subtitle:o,label:l,defaultMode:c="cover",storageKey:d="gp-stage:mode",allowedModes:h,overlayOnly:f=!1})=>{const p=u.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette"],[e,h]),y=u.useMemo(()=>{const $=p.includes(c)?c:p[0];try{const O=localStorage.getItem(d);if(!O)return $;const I=JSON.parse(O);return p.includes(I)?I:$}catch{return $}},[p,c,d]),[m,x]=Yp(d,y),b=u.useRef(null),[g,S]=u.useState(0),v=u.useRef(null),k=u.useRef(null),M=u.useRef(null),T=u.useRef(null),N=u.useRef(null),j=u.useRef(0),R=m==="spectrum"||m==="bars"||m==="waveform"||m==="palette";u.useEffect(()=>{var _;if(e==="youtube")return;if(!R){v.current&&cancelAnimationFrame(v.current);return}Bt();const $=yn(),O=t.current;if(!O)return;if(!k.current)try{k.current=$.createMediaElementSource(O)}catch{}if(!M.current){const W=$.createAnalyser();W.fftSize=2048,W.smoothingTimeConstant=.85,M.current=W;try{(_=k.current)==null||_.connect(W)}catch{}try{W.connect($.destination)}catch{}}const I=M.current;T.current=new Uint8Array(I.frequencyBinCount),N.current=new Uint8Array(I.fftSize);const U=()=>{if(!b.current)return;const W=b.current,K=W.getContext("2d");if(!K)return;const re=W.width,X=W.height;K.clearRect(0,0,re,X),m==="waveform"?I.getByteTimeDomainData(N.current):I.getByteFrequencyData(T.current);let q=0;const E=m==="waveform"?N.current:T.current;for(let P=0;P<E.length;P++){const C=m==="waveform"?(E[P]-128)/128:E[P]/255;q+=C*C}if(q=Math.sqrt(q/E.length),S(Math.min(1,q)),m==="spectrum"||m==="bars"){const P=T.current,C=m==="bars"?48:Math.min(P.length,256),L=Math.floor(P.length/C),w=re/C;for(let D=0;D<C;D++){const F=P[D*L]/255,B=F*(X-6),V=D*w,Y=X-B,oe=D/C*240+j.current;K.fillStyle=`hsl(${oe%360}, 80%, ${Math.max(30,40+F*30)}%)`,K.fillRect(V+1,Y,w-2,B)}}else if(m==="waveform"){const P=N.current;K.lineWidth=2,K.strokeStyle=we.resolveCssColor("var(--nice-primary-light, #c7d2fe)",K.canvas),K.beginPath();const C=re/P.length;for(let L=0;L<P.length;L++){const w=(P[L]-128)/128,D=L*C,F=X/2+w*(X*.45);L===0?K.moveTo(D,F):K.lineTo(D,F)}K.stroke()}else if(m==="palette"){const L=re/12,w=X/6,D=(j.current+q*120)%360;for(let F=0;F<6;F++)for(let B=0;B<12;B++){const V=(F*12+B)%T.current.length,Y=T.current[V]/255,oe=(D+B/12*180+F/6*90)%360,ie=70+Y*25,ne=25+Y*35;K.fillStyle=`hsl(${oe}, ${ie}%, ${ne}%)`,K.fillRect(B*L,F*w,Math.ceil(L),Math.ceil(w))}}K.strokeStyle=we.resolveCssColor(getComputedStyle(document.documentElement).getPropertyValue("--waveform-stroke")||"var(--nice-primary-light, #c7d2fe)",K.canvas),v.current=requestAnimationFrame(U)},J=()=>{var re;const W=b.current,K=Math.max(1,Math.floor(window.devicePixelRatio||1));W.width=Math.floor(W.clientWidth*K),W.height=Math.floor(W.clientHeight*K),(re=W.getContext("2d"))==null||re.scale(K,K)};return J(),window.addEventListener("resize",J),v.current=requestAnimationFrame(U),()=>{window.removeEventListener("resize",J),v.current&&cancelAnimationFrame(v.current)}},[R,e,t,m]);const z=()=>{if(e==="youtube")return null;const $=12,O=Math.round(g*$);return n.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px 8px",borderRadius:8,border:"1px solid var(--nice-border-color, #334155)",backdropFilter:"blur(2px)"},children:Array.from({length:$}).map((I,U)=>{const J=120*(U/$);return n.jsx("div",{style:{width:6,height:18,borderRadius:2,background:U<O?`hsl(${J}, 80%, 50%)`:"var(--nice-text, #1f2937)"}},U)})})},A=()=>n.jsx("div",{style:{textAlign:"center",color:"var(--nice-overlay-light-90, #e2e8f0)"},children:s?n.jsx("img",{alt:"cover",src:s,style:{height:a-24,objectFit:"contain"}}):n.jsxs("div",{style:{opacity:.8},children:[n.jsx("div",{style:{fontSize:18,fontWeight:600},children:i??""}),n.jsx("div",{style:{marginTop:8,fontSize:12,color:Zp},children:l??o??""})]})});return n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:m==="cover"?n.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center",background:"transparent"},children:A()}):n.jsx("canvas",{ref:b,style:{width:typeof r=="number"?`${r}px`:r,height:a,borderRadius:8},role:"img","aria-label":"Stage visualizer canvas"})}),n.jsxs("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:[n.jsx("div",{style:{position:"absolute",top:10,right:10,display:"flex",gap:6,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px",borderRadius:10,border:"1px solid var(--nice-border-color, #334155)",backdropFilter:"blur(2px)",pointerEvents:"auto",zIndex:9999},children:p.map($=>n.jsx(Xp,{active:m===$,onClick:()=>x($),title:`Tryb: ${$}`,children:$},$))}),n.jsx("div",{style:{position:"absolute",right:10,bottom:10,pointerEvents:"none",zIndex:9998},children:n.jsx(z,{})})]})]})},cl=({artist:e,title:t,hideControls:r=!0,isPlaying:a,onTimeUpdate:s,searchYouTubeByArtistTitle:i})=>{const{t:o}=Pe(),[l,c]=u.useState(e||""),[d,h]=u.useState(t||""),[f,p]=u.useState(null),[y,m]=u.useState(null),x=u.useRef(null),[b,g]=u.useState({width:Math.min(560,window.innerWidth-32),height:Math.min(315,(window.innerWidth-32)*9/16)});u.useEffect(()=>{e&&t&&i&&i(e,t).then(p)},[e,t,i]),u.useEffect(()=>{y&&(a?y.playVideo():y.pauseVideo())},[a,y]),u.useEffect(()=>{if(y&&s){const v=setInterval(()=>{const k=y.getCurrentTime();s(k)},100);return()=>clearInterval(v)}},[y,s]),u.useEffect(()=>{const v=()=>{if(x.current){const k=x.current.clientWidth,M=Math.round(k*(9/16));g({width:k,height:M})}};return v(),window.addEventListener("resize",v),()=>window.removeEventListener("resize",v)},[]);const S=async()=>{if(!i)return;const v=await i(l,d);p(v)};return n.jsxs("div",{ref:x,style:{width:"100%",maxWidth:"900px",margin:"0 auto"},children:[(!e||!t||!f)&&n.jsxs("div",{children:[n.jsx("input",{value:l,onChange:v=>c(v.target.value),placeholder:o("youtubePlayer.artist","Artist"),"aria-label":o("youtubePlayer.artist","Artist")}),n.jsx("input",{value:d,onChange:v=>h(v.target.value),placeholder:o("youtubePlayer.title","Title"),"aria-label":o("youtubePlayer.title","Title")}),n.jsx("button",{onClick:S,children:o("youtubePlayer.search","Search")})]}),f&&n.jsxs("div",{children:[n.jsx(Ta,{videoId:f,opts:{width:b.width.toString(),height:b.height.toString(),playerVars:{autoplay:1,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,annotations:0}},onReady:v=>m(v.target)}),!r&&n.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px"},children:[n.jsxs("button",{onClick:()=>y==null?void 0:y.playVideo(),children:[n.jsx(G.NtdPlay,{size:14})," ",o("youtubePlayer.play","Play")]}),n.jsxs("button",{onClick:()=>y==null?void 0:y.pauseVideo(),children:[n.jsx(G.NtdPause,{size:14})," ",o("youtubePlayer.pause","Pause")]})]})]})]})},si=e=>({name:e,dirs:new Map,files:[]}),Qp=e=>(e??[]).map(t=>t instanceof File?{file:t}:t),Jp=e=>e.replace(/\\/g,"/"),ef=e=>{const t=si("/");for(const r of e){const a=Jp(r.path??r.file.name).split("/").filter(Boolean);if(a.length<=1){t.files.push({file:r.file,path:a[0]??r.file.name});continue}let s=t;for(let i=0;i<a.length-1;i++){const o=a[i];s.dirs.has(o)||s.dirs.set(o,si(o)),s=s.dirs.get(o)}s.files.push({file:r.file,path:a[a.length-1]??r.file.name})}return t},ma=e=>e.slice().sort((t,r)=>(t.path??t.file.name).localeCompare(r.path??r.file.name)),tf={tidal:G.NtdWave,spotify:G.NtdMusic,youtube:G.NtdPlay},ga=({q:e,setQ:t,t:r})=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx("div",{style:{flex:1},children:n.jsx(ve.NiceTextInput,{value:e,onChange:t,placeholder:r("libraryExplorer.searchPlaceholder","Search…"),size:"sm"})}),e&&n.jsx(ve.NiceButton,{variant:"ghost",size:"sm",onClick:()=>t(""),children:n.jsx(G.NtdClose,{size:14})})]}),ya=({files:e,t,onOpenInEditor:r,onPlayFile:a})=>e.length?n.jsx("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:n.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[n.jsx("thead",{children:n.jsxs("tr",{style:{color:"var(--nice-text-muted, #94a3b8)",textAlign:"left"},children:[n.jsx("th",{style:{padding:"8px 12px",fontWeight:600},children:t("libraryExplorer.colFile","File")}),n.jsx("th",{style:{padding:"8px 12px",fontWeight:600},children:t("libraryExplorer.colType","Type")}),n.jsx("th",{style:{padding:"8px 12px",fontWeight:600,width:200},children:t("libraryExplorer.colActions","Actions")})]})}),n.jsx("tbody",{children:e.map(s=>{const i=s.path??s.file.name;return n.jsxs("tr",{style:{borderTop:"1px solid var(--nice-border, #1e293b)"},children:[n.jsx("td",{style:{padding:"6px 12px",maxWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),n.jsx("td",{style:{padding:"6px 12px",color:"var(--nice-text-muted, #94a3b8)"},children:s.file.type||"—"}),n.jsxs("td",{style:{padding:"6px 12px",display:"flex",gap:6},children:[r&&n.jsxs(ve.NiceButton,{variant:"outline",size:"sm",onClick:()=>r(s.file),children:[n.jsx(G.NtdEdit,{size:13})," ",t("libraryExplorer.openInEditor","Edit")]}),a&&n.jsxs(ve.NiceButton,{variant:"primary",size:"sm",onClick:()=>a(s.file),children:[n.jsx(G.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]})]},i)})})]})}):n.jsx("div",{style:{fontSize:13,color:"var(--nice-text-muted, #94a3b8)",padding:12},children:t("libraryExplorer.noFiles","No files")}),dl=({streams:e,t,onPlayStream:r})=>e.length?n.jsxs("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:[n.jsx("div",{style:{padding:"8px 12px",fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:t("libraryExplorer.streaming","Streaming")}),n.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:e.map(a=>n.jsxs("li",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,borderTop:"1px solid var(--nice-border, #1e293b)",padding:"8px 12px"},children:[n.jsxs("div",{style:{minWidth:0},children:[n.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.title}),n.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",display:"flex",alignItems:"center",gap:4},children:[u.createElement(tf[a.provider],{size:12})," ",a.provider.toUpperCase(),a.artist?` • ${a.artist}`:""]})]}),r&&n.jsxs(ve.NiceButton,{variant:"primary",size:"sm",onClick:()=>r(a),children:[n.jsx(G.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]},`${a.provider}:${a.id}`))})]}):null,ea=({name:e,enabled:t})=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 8px",fontSize:13},children:[n.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:t?"var(--nice-success, #10b981)":"var(--nice-border, #d1d5db)"}}),n.jsx("span",{style:{color:t?"inherit":"var(--nice-text-muted, #94a3b8)"},children:e})]}),nf=({variant:e="full",files:t=[],streams:r=[],enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,t:c,style:d,id:h,accessMode:f,"data-testid":p})=>{const{t:y}=Pe(),m=c??y,[x,b]=u.useState(""),g=u.useMemo(()=>Qp(t),[t]),S=u.useCallback(M=>{const T=x.trim().toLowerCase();return!T||M.toLowerCase().includes(T)},[x]),v=u.useMemo(()=>ma(g).filter(M=>S(`${M.path??M.file.name} ${M.file.type||""}`)),[g,S]),k=u.useMemo(()=>r.filter(M=>S(`${M.title} ${M.artist??""} ${M.provider}`)),[r,S]);return f==="hidden"?null:e==="minimal"?n.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...d},id:h,"data-testid":p,children:[n.jsx(ga,{q:x,setQ:b,t:m}),n.jsx(ya,{files:v,t:m,onOpenInEditor:s,onPlayFile:i}),n.jsx(dl,{streams:k,t:m,onPlayStream:o})]}):e==="onlyFiles"?n.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...d},id:h,"data-testid":p,children:[n.jsx(ga,{q:x,setQ:b,t:m}),n.jsx(ya,{files:v,t:m,onOpenInEditor:s,onPlayFile:i})]}):n.jsx(rf,{q:x,setQ:b,normFiles:g,filteredStreams:k,enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,style:d,id:h,"data-testid":p,t:m})},rf=({q:e,setQ:t,normFiles:r,filteredStreams:a,enableProviders:s,onOpenInEditor:i,onPlayFile:o,onPlayStream:l,className:c,style:d,id:h,"data-testid":f,t:p})=>{const y=u.useMemo(()=>ef(r),[r]),[m,x]=u.useState({}),[b,g]=u.useState("/"),S=T=>x(N=>({...N,[T]:!N[T]})),v=(T,N)=>{const j=N==="/"?`/${T.name}`:`${N}${T.name}/`,R=N==="/"&&T.name==="/",z=m[j]??R,A=Array.from(T.dirs.keys()).sort();return n.jsxs("div",{children:[!R&&n.jsxs("button",{type:"button",onClick:()=>{S(j),g(j)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"4px 8px",border:"none",borderRadius:6,cursor:"pointer",textAlign:"left",background:b===j?"var(--nice-accent-tint-20, rgba(99,102,241,0.2))":"transparent",color:"var(--nice-text, inherit)"},children:[n.jsx("span",{style:{display:"inline-flex"},children:z?n.jsx(G.NtdFolderOpen,{size:14}):n.jsx(G.NtdFolder,{size:14})}),n.jsx("span",{style:{fontSize:13},children:T.name})]}),(R||z)&&n.jsx("div",{style:{paddingLeft:R?0:16},children:A.map($=>v(T.dirs.get($),j))})]},j)},k=u.useMemo(()=>{let T;if(b==="/")T=ma(r);else{const N=b.replace(/^\//,"").split("/").filter(Boolean);let j=y;for(const R of N){const z=j.dirs.get(R);if(!z)return[];j=z}T=ma(j.files)}return e?T.filter(N=>(N.path??N.file.name).toLowerCase().includes(e.toLowerCase())):T},[b,y,r,e]),M={tidal:(s==null?void 0:s.tidal)??!0,spotify:(s==null?void 0:s.spotify)??!0,youtube:(s==null?void 0:s.youtube)??!0};return n.jsxs("div",{className:c,style:{display:"flex",gap:12,color:"var(--nice-text, #e2e8f0)",...d},id:h,"data-testid":f,children:[n.jsxs("div",{style:{flex:"0 0 220px",border:"1px solid var(--nice-border, #334155)",borderRadius:12,padding:8},children:[n.jsx("div",{style:{padding:"0 8px 8px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:p("libraryExplorer.library","Library")}),v(y,"/"),n.jsxs("div",{style:{marginTop:16,borderTop:"1px solid var(--nice-border, #1e293b)",paddingTop:8},children:[n.jsx("div",{style:{padding:"0 8px 4px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:p("libraryExplorer.streaming","Streaming")}),n.jsx(ea,{name:"Tidal",enabled:M.tidal}),n.jsx(ea,{name:"Spotify",enabled:M.spotify}),n.jsx(ea,{name:"YouTube",enabled:M.youtube})]})]}),n.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[n.jsx(ga,{q:e,setQ:t,t:p}),n.jsx(ya,{files:k,t:p,onOpenInEditor:i,onPlayFile:o}),(M.tidal||M.spotify||M.youtube)&&n.jsx(dl,{streams:a.filter(T=>M[T.provider]),t:p,onPlayStream:l})]})]})},af=({kind:e,color:t})=>{const r={width:14,height:14,viewBox:"0 0 24 24",fill:t,"aria-hidden":!0};switch(e){case"youtube":return n.jsx("svg",{...r,children:n.jsx("path",{d:"M23 7.2s-.2-1.6-.9-2.3c-.8-.9-1.7-.9-2.1-1C16.9 3.5 12 3.5 12 3.5s-4.9 0-8 .4c-.4.1-1.3.1-2.1 1C1.2 5.6 1 7.2 1 7.2S.8 9.1.8 11v1.8c0 1.9.2 3.8.2 3.8s.2 1.6.9 2.3c.8.9 1.9.9 2.4 1 1.7.2 7.7.4 7.7.4s4.9 0 8-.4c.4-.1 1.3-.1 2.1-1 .7-.7.9-2.3.9-2.3s.2-1.9.2-3.8V11c0-1.9-.2-3.8-.2-3.8zM9.7 14.6V8.2l6.3 3.2-6.3 3.2z"})});case"spotify":return n.jsx("svg",{...r,children:n.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.59 14.42c-.18.3-.57.4-.87.21-2.39-1.46-5.4-1.79-8.95-.98-.34.08-.68-.13-.76-.47-.08-.34.13-.68.47-.76 3.88-.89 7.21-.5 9.89 1.13.31.19.4.58.22.87zm1.23-2.72c-.23.37-.71.49-1.08.26-2.74-1.69-6.92-2.18-10.16-1.19-.41.13-.85-.11-.97-.52-.13-.41.11-.85.52-.97 3.7-1.12 8.31-.58 11.45 1.34.37.23.49.71.24 1.08zm.11-2.84C14.55 8.84 9.5 8.66 6.43 9.6c-.49.15-1.01-.13-1.16-.62-.15-.49.13-1.01.62-1.16 3.52-1.07 9.1-.86 12.69 1.27.43.26.57.82.31 1.25-.26.43-.82.57-1.25.31z"})});case"tidal":return n.jsx("svg",{...r,children:n.jsx("path",{d:"M12 2L8 6l4 4 4-4-4-4zM4 6L0 10l4 4 4-4-4-4zm16 0l-4 4 4 4 4-4-4-4zm-8 8l-4 4 4 4 4-4-4-4z"})});case"hls":return n.jsx("svg",{...r,children:n.jsx("path",{d:"M2 12h2v6H2v-6zm4-4h2v10H6V8zm4-4h2v14h-2V4zm4 4h2v10h-2V8zm4 4h2v6h-2v-6z"})});case"audio":default:return n.jsx("svg",{...r,children:n.jsx("path",{d:"M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"})})}},ss=({data:e,display:t,callbacks:r,state:a})=>{const{id:s,index:i,artist:o,title:l,version:c,lp:d,sourcesAvailable:h=[]}=e,{allowVersion:f=!0,dragHandleProps:p}=t,{onChange:y,onRemove:m,onMoveUp:x,onMoveDown:b,onChangeLp:g,onSelectSource:S}=r,{readOnly:v=!1,canMoveUp:k=!0,canMoveDown:M=!0,activeSource:T}=a,{t:N}=Pe(),j=u.useRef(null);u.useEffect(()=>{!o&&j.current&&j.current.focus()},[o]);const R=O=>{if(!v&&O.key==="Enter"){const I=O.target.closest("div.gpi-row"),U=I==null?void 0:I.querySelectorAll("input[data-role='field']");if(!U||U.length===0)return;const J=Array.from(U).indexOf(O.target),_=U[J+1]??U[0];_==null||_.focus()}},z=O=>{const I=h.includes(O),U=T===O,J={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid var(--nice-border, #e5e7eb)",background:U?"var(--nice-selected-bg, #eef2ff)":"var(--nice-bg, #fff)",opacity:I?1:.35,cursor:I&&S&&!v?"pointer":"default",transition:"transform .05s ease"},_=O==="youtube"?"var(--nice-danger, #ff0000)":O==="spotify"?"var(--nice-success, #1db954)":O==="tidal"?"var(--nice-text, #111827)":O==="hls"?"var(--nice-accent, #7c3aed)":"var(--nice-text, #374151)",W=O==="youtube"?"YouTube":O==="spotify"?"Spotify":O==="tidal"?"TIDAL":O==="hls"?"HLS":"Audio",K=N("playlistItem.sourceLabel","Source")+": "+W+(U?` ${N("playlistItem.sourceSelected","(selected)")}`:""),re=()=>{!I||!S||v||S(O)};return n.jsx("button",{type:"button",title:W,onClick:re,disabled:!I||v,style:J,"aria-pressed":U,"aria-label":K,children:n.jsx(af,{kind:O,color:_})},O)},A=["youtube","tidal","spotify","hls","audio"],$=typeof d=="number"?d:i+1;return n.jsxs("div",{className:"gpi-row",role:"group","aria-label":N("playlistItem.trackNumber","Track")+" "+(i+1),style:{display:"grid",gridTemplateColumns:f?"56px 1fr 1fr 1fr auto auto":"56px 1fr 1fr auto auto",gap:8,alignItems:"center"},children:[n.jsx("input",{type:"number",min:1,value:$,onChange:O=>g==null?void 0:g(Number(O.target.value)),disabled:v||!g,"aria-label":"Lp",title:N("playlistItem.positionOnList","Position in the list"),style:sf}),n.jsx("input",{ref:j,"data-role":"field",type:"text",value:o,onChange:O=>y({artist:O.target.value}),placeholder:"Artist",onKeyDown:R,disabled:v,"aria-label":"Artist",className:"gpi-input",style:ta}),n.jsx("input",{"data-role":"field",type:"text",value:l,onChange:O=>y({title:O.target.value}),placeholder:"Title",onKeyDown:R,disabled:v,"aria-label":"Title",className:"gpi-input",style:ta}),f&&n.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:O=>y({version:O.target.value||void 0}),placeholder:N("playlistItem.versionOptional","Version (optional)"),onKeyDown:R,disabled:v,"aria-label":"Version",className:"gpi-input",style:ta}),n.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":N("playlistItem.availableSources","Available sources"),children:A.map(z)}),n.jsxs("div",{className:"gpi-actions",style:{display:"flex",gap:6,justifyContent:"flex-end"},children:[p&&n.jsx("button",{type:"button",...p,draggable:!0,"aria-label":N("playlistItem.dragReorder","Drag to reorder"),title:N("playlistItem.dragReorder","Drag to reorder"),style:tr,children:n.jsx(G.NtdMenu,{size:14})}),n.jsx("button",{type:"button",onClick:x,disabled:!k||v,"aria-label":N("playlistItem.moveUp","Move up"),title:N("playlistItem.moveUp","Move up"),style:tr,children:n.jsx(G.NtdArrowUp,{size:14})}),n.jsx("button",{type:"button",onClick:b,disabled:!M||v,"aria-label":N("playlistItem.moveDown","Move down"),title:N("playlistItem.moveDown","Move down"),style:tr,children:n.jsx(G.NtdArrowDown,{size:14})}),n.jsx("button",{type:"button",onClick:m,disabled:v,"aria-label":N("common.delete","Delete"),title:N("common.delete","Delete"),style:{...tr,color:"var(--nice-color-danger, #b91c1c)"},children:n.jsx(G.NtdClose,{size:14})})]})]})},sf={width:48,border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 6px",fontSize:14,textAlign:"center"},ta={width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 10px",fontSize:14},tr={border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg, #fff)",padding:"6px 8px",borderRadius:6,cursor:"pointer"},ba=()=>Math.random().toString(36).slice(2,10),nr=e=>(e??[]).map(t=>({id:ba(),...t})),of=e=>e.map(({id:t,...r})=>r),lf=null,cf=e=>{const t=e.trim();if(!t)return null;const r=t.split(/\s[-–—]\s/);if(r.length<2){const o=t.split(/[;|]/).map(l=>l.trim());return o.length>=2?{artist:o[0],title:o[1],version:o[2]||void 0}:null}const a=r[0].trim(),s=r.slice(1).join(" - ").trim(),i=s.match(/^(.*?)\s*[([](.+?)[)\]]\s*$/);if(i){const o=i[1].trim(),l=i[2].trim();return{artist:a,title:o,version:l||void 0}}return{artist:a,title:s,version:void 0}},ul=({value:e,defaultValue:t,onChange:r,allowVersion:a=!0,maxItems:s,addButtonLabel:i,emptyState:o=lf,readOnly:l=!1,autoFocusNewItem:c=!0,enableBulkPaste:d=!0})=>{const{t:h}=Pe(),f=e!==void 0,[p,y]=u.useState(()=>nr(e||t)),[m,x]=u.useState(""),b=u.useRef(null),[g,S]=u.useState(null);u.useEffect(()=>{f&&y(nr(e))},[f,JSON.stringify(e)]);const v=u.useCallback(K=>{r==null||r(of(K))},[r]),k=u.useCallback(K=>{if(f){const re=K(nr(e));v(re)}else y(re=>{const X=K(re);return v(X),X})},[v,f,e]),M=s?p.length<s:!0,T=u.useCallback(()=>{!M||l||k(K=>[...K,{id:ba(),artist:"",title:"",version:void 0}])},[M,l,k]),N=u.useCallback((K,re)=>{k(X=>X.map(q=>q.id===K?{...q,...re}:q))},[k]),j=u.useCallback(K=>{l||k(re=>re.filter(X=>X.id!==K))},[l,k]),R=u.useCallback((K,re)=>{k(X=>{const q=X.findIndex(L=>L.id===K);if(q<0)return X;const E=q+re;if(E<0||E>=X.length)return X;const P=[...X],[C]=P.splice(q,1);return P.splice(E,0,C),P})},[k]),z=u.useCallback((K,re)=>{k(X=>{const q=X.findIndex(L=>L.id===K);if(q<0)return X;const E=Math.max(0,Math.min(X.length-1,re-1));if(q===E)return X;const P=[...X],[C]=P.splice(q,1);return P.splice(E,0,C),P})},[k]),A=K=>re=>{l||(b.current=K,re.dataTransfer.effectAllowed="move",re.dataTransfer.setData("text/plain",K))},$=K=>re=>{l||(re.preventDefault(),re.dataTransfer.dropEffect="move",S(K))},O=K=>()=>S(re=>re===K?null:re),I=K=>re=>{if(l)return;re.preventDefault();const X=b.current??re.dataTransfer.getData("text/plain");S(null),b.current=null,!(!X||X===K)&&k(q=>{const E=q.findIndex(w=>w.id===X),P=q.findIndex(w=>w.id===K);if(E<0||P<0||E===P)return q;const C=[...q],[L]=C.splice(E,1);return C.splice(P,0,L),C})},U=()=>{b.current=null,S(null)},J=u.useCallback(()=>{if(!d||l)return;const re=m.split(/\r?\n/).map(X=>X.trim()).filter(Boolean).map(cf).filter(X=>!!X);re.length!==0&&(k(X=>{const q=(s??1/0)-X.length,E=re.slice(0,Math.max(0,q)).map(P=>({id:ba(),...P}));return[...X,...E]}),x(""))},[d,l,m,s,k]);u.useEffect(()=>{},[p.length,c]);const _=o??n.jsx("div",{style:{padding:"0.75rem",color:"var(--nice-text-secondary, #777)",fontStyle:"italic"},children:h("genericPlaylist.emptyState","No songs. Add the first one below.")}),W=i??h("genericPlaylist.addSong","Add song");return n.jsxs("div",{className:"gp-container",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[n.jsxs("div",{className:"gp-header",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[n.jsx("h3",{style:{margin:0,fontSize:16},children:h("genericPlaylist.playlist","Playlist")}),n.jsx("div",{style:{marginLeft:"auto",display:"flex",gap:8},children:n.jsxs("button",{type:"button",onClick:T,disabled:!M||l,className:"gp-add",style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},"aria-label":W,children:["+ ",W]})})]}),p.length===0?n.jsx("div",{className:"gp-empty",children:_}):n.jsx("ol",{className:"gp-list",style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:8},children:p.map((K,re)=>{const X=g===K.id;return n.jsx("li",{draggable:!l,onDragStart:A(K.id),onDragOver:$(K.id),onDragLeave:O(K.id),onDrop:I(K.id),onDragEnd:U,style:{border:X?"2px dashed var(--nice-info, #6366f1)":"2px solid transparent",borderRadius:8,padding:X?4:0},children:n.jsx(ss,{data:{id:K.id,index:re,lp:re+1,artist:K.artist,title:K.title,version:a?K.version??void 0:void 0,sourcesAvailable:void 0},display:{allowVersion:a,dragHandleProps:{onDragStart:A(K.id)}},callbacks:{onChange:q=>N(K.id,q),onRemove:()=>j(K.id),onMoveUp:()=>R(K.id,-1),onMoveDown:()=>R(K.id,1),onChangeLp:q=>z(K.id,q)},state:{readOnly:l,canMoveUp:re>0,canMoveDown:re<p.length-1}})},K.id)})}),d&&!l&&n.jsx("div",{style:{marginTop:12},children:n.jsxs("details",{children:[n.jsx("summary",{style:{cursor:"pointer",color:"var(--nice-text, #374151)"},children:h("genericPlaylist.bulkPasteSummary","Paste multiple items at once")}),n.jsxs("div",{style:{marginTop:6},children:[n.jsx("textarea",{value:m,onChange:K=>x(K.target.value),placeholder:h("genericPlaylist.bulkPastePlaceholder",`Paste lines in format:
|
|
65
|
+
`}),r.jsxs("div",{ref:k,style:Q.container,children:[r.jsxs("div",{style:Q.header,children:[r.jsxs("h1",{style:{...Q.title,display:"inline-flex",alignItems:"center",gap:8},children:[r.jsx(O.NtdBarChart,{size:26})," ",f("vocalReport.title","Vocal Performance Report")]}),r.jsxs("p",{style:Q.subtitle,children:[E.songArtist," — ",E.songTitle," | ",f("vocalReport.difficulty","Difficulty"),": ",r.jsx("strong",{children:E.difficulty})," "," | ",new Date(E.timestamp).toLocaleString()]}),r.jsxs("div",{style:{marginTop:16,display:"flex",justifyContent:"center",alignItems:"center",gap:16},children:[r.jsx("div",{style:{width:72,height:72,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:`linear-gradient(135deg, ${gt(A)}44, ${gt(A)})`,border:`3px solid ${gt(A)}`,boxShadow:`0 0 20px ${gt(A)}44`},children:r.jsx("span",{style:{fontSize:28,fontWeight:900,color:"#fff"},children:z})}),r.jsxs("div",{style:{textAlign:"left"},children:[r.jsxs("div",{style:{fontSize:14,fontWeight:700,color:gt(A)},children:[f("vocalReport.overallGrade","Overall grade"),": ",A.toFixed(1),"%"]}),r.jsx("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",maxWidth:360},children:j[z]??""})]})]})]}),r.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end",marginBottom:16,flexWrap:"wrap"},children:[r.jsxs("button",{style:Q.btnPrimary,onClick:N,children:[r.jsx(O.NtdDownload,{size:14})," ",f("vocalReport.downloadHtml","Download HTML")]}),r.jsxs("button",{style:Q.btnSecondary,onClick:$,children:[r.jsx(O.NtdPrint,{size:14})," ",f("vocalReport.printPdf","Print / PDF")]}),r.jsxs("button",{style:Q.btnSecondary,onClick:M,children:[r.jsx(O.NtdCode,{size:14})," ",f("vocalReport.exportJson","Export JSON")]}),r.jsxs("button",{style:Q.btnSecondary,onClick:d,children:[r.jsx(O.NtdClose,{size:14})," ",f("vocalReport.close","Close")]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",f("vocalReport.scoreOverview","Score overview")]}),r.jsxs("div",{style:Q.kpiGrid,children:[r.jsxs("div",{style:Q.kpiCard,children:[r.jsx("div",{style:Q.kpiValue,children:E.totalScore.toLocaleString()}),r.jsx("div",{style:Q.kpiLabel,children:f("vocalReport.totalScore","Total score")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsx("div",{style:Q.kpiValue,children:E.classicScore.toLocaleString()}),r.jsx("div",{style:Q.kpiLabel,children:f("vocalReport.classicScore","Classic score")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsx("div",{style:Q.kpiValue,children:E.bonusScore.toLocaleString()}),r.jsx("div",{style:Q.kpiLabel,children:f("vocalReport.bonusScore","Bonus score")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsxs("div",{style:Q.kpiValue,children:[E.maxCombo,"×"]}),r.jsx("div",{style:Q.kpiLabel,children:f("vocalReport.maxCombo","Max combo")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsxs("div",{style:{...Q.kpiValue,color:gt(E.intonationAccuracyPct)},children:[E.intonationAccuracyPct,"%"]}),r.jsx("div",{style:Q.kpiLabel,children:f("vocalReport.intonationAccuracy","Intonation accuracy")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsxs("div",{style:{...Q.kpiValue,color:gt(E.perfectHitPct)},children:[E.perfectHitPct,"%"]}),r.jsx("div",{style:Q.kpiLabel,children:f("vocalReport.perfectHits","Perfect hits")})]})]}),w.length>1&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",f("vocalReport.playerComparison","Player comparison")]}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:"#"}),r.jsx("th",{style:Q.th,children:f("vocalReport.player","Player")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.classic","Classic")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.bonus","Bonus")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.total","Total")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.intonation","Intonation")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.perfect","Perfect")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.range","Range")})]})}),r.jsx("tbody",{children:w.map((S,F)=>r.jsxs("tr",{children:[r.jsx("td",{style:Q.td,children:F+1}),r.jsx("td",{style:{...Q.tdBold,color:S.playerColor},children:S.playerName}),r.jsx("td",{style:Q.tdRight,children:S.classicScore.toLocaleString()}),r.jsx("td",{style:Q.tdRight,children:S.bonusScore.toLocaleString()}),r.jsx("td",{style:{...Q.tdRight,fontWeight:700,color:"var(--nice-warning, #fbbf24)"},children:S.totalScore.toLocaleString()}),r.jsx("td",{style:Q.tdRight,children:r.jsxs("span",{style:Q.badge(gt(S.intonationAccuracyPct)),children:[S.intonationAccuracyPct,"%"]})}),r.jsx("td",{style:Q.tdRight,children:r.jsxs("span",{style:Q.badge(gt(S.perfectHitPct)),children:[S.perfectHitPct,"%"]})}),r.jsxs("td",{style:Q.tdRight,children:[S.lowestNote,"–",S.highestNote]})]},F))})]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",f("vocalReport.pitchAccuracy","Pitch accuracy")]}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:f("vocalReport.metric","Metric")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.value","Value")}),r.jsx("th",{style:Q.th,children:f("vocalReport.description","Description")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.meanAbsDev","Mean abs. deviation")}),r.jsxs("td",{style:Q.tdRight,children:[E.avgCentDeviation,r.jsxs("span",{style:Q.kpiUnit,children:[" ",T]})]}),r.jsx("td",{style:Q.td,children:f("vocalReport.meanAbsDevDesc","Average distance from the target pitch.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.medianDev","Median deviation")}),r.jsxs("td",{style:Q.tdRight,children:[E.medianCentDeviation,r.jsxs("span",{style:Q.kpiUnit,children:[" ",T]})]}),r.jsx("td",{style:Q.td,children:f("vocalReport.medianDevDesc","Typical deviation, robust to outliers.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.stdDev","Std. deviation")}),r.jsxs("td",{style:Q.tdRight,children:[E.stdDevCents,r.jsxs("span",{style:Q.kpiUnit,children:[" ",T]})]}),r.jsx("td",{style:Q.td,children:f("vocalReport.stdDevDesc","Consistency of pitch (lower = steadier).")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.intonationAccuracyLabel","Intonation accuracy")}),r.jsxs("td",{style:{...Q.tdRight,color:gt(E.intonationAccuracyPct)},children:[E.intonationAccuracyPct,"%"]}),r.jsx("td",{style:Q.td,children:f("vocalReport.intonationAccuracyDesc","Share of frames within tolerance.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.perfectHitRate","Perfect-hit rate")}),r.jsxs("td",{style:{...Q.tdRight,color:gt(E.perfectHitPct)},children:[E.perfectHitPct,"%"]}),r.jsx("td",{style:Q.td,children:f("vocalReport.perfectHitRateDesc","Notes hit dead-on.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.totalPitchSamples","Total pitch samples")}),r.jsx("td",{style:Q.tdRight,children:E.totalPitchPoints.toLocaleString()}),r.jsx("td",{style:Q.td,children:f("vocalReport.totalPitchSamplesDesc","Number of analysed pitch frames.")})]})]})]}),r.jsxs("div",{style:Q.chartWrap,children:[r.jsx("div",{style:Q.chartTitle,children:f("vocalReport.deviationDistribution","Deviation distribution")}),r.jsx("div",{style:{height:220},children:r.jsx(ie.NiceChart,{width:860,height:220,stacked:!0,showLegend:!1,categories:q.map(S=>S.centRange),series:Ks(q.map(S=>`${G} (${S.centRange})`),q.map(S=>S.count),q.map(S=>Xh(S.centRange)))})})]}),r.jsxs("div",{style:Q.row,children:[r.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[r.jsx("div",{style:Q.chartTitle,children:f("vocalReport.hitClassification","Hit classification")}),r.jsx("div",{style:{height:220},children:r.jsx(ie.NicePieChart,{width:400,height:260,data:H.map(S=>({label:S.name,value:Ut(S.value),color:S.fill}))})})]}),r.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[r.jsx("div",{style:Q.chartTitle,children:f("vocalReport.performanceProfile","Performance profile")}),r.jsx("div",{style:{height:220},children:r.jsx(ie.NiceChart,{width:400,height:220,showLegend:!1,categories:Y.map(S=>S.metric),series:[{name:f("vocalReport.performanceProfile","Performance profile"),type:"radar",color:"var(--nice-info, #3b82f6)",data:Y.map(S=>Ut(S.value))},{name:"100%",type:"radar",color:"transparent",data:Y.map(S=>S.max)}]})})]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",f("vocalReport.pitchTracking","Pitch tracking")]}),r.jsxs("div",{style:Q.chartWrap,children:[r.jsx("div",{style:Q.chartTitle,children:f("vocalReport.sungVsExpected","Sung vs expected")}),r.jsx("div",{style:{height:260},children:r.jsx(ie.NiceChart,{width:860,height:230,categories:Zs(Z.map(S=>S.t)),series:[{name:f("vocalReport.expected","Expected"),type:"line",color:"var(--nice-success, #22c55e)",data:Z.map(S=>Ut(S.expected))},{name:f("vocalReport.sung","Sung"),type:"line",color:"var(--nice-info, #3b82f6)",data:Z.map(S=>Ut(S.sung))}]})})]}),r.jsxs("div",{style:Q.chartWrap,children:[r.jsx("div",{style:Q.chartTitle,children:f("vocalReport.rollingAccuracy","Rolling accuracy")}),r.jsx("div",{style:{height:180},children:r.jsx(ie.NiceChart,{width:860,height:180,showLegend:!1,categories:Zs(X.map(S=>S.t)),series:[{name:f("vocalReport.rollingAccuracy","Rolling accuracy"),type:"area",color:"var(--nice-accent, #8b5cf6)",data:X.map(S=>Ut(S.accuracy))}]})})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",f("vocalReport.vocalRange","Vocal range")]}),r.jsxs("div",{style:Q.row,children:[r.jsx("div",{style:Q.half,children:r.jsx("table",{style:Q.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.lowestNote","Lowest note")}),r.jsxs("td",{style:Q.tdRight,children:[E.lowestNote," (",E.lowestHz," Hz)"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.highestNote","Highest note")}),r.jsxs("td",{style:Q.tdRight,children:[E.highestNote," (",E.highestHz," Hz)"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.rangeLabel","Range")}),r.jsxs("td",{style:Q.tdRight,children:[E.rangeInSemitones," ",f("vocalReport.semitones","semitones")]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.tessitura","Tessitura")}),r.jsxs("td",{style:Q.tdRight,children:[E.tessituraLow," — ",E.tessituraHigh]})]})]})})}),r.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[r.jsx("div",{style:Q.chartTitle,children:f("vocalReport.chromagram","Chromagram")}),r.jsx("div",{style:{height:180},children:r.jsx(ie.NiceChart,{width:400,height:180,showLegend:!1,categories:D.map(S=>S.note),series:[{name:f("vocalReport.usagePct","Usage %"),type:"bar",color:"var(--nice-primary, #6366f1)",data:D.map(S=>Ut(S.pct))}]})})]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",f("vocalReport.vibratoStability","Vibrato & stability")]}),r.jsxs("div",{style:Q.row,children:[r.jsx("div",{style:Q.half,children:r.jsx("table",{style:Q.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.vibratoDetected","Vibrato detected")}),r.jsx("td",{style:Q.tdRight,children:r.jsx("span",{style:Q.badge(E.vibrato.detected?"var(--nice-success, #22c55e)":"var(--nice-text-muted, #64748b)"),children:E.vibrato.detected?f("vocalReport.yes","Yes"):f("vocalReport.no","No")})})]}),E.vibrato.detected&&r.jsxs(r.Fragment,{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.avgRate","Avg. rate")}),r.jsxs("td",{style:Q.tdRight,children:[E.vibrato.avgRateHz," Hz"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.avgExtent","Avg. extent")}),r.jsxs("td",{style:Q.tdRight,children:["±",E.vibrato.avgExtentCents," ",T]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.regularity","Regularity")}),r.jsxs("td",{style:Q.tdRight,children:[E.vibrato.regularityPct,"%"]})]})]})]})})}),r.jsx("div",{style:Q.half,children:r.jsx("table",{style:Q.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.jitter","Jitter")}),r.jsxs("td",{style:Q.tdRight,children:[E.jitterPct,"%"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.vocalPresence","Vocal presence")}),r.jsxs("td",{style:Q.tdRight,children:[E.shimmerProxy,"%"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.avgOnsetDev","Avg. onset deviation")}),r.jsxs("td",{style:Q.tdRight,children:[E.avgOnsetDeviationMs," ms"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.rhythmStability","Rhythm stability")}),r.jsx("td",{style:Q.tdRight,children:r.jsxs("span",{style:Q.badge(gt(E.rhythmStabilityPct)),children:[E.rhythmStabilityPct,"%"]})})]})]})})})]}),E.verseMetrics.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",f("vocalReport.verseBreakdown","Per-verse breakdown")]}),r.jsxs("div",{style:Q.chartWrap,children:[r.jsx("div",{style:Q.chartTitle,children:f("vocalReport.accuracyByVerse","Accuracy by verse")}),r.jsx("div",{style:{height:200},children:r.jsx(ie.NiceChart,{width:860,height:200,stacked:!0,showLegend:!1,categories:V.map(S=>S.verse),series:Ks(V.map(S=>`${C} (${S.verse})`),V.map(S=>S.accuracy),V.map(S=>Hs(S.label)))})})]}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:f("vocalReport.verse","Verse")}),r.jsx("th",{style:Q.th,children:f("vocalReport.rating","Rating")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.hitPct","Hit %")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.avgDeviation","Avg. dev.")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.notes","Notes")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.notesHit","Hit")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.comboBonus","Combo bonus")})]})}),r.jsx("tbody",{children:E.verseMetrics.map((S,F)=>r.jsxs("tr",{children:[r.jsxs("td",{style:Q.td,children:[f("vocalReport.verse","Verse")," ",S.verseIndex+1]}),r.jsx("td",{style:Q.td,children:r.jsx("span",{style:Q.badge(Hs(S.label)),children:S.label})}),r.jsxs("td",{style:Q.tdRight,children:[(S.hitFraction*100).toFixed(1),"%"]}),r.jsxs("td",{style:Q.tdRight,children:[S.avgCentDeviation," ¢"]}),r.jsx("td",{style:Q.tdRight,children:S.noteCount}),r.jsx("td",{style:Q.tdRight,children:S.notesHit}),r.jsxs("td",{style:Q.tdRight,children:["+",S.comboBonus]})]},F))})]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",f("vocalReport.scoringConfig","Scoring configuration")]}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:f("vocalReport.parameter","Parameter")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.value","Value")}),r.jsx("th",{style:Q.th,children:f("vocalReport.description","Description")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.difficultyLevel","Difficulty level")}),r.jsx("td",{style:Q.tdRight,children:E.difficulty}),r.jsx("td",{style:Q.td,children:f("vocalReport.difficultyLevelDesc","Affects tolerance and multiplier.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.semitoneTolerance","Semitone tolerance")}),r.jsx("td",{style:Q.tdRight,children:L.semitoneTolerance}),r.jsx("td",{style:Q.td,children:f("vocalReport.semitoneToleranceDesc","Pitch window counted as a hit.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.preWindow","Pre window")}),r.jsxs("td",{style:Q.tdRight,children:[L.preWindow," s"]}),r.jsx("td",{style:Q.td,children:f("vocalReport.preWindowDesc","Lead-in time before a note.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.postExtra","Post extra")}),r.jsxs("td",{style:Q.tdRight,children:[L.postExtra," s"]}),r.jsx("td",{style:Q.td,children:f("vocalReport.postExtraDesc","Grace time after a note.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.difficultyMultiplier","Difficulty multiplier")}),r.jsxs("td",{style:Q.tdRight,children:[L.difficultyMult,"×"]}),r.jsx("td",{style:Q.td,children:f("vocalReport.difficultyMultiplierDesc","Score scaling for difficulty.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.songBpm","Song BPM")}),r.jsx("td",{style:Q.tdRight,children:E.songBpm}),r.jsx("td",{style:Q.td,children:f("vocalReport.songBpmDesc","Tempo used for note timing.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.totalNotes","Total notes")}),r.jsx("td",{style:Q.tdRight,children:R}),r.jsx("td",{style:Q.td,children:f("vocalReport.totalNotesDesc","Number of scored notes in the song.")})]})]})]}),w.some(S=>S.micSettings)&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:Q.sectionTitle,children:[++I,". ",f("vocalReport.micConfig","Microphone configuration")]}),w.map((S,F)=>S.micSettings&&r.jsxs("div",{style:{marginBottom:16},children:[w.length>1&&r.jsx("h4",{style:{color:S.playerColor,margin:"0 0 8px",fontSize:14},children:S.playerName}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:f("vocalReport.setting","Setting")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.value","Value")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.device","Device")}),r.jsx("td",{style:Q.tdRight,children:S.micSettings.deviceLabel||S.micSettings.deviceId})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.pitchAlgorithm","Pitch algorithm")}),r.jsx("td",{style:Q.tdRight,children:S.micSettings.algorithm})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.inputGain","Input gain")}),r.jsxs("td",{style:Q.tdRight,children:[S.micSettings.gain,"×"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.rmsThreshold","RMS threshold")}),r.jsx("td",{style:Q.tdRight,children:S.micSettings.rmsThreshold})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.pitchThreshold","Pitch threshold")}),r.jsx("td",{style:Q.tdRight,children:S.micSettings.pitchThreshold})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.smoothingWindow","Smoothing window")}),r.jsxs("td",{style:Q.tdRight,children:[S.micSettings.smoothingWindow," ",f("vocalReport.frames","frames")]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.hysteresisFrames","Hysteresis frames")}),r.jsx("td",{style:Q.tdRight,children:S.micSettings.hysteresisFrames})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.hanningWindow","Hanning window")}),r.jsx("td",{style:Q.tdRight,children:S.micSettings.useHanning?f("vocalReport.enabled","Enabled"):f("vocalReport.disabled","Disabled")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.latencyOffset","Latency offset")}),r.jsxs("td",{style:Q.tdRight,children:[S.micSettings.latencyOffsetMs," ms"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.monitor","Monitor")}),r.jsx("td",{style:Q.tdRight,children:S.micSettings.monitorEnabled?`${f("vocalReport.on","On")} (${Math.round(S.micSettings.monitorVolume*100)}%)`:f("vocalReport.off","Off")})]})]})]})]},F))]}),r.jsx("div",{style:Q.footer,children:r.jsxs("p",{children:[f("vocalReport.footerGenerated","Report generated")," ·"," ",E.timestamp.replace(/[-:T.Z]/g,"").slice(0,14)]})})]})]})},Jh="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100'%3E%3Crect width='100' height='100' fill='%23334155'/%3E%3Ccircle cx='42' cy='64' r='8' fill='%2394a3b8'/%3E%3Crect x='48' y='34' width='3' height='32' fill='%2394a3b8'/%3E%3C/svg%3E";function ep(e){if(!e)return"";const t=Math.floor(e/60),n=Math.round(e%60);return`${t}:${n.toString().padStart(2,"0")}`}function Qs(e){return Array.from(new Set(e.filter(t=>!!t))).sort((t,n)=>t.localeCompare(n))}const tp=Object.assign(u.memo(({song:e,index:t,active:n,coverUrl:a,topScore:s,selected:i,multiSelect:o,disabled:l,t:c,onPlay:d,onToggleSelect:h,onFocusRow:p})=>{const g=()=>{o?h(e.id):l||d==null||d(e)};return r.jsxs("div",{className:`nice-ksb-row${i?" nice-ksb-row--selected":""}${n?" nice-ksb-row--active":""}`,role:"option","aria-selected":i,"data-ksb-index":t,tabIndex:n?0:-1,onClick:g,onFocus:()=>p(t),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),g())},children:[o&&r.jsx("input",{type:"checkbox",className:"nice-ksb-row__check",checked:i,onChange:()=>h(e.id),onClick:y=>y.stopPropagation(),"aria-label":e.title}),r.jsx("img",{className:"nice-ksb-row__cover",src:a,alt:"",loading:"lazy"}),r.jsxs("div",{className:"nice-ksb-row__main",children:[r.jsx("div",{className:"nice-ksb-row__title",children:e.title}),r.jsx("div",{className:"nice-ksb-row__artist",children:e.artist||"—"})]}),r.jsxs("div",{className:"nice-ksb-row__meta",children:[e.genre&&r.jsx("span",{className:"nice-ksb-badge",children:e.genre}),e.year&&r.jsx("span",{className:"nice-ksb-badge",children:e.year}),e.durationSec?r.jsx("span",{className:"nice-ksb-badge",children:ep(e.durationSec)}):null,e.externalSource&&r.jsx("span",{className:"nice-ksb-badge nice-ksb-badge--src",children:e.externalSource}),s&&r.jsxs("span",{className:"nice-ksb-badge nice-ksb-badge--score",title:s.playerName,children:[r.jsx(O.NtdTrophy,{size:11})," ",s.score.toLocaleString()]})]}),!o&&r.jsxs("button",{type:"button",className:"nice-ksb-row__play",disabled:l,onClick:y=>{y.stopPropagation(),d==null||d(e)},children:[r.jsx(O.NtdPlay,{size:13})," ",c("karaokeBrowser.play","Play")]})]})}),{displayName:"NiceKaraokeSongRow"}),np={artist:"Artist",title:"Title",year:"Year",genre:"Genre"},rp=({songs:e,fetchSongs:t,loading:n=!1,getCover:a,getTopScore:s,onPlay:i,onSelect:o,multiSelect:l=!1,maxSelections:c=0,showSidebar:d=!0,enableGamepad:h=!0,disabled:p=!1,disabledReason:g,t:y,className:m,style:x,id:v,accessMode:f,"data-testid":k})=>{const{t:b}=be(),w=y??b,[N,$]=u.useState(""),[M,E]=u.useState(""),[R,L]=u.useState(""),[A,z]=u.useState(""),[j,I]=u.useState("artist"),[Y,H]=u.useState("asc"),[D,V]=u.useState({type:"all"}),[Z,X]=u.useState(new Set),[q,G]=u.useState([]),[C,T]=u.useState(!1);u.useEffect(()=>{const pe=setTimeout(()=>E(N),300);return()=>clearTimeout(pe)},[N]),u.useEffect(()=>{if(e||!t)return;let pe=!1;return T(!0),Promise.resolve(t({searchQuery:M.trim()||void 0,genres:R?[R]:void 0,languages:A?[A]:void 0})).then(Se=>!pe&&G(Se)).catch(()=>!pe&&G([])).finally(()=>!pe&&T(!1)),()=>{pe=!0}},[e,t,M,R,A]);const S=e??q,F=u.useMemo(()=>Qs(S.map(pe=>pe.genre)),[S]),K=u.useMemo(()=>Qs(S.map(pe=>pe.language)),[S]),P=u.useMemo(()=>{let pe=S;const Se=M.trim().toLowerCase();Se&&(pe=pe.filter($e=>`${$e.title} ${$e.artist}`.toLowerCase().includes(Se))),R&&(pe=pe.filter($e=>$e.genre===R)),A&&(pe=pe.filter($e=>$e.language===A)),D.type==="genre"&&(pe=pe.filter($e=>$e.genre===D.value)),D.type==="language"&&(pe=pe.filter($e=>$e.language===D.value));const je=Y==="asc"?1:-1;return[...pe].sort(($e,Te)=>{const He=$e[j]??"",de=Te[j]??"";return typeof He=="number"&&typeof de=="number"?(He-de)*je:String(He).localeCompare(String(de))*je})},[S,M,R,A,D,j,Y]),B=pe=>{X(Se=>{const je=new Set(Se);return je.has(pe)?je.delete(pe):(c===0||je.size<c)&&je.add(pe),je})},_=()=>{const pe=S.filter(Se=>Z.has(Se.id));o==null||o({songs:pe})},U=n||C,J=pe=>{pe===j?H(Se=>Se==="asc"?"desc":"asc"):(I(pe),H("asc"))},se=u.useRef(null),[oe,re]=u.useState(0),W=u.useRef(0),ee=u.useRef(P);ee.current=P,u.useEffect(()=>{re(pe=>{const Se=Math.min(Math.max(0,pe),Math.max(0,P.length-1));return W.current=Se,Se})},[P.length]);const ae=u.useCallback(pe=>{var je;const Se=(je=se.current)==null?void 0:je.querySelector(`[data-ksb-index="${pe}"]`);Se==null||Se.focus(),Se==null||Se.scrollIntoView({block:"nearest"})},[]),le=u.useCallback(pe=>{W.current=pe,re(pe)},[]),ce=u.useCallback((pe,Se=!0)=>{const je=ee.current.length;if(je===0)return;const $e=Math.min(je-1,Math.max(0,pe));W.current=$e,re($e),Se&&requestAnimationFrame(()=>ae($e))},[ae]),te=u.useCallback(pe=>ce(W.current+pe),[ce]),he=pe=>{const Se=ee.current[pe];Se&&(l?B(Se.id):p||i==null||i(Se))},ue=pe=>{switch(pe.key){case"ArrowDown":pe.preventDefault(),te(1);break;case"ArrowUp":pe.preventDefault(),te(-1);break;case"Home":pe.preventDefault(),ce(0);break;case"End":pe.preventDefault(),ce(ee.current.length-1);break;case"PageDown":pe.preventDefault(),te(5);break;case"PageUp":pe.preventDefault(),te(-5);break}},xe=we.useGamepad({enabled:h,actions:{navUp:{button:"DpadUp",onPress:()=>te(-1),repeatDelay:350,repeatRate:110},navDown:{button:"DpadDown",onPress:()=>te(1),repeatDelay:350,repeatRate:110},stickUp:{axis:"LeftY",axisDirection:"negative",onPress:()=>te(-1),repeatDelay:350,repeatRate:130},stickDown:{axis:"LeftY",axisDirection:"positive",onPress:()=>te(1),repeatDelay:350,repeatRate:130},select:{button:"A",onPress:()=>he(W.current)},confirm:{button:"Start",onPress:()=>{l&&_()}}}});return f==="hidden"?null:r.jsxs("div",{className:`nice-ksb${m?` ${m}`:""}`,style:x,id:v,"data-testid":k,children:[d&&r.jsxs("aside",{className:"nice-ksb__sidebar",children:[r.jsxs("button",{type:"button",className:`nice-ksb__node${D.type==="all"?" nice-ksb__node--active":""}`,onClick:()=>V({type:"all"}),children:[r.jsx(O.NtdMusic,{size:14})," ",w("karaokeBrowser.allSongs","All songs")," (",S.length,")"]}),F.length>0&&r.jsxs("div",{className:"nice-ksb__facet",children:[r.jsx("div",{className:"nice-ksb__facet-title",children:w("karaokeBrowser.genres","Genres")}),F.map(pe=>r.jsx("button",{type:"button",className:`nice-ksb__node${D.type==="genre"&&D.value===pe?" nice-ksb__node--active":""}`,onClick:()=>V({type:"genre",value:pe}),children:pe},pe))]}),K.length>0&&r.jsxs("div",{className:"nice-ksb__facet",children:[r.jsx("div",{className:"nice-ksb__facet-title",children:w("karaokeBrowser.languages","Languages")}),K.map(pe=>r.jsx("button",{type:"button",className:`nice-ksb__node${D.type==="language"&&D.value===pe?" nice-ksb__node--active":""}`,onClick:()=>V({type:"language",value:pe}),children:pe},pe))]})]}),r.jsxs("div",{className:"nice-ksb__main",children:[r.jsxs("div",{className:"nice-ksb__toolbar",children:[r.jsx("input",{className:"nice-ksb__search",type:"search",value:N,placeholder:w("karaokeBrowser.search","Search title or artist…"),onChange:pe=>$(pe.target.value)}),r.jsx("div",{className:"nice-ksb__sort",children:["artist","title","year","genre"].map(pe=>r.jsxs("button",{type:"button",className:`nice-ksb__sort-btn${j===pe?" nice-ksb__sort-btn--active":""}`,onClick:()=>J(pe),children:[w(`karaokeBrowser.sort.${pe}`,np[pe]??pe),j===pe&&(Y==="asc"?r.jsx(O.NtdChevronUp,{size:12}):r.jsx(O.NtdChevronDown,{size:12}))]},pe))}),r.jsxs("span",{className:`nice-ksb__navhint${xe.connected?" nice-ksb__navhint--pad":""}`,title:w("karaokeBrowser.navHint","Navigate with ↑ ↓ or the D-pad · Enter / A to play"),children:[xe.connected?r.jsx(O.NtdGamepad,{size:14}):r.jsx(O.NtdMove,{size:14}),r.jsx("span",{className:"nice-ksb__navhint-keys",children:xe.connected?"D-pad · A":"↑ ↓ · Enter"})]})]}),p&&g&&r.jsx("div",{className:"nice-ksb__disabled",children:g}),r.jsx("div",{className:"nice-ksb__list",role:"listbox","aria-multiselectable":l,"aria-label":w("karaokeBrowser.songs","Songs"),ref:se,onKeyDown:ue,children:U?r.jsx("div",{className:"nice-ksb__empty",children:w("karaokeBrowser.loading","Loading…")}):P.length===0?r.jsx("div",{className:"nice-ksb__empty",children:w("karaokeBrowser.noResults","No songs found")}):P.map((pe,Se)=>r.jsx(tp,{song:pe,index:Se,active:Se===oe,coverUrl:(a==null?void 0:a(pe))||pe.coverImage||pe.externalCoverUrl||pe.coverPath||Jh,topScore:s==null?void 0:s(pe),selected:Z.has(pe.id),multiSelect:l,disabled:p,t:w,onPlay:i,onToggleSelect:B,onFocusRow:le},pe.id))}),l&&r.jsxs("div",{className:"nice-ksb__footer",children:[r.jsxs("span",{children:[Z.size,c>0?` / ${c}`:""," ",w("karaokeBrowser.selected","selected")]}),r.jsx("button",{type:"button",className:"nice-ksb__confirm",disabled:Z.size===0,onClick:_,children:w("karaokeBrowser.confirm","Add selected")})]})]})]})};function ll(e,t,n=50,a=30){const s=Math.round(e/1e3*t),i=Math.round(n/1e3*t),o=Math.max(1,Math.round(a/1e3*t)),l=new Float32Array(s);for(let c=0;c<o;c++){const d=.5*(1-Math.cos(2*Math.PI*c/(o-1))),h=i+c-Math.floor(o/2);h>=0&&h<s&&(l[h]=d)}return l}function Js(e,t,n=1e3){const a=Math.max(1,Math.round(t/n)),s=Math.ceil(e.length/a),i=new Float32Array(s);for(let l=0;l<s;l++){const c=l*a,d=Math.min(e.length,c+a);let h=0;for(let p=c;p<d;p++)h+=Math.abs(e[p]);i[l]=h/(d-c||1)}let o=0;for(let l=0;l<i.length;l++)i[l]>o&&(o=i[l]);if(o>0)for(let l=0;l<i.length;l++)i[l]=i[l]/o;return{env:i,factor:a}}function ap(e,t){const n=e.length,a=t.length;if(n===0||a===0)return 0;let s={lag:0,score:-1/0};const i=Math.min(2e3,a);for(let o=-i;o<=i;o++){let l=0,c=0,d=0;for(let g=0;g<n;g++){const y=g+o+Math.floor((a-n)/2);if(y<0||y>=a)continue;const m=e[g],x=t[y];l+=m*x,c+=m*m,d+=x*x}const h=Math.sqrt(Math.max(1e-9,c*d)),p=l/h;p>s.score&&(s={lag:o,score:p})}return s.lag}function cl(e,t,n=50,a=30){try{const s=Math.max(300,Math.round(e.length/t*1e3)),i=ll(s,t,n,a),o=Js(e,t,1e3),l=Js(i,t,1e3),d=ap(l.env,o.env)*1e3/1e3;return Math.round(d)}catch{return null}}const sp=({deviceId:e,initialOffsetMs:t=null,onSave:n,onClose:a,rounds:s=3,t:i,className:o,style:l,id:c,accessMode:d,"data-testid":h})=>{const{t:p}=be(),g=i??p,[y,m]=u.useState(null),[x,v]=u.useState(t),[f,k]=u.useState(!1),[b,w]=u.useState([]),[N,$]=u.useState(0),[M,E]=u.useState(!1),R=u.useRef(!1);u.useEffect(()=>{v(t??null)},[t,e]);const L=async()=>{const I=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),Y=new AudioContext,H=Y.sampleRate,D=Y.createMediaStreamSource(I),V=Y.createScriptProcessor(2048,1,1);D.connect(V),V.connect(Y.destination);const Z=1200,X=Math.round(Z/1e3*H),q=new Float32Array(X);let G=0,C=!1;V.onaudioprocess=B=>{if(C)return;const _=B.inputBuffer.getChannelData(0),U=Math.min(_.length,X-G);U>0&&(q.set(_.subarray(0,U),G),G+=U),G>=X&&(C=!0)},await new Promise(B=>setTimeout(B,80));const T=new AudioContext,S=T.createOscillator(),F=T.createGain();S.type="sine",S.frequency.value=1e3,F.gain.value=1e-4,S.connect(F),F.connect(T.destination);const K=T.currentTime+.05;F.gain.setValueAtTime(1e-4,K-.01),F.gain.linearRampToValueAtTime(1,K),F.gain.linearRampToValueAtTime(1e-4,K+.06),S.start(K-.02),S.stop(K+.1),await new Promise(B=>{const _=()=>{if(C||G>=X){B();return}setTimeout(_,50)};setTimeout(()=>{C=!0,B()},Z+500),_()}),V.onaudioprocess=null;try{V.disconnect()}catch{}try{D.disconnect()}catch{}try{await T.close()}catch{}try{await Y.close()}catch{}I.getTracks().forEach(B=>B.stop());const P=q.subarray(0,G);return cl(P,H,130,30)},A=async()=>{if(!R.current){R.current=!0,E(!0),m(g("latencyCalibrator.requestingMic","Requesting microphone — click allow if prompted")),v(null),w([]),$(0);try{const I=[];for(let H=0;H<s;H++){m(`${g("latencyCalibrator.playingTone","Playing test tone and recording…")} (${H+1}/${s})`),$(Math.round(H/s*100));const D=await L();D!==null&&(I.push(Math.max(-500,Math.min(2e3,Math.round(D)))),w([...I])),H<s-1&&await new Promise(V=>setTimeout(V,400))}if($(100),I.length===0){m(g("latencyCalibrator.noSignal","No signal detected — try louder or check the microphone"));return}let Y;if(I.length>=3){const D=[...I].sort((V,Z)=>V-Z).slice(1,-1);Y=Math.round(D.reduce((V,Z)=>V+Z,0)/D.length)}else Y=Math.round(I.reduce((H,D)=>H+D,0)/I.length);v(Y),m(`${g("latencyCalibrator.measured","Measured")} ~${Y} ms (${I.length}: ${I.join(", ")} ms)`)}catch(I){m(`${g("latencyCalibrator.calibrationError","Calibration error: ")}${I instanceof Error?I.message:String(I)}`)}finally{R.current=!1,E(!1)}}},z=async()=>{if(!(x===null||!n)){k(!0);try{await n(Math.round(x)),m(g("latencyCalibrator.saved","Saved"))}catch(I){m(`${g("latencyCalibrator.saveError","Save error: ")}${String(I)}`)}finally{k(!1)}}},j={padding:"7px 16px",border:"none",borderRadius:8,cursor:"pointer",fontWeight:600};return d==="hidden"?null:r.jsxs("div",{className:`nice-latency-calibrator${o?` ${o}`:""}`,style:{padding:12,color:"var(--nice-text, inherit)",...l},id:c,"data-testid":h,children:[r.jsxs("h5",{style:{margin:"0 0 8px",display:"flex",alignItems:"center",gap:6},children:[r.jsx(O.NtdSettings,{size:16})," ",g("latencyCalibrator.title","Latency calibrator — microphone")]}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:[g("latencyCalibrator.device","Device"),": ",r.jsx("small",{children:e||"—"})]}),r.jsxs("div",{style:{marginTop:8,display:"flex",gap:8},children:[r.jsx("button",{type:"button",onClick:A,disabled:M,style:{...j,background:"var(--nice-accent, #3b82f6)",color:"var(--nice-text-on-primary, #fff)"},children:g("latencyCalibrator.calibrate","Calibrate")}),r.jsx("button",{type:"button",onClick:()=>{v(null),m(null),w([]),$(0)},style:{...j,background:"var(--nice-bg-tertiary)",color:"var(--nice-text, #e2e8f0)"},children:g("latencyCalibrator.clear","Clear")})]}),M&&r.jsx("div",{style:{marginTop:8,height:6,borderRadius:3,background:"var(--nice-bg-tertiary)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${N}%`,background:"var(--nice-accent, #3b82f6)",transition:"width 0.2s"}})}),b.length>0&&r.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:[g("latencyCalibrator.rounds","Rounds"),": ",b.join(", ")," ms"]}),r.jsxs("div",{style:{marginTop:8,fontSize:13},children:[r.jsxs("div",{children:[g("latencyCalibrator.status","Status"),": ",y??g("latencyCalibrator.none","none")]}),r.jsxs("div",{children:[g("latencyCalibrator.measuredOffset","Measured offset"),":"," ",x!==null?r.jsxs("strong",{children:[x," ms"]}):"—"]})]}),r.jsxs("div",{style:{marginTop:12,display:"flex",gap:8},children:[n&&r.jsx("button",{type:"button",onClick:z,disabled:x===null||f,style:{...j,background:"var(--nice-success, #22c55e)",color:"var(--nice-text-on-primary, #fff)",opacity:x===null||f?.5:1},children:g("latencyCalibrator.save","Save")}),a&&r.jsx("button",{type:"button",onClick:a,style:{...j,background:"transparent",border:"1px solid var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)"},children:g("latencyCalibrator.close","Close")})]})]})},ip=e=>[{value:"normal",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(O.NtdMicrophone,{size:14})," ",e("karaokeSetup.modeMic","Mic")]})},{value:"pad",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(O.NtdGamepad,{size:14})," ",e("karaokeSetup.modePad","Pad")]})},{value:"demo",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(O.NtdStopwatch,{size:14})," ",e("karaokeSetup.modeDemo","Demo")]})}],dl=({players:e,defaultPlayers:t,onPlayersChange:n,gameMode:a="normal",onGameModeChange:s,gameModes:i,difficulty:o="normal",onDifficultyChange:l,audioInputs:c,maxPlayers:d=4,onCalibrate:h,t:p,className:g,style:y,id:m,accessMode:x,"data-testid":v})=>{const{t:f}=be(),k=p??f,b=u.useMemo(()=>i??ip(k),[i,k]),[w,N]=we.useControllableState({value:e,defaultValue:t,fallbackValue:[],onChange:n,componentName:"NiceKaraokeSetupPanel"}),[$,M]=u.useState([]);u.useEffect(()=>{var Y,H,D;if(c||!((Y=navigator.mediaDevices)!=null&&Y.enumerateDevices))return;let j=!1;const I=()=>navigator.mediaDevices.enumerateDevices().then(V=>!j&&M(V.filter(Z=>Z.kind==="audioinput"))).catch(()=>{});return I(),(D=(H=navigator.mediaDevices).addEventListener)==null||D.call(H,"devicechange",I),()=>{var V,Z;j=!0,(Z=(V=navigator.mediaDevices).removeEventListener)==null||Z.call(V,"devicechange",I)}},[c]);const E=c??$,R=u.useMemo(()=>[{value:"",label:k("karaokeSetup.noMic","No microphone")},...E.map((j,I)=>({value:j.deviceId,label:j.label||`${k("karaokeSetup.microphone","Microphone")} ${I+1}`}))],[E,k]),L=(j,I)=>N(w.map(Y=>Y.id===j?{...Y,...I}:Y)),A=()=>{if(w.length>=d)return;const j=w.reduce((I,Y)=>Math.max(I,Y.id),0)+1;N([...w,{id:j,name:`${k("karaokeSetup.player","Player")} ${w.length+1}`,color:et[w.length%et.length],micId:null}])},z=j=>N(w.filter(I=>I.id!==j));return x==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-setup${g?` ${g}`:""}`,style:{display:"flex",flexDirection:"column",gap:16,...y},id:m,"data-testid":v,children:[r.jsxs("div",{style:{display:"flex",gap:24,flexWrap:"wrap"},children:[r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:12,fontWeight:600,marginBottom:6,color:"var(--nice-text-muted, #94a3b8)"},children:k("karaokeSetup.mode","Game mode")}),r.jsx(ie.NiceSegmentedControl,{options:b,value:a,onChange:j=>s==null?void 0:s(j)})]}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:12,fontWeight:600,marginBottom:6,color:"var(--nice-text-muted, #94a3b8)"},children:k("karaokeSetup.difficulty","Difficulty")}),r.jsx(ie.NiceSegmentedControl,{options:[{value:"easy",label:k("karaokeSetup.easy","Easy")},{value:"normal",label:k("karaokeSetup.normal","Normal")},{value:"hard",label:k("karaokeSetup.hard","Hard")}],value:o,onChange:j=>l==null?void 0:l(j)})]})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[r.jsxs("div",{style:{fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:[k("karaokeSetup.players","Players")," (",w.length,"/",d,")"]}),w.map(j=>r.jsx(ie.NiceCard,{children:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[r.jsx(ie.NiceColorPicker,{value:j.color||et[0],onChange:I=>L(j.id,{color:I})}),r.jsx("div",{style:{flex:"1 1 160px",minWidth:140},children:r.jsx(ie.NiceTextInput,{value:j.name,onChange:I=>L(j.id,{name:I}),placeholder:k("karaokeSetup.playerName","Player name"),size:"sm"})}),r.jsx("div",{style:{flex:"1 1 180px",minWidth:150},children:r.jsx(ie.NiceSelect,{options:R,value:j.micId??"",onChange:I=>L(j.id,{micId:(typeof I=="string"?I:I[0])||null}),placeholder:k("karaokeSetup.selectMic","Microphone"),size:"sm"})}),h&&j.micId&&r.jsxs(ie.NiceButton,{variant:"ghost",size:"sm",onClick:()=>h(j.micId),children:[r.jsx(O.NtdSettings,{size:14})," ",k("karaokeSetup.calibrate","Calibrate")]}),r.jsx(ie.NiceButton,{variant:"danger",size:"sm",onClick:()=>z(j.id),"aria-label":k("karaokeSetup.remove","Remove"),children:r.jsx(O.NtdClose,{size:14})})]})},j.id)),r.jsx("div",{children:r.jsxs(ie.NiceButton,{variant:"primary",onClick:A,disabled:w.length>=d,children:[r.jsx(O.NtdPlus,{size:14})," ",k("karaokeSetup.addPlayer","Add player")]})})]})]})},op=[],lp=["freeForAll","roundRobin","hostOnly","firstCome"],cp={freeForAll:O.NtdDice,roundRobin:O.NtdRepeat,hostOnly:O.NtdCrown,firstCome:O.NtdLightning},dp={freeForAll:"success",roundRobin:"warning",hostOnly:"info",firstCome:"danger"},ul=({players:e=op,mode:t,defaultMode:n,onModeChange:a,turnTimeSec:s=30,hostIndex:i=0,onActivePlayerChange:o,myPlayerIndex:l,t:c,className:d,style:h,id:p,accessMode:g,"data-testid":y})=>{const{t:m}=be(),x=c??m,[v,f]=we.useControllableState({value:t,defaultValue:n,fallbackValue:"freeForAll",onChange:a,componentName:"NiceKaraokeSelectionMode"}),k={freeForAll:x("songSelection.freeForAll","Free for all"),roundRobin:x("songSelection.roundRobin","Round robin"),hostOnly:x("songSelection.hostOnly","Host only"),firstCome:x("songSelection.firstCome","First come")},[b,w]=u.useState(0),[N,$]=u.useState(s),M=u.useRef(null),[E,R]=u.useState(null),[L,A]=u.useState(!1),[z,j]=u.useState(null),I=u.useRef(null),Y=u.useMemo(()=>v==="hostOnly"?i:v==="roundRobin"?b%Math.max(1,e.length):v==="firstCome"?L?-1:z??-1:-1,[v,b,e.length,i,L,z]);u.useEffect(()=>{o==null||o(Y)},[Y,o]),u.useEffect(()=>{if(v!=="roundRobin"||s<=0){M.current&&clearInterval(M.current);return}return $(s),M.current=setInterval(()=>{$(X=>X<=1?(w(q=>q+1),s):X-1)},1e3),()=>{M.current&&clearInterval(M.current)}},[v,s,b]);const H=u.useCallback(()=>{j(null),A(!1),R(3),I.current&&clearInterval(I.current),I.current=setInterval(()=>{R(X=>X===null||X<=1?(I.current&&clearInterval(I.current),A(!0),null):X-1)},1e3)},[]);u.useEffect(()=>()=>{I.current&&clearInterval(I.current)},[]),u.useEffect(()=>{v!=="firstCome"&&(R(null),A(!1),j(null))},[v]);const D=u.useCallback(()=>{w(X=>X+1),$(s)},[s]),V=X=>{var q;return((q=e[X])==null?void 0:q.name)||`${x("songSelection.player","Player")} ${X+1}`},Z=Y>=0&&Y<e.length?e[Y]:null;return g==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-selection-mode${d?` ${d}`:""}`,style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,padding:"8px 12px",background:"var(--nice-bg-secondary)",borderRadius:10,border:"1px solid var(--nice-border, #333)",...h},id:p,"data-testid":y,children:[r.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:lp.map(X=>r.jsxs(ie.NiceButton,{size:"sm",variant:v===X?dp[X]:"outline",onClick:()=>f(X),children:[u.createElement(cp[X],{size:14})," ",k[X]]},X))}),v!=="freeForAll"&&v!=="firstCome"&&Z&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsxs(ie.NiceBadge,{variant:Y===l?"success":"secondary",children:[r.jsx(O.NtdMicrophone,{size:12})," ",V(Y)]}),Y===l&&r.jsx("span",{style:{color:"var(--nice-success, #4caf50)",fontSize:12,fontWeight:600},children:x("songSelection.yourTurn","Your turn!")})]}),v==="roundRobin"&&s>0&&r.jsx("div",{style:{flex:1,minWidth:120,maxWidth:200},children:r.jsx(ie.NiceProgress,{value:N,max:s,variant:N<=5?"error":N<=10?"warning":"info",showValue:!0,formatValue:X=>`${X}s`})}),v==="roundRobin"&&r.jsxs(ie.NiceButton,{size:"sm",variant:"ghost",onClick:D,children:[x("songSelection.next","Next")," ",r.jsx(O.NtdPlay,{size:12})]}),v==="firstCome"&&r.jsxs(r.Fragment,{children:[E!==null&&r.jsx("div",{style:{fontSize:32,fontWeight:900,color:"var(--nice-error, #f44336)",minWidth:60,textAlign:"center"},children:E}),L&&z===null&&r.jsxs(ie.NiceBadge,{variant:"danger",children:[r.jsx(O.NtdLightning,{size:12})," ",x("songSelection.raceGo","GO! Pick a song!")]}),z!==null&&z<e.length&&r.jsxs(ie.NiceBadge,{variant:"success",children:[r.jsx(O.NtdTrophy,{size:12})," ",V(z)," ",x("songSelection.raceWon","picks!")]}),r.jsx(ie.NiceButton,{size:"sm",variant:E!==null?"secondary":"danger",onClick:H,disabled:E!==null,children:z!==null?r.jsxs(r.Fragment,{children:[r.jsx(O.NtdRepeat,{size:12})," ",x("songSelection.raceAgain","New race")]}):r.jsxs(r.Fragment,{children:[r.jsx(O.NtdLightning,{size:12})," ",x("songSelection.raceStart","Start race")]})})]})]})};function up(e,t,n,a){return u.useMemo(()=>e==="freeForAll"?!0:e==="firstCome"?t===-1:e==="hostOnly"?a===n:e==="roundRobin"?a===t:!1,[e,t,n,a])}const hp=({players:e,defaultPlayers:t,onPlayersChange:n,gameMode:a,onGameModeChange:s,gameModes:i,difficulty:o,onDifficultyChange:l,audioInputs:c,maxPlayers:d=4,onCalibrate:h,initialSelectionMode:p="freeForAll",turnTimeSec:g=30,hostIndex:y=0,myPlayerIndex:m,onChange:x,variant:v="bar",t:f,className:k,style:b,id:w,accessMode:N,"data-testid":$})=>{const{t:M}=be(),E=f??M,[R,L]=we.useControllableState({value:e,defaultValue:t,fallbackValue:[],onChange:n,componentName:"NiceKaraokeSessionJoin"}),[A,z]=u.useState([]);u.useEffect(()=>{var K,P,B;if(c||!((K=navigator.mediaDevices)!=null&&K.enumerateDevices))return;let S=!1;const F=()=>navigator.mediaDevices.enumerateDevices().then(_=>!S&&z(_.filter(U=>U.kind==="audioinput"))).catch(()=>{});return F(),(B=(P=navigator.mediaDevices).addEventListener)==null||B.call(P,"devicechange",F),()=>{var _,U;S=!0,(U=(_=navigator.mediaDevices).removeEventListener)==null||U.call(_,"devicechange",F)}},[c]);const j=c??A,I=j.length===0,Y=R.some(S=>!S.micId),H=!Y,[D,V]=u.useState(p),[Z,X]=u.useState(-1),q=u.useCallback((S,F)=>{x==null||x({selectionMode:S,activePickerIndex:F,allMicsAssigned:H,noInputDevices:I})},[x,H,I]),G=u.useCallback(S=>{V(S),q(S,Z)},[q,Z]),C=u.useCallback(S=>{X(S),q(D,S)},[q,D]),T=u.useMemo(()=>({padding:10,borderRadius:8,fontWeight:700,marginTop:8,textAlign:"center"}),[]);return N==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-session-join${k?` ${k}`:""}`,style:v==="card"?{background:"var(--nice-bg-secondary)",borderRadius:12,padding:16,...b}:b,id:w,"data-testid":$,children:[r.jsx(dl,{players:R,onPlayersChange:L,gameMode:a,onGameModeChange:s,gameModes:i,difficulty:o,onDifficultyChange:l,audioInputs:j,maxPlayers:d,onCalibrate:h,t:E}),I&&r.jsxs("div",{style:{...T,background:"var(--nice-error, #ef4444)",color:"#fff"},children:[E("karaokeSessionJoin.noInputDevices","No microphone detected"),r.jsx("br",{}),r.jsx("span",{style:{fontWeight:400,fontSize:13},children:E("karaokeSessionJoin.noInputDevicesHint","Connect a microphone to sing.")})]}),!I&&Y&&r.jsx("div",{style:{...T,background:"var(--nice-warning, #f59e0b)",color:"var(--nice-text-on-primary, #222)",fontSize:14},children:E("karaokeSessionJoin.assignMicWarning","Assign a microphone to each player.")}),R.length>1&&r.jsx("div",{style:{marginTop:12},children:r.jsx(ul,{players:R,mode:D,onModeChange:G,onActivePlayerChange:C,turnTimeSec:g,hostIndex:y,myPlayerIndex:m,t:E})})]})};function Ue(e,t){var s;const n=((s=t.split(".").pop())==null?void 0:s.toLowerCase())??"",a=n==="otf"?"opentype":n==="woff2"?"woff2":n==="woff"?"woff":"truetype";return{family:e,url:`/fonts/${t}`,format:a}}const pp=[Ue("Belagak","BelagakRegular-dr1zE.otf"),Ue("Big Scratch Brush","BigScratchBrush-PVY9g.ttf"),Ue("Gerhaus","Gerhaus-PK69E.ttf"),Ue("Gerhaus Italic","GerhausItalic-d96l7.ttf"),Ue("Handone Medium","HandoneMedium-nAevO.otf"),Ue("Handson Bold","HandsonBold-9MnrL.otf"),Ue("Kineks Round Bold","KineksRoundBold-7OR34.ttf"),Ue("Kineks Round Light","KineksRoundLight-m2r35.ttf"),Ue("Kineks Round Medium","KineksRoundMedium-drejZ.ttf"),Ue("Kineks Round","KineksRoundRegular-PVRl7.ttf"),Ue("Kineks Round SemiBold","KineksRoundSemiBold-LVWG3.ttf"),Ue("Lemon Jelly","LemonJellyPersonalUse-dEqR.ttf"),Ue("Lemon Milk Bold","LemonMilkBold-gx2B3.otf"),Ue("Lemon Milk Bold Italic","LemonMilkBoldItalic-PKZ3P.otf"),Ue("Lemon Milk Light","LemonMilkLight-owxMq.otf"),Ue("Lemon Milk Light Italic","LemonMilkLightItalic-7BjPE.otf"),Ue("Lemon Milk Medium","LemonMilkMedium-mLZYV.otf"),Ue("Lemon Milk Medium Italic","LemonMilkMediumItalic-d95nl.otf"),Ue("Lemon Milk","LemonMilkRegular-X3XE2.otf"),Ue("Lemon Milk Italic","LemonMilkRegularItalic-L3AEy.otf"),Ue("Pemage","PemageRegular-YqrdO.otf"),Ue("Rosmatika","RosmatikaRegular-BWA45.ttf"),Ue("Scabber","Scabber-q2Mn0.ttf"),Ue("Stylish Calligraphy","StylishCalligraphyDemo-XPZZ.ttf"),Ue("Super Adorable","SuperAdorable-MAvyp.ttf"),Ue("Super Chiby","SuperChiby-BL62V.ttf"),Ue("Super Joyful","SuperJoyful-lxwPq.ttf"),Ue("Super Kindly","SuperKindly-drE8E.ttf"),Ue("Super Meatball","SuperMeatball-Yq1Gy.ttf")],Za="nice2dev-karaoke-display",fp=(function(){return[{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"},...pp.map(e=>({value:e.family,label:e.family}))]})(),hl=[{id:"default",name:"Cyan ? Yellow ? Amber",sungGradient:["#00e5ff","#ffe600","#ffab00"],goldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,229,255,0.6)"},{id:"neon-pink",name:"Neon Pink ? Violet ? Blue",sungGradient:["#ff1493","#9b59b6","var(--nice-primary, #3498db)"],goldGradient:["var(--nice-warning, #FFD700)","#FF69B4","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,20,147,0.6)"},{id:"fire",name:"Red ? Orange ? Yellow",sungGradient:["#ff1744","#ff9100","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#FF6D00","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,23,68,0.6)"},{id:"ocean",name:"Deep Blue ? Teal ? Aqua",sungGradient:["#1a237e","#00897b","#00e5ff"],goldGradient:["var(--nice-warning, #FFD700)","#00BCD4","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,137,123,0.6)"},{id:"forest",name:"Green ? Lime ? Yellow",sungGradient:["#1b5e20","#76ff03","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#76ff03","var(--nice-warning, #FFD700)"],glowColor:"rgba(118,255,3,0.6)"},{id:"retro",name:"Orange ? Pink ? Purple",sungGradient:["#ff6d00","var(--nice-color-accent-pink, #e91e63)","#7b1fa2"],goldGradient:["var(--nice-warning, #FFD700)","var(--nice-color-accent-pink, #e91e63)","var(--nice-warning, #FFD700)"],glowColor:"rgba(233,30,99,0.6)"}],gn={presetId:"default",customSungGradient:["#00e5ff","#ffe600","#ffab00"],customGoldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],customGlowColor:"rgba(0,229,255,0.6)",animationMode:"ball",fontFamily:"Arial",transitionEffect:"none",curtainPrimaryColor:"#8b0000",curtainSecondaryColor:"#1a0000",curtainDurationMs:900,immersiveMode:!1};let ei=!1;function pl(){try{const e=localStorage.getItem(Za);if(e){const t=JSON.parse(e);return{...gn,...t}}}catch{}return{...gn}}async function mp(e){if(ei||(ei=!0,!e))return;const t=await e();if(t)try{const n=JSON.parse(t),a={...gn,...n};localStorage.setItem(Za,JSON.stringify(a))}catch{}}function gp(e){const t=JSON.stringify(e);localStorage.setItem(Za,t),Xa(e)}function fl(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=hl.find(n=>n.id===e.presetId);return t?{sungGradient:t.sungGradient,goldGradient:t.goldGradient,glowColor:t.glowColor}:{sungGradient:gn.customSungGradient,goldGradient:gn.customGoldGradient,glowColor:gn.customGlowColor}}function Xa(e){const{sungGradient:t,goldGradient:n,glowColor:a}=fl(e),s=document.documentElement;s.style.setProperty("--karaoke-sung-gradient",`linear-gradient(90deg, ${t[0]} 0%, ${t[1]} 60%, ${t[2]} 100%)`),s.style.setProperty("--karaoke-gold-gradient",`linear-gradient(90deg, ${n[0]}, ${n[1]}, ${n[2]})`),s.style.setProperty("--karaoke-gold-glow-first",`0 0 12px ${n[0]}`),s.style.setProperty("--karaoke-active-glow",`0 0 10px ${a}, 0 0 4px ${t[1]}80`),s.style.setProperty("--karaoke-active-drop-first",`0 0 6px ${a}`),s.style.setProperty("--karaoke-active-bg",`linear-gradient(90deg, transparent 0%, ${t[0]}14 20%, ${t[1]}10 80%, transparent 100%)`),s.style.setProperty("--karaoke-font-family",e.fontFamily||"Arial")}function yp(){const e=pl();Xa(e)}function vp(e){const t=(e||"").split(/\r?\n/),n=[];for(let a=0;a<t.length;a++){const s=t[a].trim();if(s&&/^[:*F]\s/.test(s)){const i=s.slice(1).trim().split(/\s+/),o=parseInt(i[0]||"0",10),l=parseInt(i[1]||"0",10),c=isNaN(o)?0:o/10,d=isNaN(l)?0:l/10;n.push({lineIndex:a,start:c,duration:d,raw:t[a]})}}return n}const bp=({index:e,data:t})=>{const{lines:n,notes:a,currentIndex:s,animationConfig:i}=t,o=n[e]??"",l=a.findIndex(f=>f.lineIndex===e),c=l>=0&&l===s,d=(i==null?void 0:i.enabled)??!0,h=(i==null?void 0:i.durationMs)??300,p=(i==null?void 0:i.translateX)??8,g=(i==null?void 0:i.scale)??1.01,y=(i==null?void 0:i.easing)??"cubic-bezier(.22,1,.36,1)",m=(i==null?void 0:i.opacityInactive)??.9,x=(i==null?void 0:i.boxShadow)??"0 6px 18px var(--nice-primary-tint-8, rgba(3,102,214,0.08))",v={transition:d?`transform ${h}ms ${y}, opacity ${h}ms ${y}`:"none",transform:c?`translateX(${p}px) scale(${g})`:"translateX(0px) scale(1)",opacity:c?1:m,boxShadow:c?x:"none"};return r.jsx("div",{style:{height:"100%",padding:"4px 6px",borderRadius:4},"data-note-idx":l>=0?l:void 0,children:r.jsx("div",{style:{...v,background:c?"var(--nice-primary-tint-12, rgba(0,130,200,0.12))":"transparent",padding:"4px 6px",borderRadius:4},children:r.jsx("code",{style:{fontFamily:"monospace",whiteSpace:"pre-wrap"},children:o})})})},xp=({ultrastarText:e,audioUrl:t,audioRef:n,animationConfig:a})=>{const{t:s}=be(),i=u.useRef(null),o=n??i,[l,c]=u.useState(!1),d=u.useMemo(()=>vp(e),[e]),h=u.useRef(null),p=u.useRef(null),g=u.useRef(0),y=u.useRef(0),[m,x]=u.useState(-1),v=u.useMemo(()=>(e||"").split(/\r?\n/),[e]),f=28,k=v.length*f,b=u.useMemo(()=>({lines:v,notes:d,currentIndex:m,animationConfig:a}),[v,d,m,a]),w=u.useCallback((N,$)=>r.jsx(bp,{index:$,data:b}),[b]);return u.useEffect(()=>{const N=o.current;N&&(l?N.play().catch(()=>c(!1)):N.pause())},[l,o]),u.useEffect(()=>{const N=o.current;if(!N)return;let $=-1;const M=a??null,E=M&&typeof M.scrollSmooth=="number"?M.scrollSmooth:.18;let R=performance.now();const L=()=>{var q,G;const A=performance.now(),z=Math.max(0,Math.min(.2,(A-R)/1e3));R=A;const j=N.currentTime||0;g.current=j;let I=-1;for(let C=0;C<d.length;C++){const T=d[C];if(j>=T.start&&j<T.start+Math.max(.001,T.duration)){I=C;break}}I!==$&&($=I,x(I));let Y=0;if($>=0){const C=((q=d[$])==null?void 0:q.lineIndex)??0,T=((G=h.current)==null?void 0:G.clientHeight)??220;Y=C*f-T/2+f/2;const S=Math.max(0,k-T);(isNaN(Y)||!isFinite(Y))&&(Y=0),Y=Math.max(0,Math.min(Y,S))}const H=1-Math.pow(Math.max(0,1-E),Math.min(4,z*60)),X=(((a==null?void 0:a.scrollEasing)||"easeOutCubic")==="linear"?C=>C:C=>1-Math.pow(1-C,3))(H);y.current=y.current+(Y-y.current)*X;try{const C=h.current;C&&typeof C.scrollTop=="number"&&(C.scrollTop=Math.round(y.current))}catch{}p.current=requestAnimationFrame(L)};return p.current=requestAnimationFrame(L),()=>{p.current&&cancelAnimationFrame(p.current)}},[o,d,k,a]),r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[r.jsx("button",{onClick:()=>c(N=>!N),disabled:!t,children:l?"Pause":"Play"}),r.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-secondary, #666)"},children:[(g.current||0).toFixed(2),"s"]}),r.jsxs("div",{style:{marginLeft:"auto",fontSize:13,color:"var(--nice-text-secondary, #666)"},children:["Notes: ",d.length]})]}),r.jsx("div",{style:{border:"1px solid var(--nice-border, #ddd)",height:220,overflow:"hidden",padding:8,position:"relative"},children:e?r.jsx(ie.NiceVirtualScroller,{ref:h,items:v,itemHeight:f,height:220,renderItem:w,style:{border:"none",borderRadius:0,background:"transparent",fontSize:"inherit"}}):r.jsx("div",{style:{color:"var(--nice-text-secondary, #888)"},children:s("karaokeEditor.noText","No text")})}),!n&&r.jsx("audio",{ref:i,src:t||void 0,preload:"metadata",style:{display:"none"}})]})};function Sp(e){const t=(e||"").split(/\r?\n/).map(a=>a.replace(/\s+$/,"")),n=[];for(let a=0;a<t.length;a++){const s=t[a].trim();if(/^[:*F]\s/.test(s)){const i=s.slice(1).trim().split(/\s+/),o=parseInt(i[0]||"0",10)/10||0,l=parseInt(i[1]||"0",10)/10||.1;n.push({lineIndex:a,start:o,duration:l})}}return{lines:t,notes:n}}const kp=new Set;function wp({ultrastarText:e,audioUrl:t,audioRef:n,ytRef:a}){const{lines:s,notes:i}=u.useMemo(()=>Sp(e),[e]),[o,l]=u.useState(kp),c=u.useRef(i);c.current=i;const d=u.useRef(t);return d.current=t,u.useEffect(()=>{let h=null,p=null;if(!(a!=null&&a.current))if(n!=null&&n.current)h=n.current;else{const x=document.querySelector("audio");x instanceof HTMLAudioElement?h=x:d.current&&(p=document.createElement("audio"),p.src=d.current,p.preload="metadata",p.style.display="none",document.body.appendChild(p),h=p)}let g=0,y="";const m=()=>{let x=0;const v=a==null?void 0:a.current;if(v&&typeof v.getCurrentTime=="function")try{x=v.getCurrentTime()||0}catch{x=0}else x=h&&h.currentTime||0;const f=new Set;for(const b of c.current)x>=b.start&&x<b.start+Math.max(.001,b.duration)&&f.add(b.lineIndex);const k=[...f].join(",");k!==y&&(y=k,l(f)),g=requestAnimationFrame(m)};return g=requestAnimationFrame(m),()=>{cancelAnimationFrame(g),p==null||p.remove()}},[]),r.jsx("div",{style:{width:"100%",height:340,overflow:"hidden",background:"#101010",padding:"20px 0",boxSizing:"border-box"},children:s.map((h,p)=>{const g=o.has(p);return r.jsx("div",{"aria-current":g||void 0,style:{font:"18px monospace",lineHeight:"22px",whiteSpace:"pre",padding:"0 10px",color:g?"var(--nice-info, #00aaff)":"var(--nice-overlay-light-90, #e2e8f0)",background:g?"color-mix(in srgb, var(--nice-info, #00aaff) 16%, transparent)":void 0},children:h||" "},p)})})}const Cp=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),ti=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")}`},ea={border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},jp=({isPlaying:e,index:t,count:n,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek:d,onVolume:h})=>{const{t:p}=be();return r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[r.jsx("div",{}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-secondary)"},children:[ti(a)," / ",ti(s)]})]}),r.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("button",{onClick:o,disabled:t<=0,title:p("playerControls.prev","Prev"),"aria-label":p("playerControls.previousTrack","Previous track"),style:ea,children:r.jsx(O.NtdSkipBack,{size:16})}),r.jsx("button",{onClick:c,title:e?p("playerControls.pause","Pause"):p("playerControls.play","Play"),"aria-label":e?p("playerControls.pause","Pause"):p("playerControls.play","Play"),style:ea,children:e?r.jsx(O.NtdPause,{size:16}):r.jsx(O.NtdPlay,{size:16})}),r.jsx("button",{onClick:l,disabled:t>=n-1,title:p("playerControls.next","Next"),"aria-label":p("playerControls.nextTrack","Next track"),style:ea,children:r.jsx(O.NtdSkipForward,{size:16})})]}),r.jsx("input",{type:"range",min:0,max:Math.max(1,s),step:.1,value:a,"aria-label":p("playerControls.seekPosition","Seek position"),onChange:g=>d(parseFloat(g.target.value))}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx(O.NtdVolume,{size:16}),r.jsx("input",{type:"range",min:0,max:1,step:.01,value:i,"aria-label":p("playerControls.volume","Volume"),onChange:g=>h(parseFloat(g.target.value))})]})]})]})},Mp=u.memo(jp);function Rp(e,t,n,a,s){const o=Math.max(1,Math.floor(a.length/48)),l=t/48;for(let c=0;c<48;c++){const d=a[c*o]/255,h=d*(n-6),p=c*l,g=n-h,y=c/48*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(p+1,g,l-2,h)}}function Np(e,t,n,a,s,i){if(!i.current){const p=[];for(let y=0;y<24;y++)p.push({ang:y/24*Math.PI*2,phase:Math.random()*Math.PI*2,baseR:Math.min(t,n)*.22+Math.random()*30});i.current={nodes:p}}const o=i.current,l=t/2,c=n/2,d=26+a*80,h=[];for(const p of o.nodes){p.phase+=.02+a*.06;const g=p.baseR+Math.sin(p.phase)*d,y=l+Math.cos(p.ang)*g,m=c+Math.sin(p.ang)*g;h.push([y,m])}e.fillStyle=`hsla(${s}, 70%, 55%, .22)`,e.strokeStyle=`hsla(${(s+40)%360}, 90%, 65%, .9)`,e.lineWidth=2,e.beginPath();for(let p=0;p<h.length;p++){const[g,y]=h[p],[m,x]=h[(p+1)%h.length],v=(g+m)/2,f=(y+x)/2;p===0?e.moveTo(v,f):e.quadraticCurveTo(g,y,v,f)}e.closePath(),e.fill(),e.stroke()}function Tp(e,t,n,a,s,i){i.current||(i.current={items:[]});const o=i.current;Math.random()<.06+a*.25&&o.items.push({x:Math.random()*t,y:Math.random()*n,r:8+Math.random()*24,life:1,hue:(s+Math.random()*120)%360});const l=[];for(const c of o.items){c.r+=2+a*14,c.life*=.975-a*.02,c.life>.04&&l.push(c);const d=e.createRadialGradient(c.x,c.y,1,c.x,c.y,c.r);d.addColorStop(0,`hsla(${c.hue}, 90%, 60%, ${.35*c.life})`),d.addColorStop(.6,`hsla(${(c.hue+40)%360}, 80%, 55%, ${.18*c.life})`),d.addColorStop(1,`hsla(${(c.hue+80)%360}, 70%, 50%, 0)`),e.fillStyle=d,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}o.items=l}const Pp="var(--nice-text-muted, #94a3b8)",$p=({height:e,coverUrl:t,title:n,subtitle:a,label:s})=>r.jsx("div",{style:{textAlign:"center",color:"var(--nice-text-secondary, #e2e8f0)"},children:t?r.jsx("img",{alt:"cover",src:t,style:{height:e-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsx("div",{style:{fontSize:18,fontWeight:600},children:n??"—"}),r.jsx("div",{style:{marginTop:8,fontSize:12,color:Pp},children:s??a??"—"})]})});function tn(e,t){return e+Math.random()*(t-e)}function Ep(e,t,n,a,s,i,o){o.current||(o.current={embers:[],t:0});const l=o.current,c=e.createLinearGradient(0,n,0,n*.4);c.addColorStop(0,`hsla(${(i+30)%360}, 90%, 50%, .35)`),c.addColorStop(1,`hsla(${(i+10)%360}, 90%, 50%, 0)`),e.fillStyle=c,e.fillRect(0,0,t,n);const d=6;for(let p=0;p<d;p++){const g=(p+.5)/d*t,y=(a[Math.floor((p+1)/(d+1)*a.length)]||0)/255,m=n*.18+(.25+s*.6+y*.7)*n*.55,x=e.createLinearGradient(g,n,g,n-m);x.addColorStop(0,`hsla(${(i+40)%360},100%,55%,.9)`),x.addColorStop(.5,`hsla(${(i+10)%360},100%,60%,.75)`),x.addColorStop(1,`hsla(${(i-20)%360},100%,80%,.05)`);const v=Math.sin(l.t*1.2+p*.8)*(15+s*30);e.fillStyle=x,e.beginPath(),e.moveTo(g-20,n),e.bezierCurveTo(g-35,n-m*.45,g-25+v,n-m*.75,g+v,n-m),e.bezierCurveTo(g+25+v*.3,n-m*.65,g+35,n-m*.35,g+20,n),e.closePath(),e.fill()}const h=Math.floor(1+s*6);for(let p=0;p<h;p++)l.embers.push({x:tn(t*.25,t*.75),y:n-tn(4,14),r:tn(1,3),vx:tn(-.15,.15),vy:-tn(.6,1.8)-s*1.2,life:tn(.8,1.6)});e.save(),e.globalCompositeOperation="lighter";for(let p=l.embers.length-1;p>=0;p--){const g=l.embers[p];if(g.x+=g.vx,g.y+=g.vy,g.vy-=.01,g.life-=.015+s*.02,g.life<=0||g.y<-10){l.embers.splice(p,1);continue}const y=e.createRadialGradient(g.x,g.y,0,g.x,g.y,g.r*3);y.addColorStop(0,`hsla(${(i+25)%360},100%,65%,.9)`),y.addColorStop(1,`hsla(${(i+25)%360},100%,65%,0)`),e.fillStyle=y,e.beginPath(),e.arc(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+s*.08}function Ap(e,t,n,a,s){const i=t/2,o=n/2,l=Math.min(t,n)*.28,c=96,d=Math.max(1,Math.floor(a.length/c));for(let h=0;h<c;h++){const p=(a[h*d]??0)/255,g=h/c*Math.PI*2,y=p*(Math.min(t,n)*.22)+6,m=i+Math.cos(g)*l,x=o+Math.sin(g)*l,v=i+Math.cos(g)*(l+y),f=o+Math.sin(g)*(l+y);e.strokeStyle=`hsl(${(s+h*3)%360}, 90%, ${40+p*40}%)`,e.lineWidth=3,e.beginPath(),e.moveTo(m,x),e.lineTo(v,f),e.stroke()}e.fillStyle=`hsla(${(s+180)%360}, 60%, 15%, .4)`,e.beginPath(),e.arc(i,o,l-8,0,Math.PI*2),e.fill()}function Ip(e,t,n,a,s){const l=t/14,c=n/8;for(let d=0;d<8;d++)for(let h=0;h<14;h++){const p=Math.min(a.length-1,d*14+h),g=a[p]/255,y=(s+h/14*210+d/8*90)%360,m=65+g*30,x=20+g*40,v=(1-g)*4;e.fillStyle=`hsl(${y}, ${m}%, ${x}%)`,e.fillRect(h*l+v,d*c+v,Math.max(1,l-2*v),Math.max(1,c-2*v))}}function Lp(e){const n=Array.from(new Set(e.filter(Boolean))).map(a=>new Promise(s=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>s(i),i.onerror=()=>s(i),i.src=a}));return Promise.all(n)}async function _p(e,t,n,a,s){e.current||(e.current={sprites:[],loadedUrls:[],ready:!1});const i=e.current,o=t.join("|")!==i.loadedUrls.join("|");if(!i.ready||o){const l=await Lp(t.length?t:[]);i.loadedUrls=t,i.sprites=[],i.ready=!0;const c=d=>l[d%Math.max(1,l.length)]??new Image;for(let d=0;d<n;d++){const h=Math.random()*Math.min(a,s)*.38+40;i.sprites.push({img:c(d),x:(Math.random()-.5)*h*.4,y:(Math.random()-.5)*h*.4,z:Math.random()*600+100,ang:Math.random()*Math.PI*2,spin:(Math.random()*.03+.01)*(Math.random()<.5?-1:1),vz:Math.random()*1.2+.2,size:Math.random()*.35+.65})}}}function zp(e,t,n,a,s,i,o,l){const c=i.current;if(!(c!=null&&c.ready))return;const d=t/2,h=n/2,p=900,g=1+a*2;for(const m of c.sprites){m.ang+=m.spin*g,m.z-=m.vz*(.8+a*2.4),m.z<40&&(m.z=p);const x=Math.min(t,n)*.32+Math.sin(m.ang*.8)*18;m.x=Math.cos(m.ang)*x,m.y=Math.sin(m.ang*1.1)*x*.6}const y=[...c.sprites].sort((m,x)=>x.z-m.z);for(const m of y){const x=p/(p-m.z)*.6*m.size,v=d+m.x*x,f=h+m.y*x,k=64*x,b=64*x;e.save(),e.globalAlpha=.12+(1-m.z/p)*.2,e.fillStyle=`hsl(${(s+(1-m.z/p)*60)%360}, 90%, 60%)`,e.beginPath(),e.ellipse(v,f,k*.7,b*.7,0,0,Math.PI*2),e.fill(),e.restore(),m.img&&m.img.width?e.drawImage(m.img,v-k/2,f-b/2,k,b):(e.save(),e.fillStyle=`hsl(${(s+180)%360}, 40%, 55%)`,e.fillRect(v-k/2,f-b/2,k,b),e.restore())}}function wn(e,t){return e+Math.random()*(t-e)}function Dp(e,t,n,a,s,i){i.current||(i.current={blobs:Array.from({length:7},(d,h)=>({x:wn(t*.2,t*.8),y:wn(n*.2,n*.8),r:wn(Math.min(t,n)*.05,Math.min(t,n)*.12),vx:wn(-.6,.6),vy:wn(-.6,.6),hue:(s+h*10)%360}))});const o=i.current,l=.6+a*2.2;e.save(),e.globalCompositeOperation="lighter";for(const c of o.blobs){c.x+=c.vx*l,c.y+=c.vy*l,c.vy-=.01-a*.015,c.x<c.r&&(c.x=c.r,c.vx=Math.abs(c.vx)),c.x>t-c.r&&(c.x=t-c.r,c.vx=-Math.abs(c.vx)),c.y<c.r&&(c.y=c.r,c.vy=Math.abs(c.vy)),c.y>n-c.r&&(c.y=n-c.r,c.vy=-Math.abs(c.vy));const d=(c.hue+a*120)%360,h=e.createRadialGradient(c.x,c.y,c.r*.2,c.x,c.y,c.r);h.addColorStop(0,`hsla(${d}, 95%, 70%, .8)`),h.addColorStop(1,`hsla(${(d+40)%360}, 90%, 30%, 0)`),e.fillStyle=h,e.shadowBlur=18,e.shadowColor=`hsl(${d}, 100%, 60%)`,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}e.restore(),e.strokeStyle=we.resolveCssColor("var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",e.canvas),e.lineWidth=2,e.strokeRect(1,1,t-2,n-2)}function Fp(e,t,n,a,s,i){i.current||(i.current={tris:[]});const o=i.current,l=6;for(;o.tris.length<l;)o.tris.push({a:Math.random()*Math.PI*2,r:30+Math.random()*Math.min(t,n)*.35,dr:(Math.random()*.6+.2)*(Math.random()<.5?-1:1)});const c=t/2,d=n/2;for(const h of o.tris){h.a+=.002+a*.02*(h.dr>0?1:-1),h.r+=Math.sin(h.a*2)*(.3+a*1.4);const p=Math.max(40,Math.min(h.r,Math.min(t,n)*.48));e.save(),e.translate(c,d),e.rotate(h.a),e.strokeStyle=`hsla(${(s+p*.2)%360}, 90%, 60%, .9)`,e.lineWidth=2.5,e.beginPath(),e.moveTo(p,0);for(let g=1;g<3;g++){const y=g*Math.PI*2/3;e.lineTo(Math.cos(y)*p,Math.sin(y)*p)}e.closePath(),e.shadowBlur=12,e.shadowColor=e.strokeStyle,e.stroke(),e.restore()}}function Op(e,t,n,a,s,i){const o=t/2,l=n/2,c=5,d=Math.min(t,n)*.42;i.current+=.01;for(let h=0;h<c;h++){const p=(h+1)/(c+1),g=p*d;e.strokeStyle=`hsla(${(s+h*30)%360}, 70%, 45%, 0.35)`,e.lineWidth=1,e.beginPath(),e.arc(o,l,g,0,Math.PI*2),e.stroke();const y=Math.floor(a.length*p|0),m=(a[y]??0)/255,x=6+h*2;for(let v=0;v<x;v++){const f=i.current*(1+h*.15)+v/x*Math.PI*2,k=g+Math.sin(f*2)*6*m,b=o+Math.cos(f)*k,w=l+Math.sin(f)*k;e.fillStyle=`hsla(${(s+h*30+v*6)%360}, 90%, ${55+m*30}%, ${.6+m*.3})`,e.beginPath(),e.arc(b,w,2+m*4,0,Math.PI*2),e.fill()}}}function Bp(e,t,n,a,s){const l=t/12,c=n/6;for(let d=0;d<6;d++)for(let h=0;h<12;h++){const p=(d*12+h)%a.length,g=a[p]/255,y=(s+h/12*180+d/6*90)%360,m=70+g*25,x=25+g*35;e.fillStyle=`hsl(${y}, ${m}%, ${x}%)`,e.fillRect(h*l,d*c,Math.ceil(l),Math.ceil(c))}}function Gp(e,t,n,a,s,i){const o=t/2,l=n/2,c=2+Math.floor(a*14);for(let h=0;h<c;h++){const p=Math.random()*Math.PI*2,g=.5+Math.random()*(2.5+a*4);i.current.push({x:o,y:l,vx:Math.cos(p)*g,vy:Math.sin(p)*g,life:0,max:40+Math.random()*60,hue:(s+Math.random()*60)%360})}e.fillStyle="rgba(2,6,23,0.2)",e.fillRect(0,0,t,n);const d=i.current;for(let h=d.length-1;h>=0;h--){const p=d[h];p.x+=p.vx,p.y+=p.vy,p.life+=1;const g=1-p.life/p.max;e.fillStyle=`hsla(${p.hue},85%,60%,${Math.max(0,g)})`,e.beginPath(),e.arc(p.x,p.y,2+g*3,0,Math.PI*2),e.fill(),(p.life>=p.max||p.x<-20||p.y<-20||p.x>t+20||p.y>n+20)&&d.splice(h,1)}d.length>1200&&d.splice(0,d.length-1200)}function Wp(e,t,n,a,s,i){e.fillStyle="rgba(10,16,28,0.25)",e.fillRect(0,0,t,n);const o=t/2,l=n/2,c=Math.min(t,n)*(.38+s*.12),d=e.createRadialGradient(o,l,c*.1,o,l,c);d.addColorStop(0,`hsla(${(i+200)%360},90%,70%,0.95)`),d.addColorStop(.5,`hsla(${(i+260)%360},80%,55%,0.6)`),d.addColorStop(1,"transparent"),e.fillStyle=d,e.beginPath(),e.arc(o,l,c,0,Math.PI*2),e.fill();const h=18+Math.floor(s*50);for(let p=0;p<h;p++){const g=p/h*Math.PI*2+a*(.6+s*1.4),y=(Math.sin(a*2+p*1.7)+Math.cos(a*1.3+p*2.1))*.15,m=c*(.4+.55*Math.abs(Math.sin(a*1.2+p))),x=6;e.save(),e.translate(o,l),e.rotate(g+y),e.beginPath(),e.moveTo(0,0);for(let f=1;f<=x;f++){const k=m/x*f,b=(Math.sin(a*3+p*.8+f)*.6+Math.cos(a*2+p+f*.7))*(8+24*s),w=k,N=b;e.lineTo(N,w)}e.globalCompositeOperation="lighter";const v=(i+p*(240/h))%360;e.strokeStyle=`hsla(${v}, 90%, ${60+s*20}%, ${.35+s*.4})`,e.lineWidth=2+s*2,e.stroke(),e.restore()}e.beginPath(),e.arc(o,l,c*(.98+.02*Math.sin(a*2)),0,Math.PI*2),e.strokeStyle=`hsla(${(i+40)%360},90%,70%,${.25+s*.25})`,e.lineWidth=1.5,e.stroke(),e.globalCompositeOperation="source-over"}function Vp(e,t,n,a,s){const o=Math.max(1,Math.floor(a.length/96)),l=t/2,c=n/2,d=Math.min(t,n)*.22,h=Math.min(t,n)*.48;for(let p=0;p<96;p++){const g=a[p*o]/255,y=p/96*Math.PI*2,m=d,x=d+g*(h-d),v=l+Math.cos(y)*m,f=c+Math.sin(y)*m,k=l+Math.cos(y)*x,b=c+Math.sin(y)*x;e.strokeStyle=`hsl(${p/96*360+s},85%,60%)`,e.lineWidth=3,e.beginPath(),e.moveTo(v,f),e.lineTo(k,b),e.stroke()}e.fillStyle=we.resolveCssColor("var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.canvas),e.beginPath(),e.arc(l,c,d*.85,0,Math.PI*2),e.fill()}function Up(e,t,n,a,s,i){const o=t/2,l=n/2,c=Math.min(t,n)*.5,d=ni(a,0,Math.floor(a.length*.1))/255,h=ni(a,Math.floor(a.length*.6),a.length)/255;i.current+=.01+h*.03;const p=24;for(let g=0;g<p;g++){const y=i.current+g/p*Math.PI*2,m=(.35+d*.55)*c,x=o+Math.cos(y)*m,v=l+Math.sin(y)*m,f=e.createRadialGradient(o,l,0,o,l,m),k=g/p*360+s;f.addColorStop(0,`hsla(${k},85%,65%,0.0)`),f.addColorStop(1,`hsla(${k},85%,65%,0.9)`),e.strokeStyle=f,e.lineWidth=6+h*8,e.beginPath(),e.moveTo(o,l),e.lineTo(x,v),e.stroke()}e.fillStyle="rgba(2,6,23,0.25)",e.fillRect(0,0,t,n)}function ni(e,t,n){let a=0,s=0;for(let i=t;i<n;i++)a+=e[i],s++;return s?a/s:0}function qp(e,t,n,a,s,i){e.fillStyle="rgba(10,16,28,0.35)",e.fillRect(0,0,t,n);const o=n/2,l=Math.max(8,18-s*10),c=n*.35*(.6+s*.7),d=a.length,h=t/(d-1);e.beginPath();for(let y=0;y<d;y++){const m=(a[y]-128)/128,x=Math.sin(i*1.5+y*.03)*.12,v=y*h,f=o-l-(m+x)*c;y===0?e.moveTo(v,f):e.lineTo(v,f)}const p=e.createLinearGradient(0,0,0,o-l);p.addColorStop(0,"hsla(260,90%,75%,0.9)"),p.addColorStop(1,"hsla(220,85%,60%,0.4)"),e.strokeStyle=p,e.lineWidth=2,e.stroke(),e.beginPath();for(let y=0;y<d;y++){const m=(a[y]-128)/128,x=Math.cos(i*1.3+y*.035)*.12,v=y*h,f=o+l+(m+x)*c;y===0?e.moveTo(v,f):e.lineTo(v,f)}const g=e.createLinearGradient(0,o+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=we.resolveCssColor("var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.canvas),e.lineWidth=6,e.beginPath(),e.moveTo(0,o-l),e.lineTo(t,o-l),e.stroke(),e.beginPath(),e.moveTo(0,o+l),e.lineTo(t,o+l),e.stroke(),e.globalCompositeOperation="source-over"}function Hp(e,t,n,a,s,i){const o=t/2,l=n/2,c=5,d=Math.min(t,n)*.12;for(let h=0;h<c;h++){const p=Math.floor(h/c*a.length),g=a[p]/255,y=d+h*d*.55+g*d*.5,m=(i+h*40)%360;e.lineWidth=3+g*6,e.strokeStyle=`hsla(${m},80%,60%,${.5+.5*s})`,e.beginPath(),e.arc(o,l,y,0,Math.PI*2),e.stroke()}}function Kp(e,t,n,a,s){const i=Math.min(a.length,256),o=Math.max(1,Math.floor(a.length/i)),l=t/i;for(let c=0;c<i;c++){const d=a[c*o]/255,h=d*(n-6),p=c*l,g=n-h,y=c/i*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(p+1,g,l-2,h)}}function Yp(e,t,n,a){e.current||(e.current={stars:[],ready:!1});const s=e.current;if(!s.ready||s.stars.length!==t){const i=[];for(let o=0;o<t;o++){const l={x:(Math.random()-.5)*n,y:(Math.random()-.5)*a,z:Math.random()*800+100,pz:0};i.push(l)}s.stars=i,s.ready=!0}}function Zp(e,t,n,a,s,i){const o=i.current,l=t/2,c=n/2,d=4+a*18;e.save(),e.translate(l,c);for(const h of o.stars){h.z-=d,h.z<20&&(h.x=(Math.random()-.5)*t,h.y=(Math.random()-.5)*n,h.z=900,h.pz=h.z);const p=h.x/h.z*600,g=h.y/h.z*600,y=h.x/h.pz*600,m=h.y/h.pz*600;h.pz=h.z,e.strokeStyle=`hsla(${(s+200)%360}, 90%, 70%, 0.7)`,e.lineWidth=Math.max(1,(1-h.z/900)*2),e.beginPath(),e.moveTo(y,m),e.lineTo(p,g),e.stroke()}e.restore()}function Xp(e,t,n,a){e.lineWidth=2,e.strokeStyle=we.resolveCssColor("var(--nice-primary-light, #c7d2fe)",e.canvas),e.beginPath();const s=t/a.length;for(let i=0;i<a.length;i++){const o=(a[i]-128)/128,l=i*s,c=n/2+o*(n*.45);i===0?e.moveTo(l,c):e.lineTo(l,c)}e.stroke()}const Qp=({active:e,onClick:t,title:n,children:a})=>r.jsx("button",{type:"button",onClick:t,title:n,"aria-pressed":e,style:{padding:"4px 8px",borderRadius:6,fontSize:12,border:`1px solid ${e?"var(--nice-info, #6366f1)":"var(--nice-border-color, #334155)"}`,background:e?"var(--nice-accent-tint-12, rgba(99,102,241,.12))":"var(--nice-overlay-60, rgba(15,23,42,.6))",color:e?"var(--nice-color-white, #e2e8f0)":"var(--nice-color-white, #cbd5e1)",cursor:"pointer",whiteSpace:"nowrap",lineHeight:1.2},children:a}),ml=({modes:e=[],active:t,setActive:n,rows:a=2})=>{const{t:s}=be(),i=Math.max(1,a);return!e||e.length===0?null:r.jsx("div",{style:{position:"absolute",top:10,right:10,pointerEvents:"auto",zIndex:9999},children:r.jsx("div",{style:{display:"grid",gridAutoFlow:"column",gridTemplateRows:`repeat(${i}, auto)`,gridAutoColumns:"max-content",gap:6,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:6,borderRadius:10,border:"1px solid var(--nice-border-color, #334155)",backdropFilter:"blur(2px)",justifyItems:"end",alignItems:"start"},children:e.map(o=>r.jsx(Qp,{active:t===o,onClick:()=>n(o),title:`${s("visualizer.mode","Mode")}: ${o}`,children:o},o))})})};function Jp(e,t){const[n,a]=u.useState(()=>{try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}});return u.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(n))}catch{}},[e,n]),[n,a]}const ef=({vu:e,hide:t})=>{if(t)return null;const n=12,a=Math.round(e*n);return r.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px 8px",borderRadius:8,border:"1px solid var(--nice-border-color, #334155)",backdropFilter:"blur(2px)",pointerEvents:"none",zIndex:9998},children:Array.from({length:n}).map((s,i)=>{const o=120*(i/n);return r.jsx("div",{style:{width:6,height:18,borderRadius:2,background:i<a?`hsl(${o}, 80%, 50%)`:"var(--nice-text, #1f2937)"}},i)})})},tf="var(--player-bg, #0f172a)";function nf(e,t){const n=e.length;for(let a=0;a<n;a++){const s=a/n,i=.55*Math.exp(-Math.pow((s-(.12+.08*Math.sin(t*.7)))*7,2))+.45*Math.exp(-Math.pow((s-(.4+.15*Math.sin(t*1.1+1)))*9,2))+.3*(1-s)*(.55+.45*Math.sin(t*2+a*.06));e[a]=Math.max(0,Math.min(255,Math.floor(i*255)))}}function rf(e,t){const n=e.length;for(let a=0;a<n;a++){const s=a/n*Math.PI*2,i=Math.sin(s*3+t*3)*.5+Math.sin(s*7+t*2)*.28;e[a]=Math.max(0,Math.min(255,Math.floor(128+i*110)))}}const gl=({kind:e,audioRef:t,width:n="100%",height:a=360,coverUrl:s,title:i,subtitle:o,label:l,defaultMode:c="cover",storageKey:d="gp-stage:mode",allowedModes:h,imageUrls:p,imageCount:g=14,autoAnimate:y=!1})=>{const{t:m}=be(),x=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]),v=u.useMemo(()=>{const G=x.includes(c)?c:x[0];try{const C=localStorage.getItem(d);if(!C)return G;const T=JSON.parse(C);return x.includes(T)?T:G}catch{return G}},[x,c,d]),[f,k]=Jp(d,v),b=u.useRef(null),w=u.useRef(null),N=u.useRef(null),$=u.useRef(null),M=u.useRef(null),E=u.useRef(null),R=u.useRef(0),L=u.useRef(0),A=u.useRef([]),[z,j]=u.useState(0),I=u.useRef(null),Y=u.useRef(null),H=u.useRef(null),D=u.useRef(null),V=u.useRef(null),Z=u.useRef(null),X=u.useRef(null),q=f!=="cover"&&f!=="video";return u.useEffect(()=>{var P;if(e==="youtube"||(w.current&&(cancelAnimationFrame(w.current),w.current=null),!q))return;Yt();const G=qn(),C=t.current;if(!C&&!y)return;if(C&&!N.current)try{N.current=G.createMediaElementSource(C)}catch{}if(C&&!$.current){const B=G.createAnalyser();B.fftSize=2048,B.smoothingTimeConstant=.85,$.current=B;try{(P=N.current)==null||P.connect(B)}catch{}try{B.connect(G.destination)}catch{}}const T=$.current;M.current=new Uint8Array(T?T.frequencyBinCount:1024),E.current=new Uint8Array(T?T.fftSize:2048);const S=()=>{const B=b.current,_=Math.max(1,Math.floor(window.devicePixelRatio||1));B.width=Math.floor(B.clientWidth*_),B.height=Math.floor(B.clientHeight*_);const U=B.getContext("2d");U==null||U.setTransform(1,0,0,1,0,0),U==null||U.scale(_,_)};S();const F=()=>S();window.addEventListener("resize",F),Yp(H,220,b.current.width,b.current.height);const K=async()=>{const B=b.current;if(!B)return;const _=B.getContext("2d");if(!_)return;const U=Math.max(1,Math.floor(window.devicePixelRatio||1)),J=B.width/U,se=B.height/U,oe=performance.now()*.001,re=f==="waveform"||f==="rift";T&&(re?T.getByteTimeDomainData(E.current):T.getByteFrequencyData(M.current)),y&&(nf(M.current,oe),rf(E.current,oe));let W=0;const ee=re?E.current:M.current;for(let ae=0;ae<ee.length;ae++){const le=re?(ee[ae]-128)/128:ee[ae]/255;W+=le*le}if(W=Math.sqrt(W/ee.length),j(Math.min(1,W)),_.clearRect(0,0,J,se),f==="spectrum")Kp(_,J,se,M.current,R.current);else if(f==="bars")Rp(_,J,se,M.current,R.current);else if(f==="waveform")Xp(_,J,se,E.current);else if(f==="palette"){const ae=(R.current+W*120)%360;Bp(_,J,se,M.current,ae)}else if(f==="radial")Vp(_,J,se,M.current,R.current);else if(f==="rays")Up(_,J,se,M.current,R.current,L);else if(f==="particles")Gp(_,J,se,W,R.current,A);else if(f==="rings")Hp(_,J,se,M.current,W,R.current);else if(f==="grid"){const ae=(R.current+W*160)%360;Ip(_,J,se,M.current,ae)}else if(f==="imageTornado"){const ae=p!=null&&p.length?p:s?[s]:[];await _p(I,ae,g,J,se);const le=(R.current+W*100)%360;zp(_,J,se,W,le,I)}else if(f==="colorRipples"){const ae=(R.current+W*120)%360;Tp(_,J,se,W,ae,Y)}else if(f==="starfield"){const ae=(R.current+60)%360;Zp(_,J,se,W,ae,H)}else if(f==="orbitals"){const ae=(R.current+W*180)%360;Op(_,J,se,M.current,ae,L)}else if(f==="eqcircle"){const ae=(R.current+120)%360;Ap(_,J,se,M.current,ae)}else if(f==="triangles"){const ae=(R.current+40)%360;Fp(_,J,se,W,ae,D)}else if(f==="blob"){const ae=(R.current+90)%360;Np(_,J,se,W,ae,V)}else if(f==="plasma"){const ae=(R.current+W*200)%360;Wp(_,J,se,oe,W,ae)}else if(f==="rift")qp(_,J,se,E.current,W,oe);else if(f==="lavaLamp"){const ae=(R.current+W*80)%360;Dp(_,J,se,W,ae,Z)}else if(f==="cozyFire"){const ae=(R.current+W*140)%360;Ep(_,J,se,M.current,W,ae,X)}R.current=(R.current+.4)%360,w.current=requestAnimationFrame(K)};return w.current=requestAnimationFrame(K),()=>{window.removeEventListener("resize",F),w.current&&cancelAnimationFrame(w.current)}},[q,e,t,f,p,g,s,y]),r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none",background:f==="cover"?"transparent":tf},children:f==="cover"?r.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:r.jsx($p,{height:a,coverUrl:s,title:i,subtitle:o,label:l})}):r.jsx("canvas",{ref:b,style:{width:typeof n=="number"?`${n}px`:n,height:a,borderRadius:8},role:"img","aria-label":m("stageVisualizer.stageVisualizerCanvas","Stage visualizer canvas")})}),r.jsxs("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:[r.jsx(ml,{modes:x,active:f,setActive:k,rows:2}),r.jsx(ef,{vu:z,hide:e==="youtube"})]})]})},af=({height:e,autoPlay:t,track:n,source:a,ytRef:s,audioRef:i,hlsRef:o,setVol:l,onEnd:c,volume:d,extractVideoId:h})=>{u.useEffect(()=>{const m=i.current;if(m){if(m.volume=d,m.crossOrigin=a!=null&&a.withCredentials?"use-credentials":"anonymous",(a==null?void 0:a.kind)==="hls"&&Cp(a.url)){const x=()=>{m.src=a.url,m.load(),t&&m.play().catch(()=>{})};if(m.canPlayType("application/vnd.apple.mpegurl")){x();return}(async()=>{const f=(await import("hls.js")).default;if(f.isSupported()){const k=new f({xhrSetup:b=>{if(a!=null&&a.withCredentials&&(b.withCredentials=!0),a!=null&&a.headers)for(const[w,N]of Object.entries(a.headers))b.setRequestHeader(w,String(N))}});o.current=k,k.loadSource(a.url),k.attachMedia(m),k.on(f.Events.MANIFEST_PARSED,()=>t&&m.play().catch(()=>{}))}else x()})()}(a==null?void 0:a.kind)==="audio"&&a.url&&(m.src=a.url,m.load(),t&&m.play().catch(()=>{}))}},[a==null?void 0:a.url,a==null?void 0:a.kind,a==null?void 0:a.withCredentials,d,t]);const p=(a==null?void 0:a.kind)==="youtube",g=p?"video":"cover",y=`gp-stage:mode:${(a==null?void 0:a.kind)??"none"}`;return r.jsxs("div",{className:"gp-stage",style:{width:"100%",height:e,background:p?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(a==null?void 0:a.kind)==="youtube"&&r.jsx(Pa,{videoId:a.videoId??h(a.url),onReady:m=>{s.current=m.target,l(d),t&&m.target.playVideo()},onEnd:c,opts:{width:"100%",height:"100%",playerVars:{autoplay:t?1:0,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3}},style:{width:"100%",height:"100%"}}),((a==null?void 0:a.kind)==="audio"||(a==null?void 0:a.kind)==="hls")&&r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{textAlign:"center",color:"var(--nice-overlay-light-90, #e2e8f0)"},children:n!=null&&n.coverUrl?r.jsx("img",{alt:"cover",src:n.coverUrl,style:{height:e-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[n==null?void 0:n.artist," — ",n==null?void 0:n.title]}),r.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--nice-text-dim, #94a3b8)"},children:(a==null?void 0:a.label)??`${(a==null?void 0:a.codec)??""} ${(a==null?void 0:a.quality)??""}`.trim()})]})}),r.jsx("audio",{ref:i,onEnded:c,onLoadedMetadata:()=>{},crossOrigin:a!=null&&a.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]}),r.jsx(gl,{kind:(a==null?void 0:a.kind)==="hls"?"hls":(a==null?void 0:a.kind)??"audio",audioRef:i,hlsRef:o,height:e,coverUrl:n==null?void 0:n.coverUrl,title:n==null?void 0:n.title,subtitle:n==null?void 0:n.artist,label:(a==null?void 0:a.label)??`${(a==null?void 0:a.codec)??""} ${(a==null?void 0:a.quality)??""}`.trim(),defaultMode:g,storageKey:y},`vis-${y}`)]})},sf=({artist:e,title:t,hideControls:n=!0,isPlaying:a,onTimeUpdate:s,searchYouTubeByArtistTitle:i})=>{const{t:o}=be(),[l,c]=u.useState(e||""),[d,h]=u.useState(t||""),[p,g]=u.useState(null),[y,m]=u.useState(null),x=u.useRef(null),[v,f]=u.useState({width:Math.min(560,window.innerWidth-32),height:Math.min(315,(window.innerWidth-32)*9/16)});u.useEffect(()=>{e&&t&&i&&i(e,t).then(g)},[e,t,i]),u.useEffect(()=>{y&&(a?y.playVideo():y.pauseVideo())},[a,y]),u.useEffect(()=>{if(y&&s){const b=setInterval(()=>{const w=y.getCurrentTime();s(w)},100);return()=>clearInterval(b)}},[y,s]),u.useEffect(()=>{const b=()=>{if(x.current){const w=x.current.clientWidth,N=Math.round(w*(9/16));f({width:w,height:N})}};return b(),window.addEventListener("resize",b),()=>window.removeEventListener("resize",b)},[]);const k=async()=>{if(!i)return;const b=await i(l,d);g(b)};return r.jsxs("div",{ref:x,style:{width:"100%",maxWidth:"900px",margin:"0 auto"},children:[(!e||!t||!p)&&r.jsxs("div",{children:[r.jsx("input",{value:l,onChange:b=>c(b.target.value),placeholder:o("youtubePlayer.artist","Artist"),"aria-label":o("youtubePlayer.artist","Artist")}),r.jsx("input",{value:d,onChange:b=>h(b.target.value),placeholder:o("youtubePlayer.title","Title"),"aria-label":o("youtubePlayer.title","Title")}),r.jsx("button",{onClick:k,children:o("youtubePlayer.search","Search")})]}),p&&r.jsxs("div",{children:[r.jsx(Pa,{videoId:p,opts:{width:v.width.toString(),height:v.height.toString(),playerVars:{autoplay:1,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,annotations:0}},onReady:b=>m(b.target)}),!n&&r.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px"},children:[r.jsxs("button",{onClick:()=>y==null?void 0:y.playVideo(),children:[r.jsx(O.NtdPlay,{size:14})," ",o("youtubePlayer.play","Play")]}),r.jsxs("button",{onClick:()=>y==null?void 0:y.pauseVideo(),children:[r.jsx(O.NtdPause,{size:14})," ",o("youtubePlayer.pause","Pause")]})]})]})]})},ri=e=>({name:e,dirs:new Map,files:[]}),of=e=>(e??[]).map(t=>t instanceof File?{file:t}:t),lf=e=>e.replace(/\\/g,"/"),cf=e=>{const t=ri("/");for(const n of e){const a=lf(n.path??n.file.name).split("/").filter(Boolean);if(a.length<=1){t.files.push({file:n.file,path:a[0]??n.file.name});continue}let s=t;for(let i=0;i<a.length-1;i++){const o=a[i];s.dirs.has(o)||s.dirs.set(o,ri(o)),s=s.dirs.get(o)}s.files.push({file:n.file,path:a[a.length-1]??n.file.name})}return t},ya=e=>e.slice().sort((t,n)=>(t.path??t.file.name).localeCompare(n.path??n.file.name)),df={tidal:O.NtdWave,spotify:O.NtdMusic,youtube:O.NtdPlay},va=({q:e,setQ:t,t:n})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[r.jsx("div",{style:{flex:1},children:r.jsx(ie.NiceTextInput,{value:e,onChange:t,placeholder:n("libraryExplorer.searchPlaceholder","Search…"),size:"sm"})}),e&&r.jsx(ie.NiceButton,{variant:"ghost",size:"sm",onClick:()=>t(""),children:r.jsx(O.NtdClose,{size:14})})]}),ba=({files:e,t,onOpenInEditor:n,onPlayFile:a})=>e.length?r.jsx("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:r.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[r.jsx("thead",{children:r.jsxs("tr",{style:{color:"var(--nice-text-muted, #94a3b8)",textAlign:"left"},children:[r.jsx("th",{style:{padding:"8px 12px",fontWeight:600},children:t("libraryExplorer.colFile","File")}),r.jsx("th",{style:{padding:"8px 12px",fontWeight:600},children:t("libraryExplorer.colType","Type")}),r.jsx("th",{style:{padding:"8px 12px",fontWeight:600,width:200},children:t("libraryExplorer.colActions","Actions")})]})}),r.jsx("tbody",{children:e.map(s=>{const i=s.path??s.file.name;return r.jsxs("tr",{style:{borderTop:"1px solid var(--nice-border, #1e293b)"},children:[r.jsx("td",{style:{padding:"6px 12px",maxWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),r.jsx("td",{style:{padding:"6px 12px",color:"var(--nice-text-muted, #94a3b8)"},children:s.file.type||"—"}),r.jsxs("td",{style:{padding:"6px 12px",display:"flex",gap:6},children:[n&&r.jsxs(ie.NiceButton,{variant:"outline",size:"sm",onClick:()=>n(s.file),children:[r.jsx(O.NtdEdit,{size:13})," ",t("libraryExplorer.openInEditor","Edit")]}),a&&r.jsxs(ie.NiceButton,{variant:"primary",size:"sm",onClick:()=>a(s.file),children:[r.jsx(O.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]})]},i)})})]})}):r.jsx("div",{style:{fontSize:13,color:"var(--nice-text-muted, #94a3b8)",padding:12},children:t("libraryExplorer.noFiles","No files")}),yl=({streams:e,t,onPlayStream:n})=>e.length?r.jsxs("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:[r.jsx("div",{style:{padding:"8px 12px",fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:t("libraryExplorer.streaming","Streaming")}),r.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:e.map(a=>r.jsxs("li",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,borderTop:"1px solid var(--nice-border, #1e293b)",padding:"8px 12px"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.title}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",display:"flex",alignItems:"center",gap:4},children:[u.createElement(df[a.provider],{size:12})," ",a.provider.toUpperCase(),a.artist?` • ${a.artist}`:""]})]}),n&&r.jsxs(ie.NiceButton,{variant:"primary",size:"sm",onClick:()=>n(a),children:[r.jsx(O.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]},`${a.provider}:${a.id}`))})]}):null,ta=({name:e,enabled:t})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 8px",fontSize:13},children:[r.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:t?"var(--nice-success, #10b981)":"var(--nice-border, #d1d5db)"}}),r.jsx("span",{style:{color:t?"inherit":"var(--nice-text-muted, #94a3b8)"},children:e})]}),uf=({variant:e="full",files:t=[],streams:n=[],enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,t:c,style:d,id:h,accessMode:p,"data-testid":g})=>{const{t:y}=be(),m=c??y,[x,v]=u.useState(""),f=u.useMemo(()=>of(t),[t]),k=u.useCallback(N=>{const $=x.trim().toLowerCase();return!$||N.toLowerCase().includes($)},[x]),b=u.useMemo(()=>ya(f).filter(N=>k(`${N.path??N.file.name} ${N.file.type||""}`)),[f,k]),w=u.useMemo(()=>n.filter(N=>k(`${N.title} ${N.artist??""} ${N.provider}`)),[n,k]);return p==="hidden"?null:e==="minimal"?r.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...d},id:h,"data-testid":g,children:[r.jsx(va,{q:x,setQ:v,t:m}),r.jsx(ba,{files:b,t:m,onOpenInEditor:s,onPlayFile:i}),r.jsx(yl,{streams:w,t:m,onPlayStream:o})]}):e==="onlyFiles"?r.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...d},id:h,"data-testid":g,children:[r.jsx(va,{q:x,setQ:v,t:m}),r.jsx(ba,{files:b,t:m,onOpenInEditor:s,onPlayFile:i})]}):r.jsx(hf,{q:x,setQ:v,normFiles:f,filteredStreams:w,enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,style:d,id:h,"data-testid":g,t:m})},hf=({q:e,setQ:t,normFiles:n,filteredStreams:a,enableProviders:s,onOpenInEditor:i,onPlayFile:o,onPlayStream:l,className:c,style:d,id:h,"data-testid":p,t:g})=>{const y=u.useMemo(()=>cf(n),[n]),[m,x]=u.useState({}),[v,f]=u.useState("/"),k=$=>x(M=>({...M,[$]:!M[$]})),b=($,M)=>{const E=M==="/"?`/${$.name}`:`${M}${$.name}/`,R=M==="/"&&$.name==="/",L=m[E]??R,A=Array.from($.dirs.keys()).sort();return r.jsxs("div",{children:[!R&&r.jsxs("button",{type:"button",onClick:()=>{k(E),f(E)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"4px 8px",border:"none",borderRadius:6,cursor:"pointer",textAlign:"left",background:v===E?"var(--nice-accent-tint-20, rgba(99,102,241,0.2))":"transparent",color:"var(--nice-text, inherit)"},children:[r.jsx("span",{style:{display:"inline-flex"},children:L?r.jsx(O.NtdFolderOpen,{size:14}):r.jsx(O.NtdFolder,{size:14})}),r.jsx("span",{style:{fontSize:13},children:$.name})]}),(R||L)&&r.jsx("div",{style:{paddingLeft:R?0:16},children:A.map(z=>b($.dirs.get(z),E))})]},E)},w=u.useMemo(()=>{let $;if(v==="/")$=ya(n);else{const M=v.replace(/^\//,"").split("/").filter(Boolean);let E=y;for(const R of M){const L=E.dirs.get(R);if(!L)return[];E=L}$=ya(E.files)}return e?$.filter(M=>(M.path??M.file.name).toLowerCase().includes(e.toLowerCase())):$},[v,y,n,e]),N={tidal:(s==null?void 0:s.tidal)??!0,spotify:(s==null?void 0:s.spotify)??!0,youtube:(s==null?void 0:s.youtube)??!0};return r.jsxs("div",{className:c,style:{display:"flex",gap:12,color:"var(--nice-text, #e2e8f0)",...d},id:h,"data-testid":p,children:[r.jsxs("div",{style:{flex:"0 0 220px",border:"1px solid var(--nice-border, #334155)",borderRadius:12,padding:8},children:[r.jsx("div",{style:{padding:"0 8px 8px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:g("libraryExplorer.library","Library")}),b(y,"/"),r.jsxs("div",{style:{marginTop:16,borderTop:"1px solid var(--nice-border, #1e293b)",paddingTop:8},children:[r.jsx("div",{style:{padding:"0 8px 4px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:g("libraryExplorer.streaming","Streaming")}),r.jsx(ta,{name:"Tidal",enabled:N.tidal}),r.jsx(ta,{name:"Spotify",enabled:N.spotify}),r.jsx(ta,{name:"YouTube",enabled:N.youtube})]})]}),r.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[r.jsx(va,{q:e,setQ:t,t:g}),r.jsx(ba,{files:w,t:g,onOpenInEditor:i,onPlayFile:o}),(N.tidal||N.spotify||N.youtube)&&r.jsx(yl,{streams:a.filter($=>N[$.provider]),t:g,onPlayStream:l})]})]})},pf=({kind:e,color:t})=>{const n={width:14,height:14,viewBox:"0 0 24 24",fill:t,"aria-hidden":!0};switch(e){case"youtube":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M23 7.2s-.2-1.6-.9-2.3c-.8-.9-1.7-.9-2.1-1C16.9 3.5 12 3.5 12 3.5s-4.9 0-8 .4c-.4.1-1.3.1-2.1 1C1.2 5.6 1 7.2 1 7.2S.8 9.1.8 11v1.8c0 1.9.2 3.8.2 3.8s.2 1.6.9 2.3c.8.9 1.9.9 2.4 1 1.7.2 7.7.4 7.7.4s4.9 0 8-.4c.4-.1 1.3-.1 2.1-1 .7-.7.9-2.3.9-2.3s.2-1.9.2-3.8V11c0-1.9-.2-3.8-.2-3.8zM9.7 14.6V8.2l6.3 3.2-6.3 3.2z"})});case"spotify":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.59 14.42c-.18.3-.57.4-.87.21-2.39-1.46-5.4-1.79-8.95-.98-.34.08-.68-.13-.76-.47-.08-.34.13-.68.47-.76 3.88-.89 7.21-.5 9.89 1.13.31.19.4.58.22.87zm1.23-2.72c-.23.37-.71.49-1.08.26-2.74-1.69-6.92-2.18-10.16-1.19-.41.13-.85-.11-.97-.52-.13-.41.11-.85.52-.97 3.7-1.12 8.31-.58 11.45 1.34.37.23.49.71.24 1.08zm.11-2.84C14.55 8.84 9.5 8.66 6.43 9.6c-.49.15-1.01-.13-1.16-.62-.15-.49.13-1.01.62-1.16 3.52-1.07 9.1-.86 12.69 1.27.43.26.57.82.31 1.25-.26.43-.82.57-1.25.31z"})});case"tidal":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 2L8 6l4 4 4-4-4-4zM4 6L0 10l4 4 4-4-4-4zm16 0l-4 4 4 4 4-4-4-4zm-8 8l-4 4 4 4 4-4-4-4z"})});case"hls":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M2 12h2v6H2v-6zm4-4h2v10H6V8zm4-4h2v14h-2V4zm4 4h2v10h-2V8zm4 4h2v6h-2v-6z"})});case"audio":default:return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"})})}},Qa=({data:e,display:t,callbacks:n,state:a})=>{const{id:s,index:i,artist:o,title:l,version:c,lp:d,sourcesAvailable:h=[]}=e,{allowVersion:p=!0,dragHandleProps:g}=t,{onChange:y,onRemove:m,onMoveUp:x,onMoveDown:v,onChangeLp:f,onSelectSource:k}=n,{readOnly:b=!1,canMoveUp:w=!0,canMoveDown:N=!0,activeSource:$}=a,{t:M}=be(),E=u.useRef(null);u.useEffect(()=>{!o&&E.current&&E.current.focus()},[o]);const R=j=>{if(!b&&j.key==="Enter"){const I=j.target.closest("div.gpi-row"),Y=I==null?void 0:I.querySelectorAll("input[data-role='field']");if(!Y||Y.length===0)return;const H=Array.from(Y).indexOf(j.target),D=Y[H+1]??Y[0];D==null||D.focus()}},L=j=>{const I=h.includes(j),Y=$===j,H={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid var(--nice-border, #e5e7eb)",background:Y?"var(--nice-selected-bg, #eef2ff)":"var(--nice-bg, #fff)",opacity:I?1:.35,cursor:I&&k&&!b?"pointer":"default",transition:"transform .05s ease"},D=j==="youtube"?"var(--nice-danger, #ff0000)":j==="spotify"?"var(--nice-success, #1db954)":j==="tidal"?"var(--nice-text, #111827)":j==="hls"?"var(--nice-accent, #7c3aed)":"var(--nice-text, #374151)",V=j==="youtube"?"YouTube":j==="spotify"?"Spotify":j==="tidal"?"TIDAL":j==="hls"?"HLS":"Audio",Z=M("playlistItem.sourceLabel","Source")+": "+V+(Y?` ${M("playlistItem.sourceSelected","(selected)")}`:""),X=()=>{!I||!k||b||k(j)};return r.jsx("button",{type:"button",title:V,onClick:X,disabled:!I||b,style:H,"aria-pressed":Y,"aria-label":Z,children:r.jsx(pf,{kind:j,color:D})},j)},A=["youtube","tidal","spotify","hls","audio"],z=typeof d=="number"?d:i+1;return r.jsxs("div",{className:"gpi-row",role:"group","aria-label":M("playlistItem.trackNumber","Track")+" "+(i+1),style:{display:"grid",gridTemplateColumns:p?"56px 1fr 1fr 1fr auto auto":"56px 1fr 1fr auto auto",gap:8,alignItems:"center"},children:[r.jsx("input",{type:"number",min:1,value:z,onChange:j=>f==null?void 0:f(Number(j.target.value)),disabled:b||!f,"aria-label":M("playlistItem.lp","Lp"),title:M("playlistItem.positionOnList","Position in the list"),style:ff}),r.jsx("input",{ref:E,"data-role":"field",type:"text",value:o,onChange:j=>y({artist:j.target.value}),placeholder:M("playlistItem.artist","Artist"),onKeyDown:R,disabled:b,"aria-label":M("playlistItem.artist","Artist"),className:"gpi-input",style:na}),r.jsx("input",{"data-role":"field",type:"text",value:l,onChange:j=>y({title:j.target.value}),placeholder:M("playlistItem.title","Title"),onKeyDown:R,disabled:b,"aria-label":M("playlistItem.title","Title"),className:"gpi-input",style:na}),p&&r.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:j=>y({version:j.target.value||void 0}),placeholder:M("playlistItem.versionOptional","Version (optional)"),onKeyDown:R,disabled:b,"aria-label":M("playlistItem.version","Version"),className:"gpi-input",style:na}),r.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":M("playlistItem.availableSources","Available sources"),children:A.map(L)}),r.jsxs("div",{className:"gpi-actions",style:{display:"flex",gap:6,justifyContent:"flex-end"},children:[g&&r.jsx("button",{type:"button",...g,draggable:!0,"aria-label":M("playlistItem.dragReorder","Drag to reorder"),title:M("playlistItem.dragReorder","Drag to reorder"),style:tr,children:r.jsx(O.NtdMenu,{size:14})}),r.jsx("button",{type:"button",onClick:x,disabled:!w||b,"aria-label":M("playlistItem.moveUp","Move up"),title:M("playlistItem.moveUp","Move up"),style:tr,children:r.jsx(O.NtdArrowUp,{size:14})}),r.jsx("button",{type:"button",onClick:v,disabled:!N||b,"aria-label":M("playlistItem.moveDown","Move down"),title:M("playlistItem.moveDown","Move down"),style:tr,children:r.jsx(O.NtdArrowDown,{size:14})}),r.jsx("button",{type:"button",onClick:m,disabled:b,"aria-label":M("common.delete","Delete"),title:M("common.delete","Delete"),style:{...tr,color:"var(--nice-color-danger, #b91c1c)"},children:r.jsx(O.NtdClose,{size:14})})]})]})},ff={width:48,border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 6px",fontSize:14,textAlign:"center"},na={width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 10px",fontSize:14},tr={border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg, #fff)",padding:"6px 8px",borderRadius:6,cursor:"pointer"},xa=()=>Math.random().toString(36).slice(2,10),nr=e=>(e??[]).map(t=>({id:xa(),...t})),mf=e=>e.map(({id:t,...n})=>n),gf=null,yf=e=>{const t=e.trim();if(!t)return null;const n=t.split(/\s[-–—]\s/);if(n.length<2){const o=t.split(/[;|]/).map(l=>l.trim());return o.length>=2?{artist:o[0],title:o[1],version:o[2]||void 0}:null}const a=n[0].trim(),s=n.slice(1).join(" - ").trim(),i=s.match(/^(.*?)\s*[([](.+?)[)\]]\s*$/);if(i){const o=i[1].trim(),l=i[2].trim();return{artist:a,title:o,version:l||void 0}}return{artist:a,title:s,version:void 0}},vf=({value:e,defaultValue:t,onChange:n,allowVersion:a=!0,maxItems:s,addButtonLabel:i,emptyState:o=gf,readOnly:l=!1,autoFocusNewItem:c=!0,enableBulkPaste:d=!0})=>{const{t:h}=be(),p=e!==void 0,[g,y]=u.useState(()=>nr(e||t)),[m,x]=u.useState(""),v=u.useRef(null),[f,k]=u.useState(null);u.useEffect(()=>{p&&y(nr(e))},[p,JSON.stringify(e)]);const b=u.useCallback(Z=>{n==null||n(mf(Z))},[n]),w=u.useCallback(Z=>{if(p){const X=Z(nr(e));b(X)}else y(X=>{const q=Z(X);return b(q),q})},[b,p,e]),N=s?g.length<s:!0,$=u.useCallback(()=>{!N||l||w(Z=>[...Z,{id:xa(),artist:"",title:"",version:void 0}])},[N,l,w]),M=u.useCallback((Z,X)=>{w(q=>q.map(G=>G.id===Z?{...G,...X}:G))},[w]),E=u.useCallback(Z=>{l||w(X=>X.filter(q=>q.id!==Z))},[l,w]),R=u.useCallback((Z,X)=>{w(q=>{const G=q.findIndex(F=>F.id===Z);if(G<0)return q;const C=G+X;if(C<0||C>=q.length)return q;const T=[...q],[S]=T.splice(G,1);return T.splice(C,0,S),T})},[w]),L=u.useCallback((Z,X)=>{w(q=>{const G=q.findIndex(F=>F.id===Z);if(G<0)return q;const C=Math.max(0,Math.min(q.length-1,X-1));if(G===C)return q;const T=[...q],[S]=T.splice(G,1);return T.splice(C,0,S),T})},[w]),A=Z=>X=>{l||(v.current=Z,X.dataTransfer.effectAllowed="move",X.dataTransfer.setData("text/plain",Z))},z=Z=>X=>{l||(X.preventDefault(),X.dataTransfer.dropEffect="move",k(Z))},j=Z=>()=>k(X=>X===Z?null:X),I=Z=>X=>{if(l)return;X.preventDefault();const q=v.current??X.dataTransfer.getData("text/plain");k(null),v.current=null,!(!q||q===Z)&&w(G=>{const C=G.findIndex(K=>K.id===q),T=G.findIndex(K=>K.id===Z);if(C<0||T<0||C===T)return G;const S=[...G],[F]=S.splice(C,1);return S.splice(T,0,F),S})},Y=()=>{v.current=null,k(null)},H=u.useCallback(()=>{if(!d||l)return;const X=m.split(/\r?\n/).map(q=>q.trim()).filter(Boolean).map(yf).filter(q=>!!q);X.length!==0&&(w(q=>{const G=(s??1/0)-q.length,C=X.slice(0,Math.max(0,G)).map(T=>({id:xa(),...T}));return[...q,...C]}),x(""))},[d,l,m,s,w]);u.useEffect(()=>{},[g.length,c]);const D=o??r.jsx("div",{style:{padding:"0.75rem",color:"var(--nice-text-secondary, #777)",fontStyle:"italic"},children:h("genericPlaylist.emptyState","No songs. Add the first one below.")}),V=i??h("genericPlaylist.addSong","Add song");return r.jsxs("div",{className:"gp-container",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[r.jsxs("div",{className:"gp-header",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[r.jsx("h3",{style:{margin:0,fontSize:16},children:h("genericPlaylist.playlist","Playlist")}),r.jsx("div",{style:{marginLeft:"auto",display:"flex",gap:8},children:r.jsxs("button",{type:"button",onClick:$,disabled:!N||l,className:"gp-add",style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},"aria-label":V,children:["+ ",V]})})]}),g.length===0?r.jsx("div",{className:"gp-empty",children:D}):r.jsx("ol",{className:"gp-list",style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:8},children:g.map((Z,X)=>{const q=f===Z.id;return r.jsx("li",{draggable:!l,onDragStart:A(Z.id),onDragOver:z(Z.id),onDragLeave:j(Z.id),onDrop:I(Z.id),onDragEnd:Y,style:{border:q?"2px dashed var(--nice-info, #6366f1)":"2px solid transparent",borderRadius:8,padding:q?4:0},children:r.jsx(Qa,{data:{id:Z.id,index:X,lp:X+1,artist:Z.artist,title:Z.title,version:a?Z.version??void 0:void 0,sourcesAvailable:void 0},display:{allowVersion:a,dragHandleProps:{onDragStart:A(Z.id)}},callbacks:{onChange:G=>M(Z.id,G),onRemove:()=>E(Z.id),onMoveUp:()=>R(Z.id,-1),onMoveDown:()=>R(Z.id,1),onChangeLp:G=>L(Z.id,G)},state:{readOnly:l,canMoveUp:X>0,canMoveDown:X<g.length-1}})},Z.id)})}),d&&!l&&r.jsx("div",{style:{marginTop:12},children:r.jsxs("details",{children:[r.jsx("summary",{style:{cursor:"pointer",color:"var(--nice-text, #374151)"},children:h("genericPlaylist.bulkPasteSummary","Paste multiple items at once")}),r.jsxs("div",{style:{marginTop:6},children:[r.jsx("textarea",{value:m,onChange:Z=>x(Z.target.value),placeholder:h("genericPlaylist.bulkPastePlaceholder",`Paste lines in format:
|
|
66
66
|
Artist - Title (Version)
|
|
67
67
|
Artist — Title [Remastered 2011]
|
|
68
|
-
OR: Artist;Title;Version`),rows:3,style:{width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:8,fontFamily:"inherit"}}),n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:6},children:[n.jsx("div",{style:{color:"var(--nice-text-secondary, #6b7280)",fontSize:12},children:h("genericPlaylist.bulkPasteHint","Each line will be added as a separate song.")}),n.jsx("button",{type:"button",onClick:J,disabled:!m.trim(),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},children:h("genericPlaylist.addFromList","Add from list")})]})]})]})})]})},hl={music:G.NtdMusic,microphone:G.NtdMicrophone,volume:G.NtdVolume,wave:G.NtdWave,megaphone:G.NtdMegaphone,star:G.NtdStar,heart:G.NtdHeart,lightning:G.NtdLightning,sparkle:G.NtdSparkle,moon:G.NtdMoon,sun:G.NtdSun,mountain:G.NtdMountain,trophy:G.NtdTrophy,crown:G.NtdCrown,target:G.NtdTarget,pin:G.NtdPin},df=Object.keys(hl),va=({icon:e,size:t=14})=>{if(!e)return null;const r=hl[e];return r?n.jsx(r,{size:t}):n.jsx("span",{children:e})},ii=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #f59e0b)","var(--nice-warning, #eab308)","var(--nice-success, #84cc16)","var(--nice-success, #22c55e)","var(--nice-info, #14b8a6)","var(--nice-info, #06b6d4)","var(--nice-primary, #3b82f6)","var(--nice-info, #6366f1)","var(--nice-accent, #8b5cf6)","var(--nice-accent, #a855f7)","var(--nice-color-accent-pink, #d946ef)","var(--nice-color-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)","var(--nice-text-muted, #78716c)","var(--nice-text-secondary, #64748b)","var(--nice-text, #000000)"],rr=df,pl=({tags:e,onCreateTag:t,onUpdateTag:r,onDeleteTag:a,selectedTracks:s,onAssignTag:i,onUnassignTag:o})=>{const{t:l}=Pe(),[c,d]=u.useState(null),[h,f]=u.useState(""),[p,y]=u.useState(ii[8]),[m,x]=u.useState(rr[0]),[b,g]=u.useState(!1),[S,v]=u.useState(null),[k,M]=u.useState(""),[T,N]=u.useState(""),[j,R]=u.useState(""),z=u.useCallback(_=>{d(_.id),M(_.name),N(_.color),R(_.icon||rr[0])},[]),A=u.useCallback(()=>{c&&k.trim()&&(r(c,k.trim(),T,j),d(null))},[c,k,T,j,r]),$=u.useCallback(()=>{h.trim()&&(t(h.trim(),p,m),f(""),g(!1))},[h,p,m,t]),O=u.useCallback(_=>{S===_?(a(_),v(null)):(v(_),setTimeout(()=>v(null),3e3))},[S,a]),I=s&&s.length>0,U=_=>!s||s.length===0?!1:s.every(W=>W.tags.includes(_)),J=_=>!s||s.length===0?!1:s.some(W=>W.tags.includes(_))&&!U(_);return n.jsxs("div",{style:{border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:10,background:"var(--nice-bg-elevated, #fff)",overflow:"hidden"},children:[n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",display:"flex",alignItems:"center",gap:8,background:"var(--nice-color-surface, #f9fafb)"},children:[n.jsx(G.NtdTag,{size:16}),n.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:l("playlistManager.tagManager","Tag manager")}),n.jsx("div",{style:{flex:1}}),n.jsxs("button",{onClick:()=>g(!b),style:{background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"4px 10px",fontSize:"0.72rem",cursor:"pointer"},children:["+ ",l("playlistManager.newTag","New tag")]})]}),n.jsxs("div",{style:{padding:12},children:[b&&n.jsxs("div",{style:{border:"1px solid var(--nice-border-color, #d1d5db)",borderRadius:8,padding:10,marginBottom:12,background:"var(--nice-color-surface, #f9fafb)"},children:[n.jsxs("div",{style:{display:"flex",gap:6,marginBottom:8},children:[n.jsx("input",{type:"text",value:h,onChange:_=>f(_.target.value),placeholder:l("playlistManager.tagName","Tag name"),style:{flex:1,padding:"5px 10px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",fontSize:"0.8rem",background:"var(--nice-input-bg, #fff)",color:"var(--nice-text-primary, #1f2937)"},onKeyDown:_=>_.key==="Enter"&&$()}),n.jsx("button",{onClick:$,disabled:!h.trim(),style:{background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"5px 12px",fontSize:"0.78rem",cursor:"pointer",opacity:h.trim()?1:.5},"aria-label":l("playlistManager.createTag","Create tag"),children:n.jsx(G.NtdCheck,{size:14})})]}),n.jsxs("div",{style:{marginBottom:6},children:[n.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.color","Color")}),n.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:ii.map(_=>n.jsx("div",{onClick:()=>y(_),style:{width:20,height:20,borderRadius:"50%",background:_,cursor:"pointer",border:p===_?"3px solid var(--nice-color-accent, #3b82f6)":"2px solid transparent",boxSizing:"border-box"}},_))})]}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.icon","Icon")}),n.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:rr.map(_=>n.jsx("div",{onClick:()=>x(_),style:{width:26,height:26,borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"0.85rem",background:m===_?"var(--nice-accent-tint-10, #eff6ff)":"transparent",border:m===_?"1px solid var(--nice-color-accent, #3b82f6)":"1px solid transparent"},children:n.jsx(va,{icon:_,size:16})},_))})]})]}),I&&n.jsx("div",{style:{padding:"6px 10px",background:"var(--nice-accent-tint-10, #eff6ff)",borderRadius:6,marginBottom:8,fontSize:"0.72rem",color:"var(--nice-color-accent, #3b82f6)"},children:l("playlistManager.bulkTagHint","Click a tag to apply it to the selected tracks")+": "+s.length}),e.length===0?n.jsx("div",{style:{textAlign:"center",padding:20,opacity:.3,fontSize:"0.82rem"},children:l("playlistManager.noTags","No tags yet")}):n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.map(_=>n.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderRadius:8,border:"1px solid var(--nice-border-color, #e5e7eb)",background:c===_.id?"var(--nice-color-surface, #f9fafb)":"transparent"},children:c===_.id?n.jsxs(n.Fragment,{children:[n.jsx("select",{value:j,onChange:W=>R(W.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:rr.map(W=>n.jsx("option",{value:W,children:W},W))}),n.jsx("input",{type:"color",value:T,onChange:W=>N(W.target.value),style:{width:24,height:24,border:"none",cursor:"pointer",padding:0}}),n.jsx("input",{type:"text",value:k,onChange:W=>M(W.target.value),style:{flex:1,padding:"3px 8px",borderRadius:4,border:"1px solid var(--nice-border-color, #d1d5db)",fontSize:"0.78rem",background:"var(--nice-input-bg, #fff)",color:"var(--nice-text-primary, #1f2937)"},onKeyDown:W=>W.key==="Enter"&&A()}),n.jsx("button",{onClick:A,style:ar("var(--nice-color-accent, #3b82f6)"),"aria-label":l("common.save","Save"),children:n.jsx(G.NtdCheck,{size:14})}),n.jsx("button",{onClick:()=>d(null),style:ar("var(--nice-text-secondary, #9ca3af)"),"aria-label":l("common.cancel","Cancel"),children:n.jsx(G.NtdClose,{size:14})})]}):n.jsxs(n.Fragment,{children:[n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 10px",borderRadius:20,background:`${_.color}18`,color:_.color,fontWeight:600,fontSize:"0.78rem"},children:[n.jsx(va,{icon:_.icon,size:12}),_.name]}),I&&i&&o&&n.jsx("input",{type:"checkbox",checked:U(_.id),ref:W=>{W&&(W.indeterminate=J(_.id))},onChange:()=>{const W=s.map(K=>K.id);U(_.id)?o(W,_.id):i(W,_.id)},style:{cursor:"pointer"}}),n.jsx("div",{style:{flex:1}}),n.jsx("button",{onClick:()=>z(_),style:ar("var(--nice-text-secondary, #9ca3af)"),title:l("playlistManager.editTag","Edit tag"),"aria-label":l("playlistManager.editTag","Edit tag"),children:n.jsx(G.NtdEdit,{size:14})}),n.jsx("button",{onClick:()=>O(_.id),style:ar(S===_.id?"var(--nice-color-error, #ef4444)":"var(--nice-text-secondary, #9ca3af)"),title:S===_.id?l("playlistManager.confirmDelete","Click again to delete"):l("playlistManager.deleteTag","Delete tag"),"aria-label":S===_.id?l("playlistManager.confirmDelete","Click again to delete"):l("playlistManager.deleteTag","Delete tag"),children:n.jsx(G.NtdTrash,{size:14})})]})},_.id))})]})]})},ar=e=>({background:"none",border:"none",cursor:"pointer",fontSize:"0.82rem",color:e,padding:"2px 4px"});var is=(e=>(e.Static="static",e.Dynamic="dynamic",e))(is||{}),fl=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(fl||{}),ml=(e=>(e.Left="left",e.Right="right",e))(ml||{}),ot=(e=>(e.Artist="artist",e.Title="title",e.Album="album",e.Genre="genre",e.Year="year",e.Duration="duration",e.Rating="rating",e.PlayCount="playCount",e.Tag="tag",e.Source="source",e.AddedDate="addedDate",e))(ot||{}),lt=(e=>(e.Equals="eq",e.NotEquals="neq",e.Contains="contains",e.NotContains="notContains",e.StartsWith="startsWith",e.GreaterThan="gt",e.LessThan="lt",e.Between="between",e.In="in",e.NotIn="notIn",e))(lt||{}),gl=(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))(gl||{}),ln=(e=>(e.Asc="asc",e.Desc="desc",e))(ln||{}),St=(e=>(e.Library="library",e.Spotify="spotify",e.Tidal="tidal",e.YouTube="youtube",e.MusicBrainz="musicbrainz",e.Import="import",e.Manual="manual",e))(St||{});const uf=[{value:ot.Artist,label:"Artist"},{value:ot.Title,label:"Title"},{value:ot.Album,label:"Album"},{value:ot.Genre,label:"Genre"},{value:ot.Year,label:"Year"},{value:ot.Duration,label:"Duration (s)"},{value:ot.Rating,label:"Rating"},{value:ot.PlayCount,label:"Play Count"},{value:ot.Tag,label:"Tag"},{value:ot.Source,label:"Source"},{value:ot.AddedDate,label:"Added Date"}],hf=[{value:lt.Equals,label:"="},{value:lt.NotEquals,label:"≠"},{value:lt.Contains,label:"contains"},{value:lt.NotContains,label:"not contains"},{value:lt.StartsWith,label:"starts with"},{value:lt.GreaterThan,label:">"},{value:lt.LessThan,label:"<"},{value:lt.Between,label:"between"},{value:lt.In,label:"in"},{value:lt.NotIn,label:"not in"}];function pf(e){return"logic"in e&&"rules"in e}function xa(){return{id:crypto.randomUUID(),field:ot.Artist,operator:lt.Contains,value:""}}function yl(){return{id:crypto.randomUUID(),logic:"and",rules:[xa()]}}const ff=({rule:e,onChange:t,onRemove:r})=>n.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[n.jsx("select",{className:"form-select form-select-sm",style:{width:130},value:e.field,onChange:a=>t({...e,field:a.target.value}),children:uf.map(a=>n.jsx("option",{value:a.value,children:a.label},a.value))}),n.jsx("select",{className:"form-select form-select-sm",style:{width:130},value:e.operator,onChange:a=>t({...e,operator:a.target.value}),children:hf.map(a=>n.jsx("option",{value:a.value,children:a.label},a.value))}),n.jsx("input",{type:"text",className:"form-control form-control-sm",style:{width:160},value:e.value,placeholder:"Value",onChange:a=>t({...e,value:a.target.value})}),e.operator===lt.Between&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-muted",children:"–"}),n.jsx("input",{type:"text",className:"form-control form-control-sm",style:{width:120},value:e.value2??"",placeholder:"Value 2",onChange:a=>t({...e,value2:a.target.value})})]}),n.jsx("button",{className:"btn btn-outline-danger btn-sm",onClick:r,title:"Remove rule","aria-label":"Remove rule",children:n.jsx(G.NtdClose,{size:14})})]}),bl=({group:e,onChange:t,onRemove:r,depth:a=0})=>{const{t:s}=Pe(),i=u.useCallback((f,p)=>{const y=[...e.rules];y[f]=p,t({...e,rules:y})},[e,t]),o=u.useCallback(f=>{const p=e.rules.filter((y,m)=>m!==f);t({...e,rules:p.length>0?p:[xa()]})},[e,t]),l=u.useCallback(()=>{t({...e,rules:[...e.rules,xa()]})},[e,t]),c=u.useCallback(()=>{t({...e,rules:[...e.rules,yl()]})},[e,t]),d=u.useCallback(()=>{t({...e,logic:e.logic==="and"?"or":"and"})},[e,t]),h=e.logic==="and"?"var(--bs-primary)":"var(--bs-warning)";return n.jsxs("div",{className:"p-2 mb-2 rounded",style:{borderLeft:`3px solid ${h}`,backgroundColor:a%2===0?"rgba(var(--bs-body-color-rgb), 0.03)":"transparent"},children:[n.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[n.jsx("button",{className:`btn btn-sm ${e.logic==="and"?"btn-primary":"btn-warning"}`,onClick:d,title:s("playlistManager.toggleLogic","Toggle AND/OR"),children:e.logic.toUpperCase()}),n.jsx("span",{className:"text-muted small",children:s("playlistManager.matchAll","Match all / any of these rules")}),n.jsxs("div",{className:"ms-auto d-flex gap-1",children:[n.jsx("button",{className:"btn btn-outline-secondary btn-sm",onClick:l,title:"Add rule",children:"+ Rule"}),a<3&&n.jsx("button",{className:"btn btn-outline-secondary btn-sm",onClick:c,title:"Add nested group",children:"+ Group"}),r&&n.jsx("button",{className:"btn btn-outline-danger btn-sm",onClick:r,title:"Remove group","aria-label":"Remove group",children:n.jsx(G.NtdClose,{size:14})})]})]}),e.rules.map((f,p)=>pf(f)?n.jsx(bl,{group:f,onChange:y=>i(p,y),onRemove:()=>o(p),depth:a+1},f.id):n.jsx(ff,{rule:f,onChange:y=>i(p,y),onRemove:()=>o(p)},f.id))]})},vl=({rules:e,onChange:t,limit:r,onLimitChange:a})=>{const{t:s}=Pe(),i=e??yl();return n.jsxs("div",{className:"border rounded p-3",children:[n.jsxs("h6",{className:"mb-3",children:[n.jsx(G.NtdRepeat,{size:14})," ",s("playlistManager.dynamicRules","Dynamic Playlist Rules")]}),n.jsx("p",{className:"text-muted small mb-3",children:s("playlistManager.dynamicRulesHint","Tracks matching these rules will automatically be included in the playlist.")}),n.jsx(bl,{group:i,onChange:t}),a&&n.jsxs("div",{className:"d-flex align-items-center gap-2 mt-3 pt-2 border-top",children:[n.jsx("label",{className:"form-label mb-0 small",children:s("playlistManager.maxTracks","Max tracks:")}),n.jsx("input",{type:"number",className:"form-control form-control-sm",style:{width:100},min:0,value:r??"",placeholder:"∞",onChange:o=>{const l=parseInt(o.target.value,10);a(isNaN(l)||l<=0?void 0:l)}}),n.jsx("span",{className:"text-muted small",children:s("playlistManager.leaveEmptyForAll","(leave empty for unlimited)")})]})]})},oi=e=>{if(!e)return"--:--";const t=Math.floor(e/60),r=Math.floor(e%60);return`${t}:${String(r).padStart(2,"0")}`},mf={spotify:"var(--source-spotify, #1db954)",tidal:"var(--source-tidal, #000000)",youtube:"var(--source-youtube, #ff0000)",musicbrainz:"var(--source-musicbrainz, #ba478f)"},gf=({source:e})=>{if(e==="import")return n.jsx(G.NtdDownload,{size:12});if(e==="manual")return n.jsx(G.NtdEdit,{size:12});const t=mf[e];return t?n.jsx(G.NtdCircle,{size:10,style:{color:t}}):n.jsx(G.NtdMusic,{size:12})},os=({tracks:e,tags:t,selectedTrackIds:r,onSelectionChange:a,onPlay:s,onRemove:i,onReorder:o,onTagTracks:l,onRateTracks:c,sortField:d,sortDir:h,onSortChange:f,filterText:p,onFilterChange:y,compact:m=!1,draggable:x=!1,onDragStart:b,dropTarget:g=!1,onDrop:S})=>{const{t:v}=Pe(),[k,M]=u.useState(null),[T,N]=u.useState(null),j=u.useRef(null),R=u.useMemo(()=>{let E=e??[];if(p.trim()){const P=p.toLowerCase();E=E.filter(C=>{var L,w;return C.title.toLowerCase().includes(P)||C.artist.toLowerCase().includes(P)||((L=C.album)==null?void 0:L.toLowerCase().includes(P))||((w=C.genre)==null?void 0:w.toLowerCase().includes(P))})}return[...E].sort((P,C)=>{const L=h==="asc"?1:-1;switch(d){case"title":return L*P.title.localeCompare(C.title);case"artist":return L*P.artist.localeCompare(C.artist);case"album":return L*(P.album??"").localeCompare(C.album??"");case"duration":return L*((P.duration??0)-(C.duration??0));case"year":return L*((P.year??0)-(C.year??0));case"rating":return L*((P.rating??0)-(C.rating??0));case"addedDate":return L*(P.addedAt??"").localeCompare(C.addedAt??"");case"custom":return L*((P.customOrder??0)-(C.customOrder??0));default:return 0}})},[e,p,d,h]),z=u.useCallback((E,P)=>{const C=R[E];if(C){if(P.ctrlKey||P.metaKey){const L=new Set(r);L.has(C.id)?L.delete(C.id):L.add(C.id),a(L)}else if(P.shiftKey&&j.current!==null){const L=Math.min(j.current,E),w=Math.max(j.current,E),D=new Set(r);for(let F=L;F<=w;F++)D.add(R[F].id);a(D)}else a(new Set([C.id]));j.current=E}},[R,r,a]),A=u.useCallback(()=>{r.size===R.length?a(new Set):a(new Set(R.map(E=>E.id)))},[R,r,a]),$=({field:E,label:P,width:C})=>{const L=d===E;return n.jsxs("div",{style:{width:C,flex:C?void 0:1,cursor:"pointer",userSelect:"none",fontWeight:L?700:500,fontSize:"0.72rem",textTransform:"uppercase",letterSpacing:"0.04em",opacity:L?1:.6,display:"flex",alignItems:"center",gap:4},onClick:()=>{L?f(E,h===ln.Asc?ln.Desc:ln.Asc):f(E,ln.Asc)},children:[P,L&&(h==="asc"?n.jsx(G.NtdArrowUp,{size:10}):n.jsx(G.NtdArrowDown,{size:10}))]})},O=u.useCallback((E,P)=>{const C=r.has(E.id)?Array.from(r):[E.id];P.dataTransfer.setData("trackIds",JSON.stringify(C)),P.dataTransfer.effectAllowed="move",b==null||b(C,P)},[r,b]),I=u.useCallback((E,P)=>{P.preventDefault(),P.dataTransfer.dropEffect="move",M(E)},[]),U=u.useCallback((E,P)=>{P.preventDefault(),M(null);try{const C=P.dataTransfer.getData("trackIds");if(C&&o){const L=JSON.parse(C),w=R.filter(B=>!L.includes(B.id)),D=R.filter(B=>L.includes(B.id)),F=Math.min(E,w.length);w.splice(F,0,...D),o(w.map(B=>B.id))}}catch{}},[R,o]),J=u.useCallback(E=>{E.preventDefault(),M(null),S==null||S(E)},[S]),_=u.useMemo(()=>new Map(t.map(E=>[E.id,E])),[t]),W=E=>E.replace(/[^a-z0-9_-]/gi,"-"),K=m?36:48,re={display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",color:"var(--nice-text-secondary, #6b7280)"},X=(E,P)=>({display:"flex",alignItems:"center",gap:8,padding:m?"4px 12px":"6px 12px",height:K,cursor:"pointer",background:P?"var(--nice-color-accent-light, #dbeafe)":E?"var(--nice-selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--nice-border-light, #f3f4f6)",transition:"background 0.1s"}),q=R.length>0&&r.size===R.length;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:g?E=>{E.preventDefault(),E.dataTransfer.dropEffect="copy"}:void 0,onDrop:g?J:void 0,children:[n.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",display:"flex",gap:8,alignItems:"center"},children:[n.jsx("input",{type:"text",value:p,onChange:E=>y(E.target.value),placeholder:v("playlistManager.filterTracks","Filter tracks..."),style:{flex:1,fontSize:"0.82rem",padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",background:"var(--nice-input-bg, #f9fafb)",color:"var(--nice-text-primary, #1f2937)"}}),n.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[R.length,"/",(e??[]).length]}),r.size>0&&i&&n.jsxs("button",{style:{fontSize:"0.72rem",padding:"4px 8px",borderRadius:4,border:"1px solid var(--nice-color-error, #ef4444)",background:"transparent",color:"var(--nice-color-error, #ef4444)",cursor:"pointer"},onClick:()=>i(Array.from(r)),"aria-label":v("playlistManager.removeSelected","Remove selected"),children:[n.jsx(G.NtdTrash,{size:12})," ",r.size]})]}),n.jsxs("div",{style:re,children:[n.jsx("div",{style:{width:28},children:n.jsx("input",{type:"checkbox",checked:q,onChange:A,style:{cursor:"pointer"}})}),n.jsx("div",{style:{width:20},children:"#"}),!m&&n.jsx("div",{style:{width:44}}),n.jsx($,{field:"title",label:v("playlistManager.colTitle","Title")}),n.jsx($,{field:"artist",label:v("playlistManager.colArtist","Artist")}),!m&&n.jsx($,{field:"album",label:v("playlistManager.colAlbum","Album")}),n.jsx($,{field:"duration",label:v("playlistManager.colDuration","Duration"),width:60}),!m&&n.jsx($,{field:"year",label:v("playlistManager.colYear","Year"),width:50}),n.jsx("div",{style:{width:30}})," ",!m&&n.jsx("div",{style:{width:60}})," ",n.jsx("div",{style:{width:24}})," "]}),n.jsxs("div",{style:{flex:1,overflow:"auto"},children:[R.length===0&&n.jsx("div",{style:{padding:24,textAlign:"center",opacity:.4,fontSize:"0.85rem"},children:e.length===0?v("playlistManager.emptyPlaylist","This playlist is empty"):v("playlistManager.noMatchingTracks","No tracks match the filter")}),R.map((E,P)=>{const C=r.has(E.id),L=k===P;return n.jsxs("div",{style:X(C,L),onClick:w=>z(P,w),onDoubleClick:()=>s==null?void 0:s(E),draggable:x,onDragStart:w=>O(E,w),onDragOver:w=>I(P,w),onDrop:w=>U(P,w),onDragLeave:()=>M(null),children:[n.jsx("div",{style:{width:28},children:n.jsx("input",{type:"checkbox",checked:C,onChange:()=>{const w=new Set(r);C?w.delete(E.id):w.add(E.id),a(w)},onClick:w=>w.stopPropagation(),style:{cursor:"pointer"}})}),n.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:P+1}),!m&&n.jsx("div",{style:{width:44,height:36,flexShrink:0},children:E.coverUrl?n.jsx("img",{src:E.coverUrl,alt:E.title||v("common.coverArt","Cover art"),style:{width:36,height:36,borderRadius:4,objectFit:"cover"},loading:"lazy"}):n.jsx("div",{style:{width:36,height:36,borderRadius:4,background:"var(--nice-color-surface, #f3f4f6)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.9rem"},children:n.jsx(G.NtdMusic,{size:16})})}),n.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",fontWeight:500},children:E.title}),n.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",opacity:.7},children:E.artist}),!m&&n.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",opacity:.5},children:E.album}),n.jsx("div",{style:{width:60,fontSize:"0.78rem",opacity:.5,textAlign:"right"},children:oi(E.duration)}),!m&&n.jsx("div",{style:{width:50,fontSize:"0.72rem",opacity:.4,textAlign:"center"},children:E.year||""}),n.jsx("div",{style:{width:30,textAlign:"center",fontSize:"0.75rem"},title:E.source,children:n.jsx(gf,{source:E.source})}),!m&&n.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[E.tags.slice(0,2).map(w=>{const D=_.get(w);if(!D)return null;const F=`--tag-${W(w)}`;return n.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${F}-bg, ${D.color}22)`,color:`var(${F}, ${D.color})`,whiteSpace:"nowrap"},children:D.name},w)}),E.tags.length>2&&n.jsxs("span",{style:{fontSize:"0.6rem",opacity:.4},children:["+",E.tags.length-2]})]}),n.jsxs("div",{style:{width:24,display:"flex",alignItems:"center"},children:[n.jsx("button",{style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:2,opacity:.5,position:"relative"},onClick:w=>{w.stopPropagation(),N(T===E.id?null:E.id)},title:v("playlistManager.morActions","More actions"),"aria-label":v("playlistManager.morActions","More actions"),children:n.jsx(G.NtdTag,{size:12})}),T===E.id&&t.length>0&&n.jsxs("div",{style:{position:"absolute",right:12,marginTop:4,background:"var(--nice-bg-elevated, #fff)",border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:8,padding:8,zIndex:100,boxShadow:"0 4px 12px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",minWidth:140},children:[n.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:v("playlistManager.assignTag","Assign tag")}),t.map(w=>{const D=E.tags.includes(w.id);return n.jsxs("div",{style:{padding:"4px 8px",borderRadius:4,cursor:"pointer",fontSize:"0.78rem",display:"flex",alignItems:"center",gap:6,background:D?`var(--tag-${W(w.id)}-bg, ${w.color}22)`:"transparent"},onClick:F=>{F.stopPropagation();const B=r.size>0?Array.from(r):[E.id];D||l==null||l(B,[w.id]),N(null)},children:[n.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:`var(--tag-${W(w.id)}, ${w.color})`,flexShrink:0}}),n.jsx("span",{children:w.name}),D&&n.jsx(G.NtdCheck,{size:12,style:{marginLeft:"auto"}})]},w.id)})]})]})]},E.id)})]}),n.jsxs("div",{style:{padding:"6px 12px",borderTop:"1px solid var(--nice-border-color, #e5e7eb)",fontSize:"0.72rem",opacity:.5,display:"flex",gap:16},children:[n.jsxs("span",{children:[R.length," ",v("playlistManager.tracks","tracks")]}),n.jsx("span",{children:oi(R.reduce((E,P)=>E+(P.duration??0),0))}),r.size>0&&n.jsxs("span",{children:[r.size," ",v("playlistManager.selected","selected")]})]})]})},li=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),xl=({playlists:e=[],tags:t=[],onCopyTracks:r=()=>{},onMoveTracks:a=()=>{},onRemoveTracks:s=()=>{},onReorderTracks:i=()=>{},onPlay:o=()=>{},onTagTracks:l=()=>{},initialLeftId:c,initialRightId:d,library:h,queue:f,onAddToQueue:p,onRemoveFromQueue:y})=>{const{t:m}=Pe(),[x,b]=u.useState(()=>li(c??null)),[g,S]=u.useState(()=>li(d??null)),[v,k]=u.useState("left"),[M,T]=u.useState(null),[N,j]=u.useState(50),[R,z]=u.useState(!1),A=u.useMemo(()=>e.find(L=>L.id===x.playlistId),[e,x.playlistId]),$=u.useMemo(()=>e.find(L=>L.id===g.playlistId),[e,g.playlistId]),O=u.useCallback((L,w)=>{L==="left"?b(D=>({...D,...w})):S(D=>({...D,...w}))},[]),I=u.useCallback(L=>L==="left"?x:g,[x,g]),U=L=>L==="left"?"right":"left",J=u.useCallback(L=>{const w=I(L),D=I(U(L));!w.playlistId||!D.playlistId||w.selectedTrackIds.size===0||(r(w.playlistId,D.playlistId,Array.from(w.selectedTrackIds)),O(L,{selectedTrackIds:new Set}))},[I,r,O]),_=u.useCallback(L=>{const w=I(L),D=I(U(L));!w.playlistId||!D.playlistId||w.selectedTrackIds.size===0||(a(w.playlistId,D.playlistId,Array.from(w.selectedTrackIds)),O(L,{selectedTrackIds:new Set}))},[I,a,O]),W=u.useCallback(L=>{const w=I(L);!w.playlistId||w.selectedTrackIds.size===0||T({operation:"copy",sourcePlaylistId:w.playlistId,trackIds:Array.from(w.selectedTrackIds)})},[I]),K=u.useCallback(L=>{const w=I(L);!w.playlistId||w.selectedTrackIds.size===0||T({operation:"cut",sourcePlaylistId:w.playlistId,trackIds:Array.from(w.selectedTrackIds)})},[I]),re=u.useCallback(L=>{const w=I(L);!M||!w.playlistId||(M.operation==="copy"?r(M.sourcePlaylistId,w.playlistId,M.trackIds):a(M.sourcePlaylistId,w.playlistId,M.trackIds),T(null))},[M,I,r,a]),X=u.useCallback(L=>{L.key==="Tab"&&!L.shiftKey&&(L.preventDefault(),k(w=>U(w))),(L.ctrlKey||L.metaKey)&&L.key==="c"&&W(v),(L.ctrlKey||L.metaKey)&&L.key==="x"&&K(v),(L.ctrlKey||L.metaKey)&&L.key==="v"&&re(v)},[v,W,K,re]),q=u.useCallback(()=>z(!0),[]),E=u.useCallback(L=>{if(!R)return;const w=L.currentTarget.getBoundingClientRect(),D=(L.clientX-w.left)/w.width*100;j(Math.max(20,Math.min(80,D)))},[R]),P=u.useCallback(()=>z(!1),[]),C=L=>{const w=I(L),D=L==="left"?A:$,F=v===L,V=!!I(U(L)).playlistId;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",border:F?"2px solid var(--nice-color-accent, #3b82f6)":"2px solid transparent",borderRadius:8,overflow:"hidden",background:"var(--nice-bg-elevated, #fff)"},onClick:()=>k(L),children:[n.jsx("div",{style:{padding:"8px 12px",background:F?"var(--nice-color-accent, #3b82f6)":"var(--nice-color-surface, #f3f4f6)",color:F?"var(--btn-text, #fff)":"var(--nice-text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:n.jsxs("select",{value:w.playlistId??"",onChange:Y=>O(L,{playlistId:Y.target.value||null,selectedTrackIds:new Set}),style:{flex:1,fontSize:"0.82rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",background:F?"var(--nice-overlay-light-20, #ffffff30)":"var(--nice-input-bg, #fff)",color:F?"var(--btn-text, #fff)":"var(--nice-text-primary, #1f2937)"},children:[n.jsx("option",{value:"",children:m("playlistManager.selectPlaylist","Select a playlist")}),e.map(Y=>n.jsxs("option",{value:Y.id,children:[Y.name," (",Y.trackCount,")"]},Y.id))]})}),n.jsxs("div",{style:{display:"flex",gap:4,padding:"4px 8px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",flexWrap:"wrap"},children:[n.jsxs("button",{style:na(!1),onClick:()=>J(L),disabled:!w.playlistId||!V||w.selectedTrackIds.size===0,title:m("playlistManager.copyToOther","Copy to the other playlist"),children:[L==="left"?n.jsxs(n.Fragment,{children:[n.jsx(G.NtdCopy,{size:12}),n.jsx(G.NtdChevronRight,{size:12})]}):n.jsxs(n.Fragment,{children:[n.jsx(G.NtdChevronLeft,{size:12}),n.jsx(G.NtdCopy,{size:12})]})," ",m("playlistManager.copy","Copy")]}),n.jsxs("button",{style:na(!1),onClick:()=>_(L),disabled:!w.playlistId||!V||w.selectedTrackIds.size===0,title:m("playlistManager.moveToOther","Move to the other playlist"),children:[L==="left"?n.jsxs(n.Fragment,{children:[n.jsx(G.NtdMove,{size:12}),n.jsx(G.NtdChevronRight,{size:12})]}):n.jsxs(n.Fragment,{children:[n.jsx(G.NtdChevronLeft,{size:12}),n.jsx(G.NtdMove,{size:12})]})," ",m("playlistManager.move","Move")]}),n.jsx("div",{style:{flex:1}}),M&&n.jsxs("button",{style:na(!0),onClick:()=>re(L),disabled:!w.playlistId,children:[n.jsx(G.NtdClipboard,{size:12})," ",m("playlistManager.paste","Paste")," (",M.trackIds.length,")"]})]}),D?n.jsx(os,{tracks:D.tracks,tags:t,selectedTrackIds:w.selectedTrackIds,onSelectionChange:Y=>O(L,{selectedTrackIds:Y}),onPlay:o,onRemove:Y=>s(D.id,Y),onReorder:Y=>i(D.id,Y),onTagTracks:l,sortField:w.sortField,sortDir:w.sortDir,onSortChange:(Y,oe)=>O(L,{sortField:Y,sortDir:oe}),filterText:w.filterText,onFilterChange:Y=>O(L,{filterText:Y}),compact:!0,draggable:!0}):n.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",opacity:.3,fontSize:"0.85rem"},children:m("playlistManager.selectPlaylistPrompt","Select a playlist to see its tracks")})]})};return n.jsxs("div",{style:{display:"flex",height:"100%",userSelect:R?"none":"auto"},onKeyDown:X,onMouseMove:E,onMouseUp:P,tabIndex:0,children:[n.jsx("div",{style:{width:`${N}%`,minWidth:200},children:C("left")}),n.jsx("div",{style:{width:6,cursor:"col-resize",background:R?"var(--nice-color-accent, #3b82f6)":"var(--nice-border-color, #e5e7eb)",transition:R?"none":"background 0.15s",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseDown:q,children:n.jsx("div",{style:{width:2,height:40,borderRadius:1,background:R?"var(--btn-text, #fff)":"var(--nice-bg-tertiary, #9ca3af)"}})}),n.jsx("div",{style:{flex:1,minWidth:200},children:C("right")})]})},na=e=>({background:e?"var(--nice-color-accent, #3b82f6)":"transparent",color:e?"var(--btn-text, #fff)":"var(--nice-text-secondary, #6b7280)",border:e?"none":"1px solid var(--nice-border-color, #d1d5db)",borderRadius:6,padding:"3px 8px",fontSize:"0.72rem",cursor:"pointer",whiteSpace:"nowrap"}),Sl="av:local-playlists";function yf(){try{const e=localStorage.getItem(Sl);return e?JSON.parse(e):[]}catch{return[]}}function bf(e){const t=JSON.stringify(e);try{localStorage.setItem(Sl,t)}catch{}}function ls(){const[e,t]=u.useState(()=>yf()),r=u.useRef(!1);return u.useEffect(()=>{r.current=!0},[]),u.useEffect(()=>{bf(e)},[e]),u.useMemo(()=>({list:()=>e,get:s=>e.find(i=>i.id===s),create:s=>{const i=new Date().toISOString(),o={id:crypto.randomUUID(),name:s,items:[],updatedAt:i};return t(l=>[o,...l]),o},rename:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,name:i,updatedAt:new Date().toISOString()}:l)),remove:s=>t(i=>i.filter(o=>o.id!==s)),replaceItems:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,items:i,updatedAt:new Date().toISOString()}:l)),addItems:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,items:[...l.items,...i],updatedAt:new Date().toISOString()}:l))}),[e])}const vf=it.scoped("PlaylistList"),xf={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,background:"var(--nice-bg, #fff)"},Sf={...xf,padding:"8px 10px",cursor:"pointer"},kl={border:"1px solid var(--nice-border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg, #fff)",cursor:"pointer"},kf={...kl,background:"var(--nice-color-primary, #4f46e5)",borderColor:"var(--nice-color-primary, #4f46e5)",color:"var(--nice-text-on-primary, #fff)"},cs=({selectedId:e,onSelect:t,onCreateRemote:r})=>{const{t:a}=Pe(),s=ls(),[i,o]=u.useState(""),l=u.useMemo(()=>s.list(),[s]);return n.jsxs("div",{style:{display:"grid",gap:10},children:[n.jsxs("div",{style:{display:"flex",gap:8},children:[n.jsx("input",{placeholder:a("playlistList.playlistName","Playlist name..."),value:i,onChange:c=>o(c.target.value),style:{flex:1,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px"},"aria-label":"Playlist name"}),n.jsxs("button",{type:"button",disabled:!i.trim(),style:i.trim()?kf:{...kl,cursor:"not-allowed",color:"var(--nice-text-muted, #9ca3af)",background:"var(--nice-bg-tertiary, #f3f4f6)"},onClick:async()=>{const c=s.create(i.trim());if(o(""),r)try{await r({platform:"tidal",name:c.name,songs:c.items})}catch(d){vf.error("Remote playlist create failed:",d)}t==null||t(c)},children:["+ ",a("common.add","Add")]})]}),n.jsxs("div",{style:{display:"grid",gap:6},children:[l.map(c=>{const d=c.id===e;return n.jsxs("button",{onClick:()=>t==null?void 0:t(c),style:{...Sf,background:d?"var(--nice-selected-bg, #eef2ff)":"var(--nice-bg, #fff)"},children:[n.jsx("div",{style:{fontWeight:600},children:c.name}),n.jsxs("div",{style:{color:"var(--nice-text-dim, #64748b)",fontSize:12},children:[c.items.length+" "+a("playlistList.songs","songs")," ","• ",new Date(c.updatedAt).toLocaleString()]})]},c.id)}),!l.length&&n.jsx("div",{style:{color:"var(--nice-text-muted, #6b7280)"},children:a("playlistList.emptyState","No playlists. Add the first one ↑")})]})]})},wf=it.scoped("PlaylistBrowser"),ci={display:"grid",gap:12},di=e=>({artist:(e.artists??[]).join(", "),title:e.title}),wl=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:r,tracks:a,view:s,onSelect:i,onPlay:o})=>{var b;const{t:l}=Pe(),c=ls(),[d,h]=u.useState(null),[f,p]=u.useState(""),[,y]=u.useState([]),m=d==null?void 0:d.id,x=(g,S)=>{if("addItems"in c){c.addItems(g.id,S);const k=c.list().find(M=>M.id===g.id)||g;h(k);return}const v=c;if("update"in c&&typeof v.update=="function"){const k=Array.from([...g.items||[],...S]);v.update({...g,items:k});const M=c.list().find(T=>T.id===g.id)||{...g,items:k};h(M);return}wf.warn("useLocalPlaylists: missing addItems/update method — update hook implementation.")};return n.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(min(200px, 100%), 320px) 1fr",gap:16},children:[n.jsxs("div",{style:ci,children:[n.jsx("h3",{style:{margin:0},children:l("playlistBrowser.playlists","Playlists")}),n.jsx(cs,{selectedId:m,onSelect:h}),d&&n.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:[l("playlistBrowser.selected","Selected"),": ",n.jsx("strong",{children:d.name})," ·"," ",((b=d.items)==null?void 0:b.length)??0," ",l("playlistBrowser.tracks","tracks")]})]}),n.jsxs("div",{style:ci,children:[n.jsx("h3",{style:{margin:0},children:l("playlistBrowser.library","Library")}),n.jsxs("div",{children:[e==null?void 0:e({placeholder:l("playlistBrowser.searchAndAdd","Search and add to playlist..."),onSelect:g=>{d&&x(d,[di(g)])}}),n.jsx("input",{placeholder:l("playlistBrowser.fullSearch","Full search (Enter does not add, full list below)"),value:f,onChange:g=>p(g.target.value),style:{width:"100%",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px",marginTop:10}})]}),t==null?void 0:t({query:f,onSelect:g=>{d&&x(d,[di(g)])}}),r==null?void 0:r({onPlayNow:g=>y(g),onAddToQueue:g=>y(S=>[...S,...g]),onAddDescriptors:g=>d&&x(d,g)})]})]})};var Kt=(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))(Kt||{});const Cl=(e,t=null)=>e.filter(r=>r.parentId===t).sort((r,a)=>r.sortOrder-a.sortOrder).map(r=>({...r,children:Cl(e,r.id)})),Cf={[Kt.Spotify]:{label:"Spotify",color:"var(--source-spotify, #1DB954)",bg:"var(--source-spotify-bg, #1DB95418)"},[Kt.Tidal]:{label:"Tidal",color:"var(--source-tidal, #000000)",bg:"var(--source-tidal-bg, #00000010)"},[Kt.YouTube]:{label:"YouTube",color:"var(--source-youtube, #FF0000)",bg:"var(--source-youtube-bg, #FF000010)"}},jl=({folders:e,playlists:t,tags:r,services:a,activeFolderId:s,activePlaylistId:i,onSelectFolder:o,onSelectPlaylist:l,onCreateFolder:c,onRenameFolder:d,onDeleteFolder:h,onCreatePlaylist:f,onConnectService:p,onDisconnectService:y,onDragPlaylistToFolder:m,collapsed:x=!1,onToggleCollapse:b})=>{const{t:g}=Pe(),[S,v]=u.useState(new Set),[k,M]=u.useState(!1),[T,N]=u.useState(""),[j,R]=u.useState(null),[z,A]=u.useState(!1),[$,O]=u.useState(""),[I,U]=u.useState("static"),[J,_]=u.useState(null),[W,K]=u.useState(""),[re,X]=u.useState(null),[q,E]=u.useState(!1),P=u.useMemo(()=>Cl(e),[e]),C=u.useCallback(ee=>{v(de=>{const fe=new Set(de);return fe.has(ee)?fe.delete(ee):fe.add(ee),fe})},[]),L=u.useCallback(()=>{T.trim()&&(c(T.trim(),j),N(""),M(!1))},[T,j,c]),w=u.useCallback(()=>{$.trim()&&(f($.trim(),I,s),O(""),A(!1))},[$,I,s,f]),D=u.useCallback(ee=>{W.trim()&&(d(ee,W.trim()),_(null),K(""))},[W,d]),F=u.useCallback((ee,de)=>{ee.preventDefault(),ee.dataTransfer.dropEffect="move",X(de)},[]),B=u.useCallback((ee,de)=>{ee.preventDefault();const fe=ee.dataTransfer.getData("playlistId");fe&&m&&m(fe,de),X(null)},[m]),V=u.useCallback(()=>X(null),[]),Y=u.useCallback(ee=>t.filter(de=>(de.folderId??null)===ee),[t]),oe={width:x?48:280,minWidth:x?48:280,background:"var(--nice-bg-secondary, #f8f9fa)",borderRight:"1px solid var(--nice-border-color, #e5e7eb)",display:"flex",flexDirection:"column",transition:"width 0.2s, min-width 0.2s",overflow:"hidden",height:"100%"},ie={padding:"8px 12px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)"},ne=(ee,de=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:de?"var(--nice-color-accent-light, #dbeafe)":ee?"var(--nice-color-accent, #3b82f6)":"transparent",color:ee?"var(--btn-text, #fff)":"var(--nice-text-primary, #1f2937)",transition:"background 0.15s",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),Z={background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:"2px 6px",borderRadius:4,color:"var(--nice-text-secondary, #6b7280)"},H={fontSize:"0.8rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",background:"var(--nice-input-bg, #fff)",color:"var(--nice-text-primary, #1f2937)",width:"100%"},se=(ee,de)=>{var Me,Te;const fe=S.has(ee.id),xe=s===ee.id,ce=re===ee.id,be=Y(ee.id);return n.jsxs("div",{children:[n.jsxs("div",{style:{...ne(xe,ce),paddingLeft:12+de*16},onClick:()=>{o(ee.id),ee.children&&ee.children.length>0&&C(ee.id)},onDragOver:je=>F(je,ee.id),onDrop:je=>B(je,ee.id),onDragLeave:V,children:[n.jsx("span",{style:{width:14,textAlign:"center",flexShrink:0,fontSize:"0.7rem"},children:(((Me=ee.children)==null?void 0:Me.length)||0)>0||be.length>0?fe?n.jsx(G.NtdChevronDown,{size:10}):n.jsx(G.NtdChevronRight,{size:10}):null}),J===ee.id?n.jsx("input",{value:W,onChange:je=>K(je.target.value),onKeyDown:je=>{je.key==="Enter"&&D(ee.id),je.key==="Escape"&&_(null)},onBlur:()=>D(ee.id),autoFocus:!0,style:{...H,flex:1},onClick:je=>je.stopPropagation()}):n.jsxs(n.Fragment,{children:[n.jsx("span",{style:{display:"inline-flex"},children:ee.icon??n.jsx(G.NtdFolder,{size:14})}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:ee.name}),n.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:be.length}),n.jsx("button",{style:Z,onClick:je=>{je.stopPropagation(),_(ee.id),K(ee.name)},title:g("common.rename","Rename"),"aria-label":g("common.rename","Rename"),children:n.jsx(G.NtdEdit,{size:12})}),n.jsx("button",{style:{...Z,color:"var(--nice-color-error, #ef4444)"},onClick:je=>{je.stopPropagation(),h(ee.id)},title:g("common.delete","Delete"),"aria-label":g("common.delete","Delete"),children:n.jsx(G.NtdTrash,{size:12})})]})]}),fe&&n.jsxs(n.Fragment,{children:[be.map(je=>ae(je,de+1)),(Te=ee.children)==null?void 0:Te.map(je=>se(je,de+1))]})]},ee.id)},ae=(ee,de)=>{const fe=i===ee.id;return n.jsxs("div",{style:{...ne(fe),paddingLeft:12+de*16+22},onClick:()=>l(ee.id),draggable:!0,onDragStart:xe=>{xe.dataTransfer.setData("playlistId",ee.id),xe.dataTransfer.effectAllowed="move"},children:[n.jsx("span",{style:{display:"inline-flex"},children:ee.type==="dynamic"?n.jsx(G.NtdLightning,{size:12}):n.jsx(G.NtdMusic,{size:12})}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:ee.name}),n.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:ee.trackCount})]},ee.id)};if(x)return n.jsx("div",{style:oe,children:n.jsx("button",{style:{...Z,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:b,title:g("playlistManager.expandSidebar","Expand sidebar"),"aria-label":g("playlistManager.expandSidebar","Expand sidebar"),children:n.jsx(G.NtdChevronRight,{size:16})})});const ue=Y(null);return n.jsxs("div",{style:oe,children:[n.jsxs("div",{style:{...ie,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("span",{style:{fontWeight:700,fontSize:"0.85rem",display:"inline-flex",alignItems:"center",gap:6},children:[n.jsx(G.NtdMusic,{size:14})," ",g("playlistManager.title","Playlists")]}),n.jsx("button",{style:Z,onClick:b,title:g("playlistManager.collapseSidebar","Collapse sidebar"),"aria-label":g("playlistManager.collapseSidebar","Collapse sidebar"),children:n.jsx(G.NtdChevronLeft,{size:16})})]}),n.jsxs("div",{style:{...ie,display:"flex",gap:4,flexWrap:"wrap"},children:[n.jsxs("button",{style:{...Z,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:6,padding:"4px 10px"},onClick:()=>A(!0),children:["+ ",g("playlistManager.newPlaylist","New playlist")]}),n.jsxs("button",{style:{...Z,border:"1px solid var(--nice-border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{M(!0),R(s)},children:[n.jsx(G.NtdFolder,{size:12})," ",g("playlistManager.newFolder","New folder")]})]}),z&&n.jsxs("div",{style:{...ie,display:"flex",flexDirection:"column",gap:6},children:[n.jsx("input",{value:$,onChange:ee=>O(ee.target.value),placeholder:g("playlistManager.playlistName","Playlist name"),style:H,autoFocus:!0,onKeyDown:ee=>{ee.key==="Enter"&&w(),ee.key==="Escape"&&A(!1)}}),n.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[n.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[n.jsx("input",{type:"radio",checked:I==="static",onChange:()=>U("static")}),g("playlistManager.static","Static")]}),n.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[n.jsx("input",{type:"radio",checked:I==="dynamic",onChange:()=>U("dynamic")}),n.jsx(G.NtdLightning,{size:12})," ",g("playlistManager.dynamic","Dynamic")]}),n.jsx("div",{style:{flex:1}}),n.jsx("button",{style:{...Z,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:w,"aria-label":"Confirm create playlist",children:n.jsx(G.NtdCheck,{size:12})}),n.jsx("button",{style:Z,onClick:()=>A(!1),"aria-label":"Cancel create playlist",children:n.jsx(G.NtdClose,{size:12})})]})]}),k&&n.jsxs("div",{style:{...ie,display:"flex",gap:6},children:[n.jsx("input",{value:T,onChange:ee=>N(ee.target.value),placeholder:g("playlistManager.folderName","Folder name"),style:{...H,flex:1},autoFocus:!0,onKeyDown:ee=>{ee.key==="Enter"&&L(),ee.key==="Escape"&&M(!1)}}),n.jsx("button",{style:{...Z,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:L,"aria-label":"Confirm create folder",children:n.jsx(G.NtdCheck,{size:12})}),n.jsx("button",{style:Z,onClick:()=>M(!1),"aria-label":"Cancel create folder",children:n.jsx(G.NtdClose,{size:12})})]}),n.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[n.jsxs("div",{style:ne(s===null&&i===null,re==="__root__"),onClick:()=>o(null),onDragOver:ee=>F(ee,null),onDrop:ee=>B(ee,null),onDragLeave:V,children:[n.jsx(G.NtdHome,{size:14}),n.jsx("span",{style:{flex:1},children:g("playlistManager.allPlaylists","All playlists")}),n.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:t.length})]}),ue.map(ee=>ae(ee,0)),P.map(ee=>se(ee,0))]}),r.length>0&&n.jsxs("div",{style:ie,children:[n.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:g("playlistManager.tags","Tags")}),n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:r.map(ee=>n.jsxs("span",{style:{fontSize:"0.7rem",padding:"2px 8px",borderRadius:12,background:ee.color+"22",color:ee.color,border:`1px solid ${ee.color}44`,cursor:"pointer"},children:[n.jsx(va,{icon:ee.icon,size:10}),ee.icon?" ":"",ee.name]},ee.id))})]}),n.jsxs("div",{style:ie,children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",cursor:"pointer",fontSize:"0.7rem",fontWeight:600,opacity:.6},onClick:()=>E(!q),children:[n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(G.NtdLink,{size:12})," ",g("playlistManager.services","Services")]}),q?n.jsx(G.NtdChevronUp,{size:12}):n.jsx(G.NtdChevronDown,{size:12})]}),q&&n.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[Kt.Spotify,Kt.Tidal,Kt.YouTube].map(ee=>{const de=Cf[ee],fe=a.find(xe=>xe.platform===ee);return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 8px",borderRadius:6,border:"1px solid var(--nice-border-color, #e5e7eb)",fontSize:"0.78rem"},children:[n.jsx(G.NtdCircle,{size:10,style:{color:de.color}}),n.jsx("span",{style:{flex:1},children:de.label}),fe!=null&&fe.connected?n.jsxs(n.Fragment,{children:[n.jsx("span",{style:{fontSize:"0.65rem",opacity:.6},children:fe.username??g("playlistManager.connected","Connected")}),n.jsx("button",{style:{...Z,color:"var(--nice-danger, #ef4444)"},onClick:()=>y(ee),"aria-label":g("playlistManager.disconnect","Disconnect"),children:n.jsx(G.NtdClose,{size:12})})]}):n.jsx("button",{style:{...Z,background:de.color,color:"var(--nice-text-on-primary, #fff)",borderRadius:4,padding:"2px 8px"},onClick:()=>p(ee),children:g("playlistManager.connect","Connect")})]},ee)})})]})]})},jf=({playlist:e,tags:t,onPlay:r,selectedTrackIds:a,onSelectionChange:s})=>{const{t:i}=Pe(),o=u.useCallback(l=>{const c=new Set(a);c.has(l)?c.delete(l):c.add(l),s(c)},[a,s]);return e.tracks.length===0?n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:60,opacity:.3},children:[n.jsx("span",{style:{marginBottom:8,display:"inline-flex"},children:n.jsx(G.NtdMusic,{size:32})}),n.jsx("span",{style:{fontSize:"0.82rem"},children:i("playlistManager.emptyPlaylist","This playlist is empty")})]}):n.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(160px, 1fr))",gap:10},children:e.tracks.map(l=>{const c=a.has(l.id);return n.jsxs("div",{onClick:()=>o(l.id),onDoubleClick:()=>r(l),style:{border:c?"2px solid var(--nice-color-accent, #3b82f6)":"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:10,padding:10,cursor:"pointer",background:c?"var(--nice-accent-tint-10, #eff6ff)":"var(--nice-bg-elevated, #fff)",transition:"all 0.12s"},children:[n.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:6,background:"linear-gradient(135deg, var(--playlist-track-bg1, #6366f140), var(--playlist-track-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"1.5rem",marginBottom:6},children:n.jsx(G.NtdMusic,{size:24})}),n.jsx("div",{style:{fontWeight:500,fontSize:"0.78rem",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.title}),n.jsx("div",{style:{fontSize:"0.68rem",opacity:.5,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.artist})]},l.id)})})},Ml=u.memo(jf),ui=e=>e.replace(/[^a-z0-9_-]/gi,"-"),hi={background:"none",border:"none",cursor:"pointer",fontSize:"0.78rem",padding:"2px 4px",opacity:.4},Mf=({playlists:e,folders:t,tags:r,activeFolderId:a,onSelectPlaylist:s,onDeletePlaylist:i,onDuplicatePlaylist:o})=>{const{t:l}=Pe(),c=u.useMemo(()=>a?e.filter(d=>d.folderId===a):e,[e,a]);return c.length===0?n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:60,opacity:.4},children:[n.jsx("span",{style:{marginBottom:12,display:"inline-flex"},children:n.jsx(G.NtdMusic,{size:40})}),n.jsx("span",{style:{fontSize:"0.85rem"},children:l("playlistManager.emptyState","No playlists yet")})]}):n.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))",gap:12},children:c.map(d=>{var f;const h=t.find(p=>p.id===d.folderId);return n.jsxs("div",{onClick:()=>s(d.id),style:{border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:12,padding:16,cursor:"pointer",background:"var(--nice-bg-elevated, #fff)",transition:"box-shadow 0.15s, transform 0.15s"},onMouseEnter:p=>{p.currentTarget.style.boxShadow="0 4px 12px var(--nice-overlay-8, rgba(0, 0, 0, 0.08))",p.currentTarget.style.transform="translateY(-1px)"},onMouseLeave:p=>{p.currentTarget.style.boxShadow="none",p.currentTarget.style.transform="none"},children:[n.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:8,background:"linear-gradient(135deg, var(--playlist-cover-bg1, #6366f140), var(--playlist-cover-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"2.5rem",marginBottom:10},children:d.type===is.Dynamic?n.jsx(G.NtdLightning,{size:40}):n.jsx(G.NtdMusic,{size:40})}),n.jsx("div",{style:{fontWeight:600,fontSize:"0.85rem",marginBottom:2},children:d.name}),n.jsxs("div",{style:{fontSize:"0.72rem",opacity:.5},children:[d.trackCount," ",l("playlistManager.tracks","tracks"),h&&n.jsxs(n.Fragment,{children:[" — ",n.jsx(G.NtdFolder,{size:11})," ",h.name]})]}),((f=d.tags)==null?void 0:f.length)>0&&n.jsx("div",{style:{display:"flex",gap:4,marginTop:6,flexWrap:"wrap"},children:d.tags.slice(0,3).map(p=>{const y=r.find(m=>m.id===p);return y?n.jsx("span",{style:{padding:"1px 8px",borderRadius:12,background:`var(--tag-${ui(p)}-bg, ${y.color}18)`,color:`var(--tag-${ui(p)}, ${y.color})`,fontSize:"0.65rem",fontWeight:500},children:y.name},p):null})}),n.jsxs("div",{style:{display:"flex",gap:4,marginTop:8},children:[n.jsx("button",{onClick:p=>{p.stopPropagation(),o(d.id)},style:hi,title:l("playlistManager.duplicate","Duplicate"),"aria-label":l("playlistManager.duplicate","Duplicate"),children:n.jsx(G.NtdCopy,{size:14})}),n.jsx("button",{onClick:p=>{p.stopPropagation(),i(d.id)},style:hi,title:l("playlistManager.delete","Delete"),"aria-label":l("playlistManager.delete","Delete"),children:n.jsx(G.NtdTrash,{size:14})})]})]},d.id)})})},Rl=u.memo(Mf),pi=[{value:St.Library,label:"Library",hex:"var(--nice-info, #6366f1)",css:"var(--source-library, #6366f1)",cssBg:"var(--source-library-bg, #6366f118)"},{value:St.Spotify,label:"Spotify",hex:"var(--nice-success, #1db954)",css:"var(--source-spotify, #1db954)",cssBg:"var(--source-spotify-bg, #1db95418)"},{value:St.Tidal,label:"Tidal",hex:"var(--nice-text, #000000)",css:"var(--source-tidal, #000000)",cssBg:"var(--source-tidal-bg, #00000018)"},{value:St.YouTube,label:"YouTube",hex:"var(--nice-danger, #ff0000)",css:"var(--source-youtube, #ff0000)",cssBg:"var(--source-youtube-bg, #ff000018)"},{value:St.MusicBrainz,label:"MusicBrainz",hex:"#ba478f",css:"var(--source-musicbrainz, #ba478f)",cssBg:"var(--source-musicbrainz-bg, #ba478f18)"}],Nl=({onSearch:e,results:t,isSearching:r,onAddToPlaylist:a,onPlayPreview:s})=>{const{t:i}=Pe(),[o,l]=u.useState(""),[c,d]=u.useState(new Set([St.Library,St.Spotify,St.Tidal,St.YouTube])),[h,f]=u.useState(new Set),[p,y]=u.useState(!1),m=u.useRef(null),x=u.useCallback(N=>{d(j=>{const R=new Set(j);return R.has(N)?R.delete(N):R.add(N),R})},[]),b=u.useCallback(N=>{l(N),m.current&&clearTimeout(m.current),N.trim().length>=2&&(m.current=setTimeout(()=>{e(N.trim(),Array.from(c))},350))},[c,e]),g=u.useCallback(N=>{N.preventDefault(),o.trim().length>=2&&e(o.trim(),Array.from(c))},[o,c,e]),S=u.useCallback(N=>{f(j=>{const R=new Set(j);return R.has(N)?R.delete(N):R.add(N),R})},[]),v=u.useCallback(()=>{h.size===t.length?f(new Set):f(new Set(t.map(N=>N.id)))},[h,t]),k=u.useCallback(()=>{const N=t.filter(j=>h.has(j.id));N.length>0&&(a(N),f(new Set))},[t,h,a]),M=N=>{if(!N)return"--:--";const j=Math.floor(N/60),R=N%60;return`${j}:${R.toString().padStart(2,"0")}`},T=N=>{const j=pi.find(R=>R.value===N);return n.jsx(G.NtdCircle,{size:10,style:{color:j?j.css:"var(--nice-text-secondary, #6b7280)"}})};return n.jsxs("div",{style:{border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:10,background:"var(--nice-bg-elevated, #fff)",overflow:"hidden"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 12px",gap:8,cursor:"pointer",background:"var(--nice-color-surface, #f9fafb)"},onClick:()=>y(!p),children:[n.jsx(G.NtdSearch,{size:16}),n.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:i("playlistManager.search","Search")}),n.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",opacity:.5},children:p?n.jsx(G.NtdChevronUp,{size:12}):n.jsx(G.NtdChevronDown,{size:12})})]}),p&&n.jsxs("div",{style:{padding:"0 12px 12px"},children:[n.jsx("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap"},children:pi.map(N=>{const j=c.has(N.value);return n.jsxs("button",{onClick:()=>x(N.value),style:{padding:"4px 10px",borderRadius:20,border:j?`2px solid ${N.css}`:"1px solid var(--nice-border-color, #d1d5db)",background:j?N.cssBg:"transparent",color:j?N.css:"var(--nice-text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:j?600:400,transition:"all 0.15s"},children:[n.jsx(G.NtdCircle,{size:8,style:{color:N.css}})," ",N.label]},N.value)})}),n.jsxs("form",{onSubmit:g,style:{display:"flex",gap:6,marginBottom:8},children:[n.jsx("input",{type:"text",value:o,onChange:N=>b(N.target.value),placeholder:i("playlistManager.searchPlaceholder","Search tracks, artists, albums..."),style:{flex:1,padding:"6px 12px",borderRadius:8,border:"1px solid var(--nice-border-color, #d1d5db)",background:"var(--nice-input-bg, #fff)",color:"var(--nice-text-primary, #1f2937)",fontSize:"0.82rem"}}),n.jsx("button",{type:"submit",disabled:o.trim().length<2||r,style:{padding:"6px 14px",borderRadius:8,border:"none",background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.82rem",cursor:"pointer",opacity:o.trim().length<2?.5:1},"aria-label":i("playlistManager.search","Search"),children:r?n.jsx(G.NtdClock,{size:14}):n.jsx(G.NtdSearch,{size:14})})]}),t.length>0&&n.jsxs("div",{children:[n.jsxs("div",{style:{display:"flex",gap:6,marginBottom:4,alignItems:"center"},children:[n.jsxs("label",{style:{fontSize:"0.72rem",display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:h.size===t.length&&t.length>0,onChange:v}),i("playlistManager.selectAll","Select all")]}),n.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[t.length," ",i("playlistManager.results","results")]}),n.jsx("div",{style:{flex:1}}),h.size>0&&n.jsxs("button",{onClick:k,style:{padding:"3px 10px",borderRadius:6,border:"none",background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.72rem",cursor:"pointer"},children:[n.jsx(G.NtdPlus,{size:12})," ",i("playlistManager.addSelected","Add selected")," (",h.size,")"]})]}),n.jsx("div",{style:{maxHeight:300,overflowY:"auto",borderRadius:6,border:"1px solid var(--nice-border-color, #e5e7eb)"},children:t.map(N=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:"1px solid var(--nice-border-color, #f3f4f6)",background:h.has(N.id)?"var(--nice-accent-tint-10, #eff6ff)":"transparent",cursor:"pointer",fontSize:"0.78rem"},onClick:()=>S(N.id),children:[n.jsx("input",{type:"checkbox",checked:h.has(N.id),readOnly:!0}),T(N.source),N.imageUrl&&n.jsx("img",{src:N.imageUrl,alt:N.title||i("common.coverArt","Cover art"),style:{width:28,height:28,borderRadius:4,objectFit:"cover"}}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:N.title}),n.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[N.artist,N.album?` — ${N.album}`:""]})]}),n.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:M(N.duration)}),s&&n.jsx("button",{onClick:j=>{j.stopPropagation(),s(N)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem"},title:i("playlistManager.preview","Preview"),"aria-label":i("playlistManager.preview","Preview"),children:n.jsx(G.NtdPlay,{size:14})})]},N.id))})]}),r&&n.jsxs("div",{style:{textAlign:"center",padding:20,opacity:.5,fontSize:"0.82rem"},children:[n.jsx(G.NtdClock,{size:14})," ",i("playlistManager.searching","Searching"),"..."]}),!r&&o.trim().length>=2&&t.length===0&&n.jsx("div",{style:{textAlign:"center",padding:20,opacity:.4,fontSize:"0.82rem"},children:i("playlistManager.noResults","No results")})]})]})},Rf=[{value:1,label:"Spotify",icon:n.jsx(G.NtdMusic,{size:16}),color:"var(--source-spotify, #1db954)"},{value:2,label:"Tidal",icon:n.jsx(G.NtdMusic,{size:16}),color:"var(--source-tidal, #000000)"},{value:3,label:"Apple Music",icon:n.jsx(G.NtdMusic,{size:16}),color:"var(--source-apple, #fa243c)"},{value:4,label:"YouTube",icon:n.jsx(G.NtdMusic,{size:16}),color:"var(--source-youtube, #ff0000)"},{value:99,label:"Manual Paste",icon:n.jsx(G.NtdMusic,{size:16}),color:"var(--source-manual, #6366f1)"}],Nf={display:"flex",flexDirection:"column",gap:16,padding:24,borderRadius:12,background:"var(--nice-bg-primary, #ffffff)",border:"1px solid var(--nice-border, #e2e8f0)",maxWidth:640,minHeight:400},Tf={display:"flex",justifyContent:"space-between",alignItems:"center"},$f={display:"flex",gap:4,marginBottom:8},Ln={padding:"8px 20px",borderRadius:6,border:"none",background:"var(--nice-color-accent, #6366f1)",color:"var(--nice-text-on-primary, #fff)",cursor:"pointer",fontWeight:600},sr={...Ln,background:"transparent",color:"var(--nice-text-primary, #334155)",border:"1px solid var(--nice-border, #e2e8f0)"},fi={padding:12,borderRadius:8,border:"1px solid var(--nice-border, #e2e8f0)",cursor:"pointer",transition:"border-color 0.15s"},Tl=["connect","browse","tracks","options","importing","done"];function Pf(e){return Tl.indexOf(e)}function Ef(e){if(!e)return"--:--";const t=Math.floor(e/60),r=Math.floor(e%60);return`${t}:${r.toString().padStart(2,"0")}`}const $l=({connections:e=[],onConnect:t=()=>{},onDisconnect:r=()=>{},onFetchPlaylists:a=async()=>[],onFetchTracks:s=async()=>[],onImport:i=async()=>({playlistName:"",imported:0,skipped:0,failed:0,failedTracks:[]}),onClose:o=()=>{},targetFolders:l,sources:c})=>{const{t:d}=Pe(),[h,f]=u.useState("connect"),[p,y]=u.useState(null),[m,x]=u.useState([]),[b,g]=u.useState(null),[S,v]=u.useState([]),[k,M]=u.useState(new Set),[T,N]=u.useState(!1),[j,R]=u.useState(null),[z,A]=u.useState(null),[$,O]=u.useState(null),[I,U]=u.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[J,_]=u.useState(""),W=u.useMemo(()=>new Set(e.filter(Z=>Z.connected).map(Z=>Z.platform)),[e]),K=u.useCallback(Z=>e.find(H=>H.platform===Z),[e]),re=u.useCallback(Z=>{if(y(Z),Z===99){f("tracks"),_(""),v([]),N(!1);return}W.has(Z)?(f("browse"),N(!0),O(null),a(Z).then(H=>{x(H),N(!1)}).catch(H=>{O(String(H)),N(!1)})):t(Z)},[W,t,a]),X=u.useCallback(Z=>{g(Z),f("tracks"),N(!0),O(null),s(Z).then(H=>{v(H),M(new Set(H.map(se=>se.externalId))),N(!1)}).catch(H=>{O(String(H)),N(!1)})},[s]),q=u.useCallback(Z=>{M(H=>{const se=new Set(H);return se.has(Z)?se.delete(Z):se.add(Z),se})},[]),E=u.useCallback(()=>{M(Z=>Z.size===S.length?new Set:new Set(S.map(H=>H.externalId)))},[S]),P=u.useCallback(async()=>{if(!b)return;const Z=S.filter(H=>k.has(H.externalId));if(Z.length!==0){f("importing"),R({total:Z.length,imported:0,skipped:0,failed:0}),O(null);try{const H=await i(b,Z,I),se=H&&typeof H=="object"&&"imported"in H?H:{playlistName:b.name,imported:Z.length,skipped:0,failed:0,failedTracks:[]};A(se),f("done")}catch(H){O(String(H)),f("options")}}},[b,S,k,I,i]),C=h!=="connect"&&h!=="importing"&&h!=="done",L=u.useCallback(()=>{switch(h){case"browse":f("connect");break;case"tracks":f("browse");break;case"options":f("tracks");break}},[h]),w=()=>n.jsx("div",{style:$f,children:Tl.map((Z,H)=>n.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:H<=Pf(h)?"var(--nice-color-accent, #6366f1)":"var(--nice-border, #e2e8f0)",transition:"background 0.2s"}},Z))}),D=()=>n.jsxs("div",{style:{display:"grid",gap:12},children:[n.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.selectPlatform","Select a music platform to import from")}),Rf.map(Z=>{const H=K(Z.value),se=W.has(Z.value);return n.jsxs("div",{style:{...fi,display:"flex",alignItems:"center",gap:12,borderColor:se?Z.color:void 0},onClick:()=>re(Z.value),role:"button",tabIndex:0,onKeyDown:ae=>ae.key==="Enter"&&re(Z.value),children:[n.jsx("span",{style:{color:Z.color,display:"inline-flex"},"aria-hidden":"true",children:Z.icon}),n.jsxs("div",{style:{flex:1},children:[n.jsx("strong",{children:Z.label}),(H==null?void 0:H.username)&&n.jsx("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:H.username})]}),se?n.jsxs("span",{style:{color:Z.color,fontSize:12,fontWeight:600},children:[d("importWizard.connected","Connected")," ",n.jsx(G.NtdCheck,{size:12})]}):n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.clickToConnect","Click to connect")})]},Z.value)})]}),F=()=>n.jsxs("div",{style:{display:"grid",gap:12},children:[n.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.selectPlaylist","Select a playlist to import")}),T?n.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.loading","Loading playlists…")}):n.jsxs("div",{style:{display:"grid",gap:8,maxHeight:320,overflowY:"auto"},children:[m.map(Z=>n.jsxs("div",{style:{...fi,display:"flex",alignItems:"center",gap:12},onClick:()=>X(Z),role:"button",tabIndex:0,onKeyDown:H=>H.key==="Enter"&&X(Z),children:[Z.coverUrl&&n.jsx("img",{src:Z.coverUrl,alt:"",style:{width:48,height:48,borderRadius:6,objectFit:"cover"}}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Z.name}),Z.description&&n.jsx("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Z.description})]}),n.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)",whiteSpace:"nowrap"},children:[Z.trackCount," ",d("importWizard.tracks","tracks")]})]},Z.id)),m.length===0&&n.jsx("div",{style:{textAlign:"center",padding:24,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.noPlaylists","No playlists found")})]})]}),B=u.useCallback(Z=>{const se=Z.split(`
|
|
69
|
-
`).map(
|
|
68
|
+
OR: Artist;Title;Version`),rows:3,style:{width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:8,fontFamily:"inherit"}}),r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:6},children:[r.jsx("div",{style:{color:"var(--nice-text-secondary, #6b7280)",fontSize:12},children:h("genericPlaylist.bulkPasteHint","Each line will be added as a separate song.")}),r.jsx("button",{type:"button",onClick:H,disabled:!m.trim(),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},children:h("genericPlaylist.addFromList","Add from list")})]})]})]})})]})},vl={music:O.NtdMusic,microphone:O.NtdMicrophone,volume:O.NtdVolume,wave:O.NtdWave,megaphone:O.NtdMegaphone,star:O.NtdStar,heart:O.NtdHeart,lightning:O.NtdLightning,sparkle:O.NtdSparkle,moon:O.NtdMoon,sun:O.NtdSun,mountain:O.NtdMountain,trophy:O.NtdTrophy,crown:O.NtdCrown,target:O.NtdTarget,pin:O.NtdPin},bf=Object.keys(vl),Sa=({icon:e,size:t=14})=>{if(!e)return null;const n=vl[e];return n?r.jsx(n,{size:t}):r.jsx("span",{children:e})},ai=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #f59e0b)","var(--nice-warning, #eab308)","var(--nice-success, #84cc16)","var(--nice-success, #22c55e)","var(--nice-info, #14b8a6)","var(--nice-info, #06b6d4)","var(--nice-primary, #3b82f6)","var(--nice-info, #6366f1)","var(--nice-accent, #8b5cf6)","var(--nice-accent, #a855f7)","var(--nice-color-accent-pink, #d946ef)","var(--nice-color-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)","var(--nice-text-muted, #78716c)","var(--nice-text-secondary, #64748b)","var(--nice-text, #000000)"],rr=bf,xf=({tags:e,onCreateTag:t,onUpdateTag:n,onDeleteTag:a,selectedTracks:s,onAssignTag:i,onUnassignTag:o})=>{const{t:l}=be(),[c,d]=u.useState(null),[h,p]=u.useState(""),[g,y]=u.useState(ai[8]),[m,x]=u.useState(rr[0]),[v,f]=u.useState(!1),[k,b]=u.useState(null),[w,N]=u.useState(""),[$,M]=u.useState(""),[E,R]=u.useState(""),L=u.useCallback(D=>{d(D.id),N(D.name),M(D.color),R(D.icon||rr[0])},[]),A=u.useCallback(()=>{c&&w.trim()&&(n(c,w.trim(),$,E),d(null))},[c,w,$,E,n]),z=u.useCallback(()=>{h.trim()&&(t(h.trim(),g,m),p(""),f(!1))},[h,g,m,t]),j=u.useCallback(D=>{k===D?(a(D),b(null)):(b(D),setTimeout(()=>b(null),3e3))},[k,a]),I=s&&s.length>0,Y=D=>!s||s.length===0?!1:s.every(V=>V.tags.includes(D)),H=D=>!s||s.length===0?!1:s.some(V=>V.tags.includes(D))&&!Y(D);return r.jsxs("div",{style:{border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:10,background:"var(--nice-bg-elevated, #fff)",overflow:"hidden"},children:[r.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",display:"flex",alignItems:"center",gap:8,background:"var(--nice-color-surface, #f9fafb)"},children:[r.jsx(O.NtdTag,{size:16}),r.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:l("playlistManager.tagManager","Tag manager")}),r.jsx("div",{style:{flex:1}}),r.jsxs("button",{onClick:()=>f(!v),style:{background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"4px 10px",fontSize:"0.72rem",cursor:"pointer"},children:["+ ",l("playlistManager.newTag","New tag")]})]}),r.jsxs("div",{style:{padding:12},children:[v&&r.jsxs("div",{style:{border:"1px solid var(--nice-border-color, #d1d5db)",borderRadius:8,padding:10,marginBottom:12,background:"var(--nice-color-surface, #f9fafb)"},children:[r.jsxs("div",{style:{display:"flex",gap:6,marginBottom:8},children:[r.jsx("input",{type:"text",value:h,onChange:D=>p(D.target.value),placeholder:l("playlistManager.tagName","Tag name"),style:{flex:1,padding:"5px 10px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",fontSize:"0.8rem",background:"var(--nice-input-bg, #fff)",color:"var(--nice-text-primary, #1f2937)"},onKeyDown:D=>D.key==="Enter"&&z()}),r.jsx("button",{onClick:z,disabled:!h.trim(),style:{background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"5px 12px",fontSize:"0.78rem",cursor:"pointer",opacity:h.trim()?1:.5},"aria-label":l("playlistManager.createTag","Create tag"),children:r.jsx(O.NtdCheck,{size:14})})]}),r.jsxs("div",{style:{marginBottom:6},children:[r.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.color","Color")}),r.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:ai.map(D=>r.jsx("div",{onClick:()=>y(D),style:{width:20,height:20,borderRadius:"50%",background:D,cursor:"pointer",border:g===D?"3px solid var(--nice-color-accent, #3b82f6)":"2px solid transparent",boxSizing:"border-box"}},D))})]}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.icon","Icon")}),r.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:rr.map(D=>r.jsx("div",{onClick:()=>x(D),style:{width:26,height:26,borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"0.85rem",background:m===D?"var(--nice-accent-tint-10, #eff6ff)":"transparent",border:m===D?"1px solid var(--nice-color-accent, #3b82f6)":"1px solid transparent"},children:r.jsx(Sa,{icon:D,size:16})},D))})]})]}),I&&r.jsx("div",{style:{padding:"6px 10px",background:"var(--nice-accent-tint-10, #eff6ff)",borderRadius:6,marginBottom:8,fontSize:"0.72rem",color:"var(--nice-color-accent, #3b82f6)"},children:l("playlistManager.bulkTagHint","Click a tag to apply it to the selected tracks")+": "+s.length}),e.length===0?r.jsx("div",{style:{textAlign:"center",padding:20,opacity:.3,fontSize:"0.82rem"},children:l("playlistManager.noTags","No tags yet")}):r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.map(D=>r.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderRadius:8,border:"1px solid var(--nice-border-color, #e5e7eb)",background:c===D.id?"var(--nice-color-surface, #f9fafb)":"transparent"},children:c===D.id?r.jsxs(r.Fragment,{children:[r.jsx("select",{value:E,onChange:V=>R(V.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:rr.map(V=>r.jsx("option",{value:V,children:V},V))}),r.jsx("input",{type:"color",value:$,onChange:V=>M(V.target.value),style:{width:24,height:24,border:"none",cursor:"pointer",padding:0}}),r.jsx("input",{type:"text",value:w,onChange:V=>N(V.target.value),style:{flex:1,padding:"3px 8px",borderRadius:4,border:"1px solid var(--nice-border-color, #d1d5db)",fontSize:"0.78rem",background:"var(--nice-input-bg, #fff)",color:"var(--nice-text-primary, #1f2937)"},onKeyDown:V=>V.key==="Enter"&&A()}),r.jsx("button",{onClick:A,style:ar("var(--nice-color-accent, #3b82f6)"),"aria-label":l("common.save","Save"),children:r.jsx(O.NtdCheck,{size:14})}),r.jsx("button",{onClick:()=>d(null),style:ar("var(--nice-text-secondary, #9ca3af)"),"aria-label":l("common.cancel","Cancel"),children:r.jsx(O.NtdClose,{size:14})})]}):r.jsxs(r.Fragment,{children:[r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 10px",borderRadius:20,background:`${D.color}18`,color:D.color,fontWeight:600,fontSize:"0.78rem"},children:[r.jsx(Sa,{icon:D.icon,size:12}),D.name]}),I&&i&&o&&r.jsx("input",{type:"checkbox",checked:Y(D.id),ref:V=>{V&&(V.indeterminate=H(D.id))},onChange:()=>{const V=s.map(Z=>Z.id);Y(D.id)?o(V,D.id):i(V,D.id)},style:{cursor:"pointer"}}),r.jsx("div",{style:{flex:1}}),r.jsx("button",{onClick:()=>L(D),style:ar("var(--nice-text-secondary, #9ca3af)"),title:l("playlistManager.editTag","Edit tag"),"aria-label":l("playlistManager.editTag","Edit tag"),children:r.jsx(O.NtdEdit,{size:14})}),r.jsx("button",{onClick:()=>j(D.id),style:ar(k===D.id?"var(--nice-color-error, #ef4444)":"var(--nice-text-secondary, #9ca3af)"),title:k===D.id?l("playlistManager.confirmDelete","Click again to delete"):l("playlistManager.deleteTag","Delete tag"),"aria-label":k===D.id?l("playlistManager.confirmDelete","Click again to delete"):l("playlistManager.deleteTag","Delete tag"),children:r.jsx(O.NtdTrash,{size:14})})]})},D.id))})]})]})},ar=e=>({background:"none",border:"none",cursor:"pointer",fontSize:"0.82rem",color:e,padding:"2px 4px"});var Ja=(e=>(e.Static="static",e.Dynamic="dynamic",e))(Ja||{}),bl=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(bl||{}),xl=(e=>(e.Left="left",e.Right="right",e))(xl||{}),lt=(e=>(e.Artist="artist",e.Title="title",e.Album="album",e.Genre="genre",e.Year="year",e.Duration="duration",e.Rating="rating",e.PlayCount="playCount",e.Tag="tag",e.Source="source",e.AddedDate="addedDate",e))(lt||{}),ct=(e=>(e.Equals="eq",e.NotEquals="neq",e.Contains="contains",e.NotContains="notContains",e.StartsWith="startsWith",e.GreaterThan="gt",e.LessThan="lt",e.Between="between",e.In="in",e.NotIn="notIn",e))(ct||{}),Sl=(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))(Sl||{}),dn=(e=>(e.Asc="asc",e.Desc="desc",e))(dn||{}),St=(e=>(e.Library="library",e.Spotify="spotify",e.Tidal="tidal",e.YouTube="youtube",e.MusicBrainz="musicbrainz",e.Import="import",e.Manual="manual",e))(St||{});const Sf="_editor_qz5p3_5",kf="_heading_qz5p3_19",wf="_hint_qz5p3_35",Cf="_group_qz5p3_49",jf="_groupOr_qz5p3_61",Mf="_groupShaded_qz5p3_67",Rf="_groupHeader_qz5p3_73",Nf="_groupHint_qz5p3_87",Tf="_groupActions_qz5p3_95",Pf="_rule_qz5p3_107",$f="_value_qz5p3_121",Ef="_value2_qz5p3_127",Af="_dash_qz5p3_133",If="_limit_qz5p3_141",Lf="_limitInput_qz5p3_159",it={editor:Sf,heading:kf,hint:wf,group:Cf,groupOr:jf,groupShaded:Mf,groupHeader:Rf,groupHint:Nf,groupActions:Tf,rule:Pf,value:$f,value2:Ef,dash:Af,limit:If,limitInput:Lf},_f=[{value:lt.Artist,label:"Artist"},{value:lt.Title,label:"Title"},{value:lt.Album,label:"Album"},{value:lt.Genre,label:"Genre"},{value:lt.Year,label:"Year"},{value:lt.Duration,label:"Duration (s)"},{value:lt.Rating,label:"Rating"},{value:lt.PlayCount,label:"Play Count"},{value:lt.Tag,label:"Tag"},{value:lt.Source,label:"Source"},{value:lt.AddedDate,label:"Added Date"}],zf=[{value:ct.Equals,label:"="},{value:ct.NotEquals,label:"≠"},{value:ct.Contains,label:"contains"},{value:ct.NotContains,label:"not contains"},{value:ct.StartsWith,label:"starts with"},{value:ct.GreaterThan,label:">"},{value:ct.LessThan,label:"<"},{value:ct.Between,label:"between"},{value:ct.In,label:"in"},{value:ct.NotIn,label:"not in"}];function Df(e){return"logic"in e&&"rules"in e}function ka(){return{id:we.createId(),field:lt.Artist,operator:ct.Contains,value:""}}function kl(){return{id:we.createId(),logic:"and",rules:[ka()]}}const Ff=({rule:e,onChange:t,onRemove:n})=>{const{t:a}=be();return r.jsxs("div",{className:it.rule,children:[r.jsx(ie.NiceSelect,{size:"sm",controlWidth:150,"aria-label":a("playlistManager.ruleField","Field"),value:e.field,onChange:s=>t({...e,field:Pt(s)}),options:_f.map(s=>({value:s.value,label:a(`playlistManager.field.${s.value}`,s.label)}))}),r.jsx(ie.NiceSelect,{size:"sm",controlWidth:150,"aria-label":a("playlistManager.ruleOperator","Operator"),value:e.operator,onChange:s=>t({...e,operator:Pt(s)}),options:zf.map(s=>({value:s.value,label:a(`playlistManager.op.${s.value}`,s.label)}))}),r.jsx(ie.NiceTextInput,{size:"sm",className:it.value,"aria-label":a("playlistManager.ruleValue","Value"),placeholder:a("playlistManager.ruleValue","Value"),value:e.value,onChange:s=>t({...e,value:s})}),e.operator===ct.Between&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:it.dash,"aria-hidden":"true",children:"–"}),r.jsx(ie.NiceTextInput,{size:"sm",className:it.value2,"aria-label":a("playlistManager.ruleValue2","Value 2"),placeholder:a("playlistManager.ruleValue2","Value 2"),value:e.value2??"",onChange:s=>t({...e,value2:s})})]}),r.jsx(ie.NiceButton,{size:"sm",variant:"ghost",leftIcon:r.jsx(O.NtdClose,{size:14}),ariaLabel:a("playlistManager.removeRule","Remove rule"),title:a("playlistManager.removeRule","Remove rule"),onClick:n,children:null})]})},wl=({group:e,onChange:t,onRemove:n,depth:a=0})=>{const{t:s}=be(),i=u.useCallback((p,g)=>{const y=[...e.rules];y[p]=g,t({...e,rules:y})},[e,t]),o=u.useCallback(p=>{const g=e.rules.filter((y,m)=>m!==p);t({...e,rules:g.length>0?g:[ka()]})},[e,t]),l=u.useCallback(()=>{t({...e,rules:[...e.rules,ka()]})},[e,t]),c=u.useCallback(()=>{t({...e,rules:[...e.rules,kl()]})},[e,t]),d=u.useCallback(()=>{t({...e,logic:e.logic==="and"?"or":"and"})},[e,t]),h=e.logic==="and";return r.jsxs("div",{className:`${it.group} ${h?"":it.groupOr} ${a%2===0?it.groupShaded:""}`,children:[r.jsxs("div",{className:it.groupHeader,children:[r.jsx(ie.NiceButton,{size:"sm",variant:h?"primary":"warning",onClick:d,title:s("playlistManager.toggleLogic","Toggle AND/OR"),children:h?s("playlistManager.logicAnd","AND"):s("playlistManager.logicOr","OR")}),r.jsx("span",{className:it.groupHint,children:h?s("playlistManager.matchAllRules","Match all of these rules"):s("playlistManager.matchAnyRule","Match any of these rules")}),r.jsxs("div",{className:it.groupActions,children:[r.jsx(ie.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(O.NtdPlus,{size:14}),onClick:l,title:s("playlistManager.addRuleHint","Add rule"),children:s("playlistManager.addRule","Rule")}),a<3&&r.jsx(ie.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(O.NtdPlus,{size:14}),onClick:c,title:s("playlistManager.addGroupHint","Add nested group"),children:s("playlistManager.addGroup","Group")}),n&&r.jsx(ie.NiceButton,{size:"sm",variant:"ghost",leftIcon:r.jsx(O.NtdClose,{size:14}),ariaLabel:s("playlistManager.removeGroup","Remove group"),title:s("playlistManager.removeGroup","Remove group"),onClick:n,children:null})]})]}),e.rules.map((p,g)=>Df(p)?r.jsx(wl,{group:p,onChange:y=>i(g,y),onRemove:()=>o(g),depth:a+1},p.id):r.jsx(Ff,{rule:p,onChange:y=>i(g,y),onRemove:()=>o(g)},p.id))]})},Of=({rules:e,onChange:t,limit:n,onLimitChange:a})=>{const{t:s}=be(),[i]=u.useState(kl),o=e??i;return r.jsxs("div",{className:it.editor,children:[r.jsxs("h6",{className:it.heading,children:[r.jsx(O.NtdRepeat,{size:14})," ",s("playlistManager.dynamicRules","Dynamic Playlist Rules")]}),r.jsx("p",{className:it.hint,children:s("playlistManager.dynamicRulesHint","Tracks matching these rules will automatically be included in the playlist.")}),r.jsx(wl,{group:o,onChange:t}),a&&r.jsx("div",{className:it.limit,children:r.jsx(ie.NiceNumberInput,{size:"sm",className:it.limitInput,label:s("playlistManager.maxTracksLabel","Max tracks"),min:1,step:1,value:n??null,onChange:l=>a(l===null||l<=0?void 0:Math.round(l)),helperText:s("playlistManager.leaveEmptyForAllHint","Leave empty for unlimited")})})]})},si=e=>{if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`},Bf={spotify:"var(--source-spotify, #1db954)",tidal:"var(--source-tidal, #000000)",youtube:"var(--source-youtube, #ff0000)",musicbrainz:"var(--source-musicbrainz, #ba478f)"},Gf=({source:e})=>{if(e==="import")return r.jsx(O.NtdDownload,{size:12});if(e==="manual")return r.jsx(O.NtdEdit,{size:12});const t=Bf[e];return t?r.jsx(O.NtdCircle,{size:10,style:{color:t}}):r.jsx(O.NtdMusic,{size:12})},Cl=({tracks:e,tags:t,selectedTrackIds:n,onSelectionChange:a,onPlay:s,onRemove:i,onReorder:o,onTagTracks:l,onRateTracks:c,sortField:d,sortDir:h,onSortChange:p,filterText:g,onFilterChange:y,compact:m=!1,draggable:x=!1,onDragStart:v,dropTarget:f=!1,onDrop:k})=>{const{t:b}=be(),[w,N]=u.useState(null),[$,M]=u.useState(null),E=u.useRef(null),R=u.useMemo(()=>{let C=e??[];if(g.trim()){const T=g.toLowerCase();C=C.filter(S=>{var F,K;return S.title.toLowerCase().includes(T)||S.artist.toLowerCase().includes(T)||((F=S.album)==null?void 0:F.toLowerCase().includes(T))||((K=S.genre)==null?void 0:K.toLowerCase().includes(T))})}return[...C].sort((T,S)=>{const F=h==="asc"?1:-1;switch(d){case"title":return F*T.title.localeCompare(S.title);case"artist":return F*T.artist.localeCompare(S.artist);case"album":return F*(T.album??"").localeCompare(S.album??"");case"duration":return F*((T.duration??0)-(S.duration??0));case"year":return F*((T.year??0)-(S.year??0));case"rating":return F*((T.rating??0)-(S.rating??0));case"addedDate":return F*(T.addedAt??"").localeCompare(S.addedAt??"");case"custom":return F*((T.customOrder??0)-(S.customOrder??0));default:return 0}})},[e,g,d,h]),L=u.useCallback((C,T)=>{const S=R[C];if(S){if(T.ctrlKey||T.metaKey){const F=new Set(n);F.has(S.id)?F.delete(S.id):F.add(S.id),a(F)}else if(T.shiftKey&&E.current!==null){const F=Math.min(E.current,C),K=Math.max(E.current,C),P=new Set(n);for(let B=F;B<=K;B++)P.add(R[B].id);a(P)}else a(new Set([S.id]));E.current=C}},[R,n,a]),A=u.useCallback(()=>{n.size===R.length?a(new Set):a(new Set(R.map(C=>C.id)))},[R,n,a]),z=({field:C,label:T,width:S})=>{const F=d===C;return r.jsxs("div",{style:{width:S,flex:S?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?p(C,h===dn.Asc?dn.Desc:dn.Asc):p(C,dn.Asc)},children:[T,F&&(h==="asc"?r.jsx(O.NtdArrowUp,{size:10}):r.jsx(O.NtdArrowDown,{size:10}))]})},j=u.useCallback((C,T)=>{const S=n.has(C.id)?Array.from(n):[C.id];T.dataTransfer.setData("trackIds",JSON.stringify(S)),T.dataTransfer.effectAllowed="move",v==null||v(S,T)},[n,v]),I=u.useCallback((C,T)=>{T.preventDefault(),T.dataTransfer.dropEffect="move",N(C)},[]),Y=u.useCallback((C,T)=>{T.preventDefault(),N(null);try{const S=T.dataTransfer.getData("trackIds");if(S&&o){const F=JSON.parse(S),K=R.filter(_=>!F.includes(_.id)),P=R.filter(_=>F.includes(_.id)),B=Math.min(C,K.length);K.splice(B,0,...P),o(K.map(_=>_.id))}}catch{}},[R,o]),H=u.useCallback(C=>{C.preventDefault(),N(null),k==null||k(C)},[k]),D=u.useMemo(()=>new Map(t.map(C=>[C.id,C])),[t]),V=C=>C.replace(/[^a-z0-9_-]/gi,"-"),Z=m?36:48,X={display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",color:"var(--nice-text-secondary, #6b7280)"},q=(C,T)=>({display:"flex",alignItems:"center",gap:8,padding:m?"4px 12px":"6px 12px",height:Z,cursor:"pointer",background:T?"var(--nice-color-accent-light, #dbeafe)":C?"var(--nice-selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--nice-border-light, #f3f4f6)",transition:"background 0.1s"}),G=R.length>0&&n.size===R.length;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:f?C=>{C.preventDefault(),C.dataTransfer.dropEffect="copy"}:void 0,onDrop:f?H:void 0,children:[r.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",display:"flex",gap:8,alignItems:"center"},children:[r.jsx("input",{type:"text",value:g,onChange:C=>y(C.target.value),placeholder:b("playlistManager.filterTracks","Filter tracks..."),style:{flex:1,fontSize:"0.82rem",padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",background:"var(--nice-input-bg, #f9fafb)",color:"var(--nice-text-primary, #1f2937)"}}),r.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[R.length,"/",(e??[]).length]}),n.size>0&&i&&r.jsxs("button",{style:{fontSize:"0.72rem",padding:"4px 8px",borderRadius:4,border:"1px solid var(--nice-color-error, #ef4444)",background:"transparent",color:"var(--nice-color-error, #ef4444)",cursor:"pointer"},onClick:()=>i(Array.from(n)),"aria-label":b("playlistManager.removeSelected","Remove selected"),children:[r.jsx(O.NtdTrash,{size:12})," ",n.size]})]}),r.jsxs("div",{style:X,children:[r.jsx("div",{style:{width:28},children:r.jsx("input",{type:"checkbox",checked:G,onChange:A,style:{cursor:"pointer"}})}),r.jsx("div",{style:{width:20},children:"#"}),!m&&r.jsx("div",{style:{width:44}}),r.jsx(z,{field:"title",label:b("playlistManager.colTitle","Title")}),r.jsx(z,{field:"artist",label:b("playlistManager.colArtist","Artist")}),!m&&r.jsx(z,{field:"album",label:b("playlistManager.colAlbum","Album")}),r.jsx(z,{field:"duration",label:b("playlistManager.colDuration","Duration"),width:60}),!m&&r.jsx(z,{field:"year",label:b("playlistManager.colYear","Year"),width:50}),r.jsx("div",{style:{width:30}})," ",!m&&r.jsx("div",{style:{width:60}})," ",r.jsx("div",{style:{width:24}})," "]}),r.jsxs("div",{style:{flex:1,overflow:"auto"},children:[R.length===0&&r.jsx("div",{style:{padding:24,textAlign:"center",opacity:.4,fontSize:"0.85rem"},children:e.length===0?b("playlistManager.emptyPlaylist","This playlist is empty"):b("playlistManager.noMatchingTracks","No tracks match the filter")}),R.map((C,T)=>{const S=n.has(C.id),F=w===T;return r.jsxs("div",{style:q(S,F),onClick:K=>L(T,K),onDoubleClick:()=>s==null?void 0:s(C),draggable:x,onDragStart:K=>j(C,K),onDragOver:K=>I(T,K),onDrop:K=>Y(T,K),onDragLeave:()=>N(null),children:[r.jsx("div",{style:{width:28},children:r.jsx("input",{type:"checkbox",checked:S,onChange:()=>{const K=new Set(n);S?K.delete(C.id):K.add(C.id),a(K)},onClick:K=>K.stopPropagation(),style:{cursor:"pointer"}})}),r.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:T+1}),!m&&r.jsx("div",{style:{width:44,height:36,flexShrink:0},children:C.coverUrl?r.jsx("img",{src:C.coverUrl,alt:C.title||b("common.coverArt","Cover art"),style:{width:36,height:36,borderRadius:4,objectFit:"cover"},loading:"lazy"}):r.jsx("div",{style:{width:36,height:36,borderRadius:4,background:"var(--nice-color-surface, #f3f4f6)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.9rem"},children:r.jsx(O.NtdMusic,{size:16})})}),r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",fontWeight:500},children:C.title}),r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",opacity:.7},children:C.artist}),!m&&r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",opacity:.5},children:C.album}),r.jsx("div",{style:{width:60,fontSize:"0.78rem",opacity:.5,textAlign:"right"},children:si(C.duration)}),!m&&r.jsx("div",{style:{width:50,fontSize:"0.72rem",opacity:.4,textAlign:"center"},children:C.year||""}),r.jsx("div",{style:{width:30,textAlign:"center",fontSize:"0.75rem"},title:C.source,children:r.jsx(Gf,{source:C.source})}),!m&&r.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[C.tags.slice(0,2).map(K=>{const P=D.get(K);if(!P)return null;const B=`--tag-${V(K)}`;return r.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${B}-bg, ${P.color}22)`,color:`var(${B}, ${P.color})`,whiteSpace:"nowrap"},children:P.name},K)}),C.tags.length>2&&r.jsxs("span",{style:{fontSize:"0.6rem",opacity:.4},children:["+",C.tags.length-2]})]}),r.jsxs("div",{style:{width:24,display:"flex",alignItems:"center"},children:[r.jsx("button",{style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:2,opacity:.5,position:"relative"},onClick:K=>{K.stopPropagation(),M($===C.id?null:C.id)},title:b("playlistManager.morActions","More actions"),"aria-label":b("playlistManager.morActions","More actions"),children:r.jsx(O.NtdTag,{size:12})}),$===C.id&&t.length>0&&r.jsxs("div",{style:{position:"absolute",right:12,marginTop:4,background:"var(--nice-bg-elevated, #fff)",border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:8,padding:8,zIndex:100,boxShadow:"0 4px 12px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",minWidth:140},children:[r.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:b("playlistManager.assignTag","Assign tag")}),t.map(K=>{const P=C.tags.includes(K.id);return r.jsxs("div",{style:{padding:"4px 8px",borderRadius:4,cursor:"pointer",fontSize:"0.78rem",display:"flex",alignItems:"center",gap:6,background:P?`var(--tag-${V(K.id)}-bg, ${K.color}22)`:"transparent"},onClick:B=>{B.stopPropagation();const _=n.size>0?Array.from(n):[C.id];P||l==null||l(_,[K.id]),M(null)},children:[r.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:`var(--tag-${V(K.id)}, ${K.color})`,flexShrink:0}}),r.jsx("span",{children:K.name}),P&&r.jsx(O.NtdCheck,{size:12,style:{marginLeft:"auto"}})]},K.id)})]})]})]},C.id)})]}),r.jsxs("div",{style:{padding:"6px 12px",borderTop:"1px solid var(--nice-border-color, #e5e7eb)",fontSize:"0.72rem",opacity:.5,display:"flex",gap:16},children:[r.jsxs("span",{children:[R.length," ",b("playlistManager.tracks","tracks")]}),r.jsx("span",{children:si(R.reduce((C,T)=>C+(T.duration??0),0))}),n.size>0&&r.jsxs("span",{children:[n.size," ",b("playlistManager.selected","selected")]})]})]})},ii=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),Wf=({playlists:e=[],tags:t=[],onCopyTracks:n=()=>{},onMoveTracks:a=()=>{},onRemoveTracks:s=()=>{},onReorderTracks:i=()=>{},onPlay:o=()=>{},onTagTracks:l=()=>{},initialLeftId:c,initialRightId:d})=>{const{t:h}=be(),[p,g]=u.useState(()=>ii(c??null)),[y,m]=u.useState(()=>ii(d??null)),[x,v]=u.useState("left"),[f,k]=u.useState(null),[b,w]=u.useState(50),[N,$]=u.useState(!1),M=u.useMemo(()=>e.find(G=>G.id===p.playlistId),[e,p.playlistId]),E=u.useMemo(()=>e.find(G=>G.id===y.playlistId),[e,y.playlistId]),R=u.useCallback((G,C)=>{G==="left"?g(T=>({...T,...C})):m(T=>({...T,...C}))},[]),L=u.useCallback(G=>G==="left"?p:y,[p,y]),A=G=>G==="left"?"right":"left",z=u.useCallback(G=>{const C=L(G),T=L(A(G));!C.playlistId||!T.playlistId||C.selectedTrackIds.size===0||(n(C.playlistId,T.playlistId,Array.from(C.selectedTrackIds)),R(G,{selectedTrackIds:new Set}))},[L,n,R]),j=u.useCallback(G=>{const C=L(G),T=L(A(G));!C.playlistId||!T.playlistId||C.selectedTrackIds.size===0||(a(C.playlistId,T.playlistId,Array.from(C.selectedTrackIds)),R(G,{selectedTrackIds:new Set}))},[L,a,R]),I=u.useCallback(G=>{const C=L(G);!C.playlistId||C.selectedTrackIds.size===0||k({operation:"copy",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[L]),Y=u.useCallback(G=>{const C=L(G);!C.playlistId||C.selectedTrackIds.size===0||k({operation:"cut",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[L]),H=u.useCallback(G=>{const C=L(G);!f||!C.playlistId||(f.operation==="copy"?n(f.sourcePlaylistId,C.playlistId,f.trackIds):a(f.sourcePlaylistId,C.playlistId,f.trackIds),k(null))},[f,L,n,a]),D=u.useCallback(G=>{G.key==="Tab"&&!G.shiftKey&&(G.preventDefault(),v(C=>A(C))),(G.ctrlKey||G.metaKey)&&G.key==="c"&&I(x),(G.ctrlKey||G.metaKey)&&G.key==="x"&&Y(x),(G.ctrlKey||G.metaKey)&&G.key==="v"&&H(x)},[x,I,Y,H]),V=u.useCallback(()=>$(!0),[]),Z=u.useCallback(G=>{if(!N)return;const C=G.currentTarget.getBoundingClientRect(),T=(G.clientX-C.left)/C.width*100;w(Math.max(20,Math.min(80,T)))},[N]),X=u.useCallback(()=>$(!1),[]),q=G=>{const C=L(G),T=G==="left"?M:E,S=x===G,K=!!L(A(G)).playlistId;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",border:S?"2px solid var(--nice-color-accent, #3b82f6)":"2px solid transparent",borderRadius:8,overflow:"hidden",background:"var(--nice-bg-elevated, #fff)"},onClick:()=>v(G),children:[r.jsx("div",{style:{padding:"8px 12px",background:S?"var(--nice-color-accent, #3b82f6)":"var(--nice-color-surface, #f3f4f6)",color:S?"var(--nice-text-on-accent, #fff)":"var(--nice-text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:r.jsxs("select",{value:C.playlistId??"",onChange:P=>R(G,{playlistId:P.target.value||null,selectedTrackIds:new Set}),style:{flex:1,fontSize:"0.82rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",background:S?"var(--nice-overlay-light-20, #ffffff30)":"var(--nice-input-bg, #fff)",color:S?"var(--nice-text-on-accent, #fff)":"var(--nice-text-primary, #1f2937)"},children:[r.jsx("option",{value:"",children:h("playlistManager.selectPlaylist","Select a playlist")}),e.map(P=>r.jsxs("option",{value:P.id,children:[P.name," (",P.trackCount,")"]},P.id))]})}),r.jsxs("div",{style:{display:"flex",gap:4,padding:"4px 8px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",flexWrap:"wrap"},children:[r.jsxs("button",{style:ra(!1),onClick:()=>z(G),disabled:!C.playlistId||!K||C.selectedTrackIds.size===0,title:h("playlistManager.copyToOther","Copy to the other playlist"),children:[G==="left"?r.jsxs(r.Fragment,{children:[r.jsx(O.NtdCopy,{size:12}),r.jsx(O.NtdChevronRight,{size:12})]}):r.jsxs(r.Fragment,{children:[r.jsx(O.NtdChevronLeft,{size:12}),r.jsx(O.NtdCopy,{size:12})]})," ",h("playlistManager.copy","Copy")]}),r.jsxs("button",{style:ra(!1),onClick:()=>j(G),disabled:!C.playlistId||!K||C.selectedTrackIds.size===0,title:h("playlistManager.moveToOther","Move to the other playlist"),children:[G==="left"?r.jsxs(r.Fragment,{children:[r.jsx(O.NtdMove,{size:12}),r.jsx(O.NtdChevronRight,{size:12})]}):r.jsxs(r.Fragment,{children:[r.jsx(O.NtdChevronLeft,{size:12}),r.jsx(O.NtdMove,{size:12})]})," ",h("playlistManager.move","Move")]}),r.jsx("div",{style:{flex:1}}),f&&r.jsxs("button",{style:ra(!0),onClick:()=>H(G),disabled:!C.playlistId,children:[r.jsx(O.NtdClipboard,{size:12})," ",h("playlistManager.paste","Paste")," (",f.trackIds.length,")"]})]}),T?r.jsx(Cl,{tracks:T.tracks,tags:t,selectedTrackIds:C.selectedTrackIds,onSelectionChange:P=>R(G,{selectedTrackIds:P}),onPlay:o,onRemove:P=>s(T.id,P),onReorder:P=>i(T.id,P),onTagTracks:l,sortField:C.sortField,sortDir:C.sortDir,onSortChange:(P,B)=>R(G,{sortField:P,sortDir:B}),filterText:C.filterText,onFilterChange:P=>R(G,{filterText:P}),compact:!0,draggable:!0}):r.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",opacity:.3,fontSize:"0.85rem"},children:h("playlistManager.selectPlaylistPrompt","Select a playlist to see its tracks")})]})};return r.jsxs("div",{style:{display:"flex",height:"100%",userSelect:N?"none":"auto"},onKeyDown:D,onMouseMove:Z,onMouseUp:X,tabIndex:0,children:[r.jsx("div",{style:{width:`${b}%`,minWidth:200},children:q("left")}),r.jsx("div",{style:{width:6,cursor:"col-resize",background:N?"var(--nice-color-accent, #3b82f6)":"var(--nice-border-color, #e5e7eb)",transition:N?"none":"background 0.15s",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseDown:V,children:r.jsx("div",{style:{width:2,height:40,borderRadius:1,background:N?"var(--nice-color-accent, #3b82f6)":"var(--nice-bg-tertiary, #9ca3af)"}})}),r.jsx("div",{style:{flex:1,minWidth:200},children:q("right")})]})},ra=e=>({background:e?"var(--nice-color-accent, #3b82f6)":"transparent",color:e?"var(--nice-text-on-accent, #fff)":"var(--nice-text-secondary, #6b7280)",border:e?"none":"1px solid var(--nice-border-color, #d1d5db)",borderRadius:6,padding:"3px 8px",fontSize:"0.72rem",cursor:"pointer",whiteSpace:"nowrap"}),jl="av:local-playlists";function Vf(){try{const e=localStorage.getItem(jl);return e?JSON.parse(e):[]}catch{return[]}}function Uf(e){const t=JSON.stringify(e);try{localStorage.setItem(jl,t)}catch{}}function es(){const[e,t]=u.useState(()=>Vf()),n=u.useRef(!1);return u.useEffect(()=>{n.current=!0},[]),u.useEffect(()=>{Uf(e)},[e]),u.useMemo(()=>({list:()=>e,get:s=>e.find(i=>i.id===s),create:s=>{const i=new Date().toISOString(),o={id:we.createId(),name:s,items:[],updatedAt:i};return t(l=>[o,...l]),o},rename:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,name:i,updatedAt:new Date().toISOString()}:l)),remove:s=>t(i=>i.filter(o=>o.id!==s)),replaceItems:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,items:i,updatedAt:new Date().toISOString()}:l)),addItems:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,items:[...l.items,...i],updatedAt:new Date().toISOString()}:l))}),[e])}const qf=ot.scoped("PlaylistList"),Hf={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,background:"var(--nice-bg, #fff)"},Kf=(function(){return{...Hf,padding:"8px 10px",cursor:"pointer"}})(),Ml={border:"1px solid var(--nice-border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg, #fff)",cursor:"pointer"},Yf=(function(){return{...Ml,background:"var(--nice-color-primary, #4f46e5)",borderColor:"var(--nice-color-primary, #4f46e5)",color:"var(--nice-text-on-primary, #fff)"}})(),ts=({selectedId:e,onSelect:t,onCreateRemote:n})=>{const{t:a}=be(),s=es(),[i,o]=u.useState(""),l=u.useMemo(()=>s.list(),[s]);return r.jsxs("div",{style:{display:"grid",gap:10},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("input",{placeholder:a("playlistList.playlistName","Playlist name..."),value:i,onChange:c=>o(c.target.value),style:{flex:1,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px"},"aria-label":a("playlistList.playlistName","Playlist name")}),r.jsxs("button",{type:"button",disabled:!i.trim(),style:i.trim()?Yf:{...Ml,cursor:"not-allowed",color:"var(--nice-text-muted, #9ca3af)",background:"var(--nice-bg-tertiary, #f3f4f6)"},onClick:async()=>{const c=s.create(i.trim());if(o(""),n)try{await n({platform:"tidal",name:c.name,songs:c.items})}catch(d){qf.error("Remote playlist create failed:",d)}t==null||t(c)},children:["+ ",a("common.add","Add")]})]}),r.jsxs("div",{style:{display:"grid",gap:6},children:[l.map(c=>{const d=c.id===e;return r.jsxs("button",{onClick:()=>t==null?void 0:t(c),style:{...Kf,background:d?"var(--nice-selected-bg, #eef2ff)":"var(--nice-bg, #fff)"},children:[r.jsx("div",{style:{fontWeight:600},children:c.name}),r.jsxs("div",{style:{color:"var(--nice-text-dim, #64748b)",fontSize:12},children:[c.items.length+" "+a("playlistList.songs","songs")," ","• ",new Date(c.updatedAt).toLocaleString()]})]},c.id)}),!l.length&&r.jsx("div",{style:{color:"var(--nice-text-muted, #6b7280)"},children:a("playlistList.emptyState","No playlists. Add the first one ↑")})]})]})},Zf=ot.scoped("PlaylistBrowser"),oi={display:"grid",gap:12},li=e=>({artist:(e.artists??[]).join(", "),title:e.title}),Xf=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:n,tracks:a,view:s,onSelect:i,onPlay:o})=>{var v;const{t:l}=be(),c=es(),[d,h]=u.useState(null),[p,g]=u.useState(""),[,y]=u.useState([]),m=d==null?void 0:d.id,x=(f,k)=>{if("addItems"in c){c.addItems(f.id,k);const w=c.list().find(N=>N.id===f.id)||f;h(w);return}const b=c;if("update"in c&&typeof b.update=="function"){const w=Array.from([...f.items||[],...k]);b.update({...f,items:w});const N=c.list().find($=>$.id===f.id)||{...f,items:w};h(N);return}Zf.warn("useLocalPlaylists: missing addItems/update method — update hook implementation.")};return r.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(min(200px, 100%), 320px) 1fr",gap:16},children:[r.jsxs("div",{style:oi,children:[r.jsx("h3",{style:{margin:0},children:l("playlistBrowser.playlists","Playlists")}),r.jsx(ts,{selectedId:m,onSelect:h}),d&&r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:[l("playlistBrowser.selected","Selected"),": ",r.jsx("strong",{children:d.name})," ·"," ",((v=d.items)==null?void 0:v.length)??0," ",l("playlistBrowser.tracks","tracks")]})]}),r.jsxs("div",{style:oi,children:[r.jsx("h3",{style:{margin:0},children:l("playlistBrowser.library","Library")}),r.jsxs("div",{children:[e==null?void 0:e({placeholder:l("playlistBrowser.searchAndAdd","Search and add to playlist..."),onSelect:f=>{d&&x(d,[li(f)])}}),r.jsx("input",{placeholder:l("playlistBrowser.fullSearch","Full search (Enter does not add, full list below)"),value:p,onChange:f=>g(f.target.value),style:{width:"100%",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px",marginTop:10}})]}),t==null?void 0:t({query:p,onSelect:f=>{d&&x(d,[li(f)])}}),n==null?void 0:n({onPlayNow:f=>y(f),onAddToQueue:f=>y(k=>[...k,...f]),onAddDescriptors:f=>d&&x(d,f)})]})]})};var Kt=(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))(Kt||{});const Rl=(e,t=null)=>e.filter(n=>n.parentId===t).sort((n,a)=>n.sortOrder-a.sortOrder).map(n=>({...n,children:Rl(e,n.id)})),Qf={[Kt.Spotify]:{label:"Spotify",color:"var(--source-spotify, #1DB954)",bg:"var(--source-spotify-bg, #1DB95418)"},[Kt.Tidal]:{label:"Tidal",color:"var(--source-tidal, #000000)",bg:"var(--source-tidal-bg, #00000010)"},[Kt.YouTube]:{label:"YouTube",color:"var(--source-youtube, #FF0000)",bg:"var(--source-youtube-bg, #FF000010)"}},Jf=({folders:e,playlists:t,tags:n,services:a,activeFolderId:s,activePlaylistId:i,onSelectFolder:o,onSelectPlaylist:l,onCreateFolder:c,onRenameFolder:d,onDeleteFolder:h,onCreatePlaylist:p,onConnectService:g,onDisconnectService:y,onDragPlaylistToFolder:m,collapsed:x=!1,onToggleCollapse:v})=>{const{t:f}=be(),[k,b]=u.useState(new Set),[w,N]=u.useState(!1),[$,M]=u.useState(""),[E,R]=u.useState(null),[L,A]=u.useState(!1),[z,j]=u.useState(""),[I,Y]=u.useState("static"),[H,D]=u.useState(null),[V,Z]=u.useState(""),[X,q]=u.useState(null),[G,C]=u.useState(!1),T=u.useMemo(()=>Rl(e),[e]),S=u.useCallback(te=>{b(he=>{const ue=new Set(he);return ue.has(te)?ue.delete(te):ue.add(te),ue})},[]),F=u.useCallback(()=>{$.trim()&&(c($.trim(),E),M(""),N(!1))},[$,E,c]),K=u.useCallback(()=>{z.trim()&&(p(z.trim(),I,s),j(""),A(!1))},[z,I,s,p]),P=u.useCallback(te=>{V.trim()&&(d(te,V.trim()),D(null),Z(""))},[V,d]),B=u.useCallback((te,he)=>{te.preventDefault(),te.dataTransfer.dropEffect="move",q(he)},[]),_=u.useCallback((te,he)=>{te.preventDefault();const ue=te.dataTransfer.getData("playlistId");ue&&m&&m(ue,he),q(null)},[m]),U=u.useCallback(()=>q(null),[]),J=u.useCallback(te=>t.filter(he=>(he.folderId??null)===te),[t]),se={width:x?48:280,minWidth:x?48:280,background:"var(--nice-bg-secondary, #f8f9fa)",borderRight:"1px solid var(--nice-border-color, #e5e7eb)",display:"flex",flexDirection:"column",transition:"width 0.2s, min-width 0.2s",overflow:"hidden",height:"100%"},oe={padding:"8px 12px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)"},re=(te,he=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:he?"var(--nice-color-accent-light, #dbeafe)":te?"var(--nice-color-accent, #3b82f6)":"transparent",color:te?"var(--btn-text, #fff)":"var(--nice-text-primary, #1f2937)",transition:"background 0.15s",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),W={background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:"2px 6px",borderRadius:4,color:"var(--nice-text-secondary, #6b7280)"},ee={fontSize:"0.8rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",background:"var(--nice-input-bg, #fff)",color:"var(--nice-text-primary, #1f2937)",width:"100%"},ae=(te,he)=>{var je,$e;const ue=k.has(te.id),xe=s===te.id,pe=X===te.id,Se=J(te.id);return r.jsxs("div",{children:[r.jsxs("div",{style:{...re(xe,pe),paddingLeft:12+he*16},onClick:()=>{o(te.id),te.children&&te.children.length>0&&S(te.id)},onDragOver:Te=>B(Te,te.id),onDrop:Te=>_(Te,te.id),onDragLeave:U,children:[r.jsx("span",{style:{width:14,textAlign:"center",flexShrink:0,fontSize:"0.7rem"},children:(((je=te.children)==null?void 0:je.length)||0)>0||Se.length>0?ue?r.jsx(O.NtdChevronDown,{size:10}):r.jsx(O.NtdChevronRight,{size:10}):null}),H===te.id?r.jsx("input",{value:V,onChange:Te=>Z(Te.target.value),onKeyDown:Te=>{Te.key==="Enter"&&P(te.id),Te.key==="Escape"&&D(null)},onBlur:()=>P(te.id),autoFocus:!0,style:{...ee,flex:1},onClick:Te=>Te.stopPropagation()}):r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{display:"inline-flex"},children:te.icon??r.jsx(O.NtdFolder,{size:14})}),r.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:te.name}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:Se.length}),r.jsx("button",{style:W,onClick:Te=>{Te.stopPropagation(),D(te.id),Z(te.name)},title:f("common.rename","Rename"),"aria-label":f("common.rename","Rename"),children:r.jsx(O.NtdEdit,{size:12})}),r.jsx("button",{style:{...W,color:"var(--nice-color-error, #ef4444)"},onClick:Te=>{Te.stopPropagation(),h(te.id)},title:f("common.delete","Delete"),"aria-label":f("common.delete","Delete"),children:r.jsx(O.NtdTrash,{size:12})})]})]}),ue&&r.jsxs(r.Fragment,{children:[Se.map(Te=>le(Te,he+1)),($e=te.children)==null?void 0:$e.map(Te=>ae(Te,he+1))]})]},te.id)},le=(te,he)=>{const ue=i===te.id;return r.jsxs("div",{style:{...re(ue),paddingLeft:12+he*16+22},onClick:()=>l(te.id),draggable:!0,onDragStart:xe=>{xe.dataTransfer.setData("playlistId",te.id),xe.dataTransfer.effectAllowed="move"},children:[r.jsx("span",{style:{display:"inline-flex"},children:te.type==="dynamic"?r.jsx(O.NtdLightning,{size:12}):r.jsx(O.NtdMusic,{size:12})}),r.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:te.name}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:te.trackCount})]},te.id)};if(x)return r.jsx("div",{style:se,children:r.jsx("button",{style:{...W,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:v,title:f("playlistManager.expandSidebar","Expand sidebar"),"aria-label":f("playlistManager.expandSidebar","Expand sidebar"),children:r.jsx(O.NtdChevronRight,{size:16})})});const ce=J(null);return r.jsxs("div",{style:se,children:[r.jsxs("div",{style:{...oe,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[r.jsxs("span",{style:{fontWeight:700,fontSize:"0.85rem",display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(O.NtdMusic,{size:14})," ",f("playlistManager.title","Playlists")]}),r.jsx("button",{style:W,onClick:v,title:f("playlistManager.collapseSidebar","Collapse sidebar"),"aria-label":f("playlistManager.collapseSidebar","Collapse sidebar"),children:r.jsx(O.NtdChevronLeft,{size:16})})]}),r.jsxs("div",{style:{...oe,display:"flex",gap:4,flexWrap:"wrap"},children:[r.jsxs("button",{style:{...W,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:6,padding:"4px 10px"},onClick:()=>A(!0),children:["+ ",f("playlistManager.newPlaylist","New playlist")]}),r.jsxs("button",{style:{...W,border:"1px solid var(--nice-border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{N(!0),R(s)},children:[r.jsx(O.NtdFolder,{size:12})," ",f("playlistManager.newFolder","New folder")]})]}),L&&r.jsxs("div",{style:{...oe,display:"flex",flexDirection:"column",gap:6},children:[r.jsx("input",{value:z,onChange:te=>j(te.target.value),placeholder:f("playlistManager.playlistName","Playlist name"),style:ee,autoFocus:!0,onKeyDown:te=>{te.key==="Enter"&&K(),te.key==="Escape"&&A(!1)}}),r.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[r.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[r.jsx("input",{type:"radio",checked:I==="static",onChange:()=>Y("static")}),f("playlistManager.static","Static")]}),r.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[r.jsx("input",{type:"radio",checked:I==="dynamic",onChange:()=>Y("dynamic")}),r.jsx(O.NtdLightning,{size:12})," ",f("playlistManager.dynamic","Dynamic")]}),r.jsx("div",{style:{flex:1}}),r.jsx("button",{style:{...W,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:K,"aria-label":f("playlistManager.confirmCreatePlaylist","Confirm create playlist"),children:r.jsx(O.NtdCheck,{size:12})}),r.jsx("button",{style:W,onClick:()=>A(!1),"aria-label":f("playlistManager.cancelCreatePlaylist","Cancel create playlist"),children:r.jsx(O.NtdClose,{size:12})})]})]}),w&&r.jsxs("div",{style:{...oe,display:"flex",gap:6},children:[r.jsx("input",{value:$,onChange:te=>M(te.target.value),placeholder:f("playlistManager.folderName","Folder name"),style:{...ee,flex:1},autoFocus:!0,onKeyDown:te=>{te.key==="Enter"&&F(),te.key==="Escape"&&N(!1)}}),r.jsx("button",{style:{...W,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:F,"aria-label":f("playlistManager.confirmCreateFolder","Confirm create folder"),children:r.jsx(O.NtdCheck,{size:12})}),r.jsx("button",{style:W,onClick:()=>N(!1),"aria-label":f("playlistManager.cancelCreateFolder","Cancel create folder"),children:r.jsx(O.NtdClose,{size:12})})]}),r.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[r.jsxs("div",{style:re(s===null&&i===null,X==="__root__"),onClick:()=>o(null),onDragOver:te=>B(te,null),onDrop:te=>_(te,null),onDragLeave:U,children:[r.jsx(O.NtdHome,{size:14}),r.jsx("span",{style:{flex:1},children:f("playlistManager.allPlaylists","All playlists")}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:t.length})]}),ce.map(te=>le(te,0)),T.map(te=>ae(te,0))]}),n.length>0&&r.jsxs("div",{style:oe,children:[r.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:f("playlistManager.tags","Tags")}),r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:n.map(te=>r.jsxs("span",{style:{fontSize:"0.7rem",padding:"2px 8px",borderRadius:12,background:te.color+"22",color:te.color,border:`1px solid ${te.color}44`,cursor:"pointer"},children:[r.jsx(Sa,{icon:te.icon,size:10}),te.icon?" ":"",te.name]},te.id))})]}),r.jsxs("div",{style:oe,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",cursor:"pointer",fontSize:"0.7rem",fontWeight:600,opacity:.6},onClick:()=>C(!G),children:[r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(O.NtdLink,{size:12})," ",f("playlistManager.services","Services")]}),G?r.jsx(O.NtdChevronUp,{size:12}):r.jsx(O.NtdChevronDown,{size:12})]}),G&&r.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[Kt.Spotify,Kt.Tidal,Kt.YouTube].map(te=>{const he=Qf[te],ue=a.find(xe=>xe.platform===te);return r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 8px",borderRadius:6,border:"1px solid var(--nice-border-color, #e5e7eb)",fontSize:"0.78rem"},children:[r.jsx(O.NtdCircle,{size:10,style:{color:he.color}}),r.jsx("span",{style:{flex:1},children:he.label}),ue!=null&&ue.connected?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{fontSize:"0.65rem",opacity:.6},children:ue.username??f("playlistManager.connected","Connected")}),r.jsx("button",{style:{...W,color:"var(--nice-danger, #ef4444)"},onClick:()=>y(te),"aria-label":f("playlistManager.disconnect","Disconnect"),children:r.jsx(O.NtdClose,{size:12})})]}):r.jsx("button",{style:{...W,background:he.color,color:"var(--nice-color-white, #fff)",borderRadius:4,padding:"2px 8px"},onClick:()=>g(te),children:f("playlistManager.connect","Connect")})]},te)})})]})]})},em=({playlist:e,tags:t,onPlay:n,selectedTrackIds:a,onSelectionChange:s})=>{const{t:i}=be(),o=u.useCallback(l=>{const c=new Set(a);c.has(l)?c.delete(l):c.add(l),s(c)},[a,s]);return e.tracks.length===0?r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:60,opacity:.3},children:[r.jsx("span",{style:{marginBottom:8,display:"inline-flex"},children:r.jsx(O.NtdMusic,{size:32})}),r.jsx("span",{style:{fontSize:"0.82rem"},children:i("playlistManager.emptyPlaylist","This playlist is empty")})]}):r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(160px, 1fr))",gap:10},children:e.tracks.map(l=>{const c=a.has(l.id);return r.jsxs("div",{onClick:()=>o(l.id),onDoubleClick:()=>n(l),style:{border:c?"2px solid var(--nice-color-accent, #3b82f6)":"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:10,padding:10,cursor:"pointer",background:c?"var(--nice-accent-tint-10, #eff6ff)":"var(--nice-bg-elevated, #fff)",transition:"all 0.12s"},children:[r.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:6,background:"linear-gradient(135deg, var(--playlist-track-bg1, #6366f140), var(--playlist-track-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"1.5rem",marginBottom:6},children:r.jsx(O.NtdMusic,{size:24})}),r.jsx("div",{style:{fontWeight:500,fontSize:"0.78rem",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.title}),r.jsx("div",{style:{fontSize:"0.68rem",opacity:.5,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.artist})]},l.id)})})},tm=u.memo(em),ci=e=>e.replace(/[^a-z0-9_-]/gi,"-"),di={background:"none",border:"none",cursor:"pointer",fontSize:"0.78rem",padding:"2px 4px",opacity:.4},nm=({playlists:e,folders:t,tags:n,activeFolderId:a,onSelectPlaylist:s,onDeletePlaylist:i,onDuplicatePlaylist:o})=>{const{t:l}=be(),c=u.useMemo(()=>a?e.filter(d=>d.folderId===a):e,[e,a]);return c.length===0?r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:60,opacity:.4},children:[r.jsx("span",{style:{marginBottom:12,display:"inline-flex"},children:r.jsx(O.NtdMusic,{size:40})}),r.jsx("span",{style:{fontSize:"0.85rem"},children:l("playlistManager.emptyState","No playlists yet")})]}):r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))",gap:12},children:c.map(d=>{var p;const h=t.find(g=>g.id===d.folderId);return r.jsxs("div",{onClick:()=>s(d.id),style:{border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:12,padding:16,cursor:"pointer",background:"var(--nice-bg-elevated, #fff)",transition:"box-shadow 0.15s, transform 0.15s"},onMouseEnter:g=>{g.currentTarget.style.boxShadow="0 4px 12px var(--nice-overlay-8, 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:[r.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:8,background:"linear-gradient(135deg, var(--playlist-cover-bg1, #6366f140), var(--playlist-cover-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"2.5rem",marginBottom:10},children:d.type===Ja.Dynamic?r.jsx(O.NtdLightning,{size:40}):r.jsx(O.NtdMusic,{size:40})}),r.jsx("div",{style:{fontWeight:600,fontSize:"0.85rem",marginBottom:2},children:d.name}),r.jsxs("div",{style:{fontSize:"0.72rem",opacity:.5},children:[d.trackCount," ",l("playlistManager.tracks","tracks"),h&&r.jsxs(r.Fragment,{children:[" — ",r.jsx(O.NtdFolder,{size:11})," ",h.name]})]}),((p=d.tags)==null?void 0:p.length)>0&&r.jsx("div",{style:{display:"flex",gap:4,marginTop:6,flexWrap:"wrap"},children:d.tags.slice(0,3).map(g=>{const y=n.find(m=>m.id===g);return y?r.jsx("span",{style:{padding:"1px 8px",borderRadius:12,background:`var(--tag-${ci(g)}-bg, ${y.color}18)`,color:`var(--tag-${ci(g)}, ${y.color})`,fontSize:"0.65rem",fontWeight:500},children:y.name},g):null})}),r.jsxs("div",{style:{display:"flex",gap:4,marginTop:8},children:[r.jsx("button",{onClick:g=>{g.stopPropagation(),o(d.id)},style:di,title:l("playlistManager.duplicate","Duplicate"),"aria-label":l("playlistManager.duplicate","Duplicate"),children:r.jsx(O.NtdCopy,{size:14})}),r.jsx("button",{onClick:g=>{g.stopPropagation(),i(d.id)},style:di,title:l("playlistManager.delete","Delete"),"aria-label":l("playlistManager.delete","Delete"),children:r.jsx(O.NtdTrash,{size:14})})]})]},d.id)})})},rm=u.memo(nm),ui=[{value:St.Library,label:"Library",hex:"var(--nice-info, #6366f1)",css:"var(--source-library, #6366f1)",cssBg:"var(--source-library-bg, #6366f118)"},{value:St.Spotify,label:"Spotify",hex:"var(--nice-success, #1db954)",css:"var(--source-spotify, #1db954)",cssBg:"var(--source-spotify-bg, #1db95418)"},{value:St.Tidal,label:"Tidal",hex:"var(--nice-text, #000000)",css:"var(--source-tidal, #000000)",cssBg:"var(--source-tidal-bg, #00000018)"},{value:St.YouTube,label:"YouTube",hex:"var(--nice-danger, #ff0000)",css:"var(--source-youtube, #ff0000)",cssBg:"var(--source-youtube-bg, #ff000018)"},{value:St.MusicBrainz,label:"MusicBrainz",hex:"var(--source-musicbrainz, #ba478f)",css:"var(--source-musicbrainz, #ba478f)",cssBg:"var(--source-musicbrainz-bg, #ba478f18)"}],am=({onSearch:e,results:t,isSearching:n,onAddToPlaylist:a,onPlayPreview:s})=>{const{t:i}=be(),[o,l]=u.useState(""),[c,d]=u.useState(new Set([St.Library,St.Spotify,St.Tidal,St.YouTube])),[h,p]=u.useState(new Set),[g,y]=u.useState(!1),m=u.useRef(null),x=u.useCallback(M=>{d(E=>{const R=new Set(E);return R.has(M)?R.delete(M):R.add(M),R})},[]),v=u.useCallback(M=>{l(M),m.current&&clearTimeout(m.current),M.trim().length>=2&&(m.current=setTimeout(()=>{e(M.trim(),Array.from(c))},350))},[c,e]),f=u.useCallback(M=>{M.preventDefault(),o.trim().length>=2&&e(o.trim(),Array.from(c))},[o,c,e]),k=u.useCallback(M=>{p(E=>{const R=new Set(E);return R.has(M)?R.delete(M):R.add(M),R})},[]),b=u.useCallback(()=>{h.size===t.length?p(new Set):p(new Set(t.map(M=>M.id)))},[h,t]),w=u.useCallback(()=>{const M=t.filter(E=>h.has(E.id));M.length>0&&(a(M),p(new Set))},[t,h,a]),N=M=>{if(!M)return"--:--";const E=Math.floor(M/60),R=M%60;return`${E}:${R.toString().padStart(2,"0")}`},$=M=>{const E=ui.find(R=>R.value===M);return r.jsx(O.NtdCircle,{size:10,style:{color:E?E.css:"var(--nice-text-secondary, #6b7280)"}})};return r.jsxs("div",{style:{border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:10,background:"var(--nice-bg-elevated, #fff)",overflow:"hidden"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 12px",gap:8,cursor:"pointer",background:"var(--nice-color-surface, #f9fafb)"},onClick:()=>y(!g),children:[r.jsx(O.NtdSearch,{size:16}),r.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:i("playlistManager.search","Search")}),r.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",opacity:.5},children:g?r.jsx(O.NtdChevronUp,{size:12}):r.jsx(O.NtdChevronDown,{size:12})})]}),g&&r.jsxs("div",{style:{padding:"0 12px 12px"},children:[r.jsx("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap"},children:ui.map(M=>{const E=c.has(M.value);return r.jsxs("button",{onClick:()=>x(M.value),style:{padding:"4px 10px",borderRadius:20,border:E?`2px solid ${M.css}`:"1px solid var(--nice-border-color, #d1d5db)",background:E?M.cssBg:"transparent",color:E?M.css:"var(--nice-text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:E?600:400,transition:"all 0.15s"},children:[r.jsx(O.NtdCircle,{size:8,style:{color:M.css}})," ",M.label]},M.value)})}),r.jsxs("form",{onSubmit:f,style:{display:"flex",gap:6,marginBottom:8},children:[r.jsx("input",{type:"text",value:o,onChange:M=>v(M.target.value),placeholder:i("playlistManager.searchPlaceholder","Search tracks, artists, albums..."),style:{flex:1,padding:"6px 12px",borderRadius:8,border:"1px solid var(--nice-border-color, #d1d5db)",background:"var(--nice-input-bg, #fff)",color:"var(--nice-text-primary, #1f2937)",fontSize:"0.82rem"}}),r.jsx("button",{type:"submit",disabled:o.trim().length<2||n,style:{padding:"6px 14px",borderRadius:8,border:"none",background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.82rem",cursor:"pointer",opacity:o.trim().length<2?.5:1},"aria-label":i("playlistManager.search","Search"),children:n?r.jsx(O.NtdClock,{size:14}):r.jsx(O.NtdSearch,{size:14})})]}),t.length>0&&r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",gap:6,marginBottom:4,alignItems:"center"},children:[r.jsxs("label",{style:{fontSize:"0.72rem",display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:h.size===t.length&&t.length>0,onChange:b}),i("playlistManager.selectAll","Select all")]}),r.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[t.length," ",i("playlistManager.results","results")]}),r.jsx("div",{style:{flex:1}}),h.size>0&&r.jsxs("button",{onClick:w,style:{padding:"3px 10px",borderRadius:6,border:"none",background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.72rem",cursor:"pointer"},children:[r.jsx(O.NtdPlus,{size:12})," ",i("playlistManager.addSelected","Add selected")," (",h.size,")"]})]}),r.jsx("div",{style:{maxHeight:300,overflowY:"auto",borderRadius:6,border:"1px solid var(--nice-border-color, #e5e7eb)"},children:t.map(M=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:"1px solid var(--nice-border-color, #f3f4f6)",background:h.has(M.id)?"var(--nice-accent-tint-10, #eff6ff)":"transparent",cursor:"pointer",fontSize:"0.78rem"},onClick:()=>k(M.id),children:[r.jsx("input",{type:"checkbox",checked:h.has(M.id),readOnly:!0}),$(M.source),M.imageUrl&&r.jsx("img",{src:M.imageUrl,alt:M.title||i("common.coverArt","Cover art"),style:{width:28,height:28,borderRadius:4,objectFit:"cover"}}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsx("div",{style:{fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:M.title}),r.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[M.artist,M.album?` — ${M.album}`:""]})]}),r.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:N(M.duration)}),s&&r.jsx("button",{onClick:E=>{E.stopPropagation(),s(M)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem"},title:i("playlistManager.preview","Preview"),"aria-label":i("playlistManager.preview","Preview"),children:r.jsx(O.NtdPlay,{size:14})})]},M.id))})]}),n&&r.jsxs("div",{style:{textAlign:"center",padding:20,opacity:.5,fontSize:"0.82rem"},children:[r.jsx(O.NtdClock,{size:14})," ",i("playlistManager.searching","Searching"),"..."]}),!n&&o.trim().length>=2&&t.length===0&&r.jsx("div",{style:{textAlign:"center",padding:20,opacity:.4,fontSize:"0.82rem"},children:i("playlistManager.noResults","No results")})]})]})},sm=[{value:1,label:"Spotify",icon:r.jsx(O.NtdMusic,{size:16}),color:"var(--source-spotify, #1db954)"},{value:2,label:"Tidal",icon:r.jsx(O.NtdMusic,{size:16}),color:"var(--source-tidal, #000000)"},{value:3,label:"Apple Music",icon:r.jsx(O.NtdMusic,{size:16}),color:"var(--source-apple, #fa243c)"},{value:4,label:"YouTube",icon:r.jsx(O.NtdMusic,{size:16}),color:"var(--source-youtube, #ff0000)"},{value:99,label:"Manual Paste",icon:r.jsx(O.NtdMusic,{size:16}),color:"var(--source-manual, #6366f1)"}],im={display:"flex",flexDirection:"column",gap:16,padding:24,borderRadius:12,background:"var(--nice-bg-primary, #ffffff)",border:"1px solid var(--nice-border, #e2e8f0)",maxWidth:640,minHeight:400},om={display:"flex",justifyContent:"space-between",alignItems:"center"},lm={display:"flex",gap:4,marginBottom:8},Ln={padding:"8px 20px",borderRadius:6,border:"none",background:"var(--nice-color-accent, #6366f1)",color:"var(--nice-text-on-primary, #fff)",cursor:"pointer",fontWeight:600},sr=(function(){return{...Ln,background:"transparent",color:"var(--nice-text-primary, #334155)",border:"1px solid var(--nice-border, #e2e8f0)"}})(),hi={padding:12,borderRadius:8,border:"1px solid var(--nice-border, #e2e8f0)",cursor:"pointer",transition:"border-color 0.15s"},Nl=["connect","browse","tracks","options","importing","done"];function cm(e){return Nl.indexOf(e)}function dm(e){if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const um=({connections:e=[],onConnect:t=()=>{},onDisconnect:n=()=>{},onFetchPlaylists:a=async()=>[],onFetchTracks:s=async()=>[],onImport:i=async()=>({playlistName:"",imported:0,skipped:0,failed:0,failedTracks:[]}),onClose:o=()=>{},targetFolders:l,sources:c})=>{const{t:d}=be(),[h,p]=u.useState("connect"),[g,y]=u.useState(null),[m,x]=u.useState([]),[v,f]=u.useState(null),[k,b]=u.useState([]),[w,N]=u.useState(new Set),[$,M]=u.useState(!1),[E,R]=u.useState(null),[L,A]=u.useState(null),[z,j]=u.useState(null),[I,Y]=u.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[H,D]=u.useState(""),V=u.useMemo(()=>new Set(e.filter(W=>W.connected).map(W=>W.platform)),[e]),Z=u.useCallback(W=>e.find(ee=>ee.platform===W),[e]),X=u.useCallback(W=>{if(y(W),W===99){p("tracks"),D(""),b([]),M(!1);return}V.has(W)?(p("browse"),M(!0),j(null),a(W).then(ee=>{x(ee),M(!1)}).catch(ee=>{j(String(ee)),M(!1)})):t(W)},[V,t,a]),q=u.useCallback(W=>{f(W),p("tracks"),M(!0),j(null),s(W).then(ee=>{b(ee),N(new Set(ee.map(ae=>ae.externalId))),M(!1)}).catch(ee=>{j(String(ee)),M(!1)})},[s]),G=u.useCallback(W=>{N(ee=>{const ae=new Set(ee);return ae.has(W)?ae.delete(W):ae.add(W),ae})},[]),C=u.useCallback(()=>{N(W=>W.size===k.length?new Set:new Set(k.map(ee=>ee.externalId)))},[k]),T=u.useCallback(async()=>{if(!v)return;const W=k.filter(ee=>w.has(ee.externalId));if(W.length!==0){p("importing"),R({total:W.length,imported:0,skipped:0,failed:0}),j(null);try{const ee=await i(v,W,I),ae=ee&&typeof ee=="object"&&"imported"in ee?ee:{playlistName:v.name,imported:W.length,skipped:0,failed:0,failedTracks:[]};A(ae),p("done")}catch(ee){j(String(ee)),p("options")}}},[v,k,w,I,i]),S=h!=="connect"&&h!=="importing"&&h!=="done",F=u.useCallback(()=>{switch(h){case"browse":p("connect");break;case"tracks":p("browse");break;case"options":p("tracks");break}},[h]),K=()=>r.jsx("div",{style:lm,children:Nl.map((W,ee)=>r.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:ee<=cm(h)?"var(--nice-color-accent, #6366f1)":"var(--nice-border, #e2e8f0)",transition:"background 0.2s"}},W))}),P=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[r.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.selectPlatform","Select a music platform to import from")}),sm.map(W=>{const ee=Z(W.value),ae=V.has(W.value);return r.jsxs("div",{style:{...hi,display:"flex",alignItems:"center",gap:12,borderColor:ae?W.color:void 0},onClick:()=>X(W.value),role:"button",tabIndex:0,onKeyDown:le=>le.key==="Enter"&&X(W.value),children:[r.jsx("span",{style:{color:W.color,display:"inline-flex"},"aria-hidden":"true",children:W.icon}),r.jsxs("div",{style:{flex:1},children:[r.jsx("strong",{children:W.label}),(ee==null?void 0:ee.username)&&r.jsx("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:ee.username})]}),ae?r.jsxs("span",{style:{color:W.color,fontSize:12,fontWeight:600},children:[d("importWizard.connected","Connected")," ",r.jsx(O.NtdCheck,{size:12})]}):r.jsx("span",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.clickToConnect","Click to connect")})]},W.value)})]}),B=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[r.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.selectPlaylist","Select a playlist to import")}),$?r.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.loading","Loading playlists…")}):r.jsxs("div",{style:{display:"grid",gap:8,maxHeight:320,overflowY:"auto"},children:[m.map(W=>r.jsxs("div",{style:{...hi,display:"flex",alignItems:"center",gap:12},onClick:()=>q(W),role:"button",tabIndex:0,onKeyDown:ee=>ee.key==="Enter"&&q(W),children:[W.coverUrl&&r.jsx("img",{src:W.coverUrl,alt:"",style:{width:48,height:48,borderRadius:6,objectFit:"cover"}}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsx("div",{style:{fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:W.name}),W.description&&r.jsx("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:W.description})]}),r.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)",whiteSpace:"nowrap"},children:[W.trackCount," ",d("importWizard.tracks","tracks")]})]},W.id)),m.length===0&&r.jsx("div",{style:{textAlign:"center",padding:24,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.noPlaylists","No playlists found")})]})]}),_=u.useCallback(W=>{const ae=W.split(`
|
|
69
|
+
`).map(le=>le.trim()).filter(Boolean).map((le,ce)=>{const te=le.match(/^(.+?)\s*[-–—]\s*(.+)$/);return te?{externalId:`paste-${ce}`,title:te[2].trim(),artist:te[1].trim(),album:void 0,duration:0}:{externalId:`paste-${ce}`,title:le,artist:"",album:void 0,duration:0}});b(ae),N(new Set(ae.map(le=>le.externalId)))},[]),U=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[g===99&&k.length===0&&r.jsxs("div",{style:{display:"grid",gap:8},children:[r.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.pasteInstructions",'Paste your track list below (one track per line). Use "Artist - Title" format for best results.')}),r.jsx("textarea",{value:H,onChange:W=>D(W.target.value),placeholder:`Daft Punk - Get Lucky
|
|
70
70
|
The Weeknd - Blinding Lights
|
|
71
|
-
Tame Impala - Let It Happen`,rows:10,style:{width:"100%",padding:12,borderRadius:6,border:"1px solid var(--nice-border, #e2e8f0)",fontFamily:"monospace",fontSize:13,resize:"vertical"}}),n.jsx("button",{style:{...Ln,opacity:J.trim().length===0?.5:1},disabled:J.trim().length===0,onClick:()=>B(J),type:"button",children:d("importWizard.parseTracks","Parse Tracks")})]}),(p!==99||S.length>0)&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsxs("p",{style:{margin:0,fontWeight:600},children:[b==null?void 0:b.name," — ",k.size,"/",S.length," ",d("importWizard.selected","selected")]}),n.jsx("button",{style:sr,onClick:E,type:"button",children:k.size===S.length?d("importWizard.deselectAll","Deselect All"):d("importWizard.selectAll","Select All")})]}),T?n.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.loadingTracks","Loading tracks…")}):n.jsx("div",{style:{maxHeight:320,overflowY:"auto"},children:n.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[n.jsx("thead",{children:n.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-border, #e2e8f0)",textAlign:"left"},children:[n.jsx("th",{style:{padding:"4px 8px",width:32}}),n.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.title","Title")}),n.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.artist","Artist")}),n.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.album","Album")}),n.jsx("th",{style:{padding:"4px 8px",textAlign:"right"},children:d("importWizard.duration","Duration")})]})}),n.jsx("tbody",{children:S.map(Z=>{const H=k.has(Z.externalId);return n.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-border, #e2e8f0)",opacity:H?1:.5,cursor:"pointer"},onClick:()=>q(Z.externalId),children:[n.jsx("td",{style:{padding:"6px 8px"},children:n.jsx("input",{type:"checkbox",checked:H,readOnly:!0})}),n.jsx("td",{style:{padding:"6px 8px",fontWeight:500},children:Z.title}),n.jsx("td",{style:{padding:"6px 8px",color:"var(--nice-text-dim, #64748b)"},children:Z.artist}),n.jsx("td",{style:{padding:"6px 8px",color:"var(--nice-text-dim, #64748b)"},children:Z.album??"—"}),n.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--nice-text-dim, #64748b)"},children:Ef(Z.duration)})]},Z.externalId)})})]})}),n.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:n.jsxs("button",{style:{...Ln,opacity:k.size===0?.5:1},disabled:k.size===0,onClick:()=>f("options"),type:"button",children:[d("importWizard.next","Next")," ",n.jsx(G.NtdArrowRight,{size:12})]})})]})]}),Y=()=>n.jsxs("div",{style:{display:"grid",gap:16},children:[n.jsx("p",{style:{margin:0,fontWeight:600},children:d("importWizard.importOptions","Import options")}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:I.mergeTags,onChange:Z=>U(H=>({...H,mergeTags:Z.target.checked}))}),d("importWizard.mergeTags","Merge tags from source playlist")]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:I.mergeFolders,onChange:Z=>U(H=>({...H,mergeFolders:Z.target.checked}))}),d("importWizard.mergeFolders","Merge into existing folder structure")]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:I.overwriteExisting,onChange:Z=>U(H=>({...H,overwriteExisting:Z.target.checked}))}),d("importWizard.overwrite","Overwrite existing tracks (match by ISRC)")]}),l&&l.length>0&&n.jsxs("div",{style:{display:"grid",gap:4},children:[n.jsx("label",{style:{fontSize:13,fontWeight:500},children:d("importWizard.targetFolder","Target folder")}),n.jsxs("select",{style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #e2e8f0)"},value:I.targetFolderId??"",onChange:Z=>U(H=>({...H,targetFolderId:Z.target.value||void 0})),children:[n.jsx("option",{value:"",children:d("importWizard.root","— Root —")}),l.map(Z=>n.jsx("option",{value:Z.id,children:Z.name},Z.id))]})]}),n.jsx("div",{style:{marginTop:8,padding:12,borderRadius:8,background:"var(--nice-info-bg, #eff6ff)",fontSize:13},children:d("importWizard.summary",`Ready to import ${k.size} tracks from "${(b==null?void 0:b.name)??""}"`)}),n.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[n.jsxs("button",{style:sr,onClick:L,type:"button",children:[n.jsx(G.NtdArrowLeft,{size:12})," ",d("importWizard.back","Back")]}),n.jsx("button",{style:Ln,onClick:P,type:"button",children:d("importWizard.startImport","Start Import")})]})]}),oe=()=>{const Z=j?Math.round(j.imported/j.total*100):0;return n.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[n.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:d("importWizard.importing","Importing…")}),n.jsx("div",{style:{height:8,borderRadius:4,background:"var(--nice-border, #e2e8f0)",overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:`${Z}%`,background:"var(--nice-color-accent, #6366f1)",borderRadius:4,transition:"width 0.3s"}})}),j&&n.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-dim, #64748b)"},children:[j.imported," / ",j.total," ",d("importWizard.tracks","tracks"),j.currentTrack&&n.jsxs("div",{style:{marginTop:4},children:[n.jsx(G.NtdMusic,{size:12})," ",j.currentTrack]})]})]})},ie=()=>n.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[n.jsx("span",{style:{display:"inline-flex",justifyContent:"center"},"aria-hidden":"true",children:n.jsx(G.NtdCheck,{size:48})}),n.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:d("importWizard.complete","Import Complete")}),z&&n.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[n.jsxs("div",{children:[n.jsx("strong",{children:z.imported})," ",d("importWizard.imported","imported")]}),z.skipped>0&&n.jsxs("div",{style:{color:"var(--nice-color-warning, #f59e0b)"},children:[z.skipped," ",d("importWizard.skipped","skipped (duplicates)")]}),z.failed>0&&n.jsxs("div",{style:{color:"var(--nice-color-error, #ef4444)"},children:[z.failed," ",d("importWizard.failed","failed")]}),z.failedTracks.length>0&&n.jsxs("details",{style:{textAlign:"left",marginTop:8,fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:[n.jsx("summary",{style:{cursor:"pointer"},children:d("importWizard.showFailed","Show failed tracks")}),n.jsx("ul",{style:{marginTop:4,paddingLeft:20},children:z.failedTracks.map((Z,H)=>n.jsx("li",{children:Z},H))})]})]}),n.jsx("button",{style:Ln,onClick:o,type:"button",children:d("importWizard.close","Done")})]}),ne={connect:d("importWizard.stepConnect","Connect"),browse:d("importWizard.stepBrowse","Browse"),tracks:d("importWizard.stepTracks","Select Tracks"),options:d("importWizard.stepOptions","Options"),importing:d("importWizard.stepImporting","Importing"),done:d("importWizard.stepDone","Done")};return n.jsxs("div",{style:Nf,children:[w(),n.jsxs("div",{style:Tf,children:[n.jsxs("h2",{style:{margin:0,fontSize:18},children:[d("importWizard.title","Import Playlist")," — ",ne[h]]}),C&&n.jsxs("button",{style:sr,onClick:L,type:"button",children:[n.jsx(G.NtdArrowLeft,{size:12})," ",d("importWizard.back","Back")]}),h==="connect"&&n.jsx("button",{style:sr,onClick:o,type:"button","aria-label":d("importWizard.close","Close"),title:d("importWizard.close","Close"),children:n.jsx(G.NtdClose,{size:14})})]}),$&&n.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--nice-error-bg, #fef2f2)",color:"var(--nice-color-error, #ef4444)",fontSize:13},children:$}),h==="connect"&&D(),h==="browse"&&F(),h==="tracks"&&V(),h==="options"&&Y(),h==="importing"&&oe(),h==="done"&&ie()]})},Af=[{id:"concert-harp",name:"Concert Harp",description:"Warm concert harp",icon:"music",dir:"concert-harp",attribution:"ConcertHarp SoundFont — source: musical-artifacts.com/artifacts/375"},{id:"celtic-harp",name:"Celtic Harp",description:"Bright celtic harp",icon:"leaf",dir:"celtic-harp"},{id:"triangle",name:"Triangle",description:"Metallic percussion triangle",icon:"triangle",dir:"triangle",attribution:"Triangle SoundFont — source: polyphone.io/en/soundfonts/unpitched-percussion/298-triangle"},{id:"synth",name:"Celesta",description:"Synthesized celesta / music-box",icon:"sparkle",dir:"synth"},{id:"none",name:"Silent",description:"No sound on click",icon:"volumeMute",dir:null}],If="concert-harp",ds=Object.fromEntries(Af.map(e=>[e.id,e])),Lf="nice2dev-note-sound-set";function Pl(){try{const e=localStorage.getItem(Lf);if(e&&ds[e])return e}catch{}return If}const Ir=["quarter","eighth","sixteenth","beamed"];function El(e,t,r){const a=r*.2,s=r*.15,i=Math.max(1,r*.07),o=r*.72,l=r*.34,c=new Path2D,d=h=>{c.moveTo(h+a,l),c.ellipse(h,l,a,s,-.4,0,Math.PI*2),c.rect(h+a-i,l-o,i,o)};if(t==="beamed"){const h=-r*.24,f=r*.24;d(h),d(f),c.rect(h+a-i,l-o,f-h+i,r*.12)}else{const h=-a*.5;d(h);const f=t==="eighth"?1:t==="sixteenth"?2:0,p=h+a;for(let y=0;y<f;y++){const m=l-o+y*r*.2;c.moveTo(p,m),c.quadraticCurveTo(p+r*.32,m+r*.14,p+r*.18,m+r*.42),c.quadraticCurveTo(p+r*.2,m+r*.22,p,m+r*.14),c.closePath()}}e.stroke(c),e.fill(c)}function mi(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function Al(e){if(!e)return null;const t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle=e;const r=t.fillStyle;if(r.startsWith("#")){const s=parseInt(r.slice(1),16);return{r:s>>16&255,g:s>>8&255,b:s&255}}const a=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return a?{r:+a[1],g:+a[2],b:+a[3]}:null}function ra(e,t){const r=Al(e);return r?`rgba(${r.r},${r.g},${r.b},${t})`:`rgba(255,255,255,${t})`}function Df(e){const t=Al(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function Il(){const e=mi("--text-primary")||"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",t=mi("--nav-active")||"goldenrod",r=document.documentElement.getAttribute("data-theme")==="dark",s=Df(e)<.45;return{base:ra(e,.92),staffLine:ra(e,.22),outline:s?"var(--nice-overlay-light-75, rgba(255, 255, 255, 0.75))":"var(--nice-overlay-55, rgba(0, 0, 0, 0.55))",accents:[ra(t,.95)],isDark:r,notesDark:s}}const Gr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),Ll=46,kt=5,mr=4,zf=(Ll-(kt-1)*mr)/2,_f=6,Ff=18,Of=110,Bf=50,Wr=Gr?Bf:Of,Gf=Gr?4:2,Wf=Gr?2:4,gi=Gr?1:0,Uf=180,yi=2.8,bi=40,Vf=14,vi=1.2,qf=16,aa=[64,67,71,74,77],sn=64,Dn=77;function Hf(e){const t=Math.max(0,Math.min(kt-1,e)),r=Math.floor(t),a=Math.min(r+1,kt-1),s=t-r;return Math.round(aa[r]+(aa[a]-aa[r])*s)}function Kf(e){return(Math.max(sn-1*(Dn-sn)/(kt-1),Math.min(Dn+1*(Dn-sn)/(kt-1),e))-sn)/(Dn-sn)*(kt-1)}const xi=2.5,Si=.72,Yf=.55,zn=new Map;let gr=null;async function Zf(e){const t=e??Pl(),r=ds[t];if(!r||!r.dir){zn.clear(),gr=t;return}if(gr===t&&zn.size>0)return;zn.clear(),gr=t;const a=yn(),s=[];for(let i=sn;i<=Dn;i++)s.push(fetch(`/assets/soundfonts/notes/${r.dir}/note-${i}.mp3`).then(o=>o.arrayBuffer()).then(o=>a.decodeAudioData(o)).then(o=>{zn.set(i,o)}).catch(()=>{}));await Promise.all(s)}function ki(e){const t=zn.get(e);if(!t)return;const r=yn(),a=r.createBufferSource();a.buffer=t;const s=r.createGain();s.gain.value=.7,a.connect(s).connect(r.destination),a.start()}function Xf(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 Qf(e){const t=Xf(42),r=[];for(let a=0;a<e;a++){const i=t()<.15?0:-1;r.push({x:t(),lineIdx:t()*(kt+1)-.5,shape:Ir[Math.floor(t()*Ir.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:i})}return r.sort((a,s)=>a.x-s.x),r}const ut=Qf(Wr),Cn=new Float32Array(Wr),ir=new Float32Array(Wr),_n=new Float32Array(Wr);let Sa=!1;const Jf=(kt-1)/2;function em(){if(!Sa){Sa=!0;for(let e=0;e<ut.length;e++)_n[e]=ut[e].lineIdx}}let ka=[],wi="";function tm(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function nm(e){const t=tm(e);t===wi&&ka.length===ut.length||(wi=t,ka=ut.map(r=>{const a=Math.ceil(r.size*1.6),s=a*2,i=document.createElement("canvas");i.width=s,i.height=s;const o=i.getContext("2d");return o.translate(a,a),o.rotate(r.rot*Math.PI/180),o.lineWidth=1.8,o.strokeStyle=e.outline,o.fillStyle=r.colorIdx<0?e.base:e.accents[r.colorIdx%e.accents.length],El(o,r.shape,r.size*1.3),{canvas:i,ox:a,oy:a}}))}function Dl({pitchMidiRef:e}={}){const t=u.useRef(null),r=u.useRef(0),a=u.useRef(0),s=u.useRef(0),i=u.useRef(null),o=u.useRef(0),l=u.useRef(0),c=u.useRef(null),d=u.useRef(null),h=u.useRef(!1),f=u.useCallback((x,b,g)=>{const S=zf+x*mr,v=b/g*Math.PI*2;return S+Math.sin(v)*_f},[]),p=u.useCallback(x=>{const b=t.current;if(!b)return;if(l.current++,gi>0&&l.current%(gi+1)!==0){s.current=x,r.current=requestAnimationFrame(p);return}const g=b.getContext("2d");if(!g)return;const S=Math.min(window.devicePixelRatio||1,Wf),v=b.getBoundingClientRect(),k=v.width,M=v.height;(b.width!==Math.round(k*S)||b.height!==Math.round(M*S))&&(b.width=Math.round(k*S),b.height=Math.round(M*S),g.setTransform(S,0,0,S,0,0));const T=s.current?(x-s.current)/1e3:0;s.current=x,a.current=(a.current+Ff*T)%k,g.clearRect(0,0,k,M),o.current++,(!i.current||o.current%60===0)&&(i.current=Il());const N=i.current;nm(N),g.strokeStyle=N.staffLine,g.lineWidth=.7;for(let A=0;A<kt;A++){g.beginPath();for(let $=0;$<=k;$+=Gf){const O=f(A,$,k);$===0?g.moveTo($,O):g.lineTo($,O)}g.stroke()}const j=a.current,R=(e==null?void 0:e.current)??null;if(R!==null){em();const A=Kf(R),$=xi*T;for(let O=0;O<ut.length;O++){const U=(ut[O].lineIdx-Jf)*Yf,_=A*Si+(A+U)*(1-Si)-_n[O];_n[O]+=_>0?Math.min($,_):Math.max(-$,_)}}else if(Sa){const A=xi*.4*T;for(let $=0;$<ut.length;$++){const I=ut[$].lineIdx-_n[$];_n[$]+=I>0?Math.min(A,I):Math.max(-A,I)}}const z=c.current;z&&(z.timer-=T,z.timer<=0&&(c.current=null));for(let A=0;A<ut.length;A++){const $=ut[A];if(ir[A]>0){ir[A]-=T;const U=Math.max(0,ir[A]/yi);Cn[A]+=Uf*U*T,Cn[A]>k&&(Cn[A]-=k)}const O=ka[A];if(!O)continue;const I=$.lineIdx;for(let U=0;U<2;U++){let _=(($.x*k-j-Cn[A]+U*k)%k+k)%k;const W=f(Math.max(0,Math.min(kt-1,Math.round(I))),_,k),K=(I-Math.round(I))*mr;let re=W+K;if(z&&z.timer>0){const X=_-z.x,q=re-z.y,E=Math.sqrt(X*X+q*q);if(E<bi&&E>.1){const P=z.timer/vi,C=Vf*(1-E/bi)*P;_+=X/E*C,re+=q/E*C}}g.drawImage(O.canvas,_-O.ox,re-O.oy)}}r.current=requestAnimationFrame(p)},[f]),y=u.useCallback(x=>{const b=t.current;if(!b)return;const g=b.getBoundingClientRect(),S=x.clientX-g.left,v=x.clientY-g.top,k=g.width,M=a.current;let T=1/0,N=-1;for(let j=0;j<ut.length;j++){const R=ut[j],A=((R.x*k-M-Cn[j])%k+k)%k,$=f(Math.max(0,Math.min(kt-1,Math.round(R.lineIdx))),A,k),O=(R.lineIdx-Math.round(R.lineIdx))*mr,I=$+O,U=A-S,J=I-v,_=U*U+J*J;_<T&&(T=_,N=j)}if(N>=0&&Math.sqrt(T)<qf){ir[N]=yi;const j=ut[N],R=Hf(j.lineIdx);try{Bt();const z=Pl(),A=ds[z];A!=null&&A.dir&&(gr!==z||!h.current?(h.current=!0,Zf(z).then(()=>ki(R))):ki(R))}catch{}}c.current={x:S,y:v,timer:vi}},[f]),m=u.useCallback(x=>{const b=t.current;if(!b)return;const g=b.getBoundingClientRect(),S=x.clientX-g.left,v=x.clientY-g.top;d.current={x:S,y:v},c.current&&c.current.timer>0&&(c.current.x=S,c.current.y=v)},[]);return u.useEffect(()=>(r.current=requestAnimationFrame(p),()=>cancelAnimationFrame(r.current)),[p]),n.jsx("canvas",{ref:t,"aria-hidden":"true",role:"img","aria-label":"Note river animation canvas",onClick:y,onMouseMove:m,style:{display:"block",width:"100%",height:Ll,marginBottom:5,cursor:"pointer",background:"transparent"}})}const rm=14,am=.9,sm=320,im=160,om=6,Ci=8,lm=14;function zl(){const e=u.useRef(null),t=u.useRef([]),r=u.useRef(0),a=u.useRef(0),s=u.useRef([]),i=u.useRef(null),o=u.useRef(0),l=u.useCallback((d,h)=>{for(let f=0;f<rm;f++){const p=Math.random()*Math.PI*2,y=im*(.4+Math.random()*.6),m=am*(.6+Math.random()*.4),x=Math.random()<.15?0:-1;t.current.push({x:d,y:h,vx:Math.cos(p)*y,vy:Math.sin(p)*y-60,rot:Math.random()*Math.PI*2,vr:(Math.random()-.5)*om*2,size:Ci+Math.random()*(lm-Ci),shape:Ir[Math.floor(Math.random()*Ir.length)],life:m,maxLife:m,colorIdx:x})}},[]),c=u.useCallback(d=>{const h=e.current;if(!h){r.current=requestAnimationFrame(c);return}const f=h.getContext("2d");if(!f){r.current=requestAnimationFrame(c);return}const p=window.devicePixelRatio||1,y=window.innerWidth,m=window.innerHeight;(h.width!==Math.round(y*p)||h.height!==Math.round(m*p))&&(h.width=Math.round(y*p),h.height=Math.round(m*p),h.style.width=`${y}px`,h.style.height=`${m}px`,f.setTransform(p,0,0,p,0,0));const x=a.current?Math.min((d-a.current)/1e3,.05):0;a.current=d,f.clearRect(0,0,y,m),o.current++,(!i.current||o.current%60===0)&&(i.current=Il());const b=i.current;if(navigator.getGamepads){const S=navigator.getGamepads();for(let v=0;v<S.length;v++){const k=S[v];if(k)for(let M=0;M<k.buttons.length;M++){const T=v*100+M,N=k.buttons[M].pressed;N&&!s.current[T]&&l(y/2,m/2),s.current[T]=N}}}const g=[];for(const S of t.current){if(S.life-=x,S.life<=0)continue;S.vy+=sm*x,S.x+=S.vx*x,S.y+=S.vy*x,S.rot+=S.vr*x;const v=Math.max(0,S.life/S.maxLife),k=.5+.5*v;f.save(),f.globalAlpha=v,f.translate(S.x,S.y),f.rotate(S.rot),f.lineWidth=1.4,f.strokeStyle=b.notesDark?`rgba(255,255,255,${v*.8})`:`rgba(0,0,0,${v*.55})`;const M=S.colorIdx<0?b.base:b.accents[S.colorIdx%b.accents.length];f.fillStyle=M.replace(/[\d.]+\)$/,`${v})`),El(f,S.shape,S.size*k*1.3),f.restore(),g.push(S)}t.current=g,r.current=requestAnimationFrame(c)},[l]);return u.useEffect(()=>{const d=f=>{l(f.clientX,f.clientY)},h=f=>{if(f.key!=="Enter")return;const p=document.activeElement;if(p){const y=p.getBoundingClientRect();l(y.left+y.width/2,y.top+y.height/2)}else l(window.innerWidth/2,window.innerHeight/2)};return window.addEventListener("click",d,!0),window.addEventListener("keydown",h,!0),r.current=requestAnimationFrame(c),()=>{window.removeEventListener("click",d,!0),window.removeEventListener("keydown",h,!0),cancelAnimationFrame(r.current)}},[c,l]),n.jsx("canvas",{ref:e,"aria-hidden":"true",role:"img","aria-label":"Note particles animation canvas",style:{position:"fixed",inset:0,zIndex:99999,pointerEvents:"none"}})}const yr={type:"gain",enabled:!0,mix:1,gain:0},Fn={type:"compressor",enabled:!0,mix:1,threshold:-24,ratio:4,attack:10,release:100,knee:6,makeupGain:0},On={type:"reverb",enabled:!0,mix:.3,decay:2,preDelay:10,damping:.5,roomSize:.5},Bn={type:"delay",enabled:!0,mix:.3,time:250,feedback:.4,pingPong:!1,highCut:8e3},br={type:"chorus",enabled:!0,mix:.5,rate:1.5,depth:.5,delay:7,voices:3},vr={type:"eq",enabled:!0,mix:1,bands:[{frequency:60,gain:0,q:1,type:"lowshelf"},{frequency:250,gain:0,q:1,type:"peaking"},{frequency:1e3,gain:0,q:1,type:"peaking"},{frequency:4e3,gain:0,q:1,type:"peaking"},{frequency:12e3,gain:0,q:1,type:"highshelf"}]},xr={type:"filter",enabled:!0,mix:1,filterType:"lowpass",frequency:1e3,q:1,gain:0},Sr={type:"distortion",enabled:!0,mix:.5,drive:.5,tone:.5,curve:"soft"},kr={type:"tremolo",enabled:!0,mix:1,rate:5,depth:.5,waveform:"sine"},wr={type:"phaser",enabled:!0,mix:.5,rate:.5,depth:.5,feedback:.5,stages:4,frequency:1e3},cm={gain:{unity:{...yr,gain:0},boost:{...yr,gain:6},cut:{...yr,gain:-6}},compressor:{gentle:{...Fn,threshold:-20,ratio:2,attack:30,release:200},moderate:{...Fn,threshold:-24,ratio:4,attack:10,release:100},aggressive:{...Fn,threshold:-30,ratio:8,attack:1,release:50},limiter:{...Fn,threshold:-3,ratio:20,attack:.1,release:100}},reverb:{small_room:{...On,decay:.5,roomSize:.2,damping:.7},large_hall:{...On,decay:3,roomSize:.8,damping:.3},plate:{...On,decay:1.5,roomSize:.5,damping:.4},cathedral:{...On,decay:5,roomSize:.9,damping:.2,mix:.4}},delay:{slapback:{...Bn,time:80,feedback:.1,mix:.3},quarter_note:{...Bn,time:500,feedback:.4,mix:.3},dotted_eighth:{...Bn,time:375,feedback:.5,mix:.3},long_ambient:{...Bn,time:750,feedback:.6,highCut:3e3,mix:.4}},chorus:{subtle:{...br,rate:.5,depth:.2,voices:2,mix:.3},vintage:{...br,rate:1,depth:.4,voices:2,delay:10,mix:.4},ensemble:{...br,rate:2,depth:.6,voices:4,mix:.5}},eq:{vocal_presence:{...vr,bands:[{frequency:80,gain:-3,q:1,type:"highpass"},{frequency:250,gain:-2,q:1,type:"peaking"},{frequency:3e3,gain:3,q:1.5,type:"peaking"},{frequency:8e3,gain:2,q:1,type:"highshelf"}]},bass_boost:{...vr,bands:[{frequency:60,gain:6,q:1,type:"lowshelf"},{frequency:200,gain:2,q:1,type:"peaking"}]},brightness:{...vr,bands:[{frequency:4e3,gain:3,q:1,type:"peaking"},{frequency:1e4,gain:4,q:1,type:"highshelf"}]}},filter:{low_pass_warm:{...xr,filterType:"lowpass",frequency:2e3,q:.7},high_pass_clean:{...xr,filterType:"highpass",frequency:100,q:.7},telephone:{...xr,filterType:"bandpass",frequency:1500,q:2}},distortion:{overdrive:{...Sr,drive:.3,tone:.6,curve:"soft",mix:.7},crunch:{...Sr,drive:.5,tone:.5,curve:"tube",mix:.8},fuzz:{...Sr,drive:.8,tone:.4,curve:"fuzz",mix:1}},tremolo:{slow:{...kr,rate:3,depth:.4,waveform:"sine"},fast:{...kr,rate:8,depth:.6,waveform:"sine"},choppy:{...kr,rate:6,depth:.9,waveform:"square"}},phaser:{subtle:{...wr,rate:.3,depth:.3,feedback:.3,stages:4},jet:{...wr,rate:.1,depth:.8,feedback:.7,stages:8},rotary:{...wr,rate:1,depth:.5,feedback:.4,stages:6}}};function ji(e){return Math.pow(10,e/20)}function dm(e,t,r,a){const s=e.sampleRate,i=Math.floor(s*t),o=e.createBuffer(2,i,s);for(let l=0;l<2;l++){const c=o.getChannelData(l);for(let d=0;d<i;d++){const h=d/s,f=Math.exp(-h/r),p=1-a*(d/i);c[d]=(Math.random()*2-1)*f*p}}return o}function um(e,t){const a=new Float32Array(44100),s=Math.PI/180;for(let i=0;i<44100;i++){const o=i*2/44100-1;switch(t){case"soft":a[i]=(3+e*10)*o*20*s/(Math.PI+e*10*Math.abs(o));break;case"hard":a[i]=Math.tanh(o*(1+e*5));break;case"fuzz":a[i]=Math.sign(o)*Math.pow(Math.abs(o),1/(1+e*3));break;case"tube":o>=0?a[i]=1-Math.pow(1-o,1+e*2):a[i]=-(1-Math.pow(1+o,1+e*2));break}}return a}class hm{constructor(t){this.effects=[],this.bypass=!1,this.audioContext=t,this.inputNode=t.createGain(),this.outputNode=t.createGain(),this.inputNode.connect(this.outputNode)}get input(){return this.inputNode}get output(){return this.outputNode}addEffect(t,r){const a=`effect_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=this.createEffectInstance(a,t);return r!==void 0&&r>=0&&r<this.effects.length?this.effects.splice(r,0,s):this.effects.push(s),this.reconnectChain(),a}removeEffect(t){const r=this.effects.findIndex(s=>s.id===t);if(r===-1)return!1;const a=this.effects[r];for(const s of a.nodes)s.disconnect();return this.effects.splice(r,1),this.reconnectChain(),!0}updateEffect(t,r){const a=this.effects.find(l=>l.id===t);if(!a)return!1;const s={...a.params,...r},i=this.effects.indexOf(a);for(const l of a.nodes)l.disconnect();const o=this.createEffectInstance(t,s);return this.effects[i]=o,this.reconnectChain(),!0}reorderEffects(t,r){if(t<0||t>=this.effects.length||r<0||r>=this.effects.length)return!1;const[a]=this.effects.splice(t,1);return this.effects.splice(r,0,a),this.reconnectChain(),!0}setBypass(t){this.bypass=t,this.reconnectChain()}getEffects(){return[...this.effects]}clear(){for(const t of this.effects)for(const r of t.nodes)r.disconnect();this.effects=[],this.reconnectChain()}createEffectInstance(t,r){const{audioContext:a}=this,s=[];let i,o;switch(r.type){case"gain":{const l=a.createGain();l.gain.value=ji(r.gain),s.push(l),i=o=l;break}case"compressor":{const l=a.createDynamicsCompressor();l.threshold.value=r.threshold,l.ratio.value=r.ratio,l.attack.value=r.attack/1e3,l.release.value=r.release/1e3,l.knee.value=r.knee;const c=a.createGain();c.gain.value=ji(r.makeupGain),l.connect(c),s.push(l,c),i=l,o=c;break}case"reverb":{const l=a.createConvolver();l.buffer=dm(a,r.decay,r.decay,r.damping);const c=a.createGain(),d=a.createGain(),h=a.createGain(),f=a.createGain();c.gain.value=r.mix,d.gain.value=1-r.mix,h.connect(l),h.connect(d),l.connect(c),c.connect(f),d.connect(f),s.push(h,l,c,d,f),i=h,o=f;break}case"delay":{const l=a.createDelay(5);l.delayTime.value=r.time/1e3;const c=a.createGain();c.gain.value=r.feedback;const d=a.createBiquadFilter();d.type="lowpass",d.frequency.value=r.highCut;const h=a.createGain(),f=a.createGain(),p=a.createGain(),y=a.createGain();h.gain.value=r.mix,f.gain.value=1-r.mix,p.connect(l),p.connect(f),l.connect(d),d.connect(c),c.connect(l),d.connect(h),h.connect(y),f.connect(y),s.push(p,l,d,c,h,f,y),i=p,o=y;break}case"eq":{const l=[];let c=null;for(const d of r.bands){const h=a.createBiquadFilter();h.type=d.type,h.frequency.value=d.frequency,h.Q.value=d.q,h.gain.value=d.gain,c&&c.connect(h),c=h,l.push(h)}s.push(...l),i=l[0]||a.createGain(),o=l[l.length-1]||i;break}case"filter":{const l=a.createBiquadFilter();l.type=r.filterType,l.frequency.value=r.frequency,l.Q.value=r.q,l.gain.value=r.gain,s.push(l),i=o=l;break}case"distortion":{const l=a.createWaveShaper();l.curve=um(r.drive,r.curve),l.oversample="4x";const c=a.createBiquadFilter();c.type="lowpass",c.frequency.value=1e3+r.tone*1e4;const d=a.createGain(),h=a.createGain(),f=a.createGain(),p=a.createGain();d.gain.value=r.mix,h.gain.value=1-r.mix,f.connect(l),f.connect(h),l.connect(c),c.connect(d),d.connect(p),h.connect(p),s.push(f,l,c,d,h,p),i=f,o=p;break}case"tremolo":{const l=a.createOscillator();l.type=r.waveform,l.frequency.value=r.rate;const c=a.createGain();c.gain.value=r.depth*.5;const d=a.createGain();d.gain.value=1-r.depth*.5,l.connect(c),c.connect(d.gain),l.start(),s.push(l,c,d),i=o=d;break}case"phaser":{const l=[],c=a.createOscillator();c.type="sine",c.frequency.value=r.rate;const d=a.createGain();d.gain.value=r.depth*r.frequency;let h=null;for(let x=0;x<r.stages;x++){const b=a.createBiquadFilter();b.type="allpass",b.frequency.value=r.frequency,b.Q.value=.5,c.connect(d),d.connect(b.frequency),h&&h.connect(b),h=b,l.push(b)}const f=a.createGain(),p=a.createGain(),y=a.createGain(),m=a.createGain();f.gain.value=r.mix,p.gain.value=1-r.mix,y.connect(l[0]),y.connect(p),l[l.length-1].connect(f),f.connect(m),p.connect(m),c.start(),s.push(c,d,...l,f,p,y,m),i=y,o=m;break}default:throw new Error(`Unknown effect type: ${r.type}`)}return{id:t,params:r,nodes:s,input:i,output:o}}reconnectChain(){this.inputNode.disconnect();for(const r of this.effects)r.output.disconnect();if(this.bypass||this.effects.length===0){this.inputNode.connect(this.outputNode);return}let t=this.inputNode;for(const r of this.effects)r.params.enabled&&(t.connect(r.input),t=r.output);t.connect(this.outputNode)}dispose(){this.clear(),this.inputNode.disconnect(),this.outputNode.disconnect()}}const _l={gain:n.jsx(G.NtdVolume,{size:16}),compressor:n.jsx(G.NtdSettings,{size:16}),reverb:n.jsx(G.NtdMountain,{size:16}),delay:n.jsx(G.NtdStopwatch,{size:16}),chorus:n.jsx(G.NtdSparkle,{size:16}),eq:n.jsx(G.NtdBarChart,{size:16}),filter:n.jsx(G.NtdFilter,{size:16}),distortion:n.jsx(G.NtdLightning,{size:16}),tremolo:n.jsx(G.NtdWave,{size:16}),phaser:n.jsx(G.NtdMagicWand,{size:16})},Fl={gain:"Gain",compressor:"Compressor",reverb:"Reverb",delay:"Delay",chorus:"Chorus",eq:"EQ",filter:"Filter",distortion:"Distortion",tremolo:"Tremolo",phaser:"Phaser"},pm={gain:yr,compressor:Fn,reverb:On,delay:Bn,chorus:br,eq:vr,filter:xr,distortion:Sr,tremolo:kr,phaser:wr},fm=["gain","compressor","reverb","delay","chorus","eq","filter","distortion","tremolo","phaser"],Le=({value:e,min:t,max:r,step:a=1,label:s,unit:i="",onChange:o,disabled:l})=>{const c=u.useRef(null),[d,h]=u.useState(!1),f=u.useRef(0),p=u.useRef(e),y=u.useCallback(x=>{l||(x.preventDefault(),h(!0),f.current=x.clientY,p.current=e)},[l,e]);u.useEffect(()=>{if(!d)return;const x=g=>{const S=f.current-g.clientY,v=r-t,M=S/200*v,T=Math.min(r,Math.max(t,p.current+M));o(a<1?T:Math.round(T/a)*a)},b=()=>{h(!1)};return document.addEventListener("mousemove",x),document.addEventListener("mouseup",b),()=>{document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",b)}},[d,t,r,a,o]);const m=(e-t)/(r-t)*270-135;return n.jsxs("div",{className:`nice-fx-knob ${l?"nice-fx-knob--disabled":""}`,ref:c,children:[n.jsx("div",{className:`nice-fx-knob__dial ${d?"nice-fx-knob__dial--active":""}`,onMouseDown:y,style:{transform:`rotate(${m}deg)`},children:n.jsx("div",{className:"nice-fx-knob__indicator"})}),n.jsx("div",{className:"nice-fx-knob__label",children:s}),n.jsxs("div",{className:"nice-fx-knob__value",children:[typeof e=="number"&&a<1?e.toFixed(2):e,i]})]})};function mm({effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return n.jsx(wt,{effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:n.jsx(Le,{value:e.gain,min:-60,max:12,step:.1,label:"Gain",unit:"dB",onChange:d=>t({...e,gain:d}),disabled:!e.enabled})})}function gm({effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return n.jsx(wt,{effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:n.jsxs("div",{className:"nice-fx-card__controls",children:[n.jsx(Le,{value:e.threshold,min:-60,max:0,label:"Threshold",unit:"dB",onChange:d=>t({...e,threshold:d}),disabled:!e.enabled}),n.jsx(Le,{value:e.ratio,min:1,max:20,label:"Ratio",onChange:d=>t({...e,ratio:d}),disabled:!e.enabled}),n.jsx(Le,{value:e.attack,min:.1,max:200,label:"Attack",unit:"ms",onChange:d=>t({...e,attack:d}),disabled:!e.enabled}),n.jsx(Le,{value:e.release,min:10,max:1e3,label:"Release",unit:"ms",onChange:d=>t({...e,release:d}),disabled:!e.enabled}),!c&&n.jsxs(n.Fragment,{children:[n.jsx(Le,{value:e.knee,min:0,max:40,label:"Knee",unit:"dB",onChange:d=>t({...e,knee:d}),disabled:!e.enabled}),n.jsx(Le,{value:e.makeupGain,min:0,max:24,label:"Makeup",unit:"dB",onChange:d=>t({...e,makeupGain:d}),disabled:!e.enabled})]})]})})}function ym({effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return n.jsx(wt,{effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:n.jsxs("div",{className:"nice-fx-card__controls",children:[n.jsx(Le,{value:e.decay,min:.1,max:10,step:.1,label:"Decay",unit:"s",onChange:d=>t({...e,decay:d}),disabled:!e.enabled}),n.jsx(Le,{value:e.damping,min:0,max:1,step:.01,label:"Damping",onChange:d=>t({...e,damping:d}),disabled:!e.enabled}),n.jsx(Le,{value:e.roomSize,min:0,max:1,step:.01,label:"Room",onChange:d=>t({...e,roomSize:d}),disabled:!e.enabled}),n.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:d=>t({...e,mix:d}),disabled:!e.enabled})]})})}function bm({effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return n.jsx(wt,{effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:n.jsxs("div",{className:"nice-fx-card__controls",children:[n.jsx(Le,{value:e.time,min:0,max:2e3,label:"Time",unit:"ms",onChange:d=>t({...e,time:d}),disabled:!e.enabled}),n.jsx(Le,{value:e.feedback,min:0,max:1,step:.01,label:"Feedback",onChange:d=>t({...e,feedback:d}),disabled:!e.enabled}),n.jsx(Le,{value:e.highCut,min:200,max:2e4,label:"HiCut",unit:"Hz",onChange:d=>t({...e,highCut:d}),disabled:!e.enabled}),n.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:d=>t({...e,mix:d}),disabled:!e.enabled})]})})}function vm({effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return n.jsx(wt,{effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:n.jsxs("div",{className:"nice-fx-card__controls",children:[n.jsx(Le,{value:e.drive,min:0,max:1,step:.01,label:"Drive",onChange:d=>t({...e,drive:d}),disabled:!e.enabled}),n.jsx(Le,{value:e.tone,min:0,max:1,step:.01,label:"Tone",onChange:d=>t({...e,tone:d}),disabled:!e.enabled}),n.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:d=>t({...e,mix:d}),disabled:!e.enabled})]})})}function wt({effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:d}){const[h,f]=u.useState(!1);return n.jsxs("div",{className:`nice-fx-card ${e.enabled?"":"nice-fx-card--disabled"} ${i?"nice-fx-card--drop-target":""} ${c?"nice-fx-card--compact":""}`,draggable:!0,onDragStart:a,onDragEnd:s,children:[n.jsxs("div",{className:"nice-fx-card__header",children:[n.jsx("span",{className:"nice-fx-card__icon",children:_l[e.type]}),n.jsx("span",{className:"nice-fx-card__title",children:Fl[e.type]}),n.jsx("button",{type:"button",className:`nice-fx-card__toggle ${e.enabled?"nice-fx-card__toggle--active":""}`,onClick:()=>t({...e,enabled:!e.enabled}),title:e.enabled?"Disable":"Enable","aria-pressed":e.enabled,children:n.jsx("span",{className:"nice-fx-card__toggle-dot","aria-hidden":"true"})}),l&&Object.keys(o).length>0&&n.jsxs("div",{className:"nice-fx-card__presets",children:[n.jsx("button",{type:"button",className:"nice-fx-card__preset-btn",onClick:()=>f(!h),"aria-label":"Presets",children:n.jsx(G.NtdChevronDown,{size:12})}),h&&n.jsx("div",{className:"nice-fx-card__preset-menu",children:Object.entries(o).map(([p,y])=>n.jsx("button",{type:"button",className:"nice-fx-card__preset-item",onClick:()=>{t({...y,enabled:e.enabled}),f(!1)},children:p.replace(/_/g," ")},p))})]}),n.jsx("button",{type:"button",className:"nice-fx-card__remove",onClick:r,title:"Remove",children:"×"})]}),n.jsx("div",{className:"nice-fx-card__body",children:d})]})}function xm({effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return n.jsx(wt,{effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:n.jsx("div",{className:"nice-fx-card__generic",children:n.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:d=>t({...e,mix:d}),disabled:!e.enabled})})})}function Sm({effect:e,onChange:t,...r}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return n.jsx(wt,{effect:e,onChange:t,...r,children:n.jsxs("div",{className:"nice-fx-card__row",children:[n.jsx(Le,{value:a.rate??1.5,min:.1,max:10,step:.1,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),n.jsx(Le,{value:a.depth??.5,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),n.jsx(Le,{value:a.feedback??.3,min:0,max:.95,step:.01,label:"Feedback",onChange:i=>s("feedback",i),disabled:!e.enabled}),n.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function km({effect:e,onChange:t,...r}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return n.jsx(wt,{effect:e,onChange:t,...r,children:n.jsxs("div",{className:"nice-fx-card__row",children:[n.jsx(Le,{value:a.low??0,min:-12,max:12,step:.5,label:"Low",onChange:i=>s("low",i),disabled:!e.enabled}),n.jsx(Le,{value:a.mid??0,min:-12,max:12,step:.5,label:"Mid",onChange:i=>s("mid",i),disabled:!e.enabled}),n.jsx(Le,{value:a.high??0,min:-12,max:12,step:.5,label:"High",onChange:i=>s("high",i),disabled:!e.enabled}),n.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function wm({effect:e,onChange:t,...r}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return n.jsx(wt,{effect:e,onChange:t,...r,children:n.jsxs("div",{className:"nice-fx-card__row",children:[n.jsx(Le,{value:a.frequency??1e3,min:20,max:2e4,step:1,label:"Freq",onChange:i=>s("frequency",i),disabled:!e.enabled}),n.jsx(Le,{value:a.Q??1,min:.1,max:20,step:.1,label:"Q",onChange:i=>s("Q",i),disabled:!e.enabled}),n.jsx(Le,{value:a.gain??0,min:-24,max:24,step:.5,label:"Gain",onChange:i=>s("gain",i),disabled:!e.enabled}),n.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function Cm({effect:e,onChange:t,...r}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return n.jsx(wt,{effect:e,onChange:t,...r,children:n.jsxs("div",{className:"nice-fx-card__row",children:[n.jsx(Le,{value:a.rate??5,min:.1,max:20,step:.1,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),n.jsx(Le,{value:a.depth??.5,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),n.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function jm({effect:e,onChange:t,...r}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return n.jsx(wt,{effect:e,onChange:t,...r,children:n.jsxs("div",{className:"nice-fx-card__row",children:[n.jsx(Le,{value:a.rate??.5,min:.01,max:8,step:.01,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),n.jsx(Le,{value:a.depth??.7,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),n.jsx(Le,{value:a.feedback??.5,min:0,max:.95,step:.01,label:"Feedback",onChange:i=>s("feedback",i),disabled:!e.enabled}),n.jsx(Le,{value:a.stages??4,min:2,max:12,step:2,label:"Stages",onChange:i=>s("stages",i),disabled:!e.enabled}),n.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}const Mm=({audioContext:e,chain:t,effects:r,onChange:a,onChainUpdate:s,maxEffects:i=10,availableEffects:o=fm,showPresets:l=!0,compact:c=!1,className:d=""})=>{const[h,f]=u.useState((r==null?void 0:r.map(j=>j.params))||[]),[p,y]=u.useState({isDragging:!1,dragIndex:-1,dropIndex:-1}),[m,x]=u.useState(!1),b=u.useMemo(()=>t||(e?new hm(e):null),[e,t]),g=u.useCallback((j,R)=>{const z=[...h];z[j]=R,f(z),a==null||a(z),b&&(s==null||s(b))},[h,a,b,s]),S=u.useCallback(j=>{if(h.length>=i)return;const R={...pm[j]},z=[...h,R];f(z),a==null||a(z),x(!1)},[h,i,a]),v=u.useCallback(j=>{const R=h.filter((z,A)=>A!==j);f(R),a==null||a(R)},[h,a]),k=u.useCallback(j=>{y({isDragging:!0,dragIndex:j,dropIndex:-1})},[]),M=u.useCallback(()=>{if(p.dragIndex!==-1&&p.dropIndex!==-1&&p.dragIndex!==p.dropIndex){const j=[...h],[R]=j.splice(p.dragIndex,1);j.splice(p.dropIndex,0,R),f(j),a==null||a(j)}y({isDragging:!1,dragIndex:-1,dropIndex:-1})},[p,h,a]),T=u.useCallback((j,R)=>{j.preventDefault(),p.isDragging&&y(z=>({...z,dropIndex:R}))},[p.isDragging]),N=(j,R)=>{const z={onRemove:()=>v(R),onDragStart:()=>k(R),onDragEnd:M,isDragTarget:p.dropIndex===R,presets:cm[j.type]||{},showPresets:l,compact:c};switch(j.type){case"gain":return n.jsx(mm,{effect:j,onChange:A=>g(R,A),...z},R);case"compressor":return n.jsx(gm,{effect:j,onChange:A=>g(R,A),...z},R);case"reverb":return n.jsx(ym,{effect:j,onChange:A=>g(R,A),...z},R);case"delay":return n.jsx(bm,{effect:j,onChange:A=>g(R,A),...z},R);case"distortion":return n.jsx(vm,{effect:j,onChange:A=>g(R,A),...z},R);case"chorus":return n.jsx(Sm,{effect:j,onChange:A=>g(R,A),...z},R);case"eq":return n.jsx(km,{effect:j,onChange:A=>g(R,A),...z},R);case"filter":return n.jsx(wm,{effect:j,onChange:A=>g(R,A),...z},R);case"tremolo":return n.jsx(Cm,{effect:j,onChange:A=>g(R,A),...z},R);case"phaser":return n.jsx(jm,{effect:j,onChange:A=>g(R,A),...z},R);default:return n.jsx(xm,{effect:j,onChange:A=>g(R,A),...z},R)}};return n.jsxs("div",{className:`nice-fx-rack ${c?"nice-fx-rack--compact":""} ${d}`,children:[n.jsxs("div",{className:"nice-fx-rack__header",children:[n.jsx("h3",{className:"nice-fx-rack__title",children:"Effects Chain"}),n.jsxs("span",{className:"nice-fx-rack__count",children:[h.length,"/",i]})]}),n.jsx("div",{className:"nice-fx-rack__chain",children:h.length===0?n.jsx("div",{className:"nice-fx-rack__empty",children:"No effects. Click + to add."}):h.map((j,R)=>n.jsxs("div",{className:"nice-fx-rack__slot",onDragOver:z=>T(z,R),children:[N(j,R),R<h.length-1&&n.jsx("div",{className:"nice-fx-rack__connector","aria-hidden":"true",children:n.jsx(G.NtdArrowRight,{size:14})})]},R))}),h.length<i&&n.jsxs("div",{className:"nice-fx-rack__add",children:[n.jsx("button",{type:"button",className:"nice-fx-rack__add-btn",onClick:()=>x(!m),children:"+ Add Effect"}),m&&n.jsx("div",{className:"nice-fx-rack__add-menu",children:o.map(j=>n.jsxs("button",{type:"button",className:"nice-fx-rack__add-item",onClick:()=>S(j),children:[n.jsx("span",{className:"nice-fx-rack__add-icon",children:_l[j]}),n.jsx("span",{className:"nice-fx-rack__add-label",children:Fl[j]})]},j))})]})]})},Ol=[{type:"chipmunk",enabled:!1,intensity:60,label:"Chipmunk",icon:"sparkle"},{type:"helium",enabled:!1,intensity:80,label:"Helium",icon:"sparkle"},{type:"deep",enabled:!1,intensity:50,label:"Deep Voice",icon:"music"},{type:"demon",enabled:!1,intensity:70,label:"Demon",icon:"skull"},{type:"robot",enabled:!1,intensity:50,label:"Robot",icon:"robot"},{type:"alien",enabled:!1,intensity:60,label:"Alien",icon:"ghost"},{type:"echo",enabled:!1,intensity:50,label:"Echo",icon:"mountain"},{type:"cave",enabled:!1,intensity:60,label:"Cave",icon:"mountain"},{type:"reverb",enabled:!1,intensity:50,label:"Reverb",icon:"wave"},{type:"chorus",enabled:!1,intensity:50,label:"Chorus",icon:"music"},{type:"flanger",enabled:!1,intensity:50,label:"Flanger",icon:"wave"},{type:"distortion",enabled:!1,intensity:40,label:"Distortion",icon:"lightning"},{type:"telephone",enabled:!1,intensity:80,label:"Telephone",icon:"phone"},{type:"megaphone",enabled:!1,intensity:60,label:"Megaphone",icon:"megaphone"},{type:"radio",enabled:!1,intensity:70,label:"AM Radio",icon:"wave"},{type:"underwater",enabled:!1,intensity:50,label:"Underwater",icon:"wave"},{type:"whisper",enabled:!1,intensity:60,label:"Whisper",icon:"volume-mute"},{type:"tremolo",enabled:!1,intensity:50,label:"Tremolo",icon:"wave"},{type:"autotune",enabled:!1,intensity:60,label:"Auto-Tune",icon:"microphone"},{type:"vocoder",enabled:!1,intensity:50,label:"Vocoder",icon:"volume"}];function Mi(e,t,r){const a=e.sampleRate,s=Math.round(a*t),i=e.createBuffer(2,s,a);for(let o=0;o<2;o++){const l=i.getChannelData(o);for(let c=0;c<s;c++)l[c]=(Math.random()*2-1)*Math.pow(1-c/s,r)}return i}function or(e){const t=Math.max(1,e),r=44100,a=new Float32Array(r),s=Math.PI/180;for(let i=0;i<r;i++){const o=i*2/r-1;a[i]=(3+t)*o*20*s/(Math.PI+t*Math.abs(o))}return a}class Bl{constructor(){this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.activeEffects=new Map,this.effectOrder=[],this.monitoring=!0,this._volume=1,this._inputVolume=1,this.started=!1,this.externalStream=!1,this.analyser=null}get isStarted(){return this.started}get context(){return this.audioCtx}get activeEffectTypes(){return[...this.effectOrder]}async start(t){this.started||(this.audioCtx=new AudioContext,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),this.sourceNode=this.audioCtx.createMediaStreamSource(this.mediaStream),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}async startWithStream(t){this.started||(this.externalStream=!0,this.audioCtx=new AudioContext,this.mediaStream=t,this.sourceNode=this.audioCtx.createMediaStreamSource(t),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}stop(){var t,r,a,s,i,o;this.clearAllEffects();try{(t=this.analyser)==null||t.disconnect()}catch{}try{(r=this.outputGain)==null||r.disconnect()}catch{}try{(a=this.inputGain)==null||a.disconnect()}catch{}try{(s=this.sourceNode)==null||s.disconnect()}catch{}try{(i=this.audioCtx)==null||i.close()}catch{}if(!this.externalStream)try{(o=this.mediaStream)==null||o.getTracks().forEach(l=>l.stop())}catch{}this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.analyser=null,this.started=!1}setMonitoring(t){this.monitoring=t,this.outputGain&&(this.outputGain.gain.value=t?this._volume:0)}setVolume(t){this._volume=Math.max(0,Math.min(2,t)),this.outputGain&&this.monitoring&&(this.outputGain.gain.value=this._volume)}setInputGain(t){this._inputVolume=Math.max(0,Math.min(3,t)),this.inputGain&&(this.inputGain.gain.value=this._inputVolume)}getLevel(){if(!this.analyser)return 0;const t=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(t);let r=0;for(let a=0;a<t.length;a++){const s=(t[a]-128)/128;r+=s*s}return Math.sqrt(r/t.length)}addEffect(t,r=50){if(!this.audioCtx||!this.inputGain||!this.outputGain||this.activeEffects.has(t))return;const a=this.buildEffectChain(t,r);a&&(this.activeEffects.set(t,a),this.effectOrder.push(t),this.reconnectChain())}removeEffect(t){const r=this.activeEffects.get(t);if(r){for(const a of r.nodes)try{a.disconnect()}catch{}this.activeEffects.delete(t),this.effectOrder=this.effectOrder.filter(a=>a!==t),this.reconnectChain()}}toggleEffect(t,r=50){return this.activeEffects.has(t)?(this.removeEffect(t),!1):(this.addEffect(t,r),!0)}updateIntensity(t,r){this.activeEffects.has(t)&&(this.removeEffect(t),this.addEffect(t,r))}clearAllEffects(){for(const[t]of this.activeEffects){const r=this.activeEffects.get(t);if(r)for(const a of r.nodes)try{a.disconnect()}catch{}}this.activeEffects.clear(),this.effectOrder=[],this.reconnectChain()}reconnectChain(){if(!this.inputGain||!this.outputGain)return;try{this.inputGain.disconnect()}catch{}for(const[,r]of this.activeEffects)try{r.output.disconnect()}catch{}if(this.effectOrder.length===0){this.inputGain.connect(this.outputGain);return}let t=this.inputGain;for(const r of this.effectOrder){const a=this.activeEffects.get(r);a&&(t.connect(a.input),t=a.output)}t.connect(this.outputGain)}buildEffectChain(t,r){const a=this.audioCtx,s=r/100;switch(t){case"chipmunk":return this.buildPitchShift(a,1+s*.8,s);case"helium":return this.buildPitchShift(a,1.5+s*1,s);case"deep":return this.buildPitchShift(a,1/(1+s*.5),s);case"demon":return this.buildDemon(a,s);case"robot":return this.buildRobot(a,s);case"alien":return this.buildAlien(a,s);case"echo":return this.buildDelay(a,.15+s*.35,.3+s*.4,s);case"cave":return this.buildCave(a,s);case"reverb":return this.buildReverb(a,1.5+s*3,2+s*4,s);case"chorus":return this.buildChorus(a,s);case"flanger":return this.buildFlanger(a,s);case"distortion":return this.buildDistortion(a,20+s*100,s);case"telephone":return this.buildBandpass(a,400,3500,s);case"megaphone":return this.buildMegaphone(a,s);case"radio":return this.buildRadio(a,s);case"underwater":return this.buildUnderwater(a,s);case"whisper":return this.buildWhisper(a,s);case"tremolo":return this.buildTremolo(a,s);case"autotune":return this.buildAutotune(a,s);case"vocoder":return this.buildVocoder(a,s);default:return null}}buildPitchShift(t,r,a){const s=t.createGain();s.gain.value=1;const i=t.createGain();i.gain.value=1;const o=t.createGain();o.gain.value=.7+a*.3;const l=t.createGain();l.gain.value=1-a*.5;const c=t.createDelay(1),d=t.createDelay(1),h=t.createOscillator(),f=t.createOscillator(),p=t.createGain(),y=t.createGain(),m=r-1,x=Math.abs(m)*5+2,b=Math.abs(m)*.015;h.type="sawtooth",h.frequency.value=x,p.gain.value=b,h.connect(p),p.connect(c.delayTime),c.delayTime.value=.02,f.type="sawtooth",f.frequency.value=x,y.gain.value=b,f.connect(y),y.connect(d.delayTime),d.delayTime.value=.02+b;const g=t.createGain();g.gain.value=.5;const S=t.createGain();return S.gain.value=.5,s.connect(c),s.connect(d),c.connect(g),d.connect(S),g.connect(o),S.connect(o),s.connect(l),o.connect(i),l.connect(i),h.start(),f.start(),{type:"chipmunk",nodes:[s,c,d,h,f,p,y,g,S,o,l,i],input:s,output:i}}buildRobot(t,r){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=.6+r*.4;const o=t.createGain();o.gain.value=1-r*.6;const l=t.createOscillator();l.type="square",l.frequency.value=50+r*200;const c=t.createGain();return c.gain.value=0,l.connect(c.gain),a.connect(c),c.connect(i),a.connect(o),i.connect(s),o.connect(s),l.start(),{type:"robot",nodes:[a,l,c,i,o,s],input:a,output:s}}buildAlien(t,r){const a=t.createGain(),s=t.createGain(),i=t.createOscillator();i.type="sine",i.frequency.value=300+r*700;const o=t.createGain();o.gain.value=0,i.connect(o.gain),a.connect(o);const l=t.createDelay(.1);l.delayTime.value=.005;const c=t.createOscillator();c.type="sine",c.frequency.value=3+r*10;const d=t.createGain();d.gain.value=.004,c.connect(d),d.connect(l.delayTime),o.connect(l),l.connect(s);const h=t.createGain();return h.gain.value=.3,a.connect(h),h.connect(s),i.start(),c.start(),{type:"alien",nodes:[a,i,o,l,c,d,h,s],input:a,output:s}}buildDelay(t,r,a,s){const i=t.createGain(),o=t.createGain(),l=t.createDelay(2);l.delayTime.value=r;const c=t.createGain();c.gain.value=Math.min(.85,a);const d=t.createGain();d.gain.value=.5+s*.5;const h=t.createGain();return h.gain.value=1,i.connect(l),l.connect(c),c.connect(l),l.connect(d),i.connect(h),d.connect(o),h.connect(o),{type:"echo",nodes:[i,l,c,d,h,o],input:i,output:o}}buildCave(t,r){const a=t.createGain(),s=t.createGain(),i=t.createDelay(2);i.delayTime.value=.2+r*.3;const o=t.createDelay(2);o.delayTime.value=.35+r*.25;const l=t.createDelay(2);l.delayTime.value=.55+r*.3;const c=t.createGain();c.gain.value=.5;const d=t.createGain();d.gain.value=.35;const h=t.createGain();h.gain.value=.25;const f=t.createConvolver();f.buffer=Mi(t,2+r*3,3);const p=t.createGain();p.gain.value=.3+r*.3,a.connect(i),i.connect(c),c.connect(i),a.connect(o),o.connect(d),d.connect(o),a.connect(l),l.connect(h),h.connect(l),i.connect(p),o.connect(p),l.connect(p),a.connect(f),f.connect(p);const y=t.createGain();return y.gain.value=.7,a.connect(y),y.connect(s),p.connect(s),{type:"cave",nodes:[a,i,o,l,c,d,h,f,p,y,s],input:a,output:s}}buildReverb(t,r,a,s){const i=t.createGain(),o=t.createGain(),l=t.createConvolver();l.buffer=Mi(t,r,a);const c=t.createGain();c.gain.value=.4+s*.5;const d=t.createGain();return d.gain.value=1,i.connect(l),l.connect(c),i.connect(d),c.connect(o),d.connect(o),{type:"reverb",nodes:[i,l,c,d,o],input:i,output:o}}buildChorus(t,r){const a=t.createGain(),s=t.createGain(),i=[{delayMs:20,lfoFreq:.5,depth:.003},{delayMs:25,lfoFreq:.7,depth:.004},{delayMs:30,lfoFreq:1.1,depth:.005}],o=[a,s],l=t.createGain();l.gain.value=.7,a.connect(l),l.connect(s),o.push(l);for(const c of i){const d=t.createDelay(.1);d.delayTime.value=c.delayMs/1e3;const h=t.createOscillator();h.type="sine",h.frequency.value=c.lfoFreq;const f=t.createGain();f.gain.value=c.depth*(.5+r),h.connect(f),f.connect(d.delayTime);const p=t.createGain();p.gain.value=.3+r*.2,a.connect(d),d.connect(p),p.connect(s),h.start(),o.push(d,h,f,p)}return{type:"chorus",nodes:o,input:a,output:s}}buildFlanger(t,r){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.02);i.delayTime.value=.005;const o=t.createOscillator();o.type="sine",o.frequency.value=.2+r*2;const l=t.createGain();l.gain.value=.003+r*.002,o.connect(l),l.connect(i.delayTime);const c=t.createGain();c.gain.value=.5+r*.35;const d=t.createGain();d.gain.value=.5+r*.3;const h=t.createGain();return h.gain.value=1,a.connect(i),i.connect(c),c.connect(i),i.connect(d),a.connect(h),d.connect(s),h.connect(s),o.start(),{type:"flanger",nodes:[a,i,o,l,c,d,h,s],input:a,output:s}}buildDistortion(t,r,a){const s=t.createGain(),i=t.createGain(),o=t.createWaveShaper();o.curve=or(r),o.oversample="4x";const l=t.createGain();l.gain.value=.6+a*.4;const c=t.createGain();return c.gain.value=1-a*.4,s.connect(o),o.connect(l),s.connect(c),l.connect(i),c.connect(i),{type:"distortion",nodes:[s,o,l,c,i],input:s,output:i}}buildBandpass(t,r,a,s){const i=t.createGain(),o=t.createGain(),l=t.createBiquadFilter();l.type="highpass",l.frequency.value=r,l.Q.value=.7;const c=t.createBiquadFilter();return c.type="lowpass",c.frequency.value=a,c.Q.value=.7,i.connect(l),l.connect(c),c.connect(o),{type:"telephone",nodes:[i,l,c,o],input:i,output:o}}buildMegaphone(t,r){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500;const o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=4e3;const l=t.createWaveShaper();l.curve=or(15+r*30),l.oversample="2x";const c=t.createBiquadFilter();return c.type="peaking",c.frequency.value=2e3,c.gain.value=6+r*6,c.Q.value=1,a.connect(i),i.connect(o),o.connect(l),l.connect(c),c.connect(s),{type:"megaphone",nodes:[a,i,o,l,c,s],input:a,output:s}}buildRadio(t,r){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=300+r*200;const o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=3e3-r*500;const l=t.createBiquadFilter();l.type="peaking",l.frequency.value=1500,l.gain.value=8,l.Q.value=2;const c=t.createWaveShaper();return c.curve=or(10),a.connect(i),i.connect(o),o.connect(l),l.connect(c),c.connect(s),{type:"radio",nodes:[a,i,o,l,c,s],input:a,output:s}}buildUnderwater(t,r){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="lowpass",i.frequency.value=300+(1-r)*400,i.Q.value=5+r*10;const o=t.createOscillator();o.type="sine",o.frequency.value=.5+r*2;const l=t.createGain();l.gain.value=100+r*200,o.connect(l),l.connect(i.frequency);const c=t.createGain();c.gain.value=.7+r*.3;const d=t.createGain();return d.gain.value=.3-r*.2,a.connect(i),i.connect(c),a.connect(d),c.connect(s),d.connect(s),o.start(),{type:"underwater",nodes:[a,i,o,l,c,d,s],input:a,output:s}}buildWhisper(t,r){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500+r*500,i.Q.value=.5;const o=t.createWaveShaper(),l=new Float32Array(256);for(let d=0;d<256;d++){const h=d/255*2-1;l[d]=Math.sign(h)*Math.pow(Math.abs(h),.3+r*.5)}o.curve=l;const c=t.createBiquadFilter();return c.type="highshelf",c.frequency.value=3e3,c.gain.value=6+r*6,a.connect(i),i.connect(o),o.connect(c),c.connect(s),{type:"whisper",nodes:[a,i,o,c,s],input:a,output:s}}buildDemon(t,r){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.1);i.delayTime.value=.03;const o=t.createOscillator();o.type="sawtooth",o.frequency.value=2+r*3;const l=t.createGain();l.gain.value=.02+r*.015,o.connect(l),l.connect(i.delayTime);const c=t.createWaveShaper();c.curve=or(20+r*50),c.oversample="2x";const d=t.createBiquadFilter();d.type="lowshelf",d.frequency.value=200,d.gain.value=8+r*8;const h=t.createGain();h.gain.value=.7+r*.3;const f=t.createGain();return f.gain.value=.3,a.connect(i),i.connect(c),c.connect(d),d.connect(h),a.connect(f),h.connect(s),f.connect(s),o.start(),{type:"demon",nodes:[a,i,o,l,c,d,h,f,s],input:a,output:s}}buildTremolo(t,r){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=1;const o=t.createOscillator();o.type="sine",o.frequency.value=3+r*12;const l=t.createGain();return l.gain.value=.3+r*.5,o.connect(l),l.connect(i.gain),a.connect(i),i.connect(s),o.start(),{type:"tremolo",nodes:[a,i,o,l,s],input:a,output:s}}buildAutotune(t,r){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.05);i.delayTime.value=.005;const o=t.createOscillator();o.type="sine",o.frequency.value=6+r*8;const l=t.createGain();l.gain.value=.002+r*.002,o.connect(l),l.connect(i.delayTime);const c=[],d=[261.6,293.7,329.6,349.2,392,440,493.9,523.3],h=t.createGain();h.gain.value=.15;for(const y of d){const m=t.createBiquadFilter();m.type="peaking",m.frequency.value=y,m.Q.value=8+r*15,m.gain.value=4+r*8,a.connect(m),m.connect(h),c.push(m)}const f=t.createGain();f.gain.value=.7;const p=t.createGain();return p.gain.value=.5+r*.3,a.connect(i),i.connect(p),h.connect(p),a.connect(f),p.connect(s),f.connect(s),o.start(),{type:"autotune",nodes:[a,i,o,l,...c,h,p,f,s],input:a,output:s}}buildVocoder(t,r){const a=t.createGain(),s=t.createGain(),i=t.createOscillator();i.type="sawtooth",i.frequency.value=110+r*110;const o=t.createGain();o.gain.value=0;const l=8,c=[a,s,i,o],d=t.createGain();d.gain.value=.5+r*.5,c.push(d);for(let f=0;f<l;f++){const p=200*Math.pow(2,f*.5),y=t.createBiquadFilter();y.type="bandpass",y.frequency.value=p,y.Q.value=4;const m=t.createBiquadFilter();m.type="bandpass",m.frequency.value=p,m.Q.value=4;const x=t.createGain();x.gain.value=0,a.connect(y),y.connect(x.gain),i.connect(m),m.connect(x),x.connect(d),c.push(y,m,x)}d.connect(s);const h=t.createGain();return h.gain.value=.3-r*.2,a.connect(h),h.connect(s),c.push(h),i.start(),{type:"vocoder",nodes:c,input:a,output:s}}}const Rm={sparkle:G.NtdSparkle,music:G.NtdMusic,skull:G.NtdSkull,robot:G.NtdRobot,ghost:G.NtdGhost,mountain:G.NtdMountain,wave:G.NtdWave,lightning:G.NtdLightning,phone:G.NtdPhone,megaphone:G.NtdMegaphone,"volume-mute":G.NtdVolumeMute,microphone:G.NtdMicrophone,volume:G.NtdVolume},Nm=({deviceId:e,mediaStream:t,compact:r=!1,t:a,className:s,style:i,id:o,accessMode:l,"data-testid":c})=>{const{t:d}=Pe(),h=a??d,f=u.useRef(null),[p,y]=u.useState(!1),[m,x]=u.useState(()=>Ol.map(_=>({..._}))),[b,g]=u.useState(!0),[S,v]=u.useState(80),[k,M]=u.useState(100),[T,N]=u.useState(0),j=u.useRef(0),R=u.useCallback(()=>{const _=()=>{var W;(W=f.current)!=null&&W.isStarted&&(N(f.current.getLevel()),j.current=requestAnimationFrame(_))};j.current=requestAnimationFrame(_)},[]),z=u.useCallback(()=>{j.current&&cancelAnimationFrame(j.current)},[]),A=u.useCallback(async()=>{const _=new Bl;f.current=_;try{t?await _.startWithStream(t):await _.start(e),_.setMonitoring(b),_.setVolume(S/100),_.setInputGain(k/100);for(const W of m)W.enabled&&_.addEffect(W.type,W.intensity);y(!0),R()}catch(W){typeof console<"u"&&console.warn("[VocalEffectsRack] start error",W)}},[e,t,b,S,k,m,R]),$=u.useCallback(()=>{var _;z(),(_=f.current)==null||_.stop(),f.current=null,y(!1),N(0)},[z]);u.useEffect(()=>()=>{var _;z(),(_=f.current)==null||_.stop(),f.current=null},[z]);const O=u.useCallback(_=>{x(W=>W.map(K=>{var X;if(K.type!==_)return K;const re={...K,enabled:!K.enabled};return(X=f.current)!=null&&X.isStarted&&(re.enabled?f.current.addEffect(_,re.intensity):f.current.removeEffect(_)),re}))},[]),I=u.useCallback((_,W)=>{x(K=>K.map(re=>{var X;return re.type!==_?re:(re.enabled&&((X=f.current)!=null&&X.isStarted)&&f.current.updateIntensity(_,W),{...re,intensity:W})}))},[]);u.useEffect(()=>{var _;(_=f.current)==null||_.setVolume(S/100)},[S]),u.useEffect(()=>{var _;(_=f.current)==null||_.setInputGain(k/100)},[k]),u.useEffect(()=>{var _;(_=f.current)==null||_.setMonitoring(b)},[b]);const U=u.useCallback(()=>{var _;(_=f.current)==null||_.clearAllEffects(),x(W=>W.map(K=>({...K,enabled:!1})))},[]),J=m.filter(_=>_.enabled).length;return l==="hidden"?null:n.jsxs("div",{className:`nice-vocal-effects-rack${s?` ${s}`:""}`,style:{border:"1px solid var(--nice-border, #e2e8f0)",borderRadius:12,padding:r?12:20,background:"var(--nice-bg-secondary)",color:"var(--nice-text, inherit)",...i},id:o,"data-testid":c,children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16,gap:8},children:[n.jsxs("h3",{style:{margin:0,fontSize:r?16:20,display:"flex",alignItems:"center",gap:8},children:[n.jsx(G.NtdMicrophone,{size:r?16:20})," ",h("vocalEffects.title","Vocal effects")]}),n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[J>0&&n.jsxs(ve.NiceBadge,{variant:"primary",children:[J," ",h("vocalEffects.active","active")]}),p?n.jsx(ve.NiceButton,{variant:"danger",size:"sm",onClick:$,children:h("vocalEffects.stop","Stop")}):n.jsx(ve.NiceButton,{variant:"primary",size:"sm",onClick:A,children:h("vocalEffects.start","Start mic")})]})]}),n.jsxs("div",{style:{display:"flex",gap:16,alignItems:"center",marginBottom:16,flexWrap:"wrap"},children:[n.jsx(ve.NiceToggle,{checked:b,onChange:g,label:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(G.NtdVolume,{size:14})," ",h("vocalEffects.monitor","Monitor")]})}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[h("vocalEffects.volume","Vol"),n.jsx("div",{style:{width:100},children:n.jsx(ve.NiceSlider,{value:S,onChange:v,min:0,max:200})}),n.jsxs("span",{style:{minWidth:36,fontSize:12},children:[S,"%"]})]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[h("vocalEffects.gain","Gain"),n.jsx("div",{style:{width:100},children:n.jsx(ve.NiceSlider,{value:k,onChange:M,min:0,max:300})}),n.jsxs("span",{style:{minWidth:36,fontSize:12},children:[k,"%"]})]}),p&&n.jsx("div",{style:{width:80,height:8,borderRadius:4,background:"var(--nice-bg-tertiary)",overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:`${Math.min(100,T*300)}%`,background:T>.5?"var(--nice-danger, #ef4444)":T>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})}),J>0&&n.jsx(ve.NiceButton,{variant:"ghost",size:"sm",onClick:U,children:h("vocalEffects.clearAll","Clear all")})]}),n.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(auto-fill, minmax(${r?130:160}px, 1fr))`,gap:r?6:10},children:m.map(_=>n.jsxs("div",{style:{border:_.enabled?"2px solid var(--nice-accent, #3b82f6)":"1px solid var(--nice-border, #e2e8f0)",borderRadius:10,padding:r?"6px 8px":"10px 12px",background:_.enabled?"var(--nice-accent-tint-10, rgba(59,130,246,0.08))":"transparent",transition:"all 0.15s ease"},children:[n.jsxs("button",{type:"button",onClick:()=>O(_.type),style:{display:"flex",alignItems:"center",gap:6,width:"100%",marginBottom:_.enabled?6:0,background:"transparent",border:"none",cursor:"pointer",color:"inherit",textAlign:"left"},children:[(()=>{const W=Rm[_.icon]??G.NtdMusic;return n.jsx(W,{size:r?18:22})})(),n.jsx("span",{style:{fontSize:r?12:14,fontWeight:_.enabled?700:500,color:_.enabled?"var(--nice-accent, #3b82f6)":"inherit"},children:_.label})]}),_.enabled&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},onClick:W=>W.stopPropagation(),children:[n.jsx("div",{style:{flex:1},children:n.jsx(ve.NiceSlider,{value:_.intensity,onChange:W=>I(_.type,W),min:0,max:100})}),n.jsx("span",{style:{fontSize:11,minWidth:24,color:"var(--nice-text-muted, #64748b)"},children:_.intensity})]})]},_.type))}),n.jsx("div",{style:{marginTop:12,fontSize:12,color:"var(--nice-text-muted, #94a3b8)",textAlign:"center"},children:h("vocalEffects.hint","Click effects to toggle. Multiple effects can be active at once — adjust intensity with the slider.")})]})},Gl={algorithm:"pitchy",gain:1,rmsThreshold:.02,pitchThreshold:.6,smoothingWindow:3,hysteresisFrames:2,useHanning:!1,offsetMs:0},Tm=[{value:"pitchy",label:"Pitchy (fast)"},{value:"autocorrelation",label:"Autocorrelation"},{value:"librosa",label:"Librosa (server)"},{value:"crepe",label:"CREPE (AI, server)"}],$m=({deviceId:e,onDeviceChange:t,settings:r,onSettingsChange:a,audioInputs:s,algorithms:i=Tm,showLevelMeter:o=!0,onCalibrate:l,compact:c=!1,t:d})=>{const{t:h}=Pe(),f=d??h,p=u.useMemo(()=>({...Gl,...r}),[r]),y=A=>a==null?void 0:a({...p,...A}),[m,x]=u.useState([]);u.useEffect(()=>{var O,I,U;if(s||!((O=navigator.mediaDevices)!=null&&O.enumerateDevices))return;let A=!1;const $=()=>navigator.mediaDevices.enumerateDevices().then(J=>!A&&x(J.filter(_=>_.kind==="audioinput"))).catch(()=>{});return $(),(U=(I=navigator.mediaDevices).addEventListener)==null||U.call(I,"devicechange",$),()=>{var J,_;A=!0,(_=(J=navigator.mediaDevices).removeEventListener)==null||_.call(J,"devicechange",$)}},[s]);const b=s??m,g=u.useMemo(()=>b.map((A,$)=>({value:A.deviceId,label:A.label||`${f("audioInput.microphone","Microphone")} ${$+1}`})),[b,f]),[S,v]=u.useState(!1),[k,M]=u.useState(0),T=u.useRef(null),N=()=>{const A=T.current;A&&(cancelAnimationFrame(A.raf),A.stream.getTracks().forEach($=>$.stop()),A.ctx.close().catch(()=>{}),T.current=null),v(!1),M(0)},j=async()=>{try{const A=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0}}),$=new AudioContext,O=$.createMediaStreamSource(A),I=$.createAnalyser();I.fftSize=1024,O.connect(I);const U=new Float32Array(I.fftSize),J=()=>{I.getFloatTimeDomainData(U);let _=0;for(let W=0;W<U.length;W++)_+=U[W]*U[W];M(Math.sqrt(_/U.length)*(p.gain||1)),T.current.raf=requestAnimationFrame(J)};T.current={ctx:$,stream:A,raf:requestAnimationFrame(J)},v(!0)}catch{}};u.useEffect(()=>()=>N(),[]);const R={fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:4,display:"block"},z=(A,$,O)=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[n.jsx("span",{style:{flex:"0 0 120px",fontSize:13},children:A}),n.jsx("div",{style:{flex:1},children:$}),n.jsx("span",{style:{flex:"0 0 48px",textAlign:"right",fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:O})]});return n.jsxs("div",{className:"nice-audio-input-picker",style:{display:"flex",flexDirection:"column",gap:c?8:12,border:"1px solid var(--nice-border, #e2e8f0)",borderRadius:12,padding:c?12:16,color:"var(--nice-text, inherit)"},children:[n.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap"},children:[n.jsxs("div",{style:{flex:"1 1 220px",minWidth:180},children:[n.jsxs("label",{style:{...R,display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(G.NtdMicrophone,{size:13})," ",f("audioInput.device","Microphone")]}),n.jsx(ve.NiceSelect,{options:g,value:e??"",onChange:A=>t==null?void 0:t(typeof A=="string"?A:A[0]),placeholder:f("audioInput.selectDevice","Select microphone"),size:"sm"})]}),n.jsxs("div",{style:{flex:"1 1 200px",minWidth:160},children:[n.jsx("label",{style:R,children:f("audioInput.algorithm","Pitch algorithm")}),n.jsx(ve.NiceSelect,{options:i,value:p.algorithm,onChange:A=>y({algorithm:typeof A=="string"?A:A[0]}),size:"sm"})]})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[z(f("audioInput.gain","Gain"),n.jsx(ve.NiceSlider,{value:Math.round(p.gain*100),onChange:A=>y({gain:A/100}),min:0,max:300}),`${Math.round(p.gain*100)}%`),z(f("audioInput.rmsThreshold","RMS gate"),n.jsx(ve.NiceSlider,{value:Math.round(p.rmsThreshold*1e3),onChange:A=>y({rmsThreshold:A/1e3}),min:0,max:200}),p.rmsThreshold.toFixed(3)),z(f("audioInput.pitchThreshold","Pitch clarity"),n.jsx(ve.NiceSlider,{value:Math.round(p.pitchThreshold*100),onChange:A=>y({pitchThreshold:A/100}),min:0,max:100}),p.pitchThreshold.toFixed(2)),!c&&z(f("audioInput.smoothing","Smoothing"),n.jsx(ve.NiceSlider,{value:p.smoothingWindow,onChange:A=>y({smoothingWindow:A}),min:0,max:12}),`${p.smoothingWindow}`),!c&&z(f("audioInput.hysteresis","Hysteresis"),n.jsx(ve.NiceSlider,{value:p.hysteresisFrames,onChange:A=>y({hysteresisFrames:A}),min:0,max:12}),`${p.hysteresisFrames}`),!c&&z(f("audioInput.offset","Latency"),n.jsx(ve.NiceSlider,{value:p.offsetMs,onChange:A=>y({offsetMs:A}),min:-200,max:500}),`${p.offsetMs}ms`)]}),n.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap"},children:[n.jsx(ve.NiceToggle,{checked:p.useHanning,onChange:A=>y({useHanning:A}),label:f("audioInput.hanning","Hanning window")}),o&&n.jsxs(n.Fragment,{children:[n.jsx(ve.NiceButton,{variant:S?"danger":"secondary",size:"sm",onClick:S?N:j,children:S?f("audioInput.stopTest","Stop test"):f("audioInput.testMic","Test mic")}),n.jsx("div",{style:{width:100,height:8,borderRadius:4,background:"var(--nice-bg-tertiary)",overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:`${Math.min(100,k*300)}%`,background:k>.5?"var(--nice-danger, #ef4444)":k>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})})]}),l&&e&&n.jsxs(ve.NiceButton,{variant:"ghost",size:"sm",onClick:()=>l(e),children:[n.jsx(G.NtdSettings,{size:14})," ",f("audioInput.calibrate","Calibrate latency")]})]})]})};class Wl{constructor(t,r){this.activeNotes=new Map,this.audioContext=t,this.masterGain=t.createGain(),this.masterGain.gain.value=.3,this.masterGain.connect(r)}applyCC(t,r,a){}midiToFreq(t){return 440*Math.pow(2,(t-69)/12)}playNote(t,r=100,a=1,s="sine"){const i=this.midiToFreq(t),o=this.audioContext.createOscillator(),l=this.audioContext.createGain();o.type=s,o.frequency.value=i;const c=r/127*.8;l.gain.value=c,o.connect(l),l.connect(this.masterGain);const d=this.audioContext.currentTime;return l.gain.setValueAtTime(0,d),l.gain.linearRampToValueAtTime(c,d+.01),l.gain.exponentialRampToValueAtTime(c*.7,d+.1),l.gain.setValueAtTime(c*.7,d+a-.05),l.gain.exponentialRampToValueAtTime(.001,d+a),o.start(d),o.stop(d+a),o.onended=()=>{l.disconnect(),o.disconnect()},{osc:o,gain:l}}scheduleNote(t,r,a,s=100,i="sine"){const o=this.midiToFreq(t),l=this.audioContext.createOscillator(),c=this.audioContext.createGain();l.type=i,l.frequency.value=o;const d=s/127*.8;l.connect(c),c.connect(this.masterGain);const h=r;return c.gain.setValueAtTime(0,h),c.gain.linearRampToValueAtTime(d,h+.01),c.gain.exponentialRampToValueAtTime(d*.7,h+.1),c.gain.setValueAtTime(d*.7,h+a-.05),c.gain.exponentialRampToValueAtTime(.001,h+a),l.start(h),l.stop(h+a),l.onended=()=>{c.disconnect(),l.disconnect()},{osc:l,gain:c}}setVolume(t){this.masterGain.gain.value=Math.max(0,Math.min(1,t))}stopAll(){this.activeNotes.forEach(({osc:t,gain:r})=>{try{t.stop(),r.disconnect(),t.disconnect()}catch{}}),this.activeNotes.clear()}dispose(){this.stopAll(),this.masterGain.disconnect()}}const Ri=it.scoped("AudioPlaybackEngine");class Pm{constructor(){this.audioContext=null,this.masterGain=null,this.masterFilter=null,this.clips=new Map,this.scheduledSources=new Map,this.midiTracks=new Map,this.synths=new Map,this.isPlaying=!1,this.startTimeOffset=0,this.audioContextStartTime=0,this.currentTime=0,this.loopRegion={start:0,end:0,enabled:!1},this.bpm=120,this.duration=0,this.initAudioContext()}setMidiCCEvents(t,r){const a=this.midiTracks.get(t);a&&(a.ccEvents=r)}getMidiCCEvents(t){const r=this.midiTracks.get(t);return(r==null?void 0:r.ccEvents)||[]}addMidiCCEvent(t,r){const a=this.midiTracks.get(t);a&&(a.ccEvents||(a.ccEvents=[]),a.ccEvents.push(r))}removeMidiCCEvent(t,r){const a=this.midiTracks.get(t);a&&a.ccEvents&&(a.ccEvents=a.ccEvents.filter(s=>s.id!==r))}initAudioContext(){try{this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.masterGain=this.audioContext.createGain(),this.masterFilter=this.audioContext.createBiquadFilter(),this.masterFilter.type="peaking",this.masterFilter.frequency.value=1200,this.masterFilter.Q.value=.7,this.masterFilter.gain.value=0,this.masterGain.connect(this.masterFilter),this.masterFilter.connect(this.audioContext.destination),this.masterGain.gain.value=.8,this.audioContext.state==="suspended"&&this.audioContext.resume()}catch(t){Ri.error("Failed to initialize AudioContext:",t)}}createEffectNode(t){if(!this.audioContext||t.bypass)return null;try{switch(t.type){case"eq3":{const r=this.audioContext.createBiquadFilter(),a=this.audioContext.createBiquadFilter(),s=this.audioContext.createBiquadFilter();return r.type="lowshelf",r.frequency.value=t.params.lowFreq||250,r.gain.value=t.params.lowGain||0,a.type="peaking",a.frequency.value=1e3,a.Q.value=1,a.gain.value=t.params.midGain||0,s.type="highshelf",s.frequency.value=t.params.highFreq||4e3,s.gain.value=t.params.highGain||0,r.connect(a),a.connect(s),{input:r,output:s}}case"compressor":{const r=this.audioContext.createDynamicsCompressor();return r.threshold.value=t.params.threshold||-24,r.ratio.value=t.params.ratio||4,r.attack.value=t.params.attack||.003,r.release.value=t.params.release||.25,r.knee.value=t.params.knee||30,r}case"delay":{const r=this.audioContext.createDelay(5);r.delayTime.value=t.params.time||.25;const a=this.audioContext.createGain();a.gain.value=t.params.feedback||.3;const s=this.audioContext.createGain();s.gain.value=t.params.mix||.3;const i=this.audioContext.createGain();return i.gain.value=1-(t.params.mix||.3),r.connect(a),a.connect(r),r.connect(s),{input:r,output:s,dry:i,connect:function(o){s.connect(o),i.connect(o)}}}case"reverb":{const r=this.audioContext.createConvolver(),a=this.audioContext.sampleRate*(t.params.decay||2),s=this.audioContext.createBuffer(2,a,this.audioContext.sampleRate);for(let l=0;l<2;l++){const c=s.getChannelData(l);for(let d=0;d<a;d++)c[d]=(Math.random()*2-1)*Math.pow(1-d/a,2)}r.buffer=s;const i=this.audioContext.createGain();i.gain.value=t.params.mix||.3;const o=this.audioContext.createGain();return o.gain.value=1-(t.params.mix||.3),r.connect(i),{input:r,output:i,dry:o,connect:function(l){i.connect(l),o.connect(l)}}}case"distortion":{const r=this.audioContext.createWaveShaper(),a=t.params.amount||20,s=44100,i=new Float32Array(s),o=Math.PI/180;for(let d=0;d<s;d++){const h=d*2/s-1;i[d]=(3+a)*h*20*o/(Math.PI+a*Math.abs(h))}r.curve=i,r.oversample="4x";const l=this.audioContext.createGain();l.gain.value=t.params.mix||.5;const c=this.audioContext.createGain();return c.gain.value=1-(t.params.mix||.5),r.connect(l),{input:r,output:l,dry:c,connect:function(d){l.connect(d),c.connect(d)}}}default:return null}}catch(r){return Ri.error("Failed to create effect node:",t.type,r),null}}addClip(t){this.clips.set(t.id,t),this.updateDuration()}removeClip(t){this.clips.delete(t),this.stopClip(t),this.updateDuration()}updateClip(t,r){const a=this.clips.get(t);a&&(Object.assign(a,r),this.updateDuration())}getClipsByLayer(t){return Array.from(this.clips.values()).filter(r=>r.layerId===t)}setMidiTrack(t,r,a="sine",s=.5){if(this.midiTracks.set(t,{layerId:t,notes:r,instrument:a,volume:s}),!this.synths.has(t)&&this.audioContext&&this.masterGain){const i=new Wl(this.audioContext,this.masterGain);i.setVolume(s),this.synths.set(t,i)}}removeMidiTrack(t){this.midiTracks.delete(t);const r=this.synths.get(t);r&&(r.dispose(),this.synths.delete(t))}updateMidiTrackVolume(t,r){const a=this.midiTracks.get(t);a&&(a.volume=r);const s=this.synths.get(t);s&&s.setVolume(r)}updateDuration(){let t=0;this.clips.forEach(r=>{const a=r.startTime+r.duration;a>t&&(t=a)}),this.duration=t}play(){!this.audioContext||this.isPlaying||(this.audioContext.state==="suspended"&&this.audioContext.resume(),this.isPlaying=!0,this.audioContextStartTime=this.audioContext.currentTime,this.startTimeOffset=this.currentTime,this.scheduleClips(),this.scheduleMidiNotes(),this.startTimeTracking(),this.onPlayStateChange&&this.onPlayStateChange(!0))}pause(){this.isPlaying&&(this.isPlaying=!1,this.stopAllSources(),this.onPlayStateChange&&this.onPlayStateChange(!1))}stop(){this.pause(),this.seek(0)}seek(t){const r=this.isPlaying;r&&this.pause(),this.currentTime=Math.max(0,Math.min(t,this.duration)),this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),r&&this.play()}scheduleClips(){!this.audioContext||!this.masterGain||this.clips.forEach(t=>{if(t.startTime+t.duration<=this.currentTime)return;const a=this.audioContext.createBufferSource();a.buffer=t.buffer,t.stretchFactor&&t.stretchFactor!==1&&(a.playbackRate.value=1/t.stretchFactor);const s=this.audioContext.createGain();s.gain.value=t.volume;const i=this.audioContext.createStereoPanner();i.pan.value=t.pan,a.connect(s);let o=s;if(t.effectChain&&t.effectChain.length>0)for(const h of t.effectChain){const f=this.createEffectNode(h);if(f)if("input"in f&&"output"in f){const p=f;o.connect(p.input),o=p.output,"dry"in f&&s.connect(p.dry)}else o.connect(f),o=f}o.connect(i),i.connect(this.masterGain);const l=t.startTime,c=Math.max(0,this.currentTime-l),d=this.audioContext.currentTime+(l-this.currentTime);d>=this.audioContext.currentTime&&(a.start(d,t.offset+c,t.duration-c),this.scheduledSources.set(t.id,a),a.onended=()=>{this.scheduledSources.delete(t.id)})})}stopClip(t){const r=this.scheduledSources.get(t);if(r){try{r.stop()}catch{}this.scheduledSources.delete(t)}}stopAllSources(){this.scheduledSources.forEach(t=>{try{t.stop()}catch{}}),this.scheduledSources.clear(),this.synths.forEach(t=>t.stopAll())}scheduleMidiNotes(){this.audioContext&&this.midiTracks.forEach(t=>{const r=this.synths.get(t.layerId);if(r&&(t.notes.forEach(a=>{if(a.start+a.duration<=this.currentTime)return;const i=Math.max(0,this.currentTime-a.start),o=this.audioContext.currentTime+(a.start-this.currentTime);o>=this.audioContext.currentTime&&r.scheduleNote(a.pitch,o,a.duration-i,a.velocity,t.instrument)}),t.ccEvents&&Array.isArray(t.ccEvents)&&t.ccEvents.length>0)){const a=[...t.ccEvents].sort((o,l)=>o.time-l.time);let i=a[0];for(let o=1;o<a.length;++o){const l=a[o],c=i.time,d=l.time,h=i.value,f=l.value,p=i.handleType||"linear",y=Math.max(2,Math.ceil((d-c)*20));for(let m=0;m<=y;++m){const x=m/y;let b=h;if(p==="linear")b=h+(f-h)*x;else if(p==="step")b=x<1?h:f;else if(p==="exp"){const k=Math.max(h/127,.001),M=Math.max(f/127,.001);b=k*Math.pow(M/k,x)*127}const g=c+(d-c)*x,S=this.audioContext.currentTime+(g-this.currentTime);S>=this.audioContext.currentTime&&typeof r.applyCC=="function"&&r.applyCC(l.cc,b,S)}i=l}}})}startTimeTracking(){if(!this.audioContext)return;const t=()=>{if(!this.isPlaying||!this.audioContext)return;const r=this.audioContext.currentTime-this.audioContextStartTime;if(this.currentTime=this.startTimeOffset+r,this.loopRegion.enabled&&this.currentTime>=this.loopRegion.end){this.seek(this.loopRegion.start);return}if(this.currentTime>=this.duration){this.stop();return}this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),requestAnimationFrame(t)};requestAnimationFrame(t)}setLoopRegion(t,r,a){this.loopRegion={start:t,end:r,enabled:a}}setBPM(t){this.bpm=Math.max(20,Math.min(300,t))}getBPM(){return this.bpm}setMasterVolume(t){this.masterGain&&(this.masterGain.gain.value=Math.max(0,Math.min(1,t)))}setMasterFilter(t){this.masterFilter&&(t.type&&(this.masterFilter.type=t.type),t.frequency!=null&&(this.masterFilter.frequency.value=Math.max(20,Math.min(2e4,t.frequency))),t.q!=null&&(this.masterFilter.Q.value=Math.max(.1,Math.min(18,t.q))),t.gain!=null&&"gain"in this.masterFilter&&(this.masterFilter.gain.value=Math.max(-40,Math.min(40,t.gain))))}getCurrentTime(){return this.currentTime}getDuration(){return this.duration}getIsPlaying(){return this.isPlaying}setOnTimeUpdate(t){this.onTimeUpdate=t}setOnPlayStateChange(t){this.onPlayStateChange=t}dispose(){this.stop(),this.audioContext&&this.audioContext.close(),this.clips.clear()}}const Em=[{name:"Grand Piano",waveform:"sawtooth",attack:.02,sustain:.7,release:1.2,eq:{C:2,D:1,E:1,F:0,G:0,A:-1,B:-2,C2:-3},category:"Keyboard"},{name:"Electric Piano",waveform:"triangle",attack:.03,sustain:.8,release:1,eq:{C:0,D:1,E:2,F:3,G:1,A:-1,B:-2,C2:-2},category:"Keyboard"},{name:"Harpsichord",waveform:"square",attack:.01,sustain:.5,release:.6,eq:{C:-1,D:-1,E:0,F:2,G:3,A:1,B:0,C2:-1},category:"Keyboard"},{name:"Violin",waveform:"triangle",attack:.3,sustain:1,release:1.5,eq:{C:3,D:2,E:2,F:1,G:-1,A:-2,B:-3,C2:-3},category:"String"},{name:"Acoustic Guitar",waveform:"sawtooth",attack:.2,sustain:.6,release:.9,eq:{C:-1,D:-2,E:0,F:1,G:3,A:2,B:0,C2:-2},category:"String"},{name:"Electric Guitar",waveform:"square",attack:.05,sustain:.7,release:1.2,eq:{C:-2,D:1,E:2,F:2,G:1,A:0,B:-1,C2:-3},category:"String"},{name:"Kick Drum",waveform:"sine",attack:.005,sustain:.1,release:.2,eq:{C:5,D:3,E:0,F:-3,G:-5,A:-7,B:-9,C2:-10},category:"Percussion"},{name:"Snare Drum",waveform:"triangle",attack:.01,sustain:.2,release:.3,eq:{C:-2,D:-1,E:1,F:2,G:3,A:2,B:0,C2:-2},category:"Percussion"},{name:"Hi-Hat",waveform:"square",attack:.002,sustain:.05,release:.1,eq:{C:-5,D:-3,E:0,F:2,G:5,A:7,B:9,C2:10},category:"Percussion"},{name:"Acoustic Bass",waveform:"sine",attack:.08,sustain:.8,release:1.2,eq:{C:4,D:3,E:2,F:1,G:0,A:-1,B:-2,C2:-3},category:"Bass"},{name:"Electric Bass",waveform:"square",attack:.05,sustain:.9,release:1.3,eq:{C:3,D:2,E:1,F:0,G:-1,A:-2,B:-3,C2:-4},category:"Bass"},{name:"Trumpet",waveform:"sawtooth",attack:.1,sustain:.9,release:1.5,eq:{C:2,D:3,E:4,F:5,G:3,A:1,B:-1,C2:-3},category:"Brass"},{name:"Trombone",waveform:"triangle",attack:.2,sustain:1,release:1.7,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-2,C2:-4},category:"Brass"},{name:"Saxophone",waveform:"sawtooth",attack:.15,sustain:.8,release:1.3,eq:{C:2,D:3,E:4,F:3,G:1,A:-1,B:-2,C2:-3},category:"Woodwind"},{name:"Clarinet",waveform:"triangle",attack:.18,sustain:.9,release:1.6,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-1,C2:-2},category:"Woodwind"},{name:"Saw Synth",waveform:"sawtooth",attack:.05,sustain:.9,release:1.2,eq:{C:2,D:3,E:4,F:3,G:2,A:0,B:-1,C2:-2},category:"Synth"},{name:"Square Lead",waveform:"square",attack:.04,sustain:.85,release:1.1,eq:{C:2,D:3,E:4,F:3,G:1,A:0,B:-1,C2:-3},category:"Synth"}];function Ur(e={}){const{channelFilter:t,sysex:r=!1,onEvent:a,inputNameIncludes:s,onInputsChanged:i}=e,[o,l]=u.useState(null),[c,d]=u.useState(!1),[h,f]=u.useState([]),p=u.useRef(null),y=u.useCallback((m,x)=>{const b=m.data??new Uint8Array(0),g=b[0]??0,S=b[1]??0,v=b[2]??0,k=m.timeStamp,M=g&240,T=g&15,N=x.id,j=x.name??"MIDI Input",R=t===void 0||t===T;if((M===144||M===128)&&R){const z=M===144&&v>0;return{type:z?"noteon":"noteoff",note:S,velocity:z?v:0,channel:T,ts:k,deviceId:N,deviceName:j}}return M===176&&R?{type:"cc",controller:S,value:v,channel:T,ts:k,deviceId:N,deviceName:j}:M===208&&R?{type:"aftertouch",pressure:S,channel:T,ts:k,deviceId:N,deviceName:j}:M===224&&R?{type:"pitchbend",value:(S|v<<7)-8192,channel:T,ts:k,deviceId:N,deviceName:j}:M===192&&R?{type:"program",program:S,channel:T,ts:k,deviceId:N,deviceName:j}:{type:"unknown",status:g,data1:S,data2:v,channel:T,ts:k,deviceId:N,deviceName:j}},[t]);return u.useEffect(()=>{if(!("requestMIDIAccess"in navigator)){l(!1);return}l(!0);let m=!1;return navigator.requestMIDIAccess({sysex:r}).then(x=>{if(m)return;p.current=x,d(!0);const b=()=>{const g=Array.from(x.inputs.values()),S=s?g.filter(v=>(v.name||"").toUpperCase().includes(s.toUpperCase())):g;f(S),i==null||i(S),g.forEach(v=>v.onmidimessage=null),S.forEach(v=>{v.onmidimessage=k=>a==null?void 0:a(y(k,v))})};b(),x.onstatechange=()=>b()}),()=>{m=!0;const x=p.current;x&&(x.inputs.forEach(b=>b.onmidimessage=null),x.onstatechange=null)}},[s,a,i,y,r]),{supported:o,granted:c,inputs:h}}const us="nice2dev.midiLearn";function Am(){try{const e=localStorage.getItem(us);return e?JSON.parse(e):{}}catch{return{}}}function Ni(e){const t={};for(const r of e)t[r.id]={id:r.id,type:r.type,number:r.number,channel:r.channel,min:r.min,max:r.max};localStorage.setItem(us,JSON.stringify(t))}function Im(e){const{parameters:t,onParameterChange:r}=e,[a,s]=u.useState(()=>{const v=Am();return t.map(k=>{const M=v[k.id];return{id:k.id,paramName:k.name,type:(M==null?void 0:M.type)??"cc",number:M==null?void 0:M.number,channel:M==null?void 0:M.channel,min:(M==null?void 0:M.min)??k.min??0,max:(M==null?void 0:M.max)??k.max??127,value:0}})}),[i,o]=u.useState({learning:!1,targetId:null}),[l,c]=u.useState(null),d=u.useRef(a);d.current=a;const h=u.useRef(r);h.current=r;const f=u.useRef(i);f.current=i;const p=u.useCallback(v=>{var M;c(v);const k=f.current;if(k.learning&&k.targetId){if(!d.current.find(j=>j.id===k.targetId))return;let N={};switch(v.type){case"cc":N={type:"cc",number:v.controller,channel:v.channel};break;case"noteon":N={type:"note",number:v.note,channel:v.channel};break;case"pitchbend":N={type:"pitchbend",channel:v.channel};break;case"aftertouch":N={type:"aftertouch",channel:v.channel};break;default:return}s(j=>{const R=j.map(z=>z.id===k.targetId?{...z,...N}:z);return Ni(R),R}),o({learning:!1,targetId:null});return}for(const T of d.current){if(T.number===void 0&&T.type!=="pitchbend"&&T.type!=="aftertouch"||T.channel!==void 0&&v.channel!==T.channel)continue;let N=null,j=127;if(T.type==="cc"&&v.type==="cc"&&v.controller===T.number?N=v.value:T.type==="note"&&v.type==="noteon"&&v.note===T.number?N=v.velocity:T.type==="pitchbend"&&v.type==="pitchbend"?(N=v.value+8192,j=16383):T.type==="aftertouch"&&v.type==="aftertouch"&&(N=v.pressure),N!==null){const R=N/j,z=T.min+R*(T.max-T.min);s(A=>A.map($=>$.id===T.id?{...$,value:R}:$)),(M=h.current)==null||M.call(h,T.id,z,R)}}},[]),{supported:y,granted:m}=Ur({onEvent:p}),x=u.useCallback(v=>{o({learning:!0,targetId:v})},[]),b=u.useCallback(()=>{o({learning:!1,targetId:null})},[]),g=u.useCallback(v=>{s(k=>{const M=k.map(T=>T.id===v?{...T,type:"cc",number:void 0,channel:void 0}:T);return Ni(M),M})},[]),S=u.useCallback(()=>{s(v=>{const k=v.map(M=>({...M,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(us),k})},[]);return{bindings:a,startLearn:x,cancelLearn:b,removeBinding:g,clearAll:S,learnState:i,midiSupported:y,midiGranted:m,lastEvent:l}}const Lm={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function Dm(e={}){const{lowerZone:t=Lm,onNoteExpression:r,onNoteOn:a,onNoteOff:s}=e,[i,o]=u.useState([]),l=u.useRef(new Map),c=u.useRef(r);c.current=r;const d=u.useRef(a);d.current=a;const h=u.useRef(s);h.current=s;const f=u.useRef(new Set(t.memberChannels));u.useEffect(()=>{f.current=new Set(t.memberChannels)},[t.memberChannels]);const p=u.useCallback(x=>{var g,S,v,k,M;if(!f.current.has(x.channel??-1))return;const b=`${x.channel}`;switch(x.type){case"noteon":{const T={note:x.note,channel:x.channel,velocity:x.velocity,pitchBend:0,pressure:0,slide:0,lastUpdate:x.ts};l.current.set(b,T),o(Array.from(l.current.values())),(g=d.current)==null||g.call(d,T);break}case"noteoff":{l.current.delete(b),o(Array.from(l.current.values())),(S=h.current)==null||S.call(h,x.channel,x.note);break}case"pitchbend":{const T=l.current.get(b);T&&(T.pitchBend=x.value,T.lastUpdate=x.ts,(v=c.current)==null||v.call(c,T),o(Array.from(l.current.values())));break}case"aftertouch":{const T=l.current.get(b);T&&(T.pressure=x.pressure,T.lastUpdate=x.ts,(k=c.current)==null||k.call(c,T),o(Array.from(l.current.values())));break}case"cc":{if(x.controller===74){const T=l.current.get(b);T&&(T.slide=x.value,T.lastUpdate=x.ts,(M=c.current)==null||M.call(c,T),o(Array.from(l.current.values())))}break}}},[]),{supported:y,granted:m}=Ur({onEvent:p,sysex:!1});return{activeNotes:i,midiSupported:y,midiGranted:m}}const zm={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 _m(e={},t=zm){const[r,a]=u.useState(()=>{const y=localStorage.getItem("oxygen25.layout");return y?JSON.parse(y):t}),[s,i]=u.useState([]),o=u.useRef({mode:"idle"}),l=u.useCallback(y=>{a(m=>{const x={...m,...y};return localStorage.setItem("oxygen25.layout",JSON.stringify(x)),x})},[]),c=u.useCallback(y=>{var b,g,S,v,k,M,T,N,j;const m=y.deviceName||"MIDI";i(R=>R.includes(m)?R:[...R,m]);const x=o.current;if(x.mode!=="idle"){if(x.mode==="knob"&&y.type==="cc"){const R=x.index;l({knobs:r.knobs.map(z=>z.index===R?{...z,cc:y.controller}:z)}),o.current={mode:"idle"};return}if(x.mode==="fader"&&y.type==="cc"){l({fader:{cc:y.controller,label:"Fader"}}),o.current={mode:"idle"};return}if(x.mode==="pad"&&y.type==="noteon"){const R=r.pads.slice();R[x.padIdx]={...R[x.padIdx],note:y.note},l({pads:R}),o.current={mode:"idle"};return}if(x.mode==="transport"&&y.type==="cc"){const R={...r.transport};R[x.action]=y.controller,l({transport:R}),o.current={mode:"idle"};return}}switch(y.type){case"noteon":{r.pads.findIndex(z=>z.note===y.note)>=0?(b=e.onPad)==null||b.call(e,{note:y.note,velocity:y.velocity,ts:y.ts,device:m}):(g=e.onKey)==null||g.call(e,{note:y.note,velocity:y.velocity,ts:y.ts,device:m});break}case"cc":{if(r.fader&&y.controller===r.fader.cc){(S=e.onFader)==null||S.call(e,{cc:y.controller,value:y.value,ts:y.ts,device:m});break}const R=r.knobs.find(A=>A.cc===y.controller);if(R){(v=e.onKnob)==null||v.call(e,{index:R.index,cc:y.controller,value:y.value,ts:y.ts,device:m});break}const z=Object.keys(r.transport).find(A=>r.transport[A]===y.controller);if(z){(k=e.onTransport)==null||k.call(e,{action:z,value:y.value,ts:y.ts,device:m});break}(M=e.onUnknown)==null||M.call(e,y);break}case"pitchbend":(T=e.onPitchBend)==null||T.call(e,{value:y.value,ts:y.ts,device:m});break;case"aftertouch":(N=e.onAftertouch)==null||N.call(e,{pressure:y.pressure,ts:y.ts,device:m});break;default:(j=e.onUnknown)==null||j.call(e,y)}},[l,e,r]),{supported:d,granted:h,inputs:f}=Ur({inputNameIncludes:void 0,onEvent:c,sysex:!1,channelFilter:void 0,onInputsChanged:y=>i(y.map(m=>m.name||"MIDI"))}),p=u.useMemo(()=>({knob:y=>o.current={mode:"knob",index:y},fader:()=>o.current={mode:"fader"},pad:y=>o.current={mode:"pad",padIdx:y},transport:y=>o.current={mode:"transport",action:y},cancel:()=>o.current={mode:"idle"},state:()=>o.current}),[]);return{supported:d,granted:h,inputs:f,layout:r,setLayout:l,learn:p,inputsInfo:s}}const wa={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]},Fm=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Ca={pop:[[0,4,7],[5,9,0],[7,11,2],[5,9,0]],rock:[[0,4,7],[5,9,0],[3,7,10],[5,9,0]],jazz:[[0,4,7,11],[2,5,9,0],[5,9,0,4],[0,4,7,11]],blues12:[[0,4,7],[0,4,7],[0,4,7],[0,4,7],[5,9,0],[5,9,0],[0,4,7],[0,4,7],[7,11,2],[5,9,0],[0,4,7],[7,11,2]]},en=36,jn=38,Mt=42,tn=51,Om=49,ja={basic:[{step:0,pitch:en,vel:110},{step:0,pitch:Mt,vel:80},{step:2,pitch:Mt,vel:70},{step:4,pitch:jn,vel:100},{step:4,pitch:Mt,vel:80},{step:6,pitch:Mt,vel:70},{step:8,pitch:en,vel:100},{step:10,pitch:Mt,vel:70},{step:12,pitch:jn,vel:100},{step:12,pitch:Mt,vel:80},{step:14,pitch:Mt,vel:70}],rock:[{step:0,pitch:en,vel:120},{step:0,pitch:Om,vel:90},{step:4,pitch:jn,vel:110},{step:4,pitch:Mt,vel:80},{step:8,pitch:en,vel:110},{step:8,pitch:Mt,vel:80},{step:10,pitch:en,vel:90},{step:12,pitch:jn,vel:110},{step:12,pitch:Mt,vel:80}],swing:[{step:0,pitch:tn,vel:90},{step:3,pitch:tn,vel:70},{step:4,pitch:tn,vel:80},{step:8,pitch:tn,vel:90},{step:11,pitch:tn,vel:70},{step:12,pitch:tn,vel:80},{step:4,pitch:en,vel:80},{step:12,pitch:jn,vel:70}]},Ul={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function Bm(e){let t=e|0;return()=>{t=t+1831565813|0;let r=Math.imul(t^t>>>15,1|t);return r=r+Math.imul(r^r>>>7,61|r)^r,((r^r>>>14)>>>0)/4294967296}}let Vl=1;const lr=()=>Vl++,ql=e=>60/e,Gm=e=>ql(e)/4;function sa(e,t,r,a){const s=t.length,i=Math.floor(r/s),o=(r%s+s)%s;return e+t[o]+(a+i)*12}function Hl(e=Ul){Vl=1;const t=e.seed>0?Bm(e.seed):Math.random,r=wa[e.scale]??wa.pentatonic,a=Ca[e.progression]??Ca.pop,s=ja[e.drumPattern]??ja.basic,i=ql(e.tempo),o=Gm(e.tempo),l=Math.max(1,e.bars),c=16,d=[],h=[],f=[],p=[];let y=0;for(let m=0;m<l;m++){const x=m*4*i,b=m%a.length,g=a[b];for(const v of g)f.push({id:lr(),pitch:sa(e.root,r,v,e.octave-1),start:x,duration:4*i-.01,velocity:70+Math.floor(t()*20)});const S=g[0];for(let v=0;v<4;v++){const k=v===2?S+(t()>.5?2:0):S;h.push({id:lr(),pitch:sa(e.root,r,k,e.octave-2),start:x+v*i,duration:i*.9,velocity:80+Math.floor(t()*30)})}for(let v=0;v<c;v++){if(t()>e.density)continue;const k=x+v*o,M=t()>.8?t()>.5?2:-2:t()>.5?1:-1;y=Math.max(-3,Math.min(r.length+3,y+M));const T=1+Math.floor(t()*3);d.push({id:lr(),pitch:sa(e.root,r,y,e.octave),start:k,duration:T*o*.95,velocity:85+Math.floor(t()*30)})}for(const v of s)p.push({id:lr(),pitch:v.pitch,start:x+v.step*o,duration:o*.8,velocity:v.vel+Math.floor(t()*10-5)})}return{melody:d,bass:h,chords:f,drums:p,config:e}}const Wm=Object.keys(wa),Um=Object.keys(Ca),Vm=Object.keys(ja),qm=Hl;function Ke(e,t,r){return{cc:e,paramId:r,label:`Knob ${t}`,controlType:"knob",min:0,max:127,inverted:!1}}function qn(e,t,r){return{cc:e,paramId:r,label:t,controlType:"fader",min:0,max:127,inverted:!1}}function nn(e,t,r){return{cc:e,paramId:r,label:t,controlType:"button",min:0,max:127,inverted:!1}}const Kl={id:"oxygen25",name:"M-Audio Oxygen 25 (MkIV)",deviceMatch:"OXYGEN",mappings:[Ke(21,1,"mixer.volume"),Ke(22,2,"mixer.pan"),Ke(23,3,"fx.reverb"),Ke(24,4,"fx.delay"),Ke(25,5,"fx.chorus"),Ke(26,6,"fx.filter"),Ke(27,7,"fx.drive"),Ke(28,8,"fx.eq"),qn(7,"Master Fader","mixer.master"),nn(115,"Play","transport.play"),nn(114,"Stop","transport.stop"),nn(117,"Record","transport.record"),nn(112,"Rewind","transport.rewind"),nn(113,"Forward","transport.forward"),nn(116,"Loop","transport.loop")]},Yl={id:"mpk-mini",name:"Akai MPK Mini",deviceMatch:"MPK",mappings:[Ke(1,1,"mixer.volume"),Ke(2,2,"mixer.pan"),Ke(3,3,"fx.reverb"),Ke(4,4,"fx.delay"),Ke(5,5,"fx.chorus"),Ke(6,6,"fx.filter"),Ke(7,7,"fx.drive"),Ke(8,8,"fx.eq")]},Zl={id:"minilab",name:"Arturia MiniLab",deviceMatch:"Arturia MiniLab",mappings:[Ke(7,1,"mixer.volume"),Ke(74,2,"mixer.pan"),Ke(71,3,"fx.reverb"),Ke(76,4,"fx.delay"),Ke(77,5,"fx.chorus"),Ke(93,6,"fx.filter"),Ke(73,7,"fx.drive"),Ke(75,8,"fx.eq"),qn(1,"Mod Wheel","mixer.master")]},Xl={id:"launch-control-xl",name:"Novation Launch Control XL",deviceMatch:"Launch Control",mappings:[...Array.from({length:8},(e,t)=>Ke(13+t,t+1,`mixer.send${t+1}`)),...Array.from({length:8},(e,t)=>qn(77+t,`Fader ${t+1}`,`mixer.track${t+1}`))]},hs={id:"generic",name:"Generic MIDI Controller",deviceMatch:"",mappings:[Ke(1,1,"mixer.modWheel"),qn(7,"Volume","mixer.volume"),Ke(10,2,"mixer.pan"),qn(11,"Expression","mixer.expression")]},Ql=[Kl,Yl,Zl,Xl,hs];class Hm{constructor(t){this.ccMap=new Map,this.onChange=null,this.profile=t??hs,this.rebuildMap()}setProfile(t){this.profile=t,this.rebuildMap()}getProfile(){return this.profile}autoDetect(t){const r=t.toUpperCase(),a=Ql.find(s=>s.deviceMatch&&r.includes(s.deviceMatch.toUpperCase()));return a?(this.setProfile(a),a):null}onMappedChange(t){this.onChange=t}handleCC(t,r){var c;const a=this.ccMap.get(t);if(!a)return null;const i=(a.inverted?127-r:r)/127,o=a.min+i*(a.max-a.min),l={paramId:a.paramId,label:a.label,rawValue:r,scaledValue:o,normalizedValue:i};return(c=this.onChange)==null||c.call(this,l),l}setMapping(t,r,a,s="knob"){const i={cc:t,paramId:r,label:a,controlType:s,min:0,max:127,inverted:!1},o=this.profile.mappings.findIndex(l=>l.cc===t);o>=0?this.profile.mappings[o]=i:this.profile.mappings.push(i),this.ccMap.set(t,i)}removeMapping(t){this.profile.mappings=this.profile.mappings.filter(r=>r.cc!==t),this.ccMap.delete(t)}getMappings(){return[...this.profile.mappings]}getMapping(t){return this.ccMap.get(t)}exportConfig(){return{...this.profile,mappings:this.profile.mappings.map(t=>({...t}))}}importConfig(t){this.profile={...t,mappings:t.mappings.map(r=>({...r}))},this.rebuildMap()}static createCustomProfile(t,r){return{id:`custom-${t.toLowerCase().replace(/\s+/g,"-")}`,name:t,deviceMatch:"",mappings:r.map(a=>({...a,min:0,max:127,inverted:!1}))}}rebuildMap(){this.ccMap.clear();for(const t of this.profile.mappings)this.ccMap.set(t.cc,t)}}function Jl(e){return{past:[],present:e,future:[]}}function ec(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function tc(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 nc(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 rc(e){return e.past.length>0}function ac(e){return e.future.length>0}function Ma(e,t){return e.filter(r=>r.time>=t.start&&r.time<=t.end).map(r=>({...r}))}function sc(e,t,r){if(t.length===0)return e;const a=Math.min(...t.map(o=>o.time)),s=r-a,i=t.map(o=>({...o,id:Date.now()+Math.floor(Math.random()*1e4)+o.id,time:o.time+s}));return[...e,...i]}function ic(e,t){const r=[],a=[];for(const s of e)s.time>=t.start&&s.time<=t.end?r.push({...s}):a.push(s);return{remaining:a,cut:r}}function oc(e,t){return e.filter(r=>r.time<t.start||r.time>t.end)}function Km(e,t){return e.filter(r=>r.time>=t.start&&r.time<=t.end).map(r=>r.id)}function lc(e,t,r,a){const s={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:r,time:a};return[...e,s]}function cc(e,t=3){if(e.length<=2)return e;const r=[...e].sort((s,i)=>s.time-i.time),a=[r[0]];for(let s=1;s<r.length-1;s++)s%t===0&&a.push(r[s]);return a.push(r[r.length-1]),a}function dc(e){return JSON.stringify(e,null,2)}function uc(e){try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>typeof r=="object"&&r!==null&&"id"in r&&"cc"in r&&"value"in r&&"time"in r):[]}catch{return[]}}function gt(e,t){var r;return((r=e.find(a=>a.layerId===t))==null?void 0:r.events)??[]}function Rt(e,t,r){return e.find(s=>s.layerId===t)?e.map(s=>s.layerId===t?{...s,events:r}:s):[...e,{layerId:t,events:r}]}function Ym(e,t){switch(t.type){case"UNDO":return tc(e);case"REDO":return nc(e);default:{let r=e.present;switch(t.type){case"ADD_EVENT":{const a=[...gt(r,t.layerId),t.event];r=Rt(r,t.layerId,a);break}case"UPDATE_EVENT":{const a=gt(r,t.layerId).map(s=>s.id===t.id?{...s,value:t.value,time:t.time,handleType:t.handleType??s.handleType}:s);r=Rt(r,t.layerId,a);break}case"REMOVE_EVENT":{const a=gt(r,t.layerId).filter(s=>s.id!==t.id);r=Rt(r,t.layerId,a);break}case"SET_EVENTS":r=Rt(r,t.layerId,t.events);break;case"PASTE":{const a=gt(r,t.layerId),s=sc(a,t.clipboard,t.targetTime);r=Rt(r,t.layerId,s);break}case"CUT":{const a=gt(r,t.layerId),{remaining:s}=ic(a,t.range);r=Rt(r,t.layerId,s);break}case"DELETE_RANGE":{const a=gt(r,t.layerId),s=oc(a,t.range);r=Rt(r,t.layerId,s);break}case"RECORD":{const a=gt(r,t.layerId),s=lc(a,t.cc,t.value,t.time);r=Rt(r,t.layerId,s);break}case"THIN":{const a=gt(r,t.layerId),s=cc(a,t.keepEveryN);r=Rt(r,t.layerId,s);break}case"IMPORT":{const a=uc(t.json);a.length>0&&(r=Rt(r,t.layerId,a));break}}return ec(e,r)}}}function Zm(e=[]){const[t,r]=u.useReducer(Ym,Jl(e)),a=u.useRef([]),s=u.useCallback(v=>gt(t.present,v),[t.present]),i=u.useCallback((v,k)=>r({type:"ADD_EVENT",layerId:v,event:k}),[]),o=u.useCallback((v,k,M,T,N)=>r({type:"UPDATE_EVENT",layerId:v,id:k,value:M,time:T,handleType:N}),[]),l=u.useCallback((v,k)=>r({type:"REMOVE_EVENT",layerId:v,id:k}),[]),c=u.useCallback((v,k)=>r({type:"SET_EVENTS",layerId:v,events:k}),[]),d=u.useCallback(()=>r({type:"UNDO"}),[]),h=u.useCallback(()=>r({type:"REDO"}),[]),f=u.useCallback((v,k)=>{a.current=Ma(gt(t.present,v),k)},[t.present]),p=u.useCallback((v,k)=>{a.current=Ma(gt(t.present,v),k),r({type:"CUT",layerId:v,range:k})},[t.present]),y=u.useCallback((v,k)=>{a.current.length>0&&r({type:"PASTE",layerId:v,clipboard:a.current,targetTime:k})},[]),m=u.useCallback((v,k)=>r({type:"DELETE_RANGE",layerId:v,range:k}),[]),x=u.useCallback((v,k,M,T)=>r({type:"RECORD",layerId:v,cc:k,value:M,time:T}),[]),b=u.useCallback((v,k)=>r({type:"THIN",layerId:v,keepEveryN:k}),[]),g=u.useCallback(v=>dc(gt(t.present,v)),[t.present]),S=u.useCallback((v,k)=>r({type:"IMPORT",layerId:v,json:k}),[]);return{snapshots:t.present,getEvents:s,addEvent:i,updateEvent:o,removeEvent:l,setEvents:c,undo:d,redo:h,canUndo:rc(t),canRedo:ac(t),copy:f,cut:p,paste:y,clipboard:a.current,deleteRange:m,record:x,thin:b,exportLane:g,importLane:S}}function ps(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function Yt(e="New Pattern",t=16,r=120){return{name:e,length:t,steps:Array.from({length:t},()=>ps()),bpm:r,swing:0,rootNote:60}}function hc(e,t){const r=e.steps.map((a,s)=>s===t?{...a,active:!a.active}:a);return{...e,steps:r}}function pc(e,t,r){const a=e.steps.map((s,i)=>i===t?{...s,note:Math.max(0,Math.min(127,r))}:s);return{...e,steps:a}}function fc(e,t,r){const a=e.steps.map((s,i)=>i===t?{...s,velocity:Math.max(0,Math.min(127,r))}:s);return{...e,steps:a}}function mc(e,t,r){const a=e.steps.map((s,i)=>i===t?{...s,gate:Math.max(0,Math.min(1,r))}:s);return{...e,steps:a}}function gc(e,t,r){const a=e.steps.map((s,i)=>i===t?{...s,probability:Math.max(0,Math.min(1,r))}:s);return{...e,steps:a}}function yc(e,t){const r=e.steps.map((a,s)=>s===t?{...a,slide:!a.slide}:a);return{...e,steps:r}}function bc(e,t){const r=e.steps.map(a=>a.active?{...a,note:Math.max(0,Math.min(127,a.note+t))}:a);return{...e,steps:r,rootNote:Math.max(0,Math.min(127,e.rootNote+t))}}function vc(e){return{...e,steps:[...e.steps].reverse()}}function xc(e,t){const r=e.steps.length,a=(t%r+r)%r,s=[...e.steps.slice(a),...e.steps.slice(0,a)];return{...e,steps:s}}function Sc(e,t=60,r=127){const a=e.steps.map(s=>s.active?{...s,velocity:Math.floor(t+Math.random()*(r-t+1))}:s);return{...e,steps:a}}function kc(e){return{...e,steps:e.steps.map(()=>ps(e.rootNote))}}function fs(e,t=4){return 60/e/t}function wc(e,t,r=0,a=4){const s=fs(t,a),i=e*s;return e%2===1&&r>0?i+s*r*.5:i}function Cc(e){return e.active&&Math.random()<e.probability}function Xm(){const e=Yt("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function Qm(){const e=Yt("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function Jm(){const e=Yt("Hi-Hat",16);for(let t=0;t<16;t+=2)e.steps[t]={...e.steps[t],active:!0,note:42,velocity:80};return e}function e0(e=60){const t=Yt("Arp",16,120);return[0,4,7,12,7,4,0,-5,0,3,7,12,7,3,0,-5].forEach((a,s)=>{t.steps[s]={...t.steps[s],active:!0,note:e+a,velocity:90,gate:.5}}),{...t,rootNote:e}}function t0(e=36){const t=Yt("Bassline",16,120),r=[0,0,7,0,5,5,3,0,0,0,7,12,5,5,3,0],a=[1,0,1,0,1,0,1,1,1,0,1,1,1,0,1,0];return r.forEach((s,i)=>{t.steps[i]={...t.steps[i],active:!!a[i],note:e+s,velocity:100,gate:.7}}),{...t,rootNote:e}}function n0(e){return JSON.stringify(e,null,2)}function r0(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function a0(e={}){const{onTrigger:t,onLFOOutput:r,initialPattern:a}=e,[s,i]=u.useState(()=>a??Yt()),[o,l]=u.useState(-1),[c,d]=u.useState(!1),[h,f]=u.useState([]),p=u.useRef(s);p.current=s;const y=u.useRef(h);y.current=h;const m=u.useRef(c);m.current=c;const x=u.useRef(t);x.current=t;const b=u.useRef(r);b.current=r;const g=u.useRef(null),S=u.useRef(0),v=u.useRef(0),k=u.useCallback(()=>{var V,Y;if(!m.current)return;const C=p.current,L=S.current%C.length,w=C.steps[L];if(Cc(w)){const oe=wc(S.current,C.bpm,C.swing);(V=x.current)==null||V.call(x,w,L,oe)}const D=(Date.now()-v.current)/1e3;for(let oe=0;oe<y.current.length;oe++){const ie=y.current[oe];if(ie.enabled&&ie.targetCC!==void 0){const ne=La(ie,D,C.bpm);(Y=b.current)==null||Y.call(b,oe,ie.targetCC,ne)}}l(L),S.current++;const F=fs(C.bpm)*1e3,B=L%2===0?0:F*C.swing*.5;g.current=setTimeout(k,F+B)},[]),M=u.useCallback(()=>{m.current||(S.current=0,v.current=Date.now(),d(!0),m.current=!0,k())},[k]),T=u.useCallback(()=>{d(!1),m.current=!1,l(-1),g.current&&(clearTimeout(g.current),g.current=null)},[]),N=u.useCallback(()=>{m.current?T():M()},[M,T]);u.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const j=u.useCallback(C=>i(L=>hc(L,C)),[]),R=u.useCallback((C,L)=>i(w=>pc(w,C,L)),[]),z=u.useCallback((C,L)=>i(w=>fc(w,C,L)),[]),A=u.useCallback((C,L)=>i(w=>mc(w,C,L)),[]),$=u.useCallback((C,L)=>i(w=>gc(w,C,L)),[]),O=u.useCallback(C=>i(L=>yc(L,C)),[]),I=u.useCallback(C=>i(L=>bc(L,C)),[]),U=u.useCallback(()=>i(C=>vc(C)),[]),J=u.useCallback(C=>i(L=>xc(L,C)),[]),_=u.useCallback((C,L)=>i(w=>Sc(w,C,L)),[]),W=u.useCallback(()=>i(C=>kc(C)),[]),K=u.useCallback(C=>i(L=>({...L,bpm:Math.max(20,Math.min(300,C))})),[]),re=u.useCallback(C=>i(L=>({...L,swing:Math.max(0,Math.min(1,C))})),[]),X=u.useCallback(C=>{i(L=>{if(L.length===C)return L;const w=Array.from({length:C},(D,F)=>F<L.steps.length?L.steps[F]:{active:!1,note:L.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...L,length:C,steps:w}})},[]),q=u.useCallback(C=>{f(L=>[...L,C??Dr()])},[]),E=u.useCallback(C=>{f(L=>L.filter((w,D)=>D!==C))},[]),P=u.useCallback((C,L)=>{f(w=>w.map((D,F)=>F===C?{...D,...L}:D))},[]);return{pattern:s,currentStep:o,playing:c,lfos:h,play:M,stop:T,togglePlayback:N,toggle:j,setNote:R,setVelocity:z,setGate:A,setProbability:$,toggleSlide:O,transpose:I,reverse:U,shift:J,randomizeVel:_,clear:W,setPattern:i,setBpm:K,setSwing:re,setLength:X,addLFO:q,removeLFO:E,updateLFO:P}}function ms(e){const t=u.useRef(null),r=u.useRef(new Map),a=u.useRef(1),s=u.useCallback(()=>{if(!t.current){const o=e();o.onmessage=l=>{const{id:c}=l.data,d=r.current.get(c);d&&(r.current.delete(c),d.resolve(l.data))},o.onerror=l=>{console.error("[useWorker] Worker error:",l.message);for(const[c,d]of r.current)d.reject(new Error(`Worker error: ${l.message}`));r.current.clear(),o.terminate(),t.current=null},t.current=o}return t.current},[e]);return u.useEffect(()=>{const o=r.current;return()=>{var l;(l=t.current)==null||l.terminate(),t.current=null;for(const[,c]of o)c.reject(new Error("Worker terminated on unmount"));o.clear()}},[]),u.useCallback((o,l)=>{const c=a.current++,d=s();return new Promise((h,f)=>{r.current.set(c,{resolve:h,reject:f}),d.postMessage({...o,id:c},l??[])})},[s])}function s0(){const e=ms(u.useCallback(()=>new Worker(new URL("/assets/pitchWorker-BgAp5Z97.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:bt&&bt.tagName.toUpperCase()==="SCRIPT"&&bt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return u.useCallback(async(r,a,s=.01)=>(await e({buffer:r,sampleRate:a,rmsThreshold:s})).hz,[e])}function i0(){const e=ms(u.useCallback(()=>new Worker(new URL("/assets/scoringWorker-B1PkYu_m.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:bt&&bt.tagName.toUpperCase()==="SCRIPT"&&bt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return u.useCallback(async(r,a,s)=>(await e({notes:r,points:a,params:s})).result,[e])}const o0={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function jc(){return`
|
|
71
|
+
Tame Impala - Let It Happen`,rows:10,style:{width:"100%",padding:12,borderRadius:6,border:"1px solid var(--nice-border, #e2e8f0)",fontFamily:"monospace",fontSize:13,resize:"vertical"}}),r.jsx("button",{style:{...Ln,opacity:H.trim().length===0?.5:1},disabled:H.trim().length===0,onClick:()=>_(H),type:"button",children:d("importWizard.parseTracks","Parse Tracks")})]}),(g!==99||k.length>0)&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[r.jsxs("p",{style:{margin:0,fontWeight:600},children:[v==null?void 0:v.name," — ",w.size,"/",k.length," ",d("importWizard.selected","selected")]}),r.jsx("button",{style:sr,onClick:C,type:"button",children:w.size===k.length?d("importWizard.deselectAll","Deselect All"):d("importWizard.selectAll","Select All")})]}),$?r.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.loadingTracks","Loading tracks…")}):r.jsx("div",{style:{maxHeight:320,overflowY:"auto"},children:r.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[r.jsx("thead",{children:r.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-border, #e2e8f0)",textAlign:"left"},children:[r.jsx("th",{style:{padding:"4px 8px",width:32}}),r.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.colTitle","Title")}),r.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.artist","Artist")}),r.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.album","Album")}),r.jsx("th",{style:{padding:"4px 8px",textAlign:"right"},children:d("importWizard.duration","Duration")})]})}),r.jsx("tbody",{children:k.map(W=>{const ee=w.has(W.externalId);return r.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-border, #e2e8f0)",opacity:ee?1:.5,cursor:"pointer"},onClick:()=>G(W.externalId),children:[r.jsx("td",{style:{padding:"6px 8px"},children:r.jsx("input",{type:"checkbox",checked:ee,readOnly:!0})}),r.jsx("td",{style:{padding:"6px 8px",fontWeight:500},children:W.title}),r.jsx("td",{style:{padding:"6px 8px",color:"var(--nice-text-dim, #64748b)"},children:W.artist}),r.jsx("td",{style:{padding:"6px 8px",color:"var(--nice-text-dim, #64748b)"},children:W.album??"—"}),r.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--nice-text-dim, #64748b)"},children:dm(W.duration)})]},W.externalId)})})]})}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:r.jsxs("button",{style:{...Ln,opacity:w.size===0?.5:1},disabled:w.size===0,onClick:()=>p("options"),type:"button",children:[d("importWizard.next","Next")," ",r.jsx(O.NtdArrowRight,{size:12})]})})]})]}),J=()=>r.jsxs("div",{style:{display:"grid",gap:16},children:[r.jsx("p",{style:{margin:0,fontWeight:600},children:d("importWizard.importOptions","Import options")}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:I.mergeTags,onChange:W=>Y(ee=>({...ee,mergeTags:W.target.checked}))}),d("importWizard.mergeTags","Merge tags from source playlist")]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:I.mergeFolders,onChange:W=>Y(ee=>({...ee,mergeFolders:W.target.checked}))}),d("importWizard.mergeFolders","Merge into existing folder structure")]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:I.overwriteExisting,onChange:W=>Y(ee=>({...ee,overwriteExisting:W.target.checked}))}),d("importWizard.overwrite","Overwrite existing tracks (match by ISRC)")]}),l&&l.length>0&&r.jsxs("div",{style:{display:"grid",gap:4},children:[r.jsx("label",{style:{fontSize:13,fontWeight:500},children:d("importWizard.targetFolder","Target folder")}),r.jsxs("select",{style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #e2e8f0)"},value:I.targetFolderId??"",onChange:W=>Y(ee=>({...ee,targetFolderId:W.target.value||void 0})),children:[r.jsx("option",{value:"",children:d("importWizard.root","— Root —")}),l.map(W=>r.jsx("option",{value:W.id,children:W.name},W.id))]})]}),r.jsx("div",{style:{marginTop:8,padding:12,borderRadius:8,background:"var(--nice-info-bg, #eff6ff)",fontSize:13},children:d("importWizard.summary",'Ready to import {count} tracks from "{name}"').replace("{count}",String(w.size)).replace("{name}",(v==null?void 0:v.name)??"")}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[r.jsxs("button",{style:sr,onClick:F,type:"button",children:[r.jsx(O.NtdArrowLeft,{size:12})," ",d("importWizard.back","Back")]}),r.jsx("button",{style:Ln,onClick:T,type:"button",children:d("importWizard.startImport","Start Import")})]})]}),se=()=>{const W=E?Math.round(E.imported/E.total*100):0;return r.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[r.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:d("importWizard.importing","Importing…")}),r.jsx("div",{style:{height:8,borderRadius:4,background:"var(--nice-border, #e2e8f0)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${W}%`,background:"var(--nice-color-accent, #6366f1)",borderRadius:4,transition:"width 0.3s"}})}),E&&r.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-dim, #64748b)"},children:[E.imported," / ",E.total," ",d("importWizard.tracks","tracks"),E.currentTrack&&r.jsxs("div",{style:{marginTop:4},children:[r.jsx(O.NtdMusic,{size:12})," ",E.currentTrack]})]})]})},oe=()=>r.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[r.jsx("span",{style:{display:"inline-flex",justifyContent:"center"},"aria-hidden":"true",children:r.jsx(O.NtdCheck,{size:48})}),r.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:d("importWizard.complete","Import Complete")}),L&&r.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[r.jsxs("div",{children:[r.jsx("strong",{children:L.imported})," ",d("importWizard.imported","imported")]}),L.skipped>0&&r.jsxs("div",{style:{color:"var(--nice-color-warning, #f59e0b)"},children:[L.skipped," ",d("importWizard.skipped","skipped (duplicates)")]}),L.failed>0&&r.jsxs("div",{style:{color:"var(--nice-color-error, #ef4444)"},children:[L.failed," ",d("importWizard.failed","failed")]}),L.failedTracks.length>0&&r.jsxs("details",{style:{textAlign:"left",marginTop:8,fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:[r.jsx("summary",{style:{cursor:"pointer"},children:d("importWizard.showFailed","Show failed tracks")}),r.jsx("ul",{style:{marginTop:4,paddingLeft:20},children:L.failedTracks.map((W,ee)=>r.jsx("li",{children:W},ee))})]})]}),r.jsx("button",{style:Ln,onClick:o,type:"button",children:d("importWizard.done","Done")})]}),re={connect:d("importWizard.stepConnect","Connect"),browse:d("importWizard.stepBrowse","Browse"),tracks:d("importWizard.stepTracks","Select Tracks"),options:d("importWizard.stepOptions","Options"),importing:d("importWizard.stepImporting","Importing"),done:d("importWizard.stepDone","Done")};return r.jsxs("div",{style:im,children:[K(),r.jsxs("div",{style:om,children:[r.jsxs("h2",{style:{margin:0,fontSize:18},children:[d("importWizard.title","Import Playlist")," — ",re[h]]}),S&&r.jsxs("button",{style:sr,onClick:F,type:"button",children:[r.jsx(O.NtdArrowLeft,{size:12})," ",d("importWizard.back","Back")]}),h==="connect"&&r.jsx("button",{style:sr,onClick:o,type:"button","aria-label":d("importWizard.close","Close"),title:d("importWizard.close","Close"),children:r.jsx(O.NtdClose,{size:14})})]}),z&&r.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--nice-error-bg, #fef2f2)",color:"var(--nice-color-error, #ef4444)",fontSize:13},children:z}),h==="connect"&&P(),h==="browse"&&B(),h==="tracks"&&U(),h==="options"&&J(),h==="importing"&&se(),h==="done"&&oe()]})},hm=[{id:"concert-harp",name:"Concert Harp",description:"Warm concert harp",icon:"music",dir:"concert-harp",attribution:"ConcertHarp SoundFont — source: musical-artifacts.com/artifacts/375"},{id:"celtic-harp",name:"Celtic Harp",description:"Bright celtic harp",icon:"leaf",dir:"celtic-harp"},{id:"triangle",name:"Triangle",description:"Metallic percussion triangle",icon:"triangle",dir:"triangle",attribution:"Triangle SoundFont — source: polyphone.io/en/soundfonts/unpitched-percussion/298-triangle"},{id:"synth",name:"Celesta",description:"Synthesized celesta / music-box",icon:"sparkle",dir:"synth"},{id:"none",name:"Silent",description:"No sound on click",icon:"volumeMute",dir:null}],pm="concert-harp",ns=Object.fromEntries(hm.map(e=>[e.id,e])),fm="nice2dev-note-sound-set";function Tl(){try{const e=localStorage.getItem(fm);if(e&&ns[e])return e}catch{}return pm}const Ir=["quarter","eighth","sixteenth","beamed"];function Pl(e,t,n){const a=n*.2,s=n*.15,i=Math.max(1,n*.07),o=n*.72,l=n*.34,c=new Path2D,d=h=>{c.moveTo(h+a,l),c.ellipse(h,l,a,s,-.4,0,Math.PI*2),c.rect(h+a-i,l-o,i,o)};if(t==="beamed"){const h=-n*.24,p=n*.24;d(h),d(p),c.rect(h+a-i,l-o,p-h+i,n*.12)}else{const h=-a*.5;d(h);const p=t==="eighth"?1:t==="sixteenth"?2:0,g=h+a;for(let y=0;y<p;y++){const m=l-o+y*n*.2;c.moveTo(g,m),c.quadraticCurveTo(g+n*.32,m+n*.14,g+n*.18,m+n*.42),c.quadraticCurveTo(g+n*.2,m+n*.22,g,m+n*.14),c.closePath()}}e.stroke(c),e.fill(c)}function pi(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function $l(e){if(!e)return null;const t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle=e;const n=t.fillStyle;if(n.startsWith("#")){const s=parseInt(n.slice(1),16);return{r:s>>16&255,g:s>>8&255,b:s&255}}const a=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return a?{r:+a[1],g:+a[2],b:+a[3]}:null}function aa(e,t){const n=$l(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function mm(e){const t=$l(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function El(){const e=pi("--text-primary")||we.resolveCssColor("var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))"),t=pi("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",s=mm(e)<.45;return{base:aa(e,.92),staffLine:aa(e,.22),outline:we.resolveCssColor(s?"var(--nice-overlay-light-75, rgba(255, 255, 255, 0.75))":"var(--nice-overlay-55, rgba(0, 0, 0, 0.55))"),accents:[aa(t,.95)],isDark:n,notesDark:s}}const Gr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),Al=46,kt=5,mr=4,gm=(Al-(kt-1)*mr)/2,ym=6,vm=18,bm=110,xm=50,Wr=Gr?xm:bm,Sm=Gr?4:2,km=Gr?2:4,fi=Gr?1:0,wm=180,mi=2.8,gi=40,Cm=14,yi=1.2,jm=16,sa=[64,67,71,74,77],ln=64,_n=77;function Mm(e){const t=Math.max(0,Math.min(kt-1,e)),n=Math.floor(t),a=Math.min(n+1,kt-1),s=t-n;return Math.round(sa[n]+(sa[a]-sa[n])*s)}function Rm(e){return(Math.max(ln-1*(_n-ln)/(kt-1),Math.min(_n+1*(_n-ln)/(kt-1),e))-ln)/(_n-ln)*(kt-1)}const vi=2.5,bi=.72,Nm=.55,zn=new Map;let gr=null;async function Tm(e){const t=e??Tl(),n=ns[t];if(!n||!n.dir){zn.clear(),gr=t;return}if(gr===t&&zn.size>0)return;zn.clear(),gr=t;const a=qn(),s=[];for(let i=ln;i<=_n;i++)s.push(fetch(`/assets/soundfonts/notes/${n.dir}/note-${i}.mp3`).then(o=>o.arrayBuffer()).then(o=>a.decodeAudioData(o)).then(o=>{zn.set(i,o)}).catch(()=>{}));await Promise.all(s)}function xi(e){const t=zn.get(e);if(!t)return;const n=qn(),a=n.createBufferSource();a.buffer=t;const s=n.createGain();s.gain.value=.7,a.connect(s).connect(n.destination),a.start()}function Pm(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 $m(e){const t=Pm(42),n=[];for(let a=0;a<e;a++){const i=t()<.15?0:-1;n.push({x:t(),lineIdx:t()*(kt+1)-.5,shape:Ir[Math.floor(t()*Ir.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:i})}return n.sort((a,s)=>a.x-s.x),n}const ht=$m(Wr),Cn=new Float32Array(Wr),ir=new Float32Array(Wr),Dn=new Float32Array(Wr);let wa=!1;const Em=(kt-1)/2;function Am(){if(!wa){wa=!0;for(let e=0;e<ht.length;e++)Dn[e]=ht[e].lineIdx}}let Ca=[],Si="";function Im(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function Lm(e){const t=Im(e);t===Si&&Ca.length===ht.length||(Si=t,Ca=ht.map(n=>{const a=Math.ceil(n.size*1.6),s=a*2,i=document.createElement("canvas");i.width=s,i.height=s;const o=i.getContext("2d");return o.translate(a,a),o.rotate(n.rot*Math.PI/180),o.lineWidth=1.8,o.strokeStyle=e.outline,o.fillStyle=n.colorIdx<0?e.base:e.accents[n.colorIdx%e.accents.length],Pl(o,n.shape,n.size*1.3),{canvas:i,ox:a,oy:a}}))}function _m({pitchMidiRef:e}={}){const{t}=be(),n=u.useRef(null),a=u.useRef(0),s=u.useRef(0),i=u.useRef(0),o=u.useRef(null),l=u.useRef(0),c=u.useRef(0),d=u.useRef(null),h=u.useRef(null),p=u.useRef(!1),g=u.useCallback((v,f,k)=>{const b=gm+v*mr,w=f/k*Math.PI*2;return b+Math.sin(w)*ym},[]),y=u.useCallback(v=>{const f=n.current;if(!f)return;if(c.current++,fi>0&&c.current%(fi+1)!==0){i.current=v,a.current=requestAnimationFrame(y);return}const k=f.getContext("2d");if(!k)return;const b=Math.min(window.devicePixelRatio||1,km),w=f.getBoundingClientRect(),N=w.width,$=w.height;(f.width!==Math.round(N*b)||f.height!==Math.round($*b))&&(f.width=Math.round(N*b),f.height=Math.round($*b),k.setTransform(b,0,0,b,0,0));const M=i.current?(v-i.current)/1e3:0;i.current=v,s.current=(s.current+vm*M)%N,k.clearRect(0,0,N,$),l.current++,(!o.current||l.current%60===0)&&(o.current=El());const E=o.current;Lm(E),k.strokeStyle=E.staffLine,k.lineWidth=.7;for(let z=0;z<kt;z++){k.beginPath();for(let j=0;j<=N;j+=Sm){const I=g(z,j,N);j===0?k.moveTo(j,I):k.lineTo(j,I)}k.stroke()}const R=s.current,L=(e==null?void 0:e.current)??null;if(L!==null){Am();const z=Rm(L),j=vi*M;for(let I=0;I<ht.length;I++){const H=(ht[I].lineIdx-Em)*Nm,V=z*bi+(z+H)*(1-bi)-Dn[I];Dn[I]+=V>0?Math.min(j,V):Math.max(-j,V)}}else if(wa){const z=vi*.4*M;for(let j=0;j<ht.length;j++){const Y=ht[j].lineIdx-Dn[j];Dn[j]+=Y>0?Math.min(z,Y):Math.max(-z,Y)}}const A=d.current;A&&(A.timer-=M,A.timer<=0&&(d.current=null));for(let z=0;z<ht.length;z++){const j=ht[z];if(ir[z]>0){ir[z]-=M;const H=Math.max(0,ir[z]/mi);Cn[z]+=wm*H*M,Cn[z]>N&&(Cn[z]-=N)}const I=Ca[z];if(!I)continue;const Y=j.lineIdx;for(let H=0;H<2;H++){let V=((j.x*N-R-Cn[z]+H*N)%N+N)%N;const Z=g(Math.max(0,Math.min(kt-1,Math.round(Y))),V,N),X=(Y-Math.round(Y))*mr;let q=Z+X;if(A&&A.timer>0){const G=V-A.x,C=q-A.y,T=Math.sqrt(G*G+C*C);if(T<gi&&T>.1){const S=A.timer/yi,F=Cm*(1-T/gi)*S;V+=G/T*F,q+=C/T*F}}k.drawImage(I.canvas,V-I.ox,q-I.oy)}}a.current=requestAnimationFrame(y)},[g]),m=u.useCallback(v=>{const f=n.current;if(!f)return;const k=f.getBoundingClientRect(),b=v.clientX-k.left,w=v.clientY-k.top,N=k.width,$=s.current;let M=1/0,E=-1;for(let R=0;R<ht.length;R++){const L=ht[R],z=((L.x*N-$-Cn[R])%N+N)%N,j=g(Math.max(0,Math.min(kt-1,Math.round(L.lineIdx))),z,N),I=(L.lineIdx-Math.round(L.lineIdx))*mr,Y=j+I,H=z-b,D=Y-w,V=H*H+D*D;V<M&&(M=V,E=R)}if(E>=0&&Math.sqrt(M)<jm){ir[E]=mi;const R=ht[E],L=Mm(R.lineIdx);try{Yt();const A=Tl(),z=ns[A];z!=null&&z.dir&&(gr!==A||!p.current?(p.current=!0,Tm(A).then(()=>xi(L))):xi(L))}catch{}}d.current={x:b,y:w,timer:yi}},[g]),x=u.useCallback(v=>{const f=n.current;if(!f)return;const k=f.getBoundingClientRect(),b=v.clientX-k.left,w=v.clientY-k.top;h.current={x:b,y:w},d.current&&d.current.timer>0&&(d.current.x=b,d.current.y=w)},[]);return u.useEffect(()=>(a.current=requestAnimationFrame(y),()=>cancelAnimationFrame(a.current)),[y]),r.jsx("canvas",{ref:n,"aria-hidden":"true",role:"img","aria-label":t("noteRiver.noteRiverAnimationCanvas","Note river animation canvas"),onClick:m,onMouseMove:x,style:{display:"block",width:"100%",height:Al,marginBottom:5,cursor:"pointer",background:"transparent"}})}const zm=14,Dm=.9,Fm=320,Om=160,Bm=6,ki=8,Gm=14;function Wm(){const{t:e}=be(),t=u.useRef(null),n=u.useRef([]),a=u.useRef(0),s=u.useRef(0),i=u.useRef([]),o=u.useRef(null),l=u.useRef(0),c=u.useCallback((h,p)=>{for(let g=0;g<zm;g++){const y=Math.random()*Math.PI*2,m=Om*(.4+Math.random()*.6),x=Dm*(.6+Math.random()*.4),v=Math.random()<.15?0:-1;n.current.push({x:h,y:p,vx:Math.cos(y)*m,vy:Math.sin(y)*m-60,rot:Math.random()*Math.PI*2,vr:(Math.random()-.5)*Bm*2,size:ki+Math.random()*(Gm-ki),shape:Ir[Math.floor(Math.random()*Ir.length)],life:x,maxLife:x,colorIdx:v})}},[]),d=u.useCallback(h=>{const p=t.current;if(!p){a.current=requestAnimationFrame(d);return}const g=p.getContext("2d");if(!g){a.current=requestAnimationFrame(d);return}const y=window.devicePixelRatio||1,m=window.innerWidth,x=window.innerHeight;(p.width!==Math.round(m*y)||p.height!==Math.round(x*y))&&(p.width=Math.round(m*y),p.height=Math.round(x*y),p.style.width=`${m}px`,p.style.height=`${x}px`,g.setTransform(y,0,0,y,0,0));const v=s.current?Math.min((h-s.current)/1e3,.05):0;s.current=h,g.clearRect(0,0,m,x),l.current++,(!o.current||l.current%60===0)&&(o.current=El());const f=o.current;if(navigator.getGamepads){const b=navigator.getGamepads();for(let w=0;w<b.length;w++){const N=b[w];if(N)for(let $=0;$<N.buttons.length;$++){const M=w*100+$,E=N.buttons[$].pressed;E&&!i.current[M]&&c(m/2,x/2),i.current[M]=E}}}const k=[];for(const b of n.current){if(b.life-=v,b.life<=0)continue;b.vy+=Fm*v,b.x+=b.vx*v,b.y+=b.vy*v,b.rot+=b.vr*v;const w=Math.max(0,b.life/b.maxLife),N=.5+.5*w;g.save(),g.globalAlpha=w,g.translate(b.x,b.y),g.rotate(b.rot),g.lineWidth=1.4,g.strokeStyle=f.notesDark?`rgba(255,255,255,${w*.8})`:`rgba(0,0,0,${w*.55})`;const $=b.colorIdx<0?f.base:f.accents[b.colorIdx%f.accents.length];g.fillStyle=$.replace(/[\d.]+\)$/,`${w})`),Pl(g,b.shape,b.size*N*1.3),g.restore(),k.push(b)}n.current=k,a.current=requestAnimationFrame(d)},[c]);return u.useEffect(()=>{const h=g=>{c(g.clientX,g.clientY)},p=g=>{if(g.key!=="Enter")return;const y=document.activeElement;if(y){const m=y.getBoundingClientRect();c(m.left+m.width/2,m.top+m.height/2)}else c(window.innerWidth/2,window.innerHeight/2)};return window.addEventListener("click",h,!0),window.addEventListener("keydown",p,!0),a.current=requestAnimationFrame(d),()=>{window.removeEventListener("click",h,!0),window.removeEventListener("keydown",p,!0),cancelAnimationFrame(a.current)}},[d,c]),r.jsx("canvas",{ref:t,"aria-hidden":"true",role:"img","aria-label":e("noteParticles.noteParticlesAnimationCanvas","Note particles animation canvas"),style:{position:"fixed",inset:0,zIndex:99999,pointerEvents:"none"}})}const yr={type:"gain",enabled:!0,mix:1,gain:0},Fn={type:"compressor",enabled:!0,mix:1,threshold:-24,ratio:4,attack:10,release:100,knee:6,makeupGain:0},On={type:"reverb",enabled:!0,mix:.3,decay:2,preDelay:10,damping:.5,roomSize:.5},Bn={type:"delay",enabled:!0,mix:.3,time:250,feedback:.4,pingPong:!1,highCut:8e3},vr={type:"chorus",enabled:!0,mix:.5,rate:1.5,depth:.5,delay:7,voices:3},br={type:"eq",enabled:!0,mix:1,bands:[{frequency:60,gain:0,q:1,type:"lowshelf"},{frequency:250,gain:0,q:1,type:"peaking"},{frequency:1e3,gain:0,q:1,type:"peaking"},{frequency:4e3,gain:0,q:1,type:"peaking"},{frequency:12e3,gain:0,q:1,type:"highshelf"}]},xr={type:"filter",enabled:!0,mix:1,filterType:"lowpass",frequency:1e3,q:1,gain:0},Sr={type:"distortion",enabled:!0,mix:.5,drive:.5,tone:.5,curve:"soft"},kr={type:"tremolo",enabled:!0,mix:1,rate:5,depth:.5,waveform:"sine"},wr={type:"phaser",enabled:!0,mix:.5,rate:.5,depth:.5,feedback:.5,stages:4,frequency:1e3},Vm=(function(){return{gain:{unity:{...yr,gain:0},boost:{...yr,gain:6},cut:{...yr,gain:-6}},compressor:{gentle:{...Fn,threshold:-20,ratio:2,attack:30,release:200},moderate:{...Fn,threshold:-24,ratio:4,attack:10,release:100},aggressive:{...Fn,threshold:-30,ratio:8,attack:1,release:50},limiter:{...Fn,threshold:-3,ratio:20,attack:.1,release:100}},reverb:{small_room:{...On,decay:.5,roomSize:.2,damping:.7},large_hall:{...On,decay:3,roomSize:.8,damping:.3},plate:{...On,decay:1.5,roomSize:.5,damping:.4},cathedral:{...On,decay:5,roomSize:.9,damping:.2,mix:.4}},delay:{slapback:{...Bn,time:80,feedback:.1,mix:.3},quarter_note:{...Bn,time:500,feedback:.4,mix:.3},dotted_eighth:{...Bn,time:375,feedback:.5,mix:.3},long_ambient:{...Bn,time:750,feedback:.6,highCut:3e3,mix:.4}},chorus:{subtle:{...vr,rate:.5,depth:.2,voices:2,mix:.3},vintage:{...vr,rate:1,depth:.4,voices:2,delay:10,mix:.4},ensemble:{...vr,rate:2,depth:.6,voices:4,mix:.5}},eq:{vocal_presence:{...br,bands:[{frequency:80,gain:-3,q:1,type:"highpass"},{frequency:250,gain:-2,q:1,type:"peaking"},{frequency:3e3,gain:3,q:1.5,type:"peaking"},{frequency:8e3,gain:2,q:1,type:"highshelf"}]},bass_boost:{...br,bands:[{frequency:60,gain:6,q:1,type:"lowshelf"},{frequency:200,gain:2,q:1,type:"peaking"}]},brightness:{...br,bands:[{frequency:4e3,gain:3,q:1,type:"peaking"},{frequency:1e4,gain:4,q:1,type:"highshelf"}]}},filter:{low_pass_warm:{...xr,filterType:"lowpass",frequency:2e3,q:.7},high_pass_clean:{...xr,filterType:"highpass",frequency:100,q:.7},telephone:{...xr,filterType:"bandpass",frequency:1500,q:2}},distortion:{overdrive:{...Sr,drive:.3,tone:.6,curve:"soft",mix:.7},crunch:{...Sr,drive:.5,tone:.5,curve:"tube",mix:.8},fuzz:{...Sr,drive:.8,tone:.4,curve:"fuzz",mix:1}},tremolo:{slow:{...kr,rate:3,depth:.4,waveform:"sine"},fast:{...kr,rate:8,depth:.6,waveform:"sine"},choppy:{...kr,rate:6,depth:.9,waveform:"square"}},phaser:{subtle:{...wr,rate:.3,depth:.3,feedback:.3,stages:4},jet:{...wr,rate:.1,depth:.8,feedback:.7,stages:8},rotary:{...wr,rate:1,depth:.5,feedback:.4,stages:6}}}})();function wi(e){return Math.pow(10,e/20)}function Um(e,t,n,a){const s=e.sampleRate,i=Math.floor(s*t),o=e.createBuffer(2,i,s);for(let l=0;l<2;l++){const c=o.getChannelData(l);for(let d=0;d<i;d++){const h=d/s,p=Math.exp(-h/n),g=1-a*(d/i);c[d]=(Math.random()*2-1)*p*g}}return o}function qm(e,t){const a=new Float32Array(44100),s=Math.PI/180;for(let i=0;i<44100;i++){const o=i*2/44100-1;switch(t){case"soft":a[i]=(3+e*10)*o*20*s/(Math.PI+e*10*Math.abs(o));break;case"hard":a[i]=Math.tanh(o*(1+e*5));break;case"fuzz":a[i]=Math.sign(o)*Math.pow(Math.abs(o),1/(1+e*3));break;case"tube":o>=0?a[i]=1-Math.pow(1-o,1+e*2):a[i]=-(1-Math.pow(1+o,1+e*2));break}}return a}class Hm{constructor(t){this.effects=[],this.bypass=!1,this.audioContext=t,this.inputNode=t.createGain(),this.outputNode=t.createGain(),this.inputNode.connect(this.outputNode)}get input(){return this.inputNode}get output(){return this.outputNode}addEffect(t,n){const a=`effect_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=this.createEffectInstance(a,t);return n!==void 0&&n>=0&&n<this.effects.length?this.effects.splice(n,0,s):this.effects.push(s),this.reconnectChain(),a}removeEffect(t){const n=this.effects.findIndex(s=>s.id===t);if(n===-1)return!1;const a=this.effects[n];for(const s of a.nodes)s.disconnect();return this.effects.splice(n,1),this.reconnectChain(),!0}updateEffect(t,n){const a=this.effects.find(l=>l.id===t);if(!a)return!1;const s={...a.params,...n},i=this.effects.indexOf(a);for(const l of a.nodes)l.disconnect();const o=this.createEffectInstance(t,s);return this.effects[i]=o,this.reconnectChain(),!0}reorderEffects(t,n){if(t<0||t>=this.effects.length||n<0||n>=this.effects.length)return!1;const[a]=this.effects.splice(t,1);return this.effects.splice(n,0,a),this.reconnectChain(),!0}setBypass(t){this.bypass=t,this.reconnectChain()}getEffects(){return[...this.effects]}clear(){for(const t of this.effects)for(const n of t.nodes)n.disconnect();this.effects=[],this.reconnectChain()}createEffectInstance(t,n){const{audioContext:a}=this,s=[];let i,o;switch(n.type){case"gain":{const l=a.createGain();l.gain.value=wi(n.gain),s.push(l),i=o=l;break}case"compressor":{const l=a.createDynamicsCompressor();l.threshold.value=n.threshold,l.ratio.value=n.ratio,l.attack.value=n.attack/1e3,l.release.value=n.release/1e3,l.knee.value=n.knee;const c=a.createGain();c.gain.value=wi(n.makeupGain),l.connect(c),s.push(l,c),i=l,o=c;break}case"reverb":{const l=a.createConvolver();l.buffer=Um(a,n.decay,n.decay,n.damping);const c=a.createGain(),d=a.createGain(),h=a.createGain(),p=a.createGain();c.gain.value=n.mix,d.gain.value=1-n.mix,h.connect(l),h.connect(d),l.connect(c),c.connect(p),d.connect(p),s.push(h,l,c,d,p),i=h,o=p;break}case"delay":{const l=a.createDelay(5);l.delayTime.value=n.time/1e3;const c=a.createGain();c.gain.value=n.feedback;const d=a.createBiquadFilter();d.type="lowpass",d.frequency.value=n.highCut;const h=a.createGain(),p=a.createGain(),g=a.createGain(),y=a.createGain();h.gain.value=n.mix,p.gain.value=1-n.mix,g.connect(l),g.connect(p),l.connect(d),d.connect(c),c.connect(l),d.connect(h),h.connect(y),p.connect(y),s.push(g,l,d,c,h,p,y),i=g,o=y;break}case"eq":{const l=[];let c=null;for(const d of n.bands){const h=a.createBiquadFilter();h.type=d.type,h.frequency.value=d.frequency,h.Q.value=d.q,h.gain.value=d.gain,c&&c.connect(h),c=h,l.push(h)}s.push(...l),i=l[0]||a.createGain(),o=l[l.length-1]||i;break}case"filter":{const l=a.createBiquadFilter();l.type=n.filterType,l.frequency.value=n.frequency,l.Q.value=n.q,l.gain.value=n.gain,s.push(l),i=o=l;break}case"distortion":{const l=a.createWaveShaper();l.curve=qm(n.drive,n.curve),l.oversample="4x";const c=a.createBiquadFilter();c.type="lowpass",c.frequency.value=1e3+n.tone*1e4;const d=a.createGain(),h=a.createGain(),p=a.createGain(),g=a.createGain();d.gain.value=n.mix,h.gain.value=1-n.mix,p.connect(l),p.connect(h),l.connect(c),c.connect(d),d.connect(g),h.connect(g),s.push(p,l,c,d,h,g),i=p,o=g;break}case"tremolo":{const l=a.createOscillator();l.type=n.waveform,l.frequency.value=n.rate;const c=a.createGain();c.gain.value=n.depth*.5;const d=a.createGain();d.gain.value=1-n.depth*.5,l.connect(c),c.connect(d.gain),l.start(),s.push(l,c,d),i=o=d;break}case"phaser":{const l=[],c=a.createOscillator();c.type="sine",c.frequency.value=n.rate;const d=a.createGain();d.gain.value=n.depth*n.frequency;let h=null;for(let x=0;x<n.stages;x++){const v=a.createBiquadFilter();v.type="allpass",v.frequency.value=n.frequency,v.Q.value=.5,c.connect(d),d.connect(v.frequency),h&&h.connect(v),h=v,l.push(v)}const p=a.createGain(),g=a.createGain(),y=a.createGain(),m=a.createGain();p.gain.value=n.mix,g.gain.value=1-n.mix,y.connect(l[0]),y.connect(g),l[l.length-1].connect(p),p.connect(m),g.connect(m),c.start(),s.push(c,d,...l,p,g,y,m),i=y,o=m;break}default:throw new Error(`Unknown effect type: ${n.type}`)}return{id:t,params:n,nodes:s,input:i,output:o}}reconnectChain(){this.inputNode.disconnect();for(const n of this.effects)n.output.disconnect();if(this.bypass||this.effects.length===0){this.inputNode.connect(this.outputNode);return}let t=this.inputNode;for(const n of this.effects)n.params.enabled&&(t.connect(n.input),t=n.output);t.connect(this.outputNode)}dispose(){this.clear(),this.inputNode.disconnect(),this.outputNode.disconnect()}}const Il={gain:r.jsx(O.NtdVolume,{size:16}),compressor:r.jsx(O.NtdSettings,{size:16}),reverb:r.jsx(O.NtdMountain,{size:16}),delay:r.jsx(O.NtdStopwatch,{size:16}),chorus:r.jsx(O.NtdSparkle,{size:16}),eq:r.jsx(O.NtdBarChart,{size:16}),filter:r.jsx(O.NtdFilter,{size:16}),distortion:r.jsx(O.NtdLightning,{size:16}),tremolo:r.jsx(O.NtdWave,{size:16}),phaser:r.jsx(O.NtdMagicWand,{size:16})},Ll={gain:"Gain",compressor:"Compressor",reverb:"Reverb",delay:"Delay",chorus:"Chorus",eq:"EQ",filter:"Filter",distortion:"Distortion",tremolo:"Tremolo",phaser:"Phaser"},Km={gain:yr,compressor:Fn,reverb:On,delay:Bn,chorus:vr,eq:br,filter:xr,distortion:Sr,tremolo:kr,phaser:wr},Ym=["gain","compressor","reverb","delay","chorus","eq","filter","distortion","tremolo","phaser"],ze=({value:e,min:t,max:n,step:a=1,label:s,unit:i="",onChange:o,disabled:l})=>{const c=u.useRef(null),[d,h]=u.useState(!1),p=u.useRef(0),g=u.useRef(e),y=u.useCallback(x=>{l||(x.preventDefault(),h(!0),p.current=x.clientY,g.current=e)},[l,e]);u.useEffect(()=>{if(!d)return;const x=f=>{const k=p.current-f.clientY,b=n-t,N=k/200*b,$=Math.min(n,Math.max(t,g.current+N));o(a<1?$:Math.round($/a)*a)},v=()=>{h(!1)};return document.addEventListener("mousemove",x),document.addEventListener("mouseup",v),()=>{document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",v)}},[d,t,n,a,o]);const m=(e-t)/(n-t)*270-135;return r.jsxs("div",{className:`nice-fx-knob ${l?"nice-fx-knob--disabled":""}`,ref:c,children:[r.jsx("div",{className:`nice-fx-knob__dial ${d?"nice-fx-knob__dial--active":""}`,onMouseDown:y,style:{transform:`rotate(${m}deg)`},children:r.jsx("div",{className:"nice-fx-knob__indicator"})}),r.jsx("div",{className:"nice-fx-knob__label",children:s}),r.jsxs("div",{className:"nice-fx-knob__value",children:[typeof e=="number"&&a<1?e.toFixed(2):e,i]})]})};function Zm({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:d}=be();return r.jsx(wt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsx(ze,{value:e.gain,min:-60,max:12,step:.1,label:d("audioEffectsRack.gain","Gain"),unit:"dB",onChange:h=>t({...e,gain:h}),disabled:!e.enabled})})}function Xm({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:d}=be();return r.jsx(wt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(ze,{value:e.threshold,min:-60,max:0,label:d("audioEffectsRack.threshold","Threshold"),unit:"dB",onChange:h=>t({...e,threshold:h}),disabled:!e.enabled}),r.jsx(ze,{value:e.ratio,min:1,max:20,label:d("audioEffectsRack.ratio","Ratio"),onChange:h=>t({...e,ratio:h}),disabled:!e.enabled}),r.jsx(ze,{value:e.attack,min:.1,max:200,label:d("audioEffectsRack.attack","Attack"),unit:"ms",onChange:h=>t({...e,attack:h}),disabled:!e.enabled}),r.jsx(ze,{value:e.release,min:10,max:1e3,label:d("audioEffectsRack.release","Release"),unit:"ms",onChange:h=>t({...e,release:h}),disabled:!e.enabled}),!c&&r.jsxs(r.Fragment,{children:[r.jsx(ze,{value:e.knee,min:0,max:40,label:d("audioEffectsRack.knee","Knee"),unit:"dB",onChange:h=>t({...e,knee:h}),disabled:!e.enabled}),r.jsx(ze,{value:e.makeupGain,min:0,max:24,label:d("audioEffectsRack.makeup","Makeup"),unit:"dB",onChange:h=>t({...e,makeupGain:h}),disabled:!e.enabled})]})]})})}function Qm({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:d}=be();return r.jsx(wt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(ze,{value:e.decay,min:.1,max:10,step:.1,label:d("audioEffectsRack.decay","Decay"),unit:"s",onChange:h=>t({...e,decay:h}),disabled:!e.enabled}),r.jsx(ze,{value:e.damping,min:0,max:1,step:.01,label:d("audioEffectsRack.damping","Damping"),onChange:h=>t({...e,damping:h}),disabled:!e.enabled}),r.jsx(ze,{value:e.roomSize,min:0,max:1,step:.01,label:d("audioEffectsRack.room","Room"),onChange:h=>t({...e,roomSize:h}),disabled:!e.enabled}),r.jsx(ze,{value:e.mix,min:0,max:1,step:.01,label:d("audioEffectsRack.mix","Mix"),onChange:h=>t({...e,mix:h}),disabled:!e.enabled})]})})}function Jm({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:d}=be();return r.jsx(wt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(ze,{value:e.time,min:0,max:2e3,label:d("audioEffectsRack.time","Time"),unit:"ms",onChange:h=>t({...e,time:h}),disabled:!e.enabled}),r.jsx(ze,{value:e.feedback,min:0,max:1,step:.01,label:d("audioEffectsRack.feedback","Feedback"),onChange:h=>t({...e,feedback:h}),disabled:!e.enabled}),r.jsx(ze,{value:e.highCut,min:200,max:2e4,label:d("audioEffectsRack.hicut","HiCut"),unit:"Hz",onChange:h=>t({...e,highCut:h}),disabled:!e.enabled}),r.jsx(ze,{value:e.mix,min:0,max:1,step:.01,label:d("audioEffectsRack.mix","Mix"),onChange:h=>t({...e,mix:h}),disabled:!e.enabled})]})})}function e0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:d}=be();return r.jsx(wt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(ze,{value:e.drive,min:0,max:1,step:.01,label:d("audioEffectsRack.drive","Drive"),onChange:h=>t({...e,drive:h}),disabled:!e.enabled}),r.jsx(ze,{value:e.tone,min:0,max:1,step:.01,label:d("audioEffectsRack.tone","Tone"),onChange:h=>t({...e,tone:h}),disabled:!e.enabled}),r.jsx(ze,{value:e.mix,min:0,max:1,step:.01,label:d("audioEffectsRack.mix","Mix"),onChange:h=>t({...e,mix:h}),disabled:!e.enabled})]})})}function wt({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:d}){const{t:h}=be(),[p,g]=u.useState(!1);return r.jsxs("div",{className:`nice-fx-card ${e.enabled?"":"nice-fx-card--disabled"} ${i?"nice-fx-card--drop-target":""} ${c?"nice-fx-card--compact":""}`,draggable:!0,onDragStart:a,onDragEnd:s,children:[r.jsxs("div",{className:"nice-fx-card__header",children:[r.jsx("span",{className:"nice-fx-card__icon",children:Il[e.type]}),r.jsx("span",{className:"nice-fx-card__title",children:Ll[e.type]}),r.jsx("button",{type:"button",className:`nice-fx-card__toggle ${e.enabled?"nice-fx-card__toggle--active":""}`,onClick:()=>t({...e,enabled:!e.enabled}),title:e.enabled?"Disable":"Enable","aria-pressed":e.enabled,children:r.jsx("span",{className:"nice-fx-card__toggle-dot","aria-hidden":"true"})}),l&&Object.keys(o).length>0&&r.jsxs("div",{className:"nice-fx-card__presets",children:[r.jsx("button",{type:"button",className:"nice-fx-card__preset-btn",onClick:()=>g(!p),"aria-label":h("audioEffectsRack.presets","Presets"),children:r.jsx(O.NtdChevronDown,{size:12})}),p&&r.jsx("div",{className:"nice-fx-card__preset-menu",children:Object.entries(o).map(([y,m])=>r.jsx("button",{type:"button",className:"nice-fx-card__preset-item",onClick:()=>{t({...m,enabled:e.enabled}),g(!1)},children:y.replace(/_/g," ")},y))})]}),r.jsx("button",{type:"button",className:"nice-fx-card__remove",onClick:n,title:h("audioEffectsRack.remove","Remove"),children:r.jsx(we.NiceIcon,{name:"close",size:14})})]}),r.jsx("div",{className:"nice-fx-card__body",children:d})]})}function t0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:d}=be();return r.jsx(wt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsx("div",{className:"nice-fx-card__generic",children:r.jsx(ze,{value:e.mix,min:0,max:1,step:.01,label:d("audioEffectsRack.mix","Mix"),onChange:h=>t({...e,mix:h}),disabled:!e.enabled})})})}function n0({effect:e,onChange:t,...n}){const{t:a}=be(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(wt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(ze,{value:s.rate??1.5,min:.1,max:10,step:.1,label:a("audioEffectsRack.rate","Rate"),onChange:o=>i("rate",o),disabled:!e.enabled}),r.jsx(ze,{value:s.depth??.5,min:0,max:1,step:.01,label:a("audioEffectsRack.depth","Depth"),onChange:o=>i("depth",o),disabled:!e.enabled}),r.jsx(ze,{value:s.feedback??.3,min:0,max:.95,step:.01,label:a("audioEffectsRack.feedback","Feedback"),onChange:o=>i("feedback",o),disabled:!e.enabled}),r.jsx(ze,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}function r0({effect:e,onChange:t,...n}){const{t:a}=be(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(wt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(ze,{value:s.low??0,min:-12,max:12,step:.5,label:a("audioEffectsRack.low","Low"),onChange:o=>i("low",o),disabled:!e.enabled}),r.jsx(ze,{value:s.mid??0,min:-12,max:12,step:.5,label:a("audioEffectsRack.mid","Mid"),onChange:o=>i("mid",o),disabled:!e.enabled}),r.jsx(ze,{value:s.high??0,min:-12,max:12,step:.5,label:a("audioEffectsRack.high","High"),onChange:o=>i("high",o),disabled:!e.enabled}),r.jsx(ze,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}function a0({effect:e,onChange:t,...n}){const{t:a}=be(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(wt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(ze,{value:s.frequency??1e3,min:20,max:2e4,step:1,label:a("audioEffectsRack.freq","Freq"),onChange:o=>i("frequency",o),disabled:!e.enabled}),r.jsx(ze,{value:s.Q??1,min:.1,max:20,step:.1,label:"Q",onChange:o=>i("Q",o),disabled:!e.enabled}),r.jsx(ze,{value:s.gain??0,min:-24,max:24,step:.5,label:a("audioEffectsRack.gain","Gain"),onChange:o=>i("gain",o),disabled:!e.enabled}),r.jsx(ze,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}function s0({effect:e,onChange:t,...n}){const{t:a}=be(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(wt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(ze,{value:s.rate??5,min:.1,max:20,step:.1,label:a("audioEffectsRack.rate","Rate"),onChange:o=>i("rate",o),disabled:!e.enabled}),r.jsx(ze,{value:s.depth??.5,min:0,max:1,step:.01,label:a("audioEffectsRack.depth","Depth"),onChange:o=>i("depth",o),disabled:!e.enabled}),r.jsx(ze,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}function i0({effect:e,onChange:t,...n}){const{t:a}=be(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(wt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(ze,{value:s.rate??.5,min:.01,max:8,step:.01,label:a("audioEffectsRack.rate","Rate"),onChange:o=>i("rate",o),disabled:!e.enabled}),r.jsx(ze,{value:s.depth??.7,min:0,max:1,step:.01,label:a("audioEffectsRack.depth","Depth"),onChange:o=>i("depth",o),disabled:!e.enabled}),r.jsx(ze,{value:s.feedback??.5,min:0,max:.95,step:.01,label:a("audioEffectsRack.feedback","Feedback"),onChange:o=>i("feedback",o),disabled:!e.enabled}),r.jsx(ze,{value:s.stages??4,min:2,max:12,step:2,label:a("audioEffectsRack.stages","Stages"),onChange:o=>i("stages",o),disabled:!e.enabled}),r.jsx(ze,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}const o0=({audioContext:e,chain:t,effects:n,onChange:a,onChainUpdate:s,maxEffects:i=10,availableEffects:o=Ym,showPresets:l=!0,compact:c=!1,className:d=""})=>{const{t:h}=be(),[p,g]=u.useState((n==null?void 0:n.map(R=>R.params))||[]),[y,m]=u.useState({isDragging:!1,dragIndex:-1,dropIndex:-1}),[x,v]=u.useState(!1),f=u.useMemo(()=>t||(e?new Hm(e):null),[e,t]),k=u.useCallback((R,L)=>{const A=[...p];A[R]=L,g(A),a==null||a(A),f&&(s==null||s(f))},[p,a,f,s]),b=u.useCallback(R=>{if(p.length>=i)return;const L={...Km[R]},A=[...p,L];g(A),a==null||a(A),v(!1)},[p,i,a]),w=u.useCallback(R=>{const L=p.filter((A,z)=>z!==R);g(L),a==null||a(L)},[p,a]),N=u.useCallback(R=>{m({isDragging:!0,dragIndex:R,dropIndex:-1})},[]),$=u.useCallback(()=>{if(y.dragIndex!==-1&&y.dropIndex!==-1&&y.dragIndex!==y.dropIndex){const R=[...p],[L]=R.splice(y.dragIndex,1);R.splice(y.dropIndex,0,L),g(R),a==null||a(R)}m({isDragging:!1,dragIndex:-1,dropIndex:-1})},[y,p,a]),M=u.useCallback((R,L)=>{R.preventDefault(),y.isDragging&&m(A=>({...A,dropIndex:L}))},[y.isDragging]),E=(R,L)=>{const A={onRemove:()=>w(L),onDragStart:()=>N(L),onDragEnd:$,isDragTarget:y.dropIndex===L,presets:Vm[R.type]||{},showPresets:l,compact:c};switch(R.type){case"gain":return r.jsx(Zm,{effect:R,onChange:z=>k(L,z),...A},L);case"compressor":return r.jsx(Xm,{effect:R,onChange:z=>k(L,z),...A},L);case"reverb":return r.jsx(Qm,{effect:R,onChange:z=>k(L,z),...A},L);case"delay":return r.jsx(Jm,{effect:R,onChange:z=>k(L,z),...A},L);case"distortion":return r.jsx(e0,{effect:R,onChange:z=>k(L,z),...A},L);case"chorus":return r.jsx(n0,{effect:R,onChange:z=>k(L,z),...A},L);case"eq":return r.jsx(r0,{effect:R,onChange:z=>k(L,z),...A},L);case"filter":return r.jsx(a0,{effect:R,onChange:z=>k(L,z),...A},L);case"tremolo":return r.jsx(s0,{effect:R,onChange:z=>k(L,z),...A},L);case"phaser":return r.jsx(i0,{effect:R,onChange:z=>k(L,z),...A},L);default:return r.jsx(t0,{effect:R,onChange:z=>k(L,z),...A},L)}};return r.jsxs("div",{className:`nice-fx-rack ${c?"nice-fx-rack--compact":""} ${d}`,children:[r.jsxs("div",{className:"nice-fx-rack__header",children:[r.jsx("h3",{className:"nice-fx-rack__title",children:h("audioEffectsRack.effectsChain","Effects Chain")}),r.jsxs("span",{className:"nice-fx-rack__count",children:[p.length,"/",i]})]}),r.jsx("div",{className:"nice-fx-rack__chain",children:p.length===0?r.jsx("div",{className:"nice-fx-rack__empty",children:"No effects. Click + to add."}):p.map((R,L)=>r.jsxs("div",{className:"nice-fx-rack__slot",onDragOver:A=>M(A,L),children:[E(R,L),L<p.length-1&&r.jsx("div",{className:"nice-fx-rack__connector","aria-hidden":"true",children:r.jsx(O.NtdArrowRight,{size:14})})]},L))}),p.length<i&&r.jsxs("div",{className:"nice-fx-rack__add",children:[r.jsx("button",{type:"button",className:"nice-fx-rack__add-btn",onClick:()=>v(!x),children:"+ Add Effect"}),x&&r.jsx("div",{className:"nice-fx-rack__add-menu",children:o.map(R=>r.jsxs("button",{type:"button",className:"nice-fx-rack__add-item",onClick:()=>b(R),children:[r.jsx("span",{className:"nice-fx-rack__add-icon",children:Il[R]}),r.jsx("span",{className:"nice-fx-rack__add-label",children:Ll[R]})]},R))})]})]})},_l=[{type:"chipmunk",enabled:!1,intensity:60,label:"Chipmunk",icon:"sparkle"},{type:"helium",enabled:!1,intensity:80,label:"Helium",icon:"sparkle"},{type:"deep",enabled:!1,intensity:50,label:"Deep Voice",icon:"music"},{type:"demon",enabled:!1,intensity:70,label:"Demon",icon:"skull"},{type:"robot",enabled:!1,intensity:50,label:"Robot",icon:"robot"},{type:"alien",enabled:!1,intensity:60,label:"Alien",icon:"ghost"},{type:"echo",enabled:!1,intensity:50,label:"Echo",icon:"mountain"},{type:"cave",enabled:!1,intensity:60,label:"Cave",icon:"mountain"},{type:"reverb",enabled:!1,intensity:50,label:"Reverb",icon:"wave"},{type:"chorus",enabled:!1,intensity:50,label:"Chorus",icon:"music"},{type:"flanger",enabled:!1,intensity:50,label:"Flanger",icon:"wave"},{type:"distortion",enabled:!1,intensity:40,label:"Distortion",icon:"lightning"},{type:"telephone",enabled:!1,intensity:80,label:"Telephone",icon:"phone"},{type:"megaphone",enabled:!1,intensity:60,label:"Megaphone",icon:"megaphone"},{type:"radio",enabled:!1,intensity:70,label:"AM Radio",icon:"wave"},{type:"underwater",enabled:!1,intensity:50,label:"Underwater",icon:"wave"},{type:"whisper",enabled:!1,intensity:60,label:"Whisper",icon:"volume-mute"},{type:"tremolo",enabled:!1,intensity:50,label:"Tremolo",icon:"wave"},{type:"autotune",enabled:!1,intensity:60,label:"Auto-Tune",icon:"microphone"},{type:"vocoder",enabled:!1,intensity:50,label:"Vocoder",icon:"volume"}];function Ci(e,t,n){const a=e.sampleRate,s=Math.round(a*t),i=e.createBuffer(2,s,a);for(let o=0;o<2;o++){const l=i.getChannelData(o);for(let c=0;c<s;c++)l[c]=(Math.random()*2-1)*Math.pow(1-c/s,n)}return i}function or(e){const t=Math.max(1,e),n=44100,a=new Float32Array(n),s=Math.PI/180;for(let i=0;i<n;i++){const o=i*2/n-1;a[i]=(3+t)*o*20*s/(Math.PI+t*Math.abs(o))}return a}class zl{constructor(){this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.activeEffects=new Map,this.effectOrder=[],this.monitoring=!0,this._volume=1,this._inputVolume=1,this.started=!1,this.externalStream=!1,this.analyser=null}get isStarted(){return this.started}get context(){return this.audioCtx}get activeEffectTypes(){return[...this.effectOrder]}async start(t){this.started||(this.audioCtx=new AudioContext,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),this.sourceNode=this.audioCtx.createMediaStreamSource(this.mediaStream),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}async startWithStream(t){this.started||(this.externalStream=!0,this.audioCtx=new AudioContext,this.mediaStream=t,this.sourceNode=this.audioCtx.createMediaStreamSource(t),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}stop(){var t,n,a,s,i,o;this.clearAllEffects();try{(t=this.analyser)==null||t.disconnect()}catch{}try{(n=this.outputGain)==null||n.disconnect()}catch{}try{(a=this.inputGain)==null||a.disconnect()}catch{}try{(s=this.sourceNode)==null||s.disconnect()}catch{}try{(i=this.audioCtx)==null||i.close()}catch{}if(!this.externalStream)try{(o=this.mediaStream)==null||o.getTracks().forEach(l=>l.stop())}catch{}this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.analyser=null,this.started=!1}setMonitoring(t){this.monitoring=t,this.outputGain&&(this.outputGain.gain.value=t?this._volume:0)}setVolume(t){this._volume=Math.max(0,Math.min(2,t)),this.outputGain&&this.monitoring&&(this.outputGain.gain.value=this._volume)}setInputGain(t){this._inputVolume=Math.max(0,Math.min(3,t)),this.inputGain&&(this.inputGain.gain.value=this._inputVolume)}getLevel(){if(!this.analyser)return 0;const t=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(t);let n=0;for(let a=0;a<t.length;a++){const s=(t[a]-128)/128;n+=s*s}return Math.sqrt(n/t.length)}addEffect(t,n=50){if(!this.audioCtx||!this.inputGain||!this.outputGain||this.activeEffects.has(t))return;const a=this.buildEffectChain(t,n);a&&(this.activeEffects.set(t,a),this.effectOrder.push(t),this.reconnectChain())}removeEffect(t){const n=this.activeEffects.get(t);if(n){for(const a of n.nodes)try{a.disconnect()}catch{}this.activeEffects.delete(t),this.effectOrder=this.effectOrder.filter(a=>a!==t),this.reconnectChain()}}toggleEffect(t,n=50){return this.activeEffects.has(t)?(this.removeEffect(t),!1):(this.addEffect(t,n),!0)}updateIntensity(t,n){this.activeEffects.has(t)&&(this.removeEffect(t),this.addEffect(t,n))}clearAllEffects(){for(const[t]of this.activeEffects){const n=this.activeEffects.get(t);if(n)for(const a of n.nodes)try{a.disconnect()}catch{}}this.activeEffects.clear(),this.effectOrder=[],this.reconnectChain()}reconnectChain(){if(!this.inputGain||!this.outputGain)return;try{this.inputGain.disconnect()}catch{}for(const[,n]of this.activeEffects)try{n.output.disconnect()}catch{}if(this.effectOrder.length===0){this.inputGain.connect(this.outputGain);return}let t=this.inputGain;for(const n of this.effectOrder){const a=this.activeEffects.get(n);a&&(t.connect(a.input),t=a.output)}t.connect(this.outputGain)}buildEffectChain(t,n){const a=this.audioCtx,s=n/100;switch(t){case"chipmunk":return this.buildPitchShift(a,1+s*.8,s);case"helium":return this.buildPitchShift(a,1.5+s*1,s);case"deep":return this.buildPitchShift(a,1/(1+s*.5),s);case"demon":return this.buildDemon(a,s);case"robot":return this.buildRobot(a,s);case"alien":return this.buildAlien(a,s);case"echo":return this.buildDelay(a,.15+s*.35,.3+s*.4,s);case"cave":return this.buildCave(a,s);case"reverb":return this.buildReverb(a,1.5+s*3,2+s*4,s);case"chorus":return this.buildChorus(a,s);case"flanger":return this.buildFlanger(a,s);case"distortion":return this.buildDistortion(a,20+s*100,s);case"telephone":return this.buildBandpass(a,400,3500,s);case"megaphone":return this.buildMegaphone(a,s);case"radio":return this.buildRadio(a,s);case"underwater":return this.buildUnderwater(a,s);case"whisper":return this.buildWhisper(a,s);case"tremolo":return this.buildTremolo(a,s);case"autotune":return this.buildAutotune(a,s);case"vocoder":return this.buildVocoder(a,s);default:return null}}buildPitchShift(t,n,a){const s=t.createGain();s.gain.value=1;const i=t.createGain();i.gain.value=1;const o=t.createGain();o.gain.value=.7+a*.3;const l=t.createGain();l.gain.value=1-a*.5;const c=t.createDelay(1),d=t.createDelay(1),h=t.createOscillator(),p=t.createOscillator(),g=t.createGain(),y=t.createGain(),m=n-1,x=Math.abs(m)*5+2,v=Math.abs(m)*.015;h.type="sawtooth",h.frequency.value=x,g.gain.value=v,h.connect(g),g.connect(c.delayTime),c.delayTime.value=.02,p.type="sawtooth",p.frequency.value=x,y.gain.value=v,p.connect(y),y.connect(d.delayTime),d.delayTime.value=.02+v;const f=t.createGain();f.gain.value=.5;const k=t.createGain();return k.gain.value=.5,s.connect(c),s.connect(d),c.connect(f),d.connect(k),f.connect(o),k.connect(o),s.connect(l),o.connect(i),l.connect(i),h.start(),p.start(),{type:"chipmunk",nodes:[s,c,d,h,p,g,y,f,k,o,l,i],input:s,output:i}}buildRobot(t,n){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=.6+n*.4;const o=t.createGain();o.gain.value=1-n*.6;const l=t.createOscillator();l.type="square",l.frequency.value=50+n*200;const c=t.createGain();return c.gain.value=0,l.connect(c.gain),a.connect(c),c.connect(i),a.connect(o),i.connect(s),o.connect(s),l.start(),{type:"robot",nodes:[a,l,c,i,o,s],input:a,output:s}}buildAlien(t,n){const a=t.createGain(),s=t.createGain(),i=t.createOscillator();i.type="sine",i.frequency.value=300+n*700;const o=t.createGain();o.gain.value=0,i.connect(o.gain),a.connect(o);const l=t.createDelay(.1);l.delayTime.value=.005;const c=t.createOscillator();c.type="sine",c.frequency.value=3+n*10;const d=t.createGain();d.gain.value=.004,c.connect(d),d.connect(l.delayTime),o.connect(l),l.connect(s);const h=t.createGain();return h.gain.value=.3,a.connect(h),h.connect(s),i.start(),c.start(),{type:"alien",nodes:[a,i,o,l,c,d,h,s],input:a,output:s}}buildDelay(t,n,a,s){const i=t.createGain(),o=t.createGain(),l=t.createDelay(2);l.delayTime.value=n;const c=t.createGain();c.gain.value=Math.min(.85,a);const d=t.createGain();d.gain.value=.5+s*.5;const h=t.createGain();return h.gain.value=1,i.connect(l),l.connect(c),c.connect(l),l.connect(d),i.connect(h),d.connect(o),h.connect(o),{type:"echo",nodes:[i,l,c,d,h,o],input:i,output:o}}buildCave(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(2);i.delayTime.value=.2+n*.3;const o=t.createDelay(2);o.delayTime.value=.35+n*.25;const l=t.createDelay(2);l.delayTime.value=.55+n*.3;const c=t.createGain();c.gain.value=.5;const d=t.createGain();d.gain.value=.35;const h=t.createGain();h.gain.value=.25;const p=t.createConvolver();p.buffer=Ci(t,2+n*3,3);const g=t.createGain();g.gain.value=.3+n*.3,a.connect(i),i.connect(c),c.connect(i),a.connect(o),o.connect(d),d.connect(o),a.connect(l),l.connect(h),h.connect(l),i.connect(g),o.connect(g),l.connect(g),a.connect(p),p.connect(g);const y=t.createGain();return y.gain.value=.7,a.connect(y),y.connect(s),g.connect(s),{type:"cave",nodes:[a,i,o,l,c,d,h,p,g,y,s],input:a,output:s}}buildReverb(t,n,a,s){const i=t.createGain(),o=t.createGain(),l=t.createConvolver();l.buffer=Ci(t,n,a);const c=t.createGain();c.gain.value=.4+s*.5;const d=t.createGain();return d.gain.value=1,i.connect(l),l.connect(c),i.connect(d),c.connect(o),d.connect(o),{type:"reverb",nodes:[i,l,c,d,o],input:i,output:o}}buildChorus(t,n){const a=t.createGain(),s=t.createGain(),i=[{delayMs:20,lfoFreq:.5,depth:.003},{delayMs:25,lfoFreq:.7,depth:.004},{delayMs:30,lfoFreq:1.1,depth:.005}],o=[a,s],l=t.createGain();l.gain.value=.7,a.connect(l),l.connect(s),o.push(l);for(const c of i){const d=t.createDelay(.1);d.delayTime.value=c.delayMs/1e3;const h=t.createOscillator();h.type="sine",h.frequency.value=c.lfoFreq;const p=t.createGain();p.gain.value=c.depth*(.5+n),h.connect(p),p.connect(d.delayTime);const g=t.createGain();g.gain.value=.3+n*.2,a.connect(d),d.connect(g),g.connect(s),h.start(),o.push(d,h,p,g)}return{type:"chorus",nodes:o,input:a,output:s}}buildFlanger(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.02);i.delayTime.value=.005;const o=t.createOscillator();o.type="sine",o.frequency.value=.2+n*2;const l=t.createGain();l.gain.value=.003+n*.002,o.connect(l),l.connect(i.delayTime);const c=t.createGain();c.gain.value=.5+n*.35;const d=t.createGain();d.gain.value=.5+n*.3;const h=t.createGain();return h.gain.value=1,a.connect(i),i.connect(c),c.connect(i),i.connect(d),a.connect(h),d.connect(s),h.connect(s),o.start(),{type:"flanger",nodes:[a,i,o,l,c,d,h,s],input:a,output:s}}buildDistortion(t,n,a){const s=t.createGain(),i=t.createGain(),o=t.createWaveShaper();o.curve=or(n),o.oversample="4x";const l=t.createGain();l.gain.value=.6+a*.4;const c=t.createGain();return c.gain.value=1-a*.4,s.connect(o),o.connect(l),s.connect(c),l.connect(i),c.connect(i),{type:"distortion",nodes:[s,o,l,c,i],input:s,output:i}}buildBandpass(t,n,a,s){const i=t.createGain(),o=t.createGain(),l=t.createBiquadFilter();l.type="highpass",l.frequency.value=n,l.Q.value=.7;const c=t.createBiquadFilter();return c.type="lowpass",c.frequency.value=a,c.Q.value=.7,i.connect(l),l.connect(c),c.connect(o),{type:"telephone",nodes:[i,l,c,o],input:i,output:o}}buildMegaphone(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500;const o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=4e3;const l=t.createWaveShaper();l.curve=or(15+n*30),l.oversample="2x";const c=t.createBiquadFilter();return c.type="peaking",c.frequency.value=2e3,c.gain.value=6+n*6,c.Q.value=1,a.connect(i),i.connect(o),o.connect(l),l.connect(c),c.connect(s),{type:"megaphone",nodes:[a,i,o,l,c,s],input:a,output:s}}buildRadio(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=300+n*200;const o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=3e3-n*500;const l=t.createBiquadFilter();l.type="peaking",l.frequency.value=1500,l.gain.value=8,l.Q.value=2;const c=t.createWaveShaper();return c.curve=or(10),a.connect(i),i.connect(o),o.connect(l),l.connect(c),c.connect(s),{type:"radio",nodes:[a,i,o,l,c,s],input:a,output:s}}buildUnderwater(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="lowpass",i.frequency.value=300+(1-n)*400,i.Q.value=5+n*10;const o=t.createOscillator();o.type="sine",o.frequency.value=.5+n*2;const l=t.createGain();l.gain.value=100+n*200,o.connect(l),l.connect(i.frequency);const c=t.createGain();c.gain.value=.7+n*.3;const d=t.createGain();return d.gain.value=.3-n*.2,a.connect(i),i.connect(c),a.connect(d),c.connect(s),d.connect(s),o.start(),{type:"underwater",nodes:[a,i,o,l,c,d,s],input:a,output:s}}buildWhisper(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500+n*500,i.Q.value=.5;const o=t.createWaveShaper(),l=new Float32Array(256);for(let d=0;d<256;d++){const h=d/255*2-1;l[d]=Math.sign(h)*Math.pow(Math.abs(h),.3+n*.5)}o.curve=l;const c=t.createBiquadFilter();return c.type="highshelf",c.frequency.value=3e3,c.gain.value=6+n*6,a.connect(i),i.connect(o),o.connect(c),c.connect(s),{type:"whisper",nodes:[a,i,o,c,s],input:a,output:s}}buildDemon(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.1);i.delayTime.value=.03;const o=t.createOscillator();o.type="sawtooth",o.frequency.value=2+n*3;const l=t.createGain();l.gain.value=.02+n*.015,o.connect(l),l.connect(i.delayTime);const c=t.createWaveShaper();c.curve=or(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 p=t.createGain();return p.gain.value=.3,a.connect(i),i.connect(c),c.connect(d),d.connect(h),a.connect(p),h.connect(s),p.connect(s),o.start(),{type:"demon",nodes:[a,i,o,l,c,d,h,p,s],input:a,output:s}}buildTremolo(t,n){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=1;const o=t.createOscillator();o.type="sine",o.frequency.value=3+n*12;const l=t.createGain();return l.gain.value=.3+n*.5,o.connect(l),l.connect(i.gain),a.connect(i),i.connect(s),o.start(),{type:"tremolo",nodes:[a,i,o,l,s],input:a,output:s}}buildAutotune(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.05);i.delayTime.value=.005;const o=t.createOscillator();o.type="sine",o.frequency.value=6+n*8;const l=t.createGain();l.gain.value=.002+n*.002,o.connect(l),l.connect(i.delayTime);const c=[],d=[261.6,293.7,329.6,349.2,392,440,493.9,523.3],h=t.createGain();h.gain.value=.15;for(const y of d){const m=t.createBiquadFilter();m.type="peaking",m.frequency.value=y,m.Q.value=8+n*15,m.gain.value=4+n*8,a.connect(m),m.connect(h),c.push(m)}const p=t.createGain();p.gain.value=.7;const g=t.createGain();return g.gain.value=.5+n*.3,a.connect(i),i.connect(g),h.connect(g),a.connect(p),g.connect(s),p.connect(s),o.start(),{type:"autotune",nodes:[a,i,o,l,...c,h,g,p,s],input:a,output:s}}buildVocoder(t,n){const a=t.createGain(),s=t.createGain(),i=t.createOscillator();i.type="sawtooth",i.frequency.value=110+n*110;const o=t.createGain();o.gain.value=0;const l=8,c=[a,s,i,o],d=t.createGain();d.gain.value=.5+n*.5,c.push(d);for(let p=0;p<l;p++){const g=200*Math.pow(2,p*.5),y=t.createBiquadFilter();y.type="bandpass",y.frequency.value=g,y.Q.value=4;const m=t.createBiquadFilter();m.type="bandpass",m.frequency.value=g,m.Q.value=4;const x=t.createGain();x.gain.value=0,a.connect(y),y.connect(x.gain),i.connect(m),m.connect(x),x.connect(d),c.push(y,m,x)}d.connect(s);const h=t.createGain();return h.gain.value=.3-n*.2,a.connect(h),h.connect(s),c.push(h),i.start(),{type:"vocoder",nodes:c,input:a,output:s}}}const l0={sparkle:O.NtdSparkle,music:O.NtdMusic,skull:O.NtdSkull,robot:O.NtdRobot,ghost:O.NtdGhost,mountain:O.NtdMountain,wave:O.NtdWave,lightning:O.NtdLightning,phone:O.NtdPhone,megaphone:O.NtdMegaphone,"volume-mute":O.NtdVolumeMute,microphone:O.NtdMicrophone,volume:O.NtdVolume},c0=({deviceId:e,mediaStream:t,compact:n=!1,t:a,className:s,style:i,id:o,accessMode:l,"data-testid":c})=>{const{t:d}=be(),h=a??d,p=u.useRef(null),[g,y]=u.useState(!1),[m,x]=u.useState(()=>_l.map(D=>({...D}))),[v,f]=u.useState(!0),[k,b]=u.useState(80),[w,N]=u.useState(100),[$,M]=u.useState(0),E=u.useRef(0),R=u.useCallback(()=>{const D=()=>{var V;(V=p.current)!=null&&V.isStarted&&(M(p.current.getLevel()),E.current=requestAnimationFrame(D))};E.current=requestAnimationFrame(D)},[]),L=u.useCallback(()=>{E.current&&cancelAnimationFrame(E.current)},[]),A=u.useCallback(async()=>{const D=new zl;p.current=D;try{t?await D.startWithStream(t):await D.start(e),D.setMonitoring(v),D.setVolume(k/100),D.setInputGain(w/100);for(const V of m)V.enabled&&D.addEffect(V.type,V.intensity);y(!0),R()}catch(V){typeof console<"u"&&console.warn("[VocalEffectsRack] start error",V)}},[e,t,v,k,w,m,R]),z=u.useCallback(()=>{var D;L(),(D=p.current)==null||D.stop(),p.current=null,y(!1),M(0)},[L]);u.useEffect(()=>()=>{var D;L(),(D=p.current)==null||D.stop(),p.current=null},[L]);const j=u.useCallback(D=>{x(V=>V.map(Z=>{var q;if(Z.type!==D)return Z;const X={...Z,enabled:!Z.enabled};return(q=p.current)!=null&&q.isStarted&&(X.enabled?p.current.addEffect(D,X.intensity):p.current.removeEffect(D)),X}))},[]),I=u.useCallback((D,V)=>{x(Z=>Z.map(X=>{var q;return X.type!==D?X:(X.enabled&&((q=p.current)!=null&&q.isStarted)&&p.current.updateIntensity(D,V),{...X,intensity:V})}))},[]);u.useEffect(()=>{var D;(D=p.current)==null||D.setVolume(k/100)},[k]),u.useEffect(()=>{var D;(D=p.current)==null||D.setInputGain(w/100)},[w]),u.useEffect(()=>{var D;(D=p.current)==null||D.setMonitoring(v)},[v]);const Y=u.useCallback(()=>{var D;(D=p.current)==null||D.clearAllEffects(),x(V=>V.map(Z=>({...Z,enabled:!1})))},[]),H=m.filter(D=>D.enabled).length;return l==="hidden"?null:r.jsxs("div",{className:`nice-vocal-effects-rack${s?` ${s}`:""}`,style:{border:"1px solid var(--nice-border, #e2e8f0)",borderRadius:12,padding:n?12:20,background:"var(--nice-bg-secondary)",color:"var(--nice-text, inherit)",...i},id:o,"data-testid":c,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16,gap:8},children:[r.jsxs("h3",{style:{margin:0,fontSize:n?16:20,display:"flex",alignItems:"center",gap:8},children:[r.jsx(O.NtdMicrophone,{size:n?16:20})," ",h("vocalEffects.title","Vocal effects")]}),r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[H>0&&r.jsxs(ie.NiceBadge,{variant:"primary",children:[H," ",h("vocalEffects.active","active")]}),g?r.jsx(ie.NiceButton,{variant:"danger",size:"sm",onClick:z,children:h("vocalEffects.stop","Stop")}):r.jsx(ie.NiceButton,{variant:"primary",size:"sm",onClick:A,children:h("vocalEffects.start","Start mic")})]})]}),r.jsxs("div",{style:{display:"flex",gap:16,alignItems:"center",marginBottom:16,flexWrap:"wrap"},children:[r.jsx(ie.NiceToggle,{checked:v,onChange:f,label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(O.NtdVolume,{size:14})," ",h("vocalEffects.monitor","Monitor")]})}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[h("vocalEffects.volume","Vol"),r.jsx("div",{style:{width:100},children:r.jsx(ie.NiceSlider,{value:k,onChange:b,min:0,max:200})}),r.jsxs("span",{style:{minWidth:36,fontSize:12},children:[k,"%"]})]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[h("vocalEffects.gain","Gain"),r.jsx("div",{style:{width:100},children:r.jsx(ie.NiceSlider,{value:w,onChange:N,min:0,max:300})}),r.jsxs("span",{style:{minWidth:36,fontSize:12},children:[w,"%"]})]}),g&&r.jsx("div",{style:{width:80,height:8,borderRadius:4,background:"var(--nice-bg-tertiary)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${Math.min(100,$*300)}%`,background:$>.5?"var(--nice-danger, #ef4444)":$>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})}),H>0&&r.jsx(ie.NiceButton,{variant:"ghost",size:"sm",onClick:Y,children:h("vocalEffects.clearAll","Clear all")})]}),r.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(auto-fill, minmax(${n?130:160}px, 1fr))`,gap:n?6:10},children:m.map(D=>r.jsxs("div",{style:{border:D.enabled?"2px solid var(--nice-accent, #3b82f6)":"1px solid var(--nice-border, #e2e8f0)",borderRadius:10,padding:n?"6px 8px":"10px 12px",background:D.enabled?"var(--nice-accent-tint-10, rgba(59,130,246,0.08))":"transparent",transition:"all 0.15s ease"},children:[r.jsxs("button",{type:"button",onClick:()=>j(D.type),style:{display:"flex",alignItems:"center",gap:6,width:"100%",marginBottom:D.enabled?6:0,background:"transparent",border:"none",cursor:"pointer",color:"inherit",textAlign:"left"},children:[(()=>{const V=l0[D.icon]??O.NtdMusic;return r.jsx(V,{size:n?18:22})})(),r.jsx("span",{style:{fontSize:n?12:14,fontWeight:D.enabled?700:500,color:D.enabled?"var(--nice-accent, #3b82f6)":"inherit"},children:D.label})]}),D.enabled&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},onClick:V=>V.stopPropagation(),onKeyDown:V=>{V.key!=="Escape"&&V.stopPropagation()},children:[r.jsx("div",{style:{flex:1},children:r.jsx(ie.NiceSlider,{value:D.intensity,onChange:V=>I(D.type,V),min:0,max:100})}),r.jsx("span",{style:{fontSize:11,minWidth:24,color:"var(--nice-text-muted, #64748b)"},children:D.intensity})]})]},D.type))}),r.jsx("div",{style:{marginTop:12,fontSize:12,color:"var(--nice-text-muted, #94a3b8)",textAlign:"center"},children:h("vocalEffects.hint","Click effects to toggle. Multiple effects can be active at once — adjust intensity with the slider.")})]})},Dl={algorithm:"pitchy",gain:1,rmsThreshold:.02,pitchThreshold:.6,smoothingWindow:3,hysteresisFrames:2,useHanning:!1,offsetMs:0},d0=[{value:"pitchy",label:"Pitchy (fast)"},{value:"autocorrelation",label:"Autocorrelation"},{value:"librosa",label:"Librosa (server)"},{value:"crepe",label:"CREPE (AI, server)"}],u0=({deviceId:e,onDeviceChange:t,settings:n,onSettingsChange:a,audioInputs:s,algorithms:i=d0,showLevelMeter:o=!0,onCalibrate:l,compact:c=!1,t:d})=>{const{t:h}=be(),p=d??h,g=u.useMemo(()=>({...Dl,...n}),[n]),y=A=>a==null?void 0:a({...g,...A}),[m,x]=u.useState([]);u.useEffect(()=>{var j,I,Y;if(s||!((j=navigator.mediaDevices)!=null&&j.enumerateDevices))return;let A=!1;const z=()=>navigator.mediaDevices.enumerateDevices().then(H=>!A&&x(H.filter(D=>D.kind==="audioinput"))).catch(()=>{});return z(),(Y=(I=navigator.mediaDevices).addEventListener)==null||Y.call(I,"devicechange",z),()=>{var H,D;A=!0,(D=(H=navigator.mediaDevices).removeEventListener)==null||D.call(H,"devicechange",z)}},[s]);const v=s??m,f=u.useMemo(()=>v.map((A,z)=>({value:A.deviceId,label:A.label||`${p("audioInput.microphone","Microphone")} ${z+1}`})),[v,p]),[k,b]=u.useState(!1),[w,N]=u.useState(0),$=u.useRef(null),M=()=>{const A=$.current;A&&(cancelAnimationFrame(A.raf),A.stream.getTracks().forEach(z=>z.stop()),A.ctx.close().catch(()=>{}),$.current=null),b(!1),N(0)},E=async()=>{try{const A=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0}}),z=new AudioContext,j=z.createMediaStreamSource(A),I=z.createAnalyser();I.fftSize=1024,j.connect(I);const Y=new Float32Array(I.fftSize),H=()=>{I.getFloatTimeDomainData(Y);let D=0;for(let V=0;V<Y.length;V++)D+=Y[V]*Y[V];N(Math.sqrt(D/Y.length)*(g.gain||1)),$.current.raf=requestAnimationFrame(H)};$.current={ctx:z,stream:A,raf:requestAnimationFrame(H)},b(!0)}catch{}};u.useEffect(()=>()=>M(),[]);const R={fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:4,display:"block"},L=(A,z,j)=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[r.jsx("span",{style:{flex:"0 0 120px",fontSize:13},children:A}),r.jsx("div",{style:{flex:1},children:z}),r.jsx("span",{style:{flex:"0 0 48px",textAlign:"right",fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:j})]});return r.jsxs("div",{className:"nice-audio-input-picker",style:{display:"flex",flexDirection:"column",gap:c?8:12,border:"1px solid var(--nice-border, #e2e8f0)",borderRadius:12,padding:c?12:16,color:"var(--nice-text, inherit)"},children:[r.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap"},children:[r.jsxs("div",{style:{flex:"1 1 220px",minWidth:180},children:[r.jsxs("label",{style:{...R,display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(O.NtdMicrophone,{size:13})," ",p("audioInput.device","Microphone")]}),r.jsx(ie.NiceSelect,{options:f,value:e??"",onChange:A=>t==null?void 0:t(typeof A=="string"?A:A[0]),placeholder:p("audioInput.selectDevice","Select microphone"),size:"sm"})]}),r.jsxs("div",{style:{flex:"1 1 200px",minWidth:160},children:[r.jsx("label",{style:R,children:p("audioInput.algorithm","Pitch algorithm")}),r.jsx(ie.NiceSelect,{options:i,value:g.algorithm,onChange:A=>y({algorithm:typeof A=="string"?A:A[0]}),size:"sm"})]})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[L(p("audioInput.gain","Gain"),r.jsx(ie.NiceSlider,{value:Math.round(g.gain*100),onChange:A=>y({gain:A/100}),min:0,max:300}),`${Math.round(g.gain*100)}%`),L(p("audioInput.rmsThreshold","RMS gate"),r.jsx(ie.NiceSlider,{value:Math.round(g.rmsThreshold*1e3),onChange:A=>y({rmsThreshold:A/1e3}),min:0,max:200}),g.rmsThreshold.toFixed(3)),L(p("audioInput.pitchThreshold","Pitch clarity"),r.jsx(ie.NiceSlider,{value:Math.round(g.pitchThreshold*100),onChange:A=>y({pitchThreshold:A/100}),min:0,max:100}),g.pitchThreshold.toFixed(2)),!c&&L(p("audioInput.smoothing","Smoothing"),r.jsx(ie.NiceSlider,{value:g.smoothingWindow,onChange:A=>y({smoothingWindow:A}),min:0,max:12}),`${g.smoothingWindow}`),!c&&L(p("audioInput.hysteresis","Hysteresis"),r.jsx(ie.NiceSlider,{value:g.hysteresisFrames,onChange:A=>y({hysteresisFrames:A}),min:0,max:12}),`${g.hysteresisFrames}`),!c&&L(p("audioInput.offset","Latency"),r.jsx(ie.NiceSlider,{value:g.offsetMs,onChange:A=>y({offsetMs:A}),min:-200,max:500}),`${g.offsetMs}ms`)]}),r.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap"},children:[r.jsx(ie.NiceToggle,{checked:g.useHanning,onChange:A=>y({useHanning:A}),label:p("audioInput.hanning","Hanning window")}),o&&r.jsxs(r.Fragment,{children:[r.jsx(ie.NiceButton,{variant:k?"danger":"secondary",size:"sm",onClick:k?M:E,children:k?p("audioInput.stopTest","Stop test"):p("audioInput.testMic","Test mic")}),r.jsx("div",{style:{width:100,height:8,borderRadius:4,background:"var(--nice-bg-tertiary)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${Math.min(100,w*300)}%`,background:w>.5?"var(--nice-danger, #ef4444)":w>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})})]}),l&&e&&r.jsxs(ie.NiceButton,{variant:"ghost",size:"sm",onClick:()=>l(e),children:[r.jsx(O.NtdSettings,{size:14})," ",p("audioInput.calibrate","Calibrate latency")]})]})]})};class Fl{constructor(t,n){this.activeNotes=new Map,this.audioContext=t,this.masterGain=t.createGain(),this.masterGain.gain.value=.3,this.masterGain.connect(n)}applyCC(t,n,a){}midiToFreq(t){return 440*Math.pow(2,(t-69)/12)}playNote(t,n=100,a=1,s="sine"){const i=this.midiToFreq(t),o=this.audioContext.createOscillator(),l=this.audioContext.createGain();o.type=s,o.frequency.value=i;const c=n/127*.8;l.gain.value=c,o.connect(l),l.connect(this.masterGain);const d=this.audioContext.currentTime;return l.gain.setValueAtTime(0,d),l.gain.linearRampToValueAtTime(c,d+.01),l.gain.exponentialRampToValueAtTime(c*.7,d+.1),l.gain.setValueAtTime(c*.7,d+a-.05),l.gain.exponentialRampToValueAtTime(.001,d+a),o.start(d),o.stop(d+a),o.onended=()=>{l.disconnect(),o.disconnect()},{osc:o,gain:l}}scheduleNote(t,n,a,s=100,i="sine"){const o=this.midiToFreq(t),l=this.audioContext.createOscillator(),c=this.audioContext.createGain();l.type=i,l.frequency.value=o;const d=s/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+a-.05),c.gain.exponentialRampToValueAtTime(.001,h+a),l.start(h),l.stop(h+a),l.onended=()=>{c.disconnect(),l.disconnect()},{osc:l,gain:c}}setVolume(t){this.masterGain.gain.value=Math.max(0,Math.min(1,t))}stopAll(){this.activeNotes.forEach(({osc:t,gain:n})=>{try{t.stop(),n.disconnect(),t.disconnect()}catch{}}),this.activeNotes.clear()}dispose(){this.stopAll(),this.masterGain.disconnect()}}const ji=ot.scoped("AudioPlaybackEngine");class h0{constructor(){this.audioContext=null,this.masterGain=null,this.masterFilter=null,this.clips=new Map,this.scheduledSources=new Map,this.midiTracks=new Map,this.synths=new Map,this.isPlaying=!1,this.startTimeOffset=0,this.audioContextStartTime=0,this.currentTime=0,this.loopRegion={start:0,end:0,enabled:!1},this.bpm=120,this.duration=0,this.initAudioContext()}setMidiCCEvents(t,n){const a=this.midiTracks.get(t);a&&(a.ccEvents=n)}getMidiCCEvents(t){const n=this.midiTracks.get(t);return(n==null?void 0:n.ccEvents)||[]}addMidiCCEvent(t,n){const a=this.midiTracks.get(t);a&&(a.ccEvents||(a.ccEvents=[]),a.ccEvents.push(n))}removeMidiCCEvent(t,n){const a=this.midiTracks.get(t);a&&a.ccEvents&&(a.ccEvents=a.ccEvents.filter(s=>s.id!==n))}initAudioContext(){try{this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.masterGain=this.audioContext.createGain(),this.masterFilter=this.audioContext.createBiquadFilter(),this.masterFilter.type="peaking",this.masterFilter.frequency.value=1200,this.masterFilter.Q.value=.7,this.masterFilter.gain.value=0,this.masterGain.connect(this.masterFilter),this.masterFilter.connect(this.audioContext.destination),this.masterGain.gain.value=.8,this.audioContext.state==="suspended"&&this.audioContext.resume()}catch(t){ji.error("Failed to initialize AudioContext:",t)}}createEffectNode(t){if(!this.audioContext||t.bypass)return null;try{switch(t.type){case"eq3":{const n=this.audioContext.createBiquadFilter(),a=this.audioContext.createBiquadFilter(),s=this.audioContext.createBiquadFilter();return n.type="lowshelf",n.frequency.value=t.params.lowFreq||250,n.gain.value=t.params.lowGain||0,a.type="peaking",a.frequency.value=1e3,a.Q.value=1,a.gain.value=t.params.midGain||0,s.type="highshelf",s.frequency.value=t.params.highFreq||4e3,s.gain.value=t.params.highGain||0,n.connect(a),a.connect(s),{input:n,output:s}}case"compressor":{const n=this.audioContext.createDynamicsCompressor();return n.threshold.value=t.params.threshold||-24,n.ratio.value=t.params.ratio||4,n.attack.value=t.params.attack||.003,n.release.value=t.params.release||.25,n.knee.value=t.params.knee||30,n}case"delay":{const n=this.audioContext.createDelay(5);n.delayTime.value=t.params.time||.25;const a=this.audioContext.createGain();a.gain.value=t.params.feedback||.3;const s=this.audioContext.createGain();s.gain.value=t.params.mix||.3;const i=this.audioContext.createGain();return i.gain.value=1-(t.params.mix||.3),n.connect(a),a.connect(n),n.connect(s),{input:n,output:s,dry:i,connect:function(o){s.connect(o),i.connect(o)}}}case"reverb":{const n=this.audioContext.createConvolver(),a=this.audioContext.sampleRate*(t.params.decay||2),s=this.audioContext.createBuffer(2,a,this.audioContext.sampleRate);for(let l=0;l<2;l++){const c=s.getChannelData(l);for(let d=0;d<a;d++)c[d]=(Math.random()*2-1)*Math.pow(1-d/a,2)}n.buffer=s;const i=this.audioContext.createGain();i.gain.value=t.params.mix||.3;const o=this.audioContext.createGain();return o.gain.value=1-(t.params.mix||.3),n.connect(i),{input:n,output:i,dry:o,connect:function(l){i.connect(l),o.connect(l)}}}case"distortion":{const n=this.audioContext.createWaveShaper(),a=t.params.amount||20,s=44100,i=new Float32Array(s),o=Math.PI/180;for(let d=0;d<s;d++){const h=d*2/s-1;i[d]=(3+a)*h*20*o/(Math.PI+a*Math.abs(h))}n.curve=i,n.oversample="4x";const l=this.audioContext.createGain();l.gain.value=t.params.mix||.5;const c=this.audioContext.createGain();return c.gain.value=1-(t.params.mix||.5),n.connect(l),{input:n,output:l,dry:c,connect:function(d){l.connect(d),c.connect(d)}}}default:return null}}catch(n){return ji.error("Failed to create effect node:",t.type,n),null}}addClip(t){this.clips.set(t.id,t),this.updateDuration()}removeClip(t){this.clips.delete(t),this.stopClip(t),this.updateDuration()}updateClip(t,n){const a=this.clips.get(t);a&&(Object.assign(a,n),this.updateDuration())}getClipsByLayer(t){return Array.from(this.clips.values()).filter(n=>n.layerId===t)}setMidiTrack(t,n,a="sine",s=.5){if(this.midiTracks.set(t,{layerId:t,notes:n,instrument:a,volume:s}),!this.synths.has(t)&&this.audioContext&&this.masterGain){const i=new Fl(this.audioContext,this.masterGain);i.setVolume(s),this.synths.set(t,i)}}removeMidiTrack(t){this.midiTracks.delete(t);const n=this.synths.get(t);n&&(n.dispose(),this.synths.delete(t))}updateMidiTrackVolume(t,n){const a=this.midiTracks.get(t);a&&(a.volume=n);const s=this.synths.get(t);s&&s.setVolume(n)}updateDuration(){let t=0;this.clips.forEach(n=>{const a=n.startTime+n.duration;a>t&&(t=a)}),this.duration=t}play(){!this.audioContext||this.isPlaying||(this.audioContext.state==="suspended"&&this.audioContext.resume(),this.isPlaying=!0,this.audioContextStartTime=this.audioContext.currentTime,this.startTimeOffset=this.currentTime,this.scheduleClips(),this.scheduleMidiNotes(),this.startTimeTracking(),this.onPlayStateChange&&this.onPlayStateChange(!0))}pause(){this.isPlaying&&(this.isPlaying=!1,this.stopAllSources(),this.onPlayStateChange&&this.onPlayStateChange(!1))}stop(){this.pause(),this.seek(0)}seek(t){const n=this.isPlaying;n&&this.pause(),this.currentTime=Math.max(0,Math.min(t,this.duration)),this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),n&&this.play()}scheduleClips(){!this.audioContext||!this.masterGain||this.clips.forEach(t=>{if(t.startTime+t.duration<=this.currentTime)return;const a=this.audioContext.createBufferSource();a.buffer=t.buffer,t.stretchFactor&&t.stretchFactor!==1&&(a.playbackRate.value=1/t.stretchFactor);const s=this.audioContext.createGain();s.gain.value=t.volume;const i=this.audioContext.createStereoPanner();i.pan.value=t.pan,a.connect(s);let o=s;if(t.effectChain&&t.effectChain.length>0)for(const h of t.effectChain){const p=this.createEffectNode(h);if(p)if("input"in p&&"output"in p){const g=p;o.connect(g.input),o=g.output,"dry"in p&&s.connect(g.dry)}else o.connect(p),o=p}o.connect(i),i.connect(this.masterGain);const l=t.startTime,c=Math.max(0,this.currentTime-l),d=this.audioContext.currentTime+(l-this.currentTime);d>=this.audioContext.currentTime&&(a.start(d,t.offset+c,t.duration-c),this.scheduledSources.set(t.id,a),a.onended=()=>{this.scheduledSources.delete(t.id)})})}stopClip(t){const n=this.scheduledSources.get(t);if(n){try{n.stop()}catch{}this.scheduledSources.delete(t)}}stopAllSources(){this.scheduledSources.forEach(t=>{try{t.stop()}catch{}}),this.scheduledSources.clear(),this.synths.forEach(t=>t.stopAll())}scheduleMidiNotes(){this.audioContext&&this.midiTracks.forEach(t=>{const n=this.synths.get(t.layerId);if(n&&(t.notes.forEach(a=>{if(a.start+a.duration<=this.currentTime)return;const i=Math.max(0,this.currentTime-a.start),o=this.audioContext.currentTime+(a.start-this.currentTime);o>=this.audioContext.currentTime&&n.scheduleNote(a.pitch,o,a.duration-i,a.velocity,t.instrument)}),t.ccEvents&&Array.isArray(t.ccEvents)&&t.ccEvents.length>0)){const a=[...t.ccEvents].sort((o,l)=>o.time-l.time);let i=a[0];for(let o=1;o<a.length;++o){const l=a[o],c=i.time,d=l.time,h=i.value,p=l.value,g=i.handleType||"linear",y=Math.max(2,Math.ceil((d-c)*20));for(let m=0;m<=y;++m){const x=m/y;let v=h;if(g==="linear")v=h+(p-h)*x;else if(g==="step")v=x<1?h:p;else if(g==="exp"){const w=Math.max(h/127,.001),N=Math.max(p/127,.001);v=w*Math.pow(N/w,x)*127}const f=c+(d-c)*x,k=this.audioContext.currentTime+(f-this.currentTime);k>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(l.cc,v,k)}i=l}}})}startTimeTracking(){if(!this.audioContext)return;const t=()=>{if(!this.isPlaying||!this.audioContext)return;const n=this.audioContext.currentTime-this.audioContextStartTime;if(this.currentTime=this.startTimeOffset+n,this.loopRegion.enabled&&this.currentTime>=this.loopRegion.end){this.seek(this.loopRegion.start);return}if(this.currentTime>=this.duration){this.stop();return}this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),requestAnimationFrame(t)};requestAnimationFrame(t)}setLoopRegion(t,n,a){this.loopRegion={start:t,end:n,enabled:a}}setBPM(t){this.bpm=Math.max(20,Math.min(300,t))}getBPM(){return this.bpm}setMasterVolume(t){this.masterGain&&(this.masterGain.gain.value=Math.max(0,Math.min(1,t)))}setMasterFilter(t){this.masterFilter&&(t.type&&(this.masterFilter.type=t.type),t.frequency!=null&&(this.masterFilter.frequency.value=Math.max(20,Math.min(2e4,t.frequency))),t.q!=null&&(this.masterFilter.Q.value=Math.max(.1,Math.min(18,t.q))),t.gain!=null&&"gain"in this.masterFilter&&(this.masterFilter.gain.value=Math.max(-40,Math.min(40,t.gain))))}getCurrentTime(){return this.currentTime}getDuration(){return this.duration}getIsPlaying(){return this.isPlaying}setOnTimeUpdate(t){this.onTimeUpdate=t}setOnPlayStateChange(t){this.onPlayStateChange=t}dispose(){this.stop(),this.audioContext&&this.audioContext.close(),this.clips.clear()}}const p0=[{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 Vr(e={}){const{channelFilter:t,sysex:n=!1,onEvent:a,inputNameIncludes:s,onInputsChanged:i}=e,[o,l]=u.useState(null),[c,d]=u.useState(!1),[h,p]=u.useState([]),g=u.useRef(null),y=u.useCallback((m,x)=>{const v=m.data??new Uint8Array(0),f=v[0]??0,k=v[1]??0,b=v[2]??0,w=m.timeStamp,N=f&240,$=f&15,M=x.id,E=x.name??"MIDI Input",R=t===void 0||t===$;if((N===144||N===128)&&R){const L=N===144&&b>0;return{type:L?"noteon":"noteoff",note:k,velocity:L?b:0,channel:$,ts:w,deviceId:M,deviceName:E}}return N===176&&R?{type:"cc",controller:k,value:b,channel:$,ts:w,deviceId:M,deviceName:E}:N===208&&R?{type:"aftertouch",pressure:k,channel:$,ts:w,deviceId:M,deviceName:E}:N===224&&R?{type:"pitchbend",value:(k|b<<7)-8192,channel:$,ts:w,deviceId:M,deviceName:E}:N===192&&R?{type:"program",program:k,channel:$,ts:w,deviceId:M,deviceName:E}:{type:"unknown",status:f,data1:k,data2:b,channel:$,ts:w,deviceId:M,deviceName:E}},[t]);return u.useEffect(()=>{if(!("requestMIDIAccess"in navigator)){l(!1);return}l(!0);let m=!1;return navigator.requestMIDIAccess({sysex:n}).then(x=>{if(m)return;g.current=x,d(!0);const v=()=>{const f=Array.from(x.inputs.values()),k=s?f.filter(b=>(b.name||"").toUpperCase().includes(s.toUpperCase())):f;p(k),i==null||i(k),f.forEach(b=>b.onmidimessage=null),k.forEach(b=>{b.onmidimessage=w=>a==null?void 0:a(y(w,b))})};v(),x.onstatechange=()=>v()}),()=>{m=!0;const x=g.current;x&&(x.inputs.forEach(v=>v.onmidimessage=null),x.onstatechange=null)}},[s,a,i,y,n]),{supported:o,granted:c,inputs:h}}const rs="nice2dev.midiLearn";function f0(){try{const e=localStorage.getItem(rs);return e?JSON.parse(e):{}}catch{return{}}}function Mi(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(rs,JSON.stringify(t))}function m0(e){const{parameters:t,onParameterChange:n}=e,[a,s]=u.useState(()=>{const b=f0();return t.map(w=>{const N=b[w.id];return{id:w.id,paramName:w.name,type:(N==null?void 0:N.type)??"cc",number:N==null?void 0:N.number,channel:N==null?void 0:N.channel,min:(N==null?void 0:N.min)??w.min??0,max:(N==null?void 0:N.max)??w.max??127,value:0}})}),[i,o]=u.useState({learning:!1,targetId:null}),[l,c]=u.useState(null),d=u.useRef(a);d.current=a;const h=u.useRef(n);h.current=n;const p=u.useRef(i);p.current=i;const g=u.useCallback(b=>{var N;c(b);const w=p.current;if(w.learning&&w.targetId){if(!d.current.find(E=>E.id===w.targetId))return;let M={};switch(b.type){case"cc":M={type:"cc",number:b.controller,channel:b.channel};break;case"noteon":M={type:"note",number:b.note,channel:b.channel};break;case"pitchbend":M={type:"pitchbend",channel:b.channel};break;case"aftertouch":M={type:"aftertouch",channel:b.channel};break;default:return}s(E=>{const R=E.map(L=>L.id===w.targetId?{...L,...M}:L);return Mi(R),R}),o({learning:!1,targetId:null});return}for(const $ of d.current){if($.number===void 0&&$.type!=="pitchbend"&&$.type!=="aftertouch"||$.channel!==void 0&&b.channel!==$.channel)continue;let M=null,E=127;if($.type==="cc"&&b.type==="cc"&&b.controller===$.number?M=b.value:$.type==="note"&&b.type==="noteon"&&b.note===$.number?M=b.velocity:$.type==="pitchbend"&&b.type==="pitchbend"?(M=b.value+8192,E=16383):$.type==="aftertouch"&&b.type==="aftertouch"&&(M=b.pressure),M!==null){const R=M/E,L=$.min+R*($.max-$.min);s(A=>A.map(z=>z.id===$.id?{...z,value:R}:z)),(N=h.current)==null||N.call(h,$.id,L,R)}}},[]),{supported:y,granted:m}=Vr({onEvent:g}),x=u.useCallback(b=>{o({learning:!0,targetId:b})},[]),v=u.useCallback(()=>{o({learning:!1,targetId:null})},[]),f=u.useCallback(b=>{s(w=>{const N=w.map($=>$.id===b?{...$,type:"cc",number:void 0,channel:void 0}:$);return Mi(N),N})},[]),k=u.useCallback(()=>{s(b=>{const w=b.map(N=>({...N,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(rs),w})},[]);return{bindings:a,startLearn:x,cancelLearn:v,removeBinding:f,clearAll:k,learnState:i,midiSupported:y,midiGranted:m,lastEvent:l}}const g0={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function y0(e={}){const{lowerZone:t=g0,onNoteExpression:n,onNoteOn:a,onNoteOff:s}=e,[i,o]=u.useState([]),l=u.useRef(new Map),c=u.useRef(n);c.current=n;const d=u.useRef(a);d.current=a;const h=u.useRef(s);h.current=s;const p=u.useRef(new Set(t.memberChannels));u.useEffect(()=>{p.current=new Set(t.memberChannels)},[t.memberChannels]);const g=u.useCallback(x=>{var f,k,b,w,N;if(!p.current.has(x.channel??-1))return;const v=`${x.channel}`;switch(x.type){case"noteon":{const $={note:x.note,channel:x.channel,velocity:x.velocity,pitchBend:0,pressure:0,slide:0,lastUpdate:x.ts};l.current.set(v,$),o(Array.from(l.current.values())),(f=d.current)==null||f.call(d,$);break}case"noteoff":{l.current.delete(v),o(Array.from(l.current.values())),(k=h.current)==null||k.call(h,x.channel,x.note);break}case"pitchbend":{const $=l.current.get(v);$&&($.pitchBend=x.value,$.lastUpdate=x.ts,(b=c.current)==null||b.call(c,$),o(Array.from(l.current.values())));break}case"aftertouch":{const $=l.current.get(v);$&&($.pressure=x.pressure,$.lastUpdate=x.ts,(w=c.current)==null||w.call(c,$),o(Array.from(l.current.values())));break}case"cc":{if(x.controller===74){const $=l.current.get(v);$&&($.slide=x.value,$.lastUpdate=x.ts,(N=c.current)==null||N.call(c,$),o(Array.from(l.current.values())))}break}}},[]),{supported:y,granted:m}=Vr({onEvent:g,sysex:!1});return{activeNotes:i,midiSupported:y,midiGranted:m}}const v0={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 b0(e={},t=v0){const[n,a]=u.useState(()=>{const y=localStorage.getItem("oxygen25.layout");return y?JSON.parse(y):t}),[s,i]=u.useState([]),o=u.useRef({mode:"idle"}),l=u.useCallback(y=>{a(m=>{const x={...m,...y};return localStorage.setItem("oxygen25.layout",JSON.stringify(x)),x})},[]),c=u.useCallback(y=>{var v,f,k,b,w,N,$,M,E;const m=y.deviceName||"MIDI";i(R=>R.includes(m)?R:[...R,m]);const x=o.current;if(x.mode!=="idle"){if(x.mode==="knob"&&y.type==="cc"){const R=x.index;l({knobs:n.knobs.map(L=>L.index===R?{...L,cc:y.controller}:L)}),o.current={mode:"idle"};return}if(x.mode==="fader"&&y.type==="cc"){l({fader:{cc:y.controller,label:"Fader"}}),o.current={mode:"idle"};return}if(x.mode==="pad"&&y.type==="noteon"){const R=n.pads.slice();R[x.padIdx]={...R[x.padIdx],note:y.note},l({pads:R}),o.current={mode:"idle"};return}if(x.mode==="transport"&&y.type==="cc"){const R={...n.transport};R[x.action]=y.controller,l({transport:R}),o.current={mode:"idle"};return}}switch(y.type){case"noteon":{n.pads.findIndex(L=>L.note===y.note)>=0?(v=e.onPad)==null||v.call(e,{note:y.note,velocity:y.velocity,ts:y.ts,device:m}):(f=e.onKey)==null||f.call(e,{note:y.note,velocity:y.velocity,ts:y.ts,device:m});break}case"cc":{if(n.fader&&y.controller===n.fader.cc){(k=e.onFader)==null||k.call(e,{cc:y.controller,value:y.value,ts:y.ts,device:m});break}const R=n.knobs.find(A=>A.cc===y.controller);if(R){(b=e.onKnob)==null||b.call(e,{index:R.index,cc:y.controller,value:y.value,ts:y.ts,device:m});break}const L=Object.keys(n.transport).find(A=>n.transport[A]===y.controller);if(L){(w=e.onTransport)==null||w.call(e,{action:L,value:y.value,ts:y.ts,device:m});break}(N=e.onUnknown)==null||N.call(e,y);break}case"pitchbend":($=e.onPitchBend)==null||$.call(e,{value:y.value,ts:y.ts,device:m});break;case"aftertouch":(M=e.onAftertouch)==null||M.call(e,{pressure:y.pressure,ts:y.ts,device:m});break;default:(E=e.onUnknown)==null||E.call(e,y)}},[l,e,n]),{supported:d,granted:h,inputs:p}=Vr({inputNameIncludes:void 0,onEvent:c,sysex:!1,channelFilter:void 0,onInputsChanged:y=>i(y.map(m=>m.name||"MIDI"))}),g=u.useMemo(()=>({knob:y=>o.current={mode:"knob",index:y},fader:()=>o.current={mode:"fader"},pad:y=>o.current={mode:"pad",padIdx:y},transport:y=>o.current={mode:"transport",action:y},cancel:()=>o.current={mode:"idle"},state:()=>o.current}),[]);return{supported:d,granted:h,inputs:p,layout:n,setLayout:l,learn:g,inputsInfo:s}}const ja={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]},x0=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Ma={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]]},nn=36,jn=38,Nt=42,rn=51,S0=49,Ra={basic:[{step:0,pitch:nn,vel:110},{step:0,pitch:Nt,vel:80},{step:2,pitch:Nt,vel:70},{step:4,pitch:jn,vel:100},{step:4,pitch:Nt,vel:80},{step:6,pitch:Nt,vel:70},{step:8,pitch:nn,vel:100},{step:10,pitch:Nt,vel:70},{step:12,pitch:jn,vel:100},{step:12,pitch:Nt,vel:80},{step:14,pitch:Nt,vel:70}],rock:[{step:0,pitch:nn,vel:120},{step:0,pitch:S0,vel:90},{step:4,pitch:jn,vel:110},{step:4,pitch:Nt,vel:80},{step:8,pitch:nn,vel:110},{step:8,pitch:Nt,vel:80},{step:10,pitch:nn,vel:90},{step:12,pitch:jn,vel:110},{step:12,pitch:Nt,vel:80}],swing:[{step:0,pitch:rn,vel:90},{step:3,pitch:rn,vel:70},{step:4,pitch:rn,vel:80},{step:8,pitch:rn,vel:90},{step:11,pitch:rn,vel:70},{step:12,pitch:rn,vel:80},{step:4,pitch:nn,vel:80},{step:12,pitch:jn,vel:70}]},Ol={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function k0(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 Bl=1;const lr=()=>Bl++,Gl=e=>60/e,w0=e=>Gl(e)/4;function ia(e,t,n,a){const s=t.length,i=Math.floor(n/s),o=(n%s+s)%s;return e+t[o]+(a+i)*12}function Wl(e=Ol){Bl=1;const t=e.seed>0?k0(e.seed):Math.random,n=ja[e.scale]??ja.pentatonic,a=Ma[e.progression]??Ma.pop,s=Ra[e.drumPattern]??Ra.basic,i=Gl(e.tempo),o=w0(e.tempo),l=Math.max(1,e.bars),c=16,d=[],h=[],p=[],g=[];let y=0;for(let m=0;m<l;m++){const x=m*4*i,v=m%a.length,f=a[v];for(const b of f)p.push({id:lr(),pitch:ia(e.root,n,b,e.octave-1),start:x,duration:4*i-.01,velocity:70+Math.floor(t()*20)});const k=f[0];for(let b=0;b<4;b++){const w=b===2?k+(t()>.5?2:0):k;h.push({id:lr(),pitch:ia(e.root,n,w,e.octave-2),start:x+b*i,duration:i*.9,velocity:80+Math.floor(t()*30)})}for(let b=0;b<c;b++){if(t()>e.density)continue;const w=x+b*o,N=t()>.8?t()>.5?2:-2:t()>.5?1:-1;y=Math.max(-3,Math.min(n.length+3,y+N));const $=1+Math.floor(t()*3);d.push({id:lr(),pitch:ia(e.root,n,y,e.octave),start:w,duration:$*o*.95,velocity:85+Math.floor(t()*30)})}for(const b of s)g.push({id:lr(),pitch:b.pitch,start:x+b.step*o,duration:o*.8,velocity:b.vel+Math.floor(t()*10-5)})}return{melody:d,bass:h,chords:p,drums:g,config:e}}const C0=Object.keys(ja),j0=Object.keys(Ma),M0=Object.keys(Ra),R0=Wl;function Ke(e,t,n){return{cc:e,paramId:n,label:`Knob ${t}`,controlType:"knob",min:0,max:127,inverted:!1}}function Un(e,t,n){return{cc:e,paramId:n,label:t,controlType:"fader",min:0,max:127,inverted:!1}}function an(e,t,n){return{cc:e,paramId:n,label:t,controlType:"button",min:0,max:127,inverted:!1}}const Vl={id:"oxygen25",name:"M-Audio Oxygen 25 (MkIV)",deviceMatch:"OXYGEN",mappings:[Ke(21,1,"mixer.volume"),Ke(22,2,"mixer.pan"),Ke(23,3,"fx.reverb"),Ke(24,4,"fx.delay"),Ke(25,5,"fx.chorus"),Ke(26,6,"fx.filter"),Ke(27,7,"fx.drive"),Ke(28,8,"fx.eq"),Un(7,"Master Fader","mixer.master"),an(115,"Play","transport.play"),an(114,"Stop","transport.stop"),an(117,"Record","transport.record"),an(112,"Rewind","transport.rewind"),an(113,"Forward","transport.forward"),an(116,"Loop","transport.loop")]},Ul={id:"mpk-mini",name:"Akai MPK Mini",deviceMatch:"MPK",mappings:[Ke(1,1,"mixer.volume"),Ke(2,2,"mixer.pan"),Ke(3,3,"fx.reverb"),Ke(4,4,"fx.delay"),Ke(5,5,"fx.chorus"),Ke(6,6,"fx.filter"),Ke(7,7,"fx.drive"),Ke(8,8,"fx.eq")]},ql={id:"minilab",name:"Arturia MiniLab",deviceMatch:"Arturia MiniLab",mappings:[Ke(7,1,"mixer.volume"),Ke(74,2,"mixer.pan"),Ke(71,3,"fx.reverb"),Ke(76,4,"fx.delay"),Ke(77,5,"fx.chorus"),Ke(93,6,"fx.filter"),Ke(73,7,"fx.drive"),Ke(75,8,"fx.eq"),Un(1,"Mod Wheel","mixer.master")]},Hl=(function(){return{id:"launch-control-xl",name:"Novation Launch Control XL",deviceMatch:"Launch Control",mappings:[...Array.from({length:8},(e,t)=>Ke(13+t,t+1,`mixer.send${t+1}`)),...Array.from({length:8},(e,t)=>Un(77+t,`Fader ${t+1}`,`mixer.track${t+1}`))]}})(),as={id:"generic",name:"Generic MIDI Controller",deviceMatch:"",mappings:[Ke(1,1,"mixer.modWheel"),Un(7,"Volume","mixer.volume"),Ke(10,2,"mixer.pan"),Un(11,"Expression","mixer.expression")]},Kl=[Vl,Ul,ql,Hl,as];class N0{constructor(t){this.ccMap=new Map,this.onChange=null,this.profile=t??as,this.rebuildMap()}setProfile(t){this.profile=t,this.rebuildMap()}getProfile(){return this.profile}autoDetect(t){const n=t.toUpperCase(),a=Kl.find(s=>s.deviceMatch&&n.includes(s.deviceMatch.toUpperCase()));return a?(this.setProfile(a),a):null}onMappedChange(t){this.onChange=t}handleCC(t,n){var c;const a=this.ccMap.get(t);if(!a)return null;const i=(a.inverted?127-n:n)/127,o=a.min+i*(a.max-a.min),l={paramId:a.paramId,label:a.label,rawValue:n,scaledValue:o,normalizedValue:i};return(c=this.onChange)==null||c.call(this,l),l}setMapping(t,n,a,s="knob"){const i={cc:t,paramId:n,label:a,controlType:s,min:0,max:127,inverted:!1},o=this.profile.mappings.findIndex(l=>l.cc===t);o>=0?this.profile.mappings[o]=i:this.profile.mappings.push(i),this.ccMap.set(t,i)}removeMapping(t){this.profile.mappings=this.profile.mappings.filter(n=>n.cc!==t),this.ccMap.delete(t)}getMappings(){return[...this.profile.mappings]}getMapping(t){return this.ccMap.get(t)}exportConfig(){return{...this.profile,mappings:this.profile.mappings.map(t=>({...t}))}}importConfig(t){this.profile={...t,mappings:t.mappings.map(n=>({...n}))},this.rebuildMap()}static createCustomProfile(t,n){return{id:`custom-${t.toLowerCase().replace(/\s+/g,"-")}`,name:t,deviceMatch:"",mappings:n.map(a=>({...a,min:0,max:127,inverted:!1}))}}rebuildMap(){this.ccMap.clear();for(const t of this.profile.mappings)this.ccMap.set(t.cc,t)}}function ss(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function Zt(e="New Pattern",t=16,n=120){return{name:e,length:t,steps:Array.from({length:t},()=>ss()),bpm:n,swing:0,rootNote:60}}function Yl(e,t){const n=e.steps.map((a,s)=>s===t?{...a,active:!a.active}:a);return{...e,steps:n}}function Zl(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,note:Math.max(0,Math.min(127,n))}:s);return{...e,steps:a}}function Xl(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,velocity:Math.max(0,Math.min(127,n))}:s);return{...e,steps:a}}function Ql(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,gate:Math.max(0,Math.min(1,n))}:s);return{...e,steps:a}}function Jl(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,probability:Math.max(0,Math.min(1,n))}:s);return{...e,steps:a}}function ec(e,t){const n=e.steps.map((a,s)=>s===t?{...a,slide:!a.slide}:a);return{...e,steps:n}}function tc(e,t){const n=e.steps.map(a=>a.active?{...a,note:Math.max(0,Math.min(127,a.note+t))}:a);return{...e,steps:n,rootNote:Math.max(0,Math.min(127,e.rootNote+t))}}function nc(e){return{...e,steps:[...e.steps].reverse()}}function rc(e,t){const n=e.steps.length,a=(t%n+n)%n,s=[...e.steps.slice(a),...e.steps.slice(0,a)];return{...e,steps:s}}function ac(e,t=60,n=127){const a=e.steps.map(s=>s.active?{...s,velocity:Math.floor(t+Math.random()*(n-t+1))}:s);return{...e,steps:a}}function sc(e){return{...e,steps:e.steps.map(()=>ss(e.rootNote))}}function is(e,t=4){return 60/e/t}function ic(e,t,n=0,a=4){const s=is(t,a),i=e*s;return e%2===1&&n>0?i+s*n*.5:i}function oc(e){return e.active&&Math.random()<e.probability}function T0(){const e=Zt("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function P0(){const e=Zt("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function $0(){const e=Zt("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 E0(e=60){const t=Zt("Arp",16,120);return[0,4,7,12,7,4,0,-5,0,3,7,12,7,3,0,-5].forEach((a,s)=>{t.steps[s]={...t.steps[s],active:!0,note:e+a,velocity:90,gate:.5}}),{...t,rootNote:e}}function A0(e=36){const t=Zt("Bassline",16,120),n=[0,0,7,0,5,5,3,0,0,0,7,12,5,5,3,0],a=[1,0,1,0,1,0,1,1,1,0,1,1,1,0,1,0];return n.forEach((s,i)=>{t.steps[i]={...t.steps[i],active:!!a[i],note:e+s,velocity:100,gate:.7}}),{...t,rootNote:e}}function I0(e){return JSON.stringify(e,null,2)}function L0(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function _0(e={}){const{onTrigger:t,onLFOOutput:n,initialPattern:a}=e,[s,i]=u.useState(()=>a??Zt()),[o,l]=u.useState(-1),[c,d]=u.useState(!1),[h,p]=u.useState([]),g=u.useRef(s);g.current=s;const y=u.useRef(h);y.current=h;const m=u.useRef(c);m.current=c;const x=u.useRef(t);x.current=t;const v=u.useRef(n);v.current=n;const f=u.useRef(null),k=u.useRef(0),b=u.useRef(0),w=u.useCallback(()=>{var U,J;if(!m.current)return;const S=g.current,F=k.current%S.length,K=S.steps[F];if(oc(K)){const se=ic(k.current,S.bpm,S.swing);(U=x.current)==null||U.call(x,K,F,se)}const P=(Date.now()-b.current)/1e3;for(let se=0;se<y.current.length;se++){const oe=y.current[se];if(oe.enabled&&oe.targetCC!==void 0){const re=Ia(oe,P,S.bpm);(J=v.current)==null||J.call(v,se,oe.targetCC,re)}}l(F),k.current++;const B=is(S.bpm)*1e3,_=F%2===0?0:B*S.swing*.5;f.current=setTimeout(w,B+_)},[]),N=u.useCallback(()=>{m.current||(k.current=0,b.current=Date.now(),d(!0),m.current=!0,w())},[w]),$=u.useCallback(()=>{d(!1),m.current=!1,l(-1),f.current&&(clearTimeout(f.current),f.current=null)},[]),M=u.useCallback(()=>{m.current?$():N()},[N,$]);u.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const E=u.useCallback(S=>i(F=>Yl(F,S)),[]),R=u.useCallback((S,F)=>i(K=>Zl(K,S,F)),[]),L=u.useCallback((S,F)=>i(K=>Xl(K,S,F)),[]),A=u.useCallback((S,F)=>i(K=>Ql(K,S,F)),[]),z=u.useCallback((S,F)=>i(K=>Jl(K,S,F)),[]),j=u.useCallback(S=>i(F=>ec(F,S)),[]),I=u.useCallback(S=>i(F=>tc(F,S)),[]),Y=u.useCallback(()=>i(S=>nc(S)),[]),H=u.useCallback(S=>i(F=>rc(F,S)),[]),D=u.useCallback((S,F)=>i(K=>ac(K,S,F)),[]),V=u.useCallback(()=>i(S=>sc(S)),[]),Z=u.useCallback(S=>i(F=>({...F,bpm:Math.max(20,Math.min(300,S))})),[]),X=u.useCallback(S=>i(F=>({...F,swing:Math.max(0,Math.min(1,S))})),[]),q=u.useCallback(S=>{i(F=>{if(F.length===S)return F;const K=Array.from({length:S},(P,B)=>B<F.steps.length?F.steps[B]:{active:!1,note:F.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...F,length:S,steps:K}})},[]),G=u.useCallback(S=>{p(F=>[...F,S??_r()])},[]),C=u.useCallback(S=>{p(F=>F.filter((K,P)=>P!==S))},[]),T=u.useCallback((S,F)=>{p(K=>K.map((P,B)=>B===S?{...P,...F}:P))},[]);return{pattern:s,currentStep:o,playing:c,lfos:h,play:N,stop:$,togglePlayback:M,toggle:E,setNote:R,setVelocity:L,setGate:A,setProbability:z,toggleSlide:j,transpose:I,reverse:Y,shift:H,randomizeVel:D,clear:V,setPattern:i,setBpm:Z,setSwing:X,setLength:q,addLFO:G,removeLFO:C,updateLFO:T}}function os(e){const t=u.useRef(null),n=u.useRef(new Map),a=u.useRef(1),s=u.useCallback(()=>{if(!t.current){const o=e();o.onmessage=l=>{const{id:c}=l.data,d=n.current.get(c);d&&(n.current.delete(c),d.resolve(l.data))},o.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(),o.terminate(),t.current=null},t.current=o}return t.current},[e]);return u.useEffect(()=>{const o=n.current;return()=>{var l;(l=t.current)==null||l.terminate(),t.current=null;for(const[,c]of o)c.reject(new Error("Worker terminated on unmount"));o.clear()}},[]),u.useCallback((o,l)=>{const c=a.current++,d=s();return new Promise((h,p)=>{n.current.set(c,{resolve:h,reject:p}),d.postMessage({...o,id:c},l??[])})},[s])}function z0(){const e=os(u.useCallback(()=>new Worker(new URL("/assets/pitchWorker-BgAp5Z97.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:bt&&bt.tagName.toUpperCase()==="SCRIPT"&&bt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return u.useCallback(async(n,a,s=.01)=>(await e({buffer:n,sampleRate:a,rmsThreshold:s})).hz,[e])}function D0(){const e=os(u.useCallback(()=>new Worker(new URL("/assets/scoringWorker-3JjtDDtu.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:bt&&bt.tagName.toUpperCase()==="SCRIPT"&&bt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return u.useCallback(async(n,a,s)=>(await e({notes:n,points:a,params:s})).result,[e])}const F0={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function lc(){return`
|
|
72
72
|
/**
|
|
73
73
|
* NiceAudioProcessor — Main audio analysis processor.
|
|
74
74
|
*/
|
|
@@ -404,7 +404,7 @@ registerProcessor('nice-audio-processor', NiceAudioProcessor);
|
|
|
404
404
|
registerProcessor('nice-gain-processor', NiceGainProcessor);
|
|
405
405
|
registerProcessor('nice-compressor-processor', NiceCompressorProcessor);
|
|
406
406
|
registerProcessor('nice-vocoder-processor', NiceVocoderProcessor);
|
|
407
|
-
`}let
|
|
407
|
+
`}let Ri=!1,cr=null;async function cc(e){if(!Ri)return cr||(cr=(async()=>{const t=lc(),n=new Blob([t],{type:"application/javascript"}),a=URL.createObjectURL(n);try{await e.audioWorklet.addModule(a),Ri=!0}finally{URL.revokeObjectURL(a)}})(),cr)}function dc(e,t,n){const a=new AudioWorkletNode(e,"nice-audio-processor",{processorOptions:{...F0,...t}});return n&&(a.port.onmessage=s=>{s.data.type==="analysis"&&n(s.data.payload)}),a}function uc(e,t=1){const n=new AudioWorkletNode(e,"nice-gain-processor");return n.parameters.get("gain").value=t,n}function hc(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 pc(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 O0(e={}){const{enableAnalysis:t=!0,analysisOptions:n,enableGain:a=!1,initialGain:s=1,enableCompressor:i=!1,compressorOptions:o,enableVocoder:l=!1,vocoderOptions:c,onAnalysis:d}=e,[h,p]=u.useState(!1),[g,y]=u.useState(null),[m,x]=u.useState(null),v=u.useRef(null),f=u.useRef(null),k=u.useRef(null),b=u.useRef(null),w=u.useRef(null),N=u.useRef(null),$=u.useRef(null),M=u.useRef(null);u.useEffect(()=>{let I=!0;return(async()=>{try{const H=new AudioContext;if(v.current=H,await cc(H),!I){H.close();return}const D=[];if(t){const V=dc(H,n,Z=>{I&&(x(Z),d==null||d(Z))});f.current=V,D.push(V)}if(a){const V=uc(H,s);k.current=V,D.push(V)}if(i){const V=hc(H,o);b.current=V,D.push(V)}if(l){const V=pc(H,c);w.current=V,D.push(V)}if(D.length>0){$.current=D[0],M.current=D[D.length-1];for(let V=0;V<D.length-1;V++)D[V].connect(D[V+1])}p(!0)}catch(H){I&&y(H)}})(),()=>{var H,D,V,Z,X;I=!1,(H=f.current)==null||H.disconnect(),(D=k.current)==null||D.disconnect(),(V=b.current)==null||V.disconnect(),(Z=w.current)==null||Z.disconnect(),(X=v.current)==null||X.close()}},[t,a,i,l]);const E=u.useCallback(I=>{N.current&&N.current.disconnect(),N.current=I,$.current&&I.connect($.current)},[]),R=u.useCallback(()=>{N.current&&(N.current.disconnect(),N.current=null)},[]),L=u.useCallback(()=>M.current,[]),A=u.useCallback(I=>{var H;const Y=(H=k.current)==null?void 0:H.parameters.get("gain");Y&&(Y.value=Math.max(0,Math.min(2,I)))},[]),z=u.useCallback((I,Y)=>{var D;const H=(D=b.current)==null?void 0:D.parameters.get(I);H&&(H.value=Y)},[]),j=u.useCallback((I,Y)=>{var D;const H=(D=w.current)==null?void 0:D.parameters.get(I);H&&(H.value=Y)},[]);return{isReady:h,error:g,analysis:m,connectSource:E,disconnectSource:R,getOutputNode:L,setGain:A,setCompressorParam:z,setVocoderParam:j,audioContext:v.current}}function B0(e,t,n){const i={id:`${t}-${n}-${Date.now()}`,type:n,bypass:!1,params:{eq3:{lowGain:0,midGain:0,highGain:0,lowFreq:250,highFreq:4e3},compressor:{threshold:-24,ratio:4,attack:.003,release:.25,knee:30},delay:{time:.25,feedback:.3,mix:.3},reverb:{decay:2,mix:.3},distortion:{amount:20,mix:.5}}[n]};e(o=>{var l;return{...o,[t]:{...o[t],effectChain:[...((l=o[t])==null?void 0:l.effectChain)||[],i]}}})}function G0(e,t,n){e(a=>{var s,i;return{...a,[t]:{...a[t],effectChain:((i=(s=a[t])==null?void 0:s.effectChain)==null?void 0:i.filter(o=>o.id!==n))||[]}}})}function W0(e,t,n){e(a=>{var s,i;return{...a,[t]:{...a[t],effectChain:((i=(s=a[t])==null?void 0:s.effectChain)==null?void 0:i.map(o=>o.id===n?{...o,bypass:!o.bypass}:o))||[]}}})}function V0(e,t,n,a){e(s=>{var i,o;return{...s,[t]:{...s[t],effectChain:((o=(i=s[t])==null?void 0:i.effectChain)==null?void 0:o.map(l=>l.id===n?{...l,params:{...l.params,...a}}:l))||[]}}})}function U0(e,t,n,a,s,i,o=.5,l=100){const c={id:Date.now()+Math.floor(Math.random()*1e3),pitch:s,start:i,duration:o,velocity:l};t(d=>({...d,[a]:[...d[a]||[],c]})),n({layerId:a,noteId:c.id})}function q0(e,t,n,a){e(s=>({...s,[n]:(s[n]||[]).filter(i=>i.id!==a)})),t(null)}function H0(e,t,n){e(a=>({...a,[n]:[]})),t(null)}function K0(e,t,n){e(a=>({...a,[t]:n}))}function Y0(e,t,n,a,s){const i={id:Date.now()+Math.floor(Math.random()*1e3),cc:n,value:a,time:s};e(o=>({...o,[t]:[...o[t]||[],i]}))}function Z0(e,t,n,a,s,i){e(o=>({...o,[t]:(o[t]||[]).map(l=>l.id===n?{...l,value:a,time:s,handleType:i??l.handleType}:l)}))}function X0(e,t,n){e(a=>({...a,[t]:(a[t]||[]).filter(s=>s.id!==n)}))}function dr(e){if(!e||e<=0)return null;const t=12*Math.log2(e/440)+69;return Math.round(t-12)}function Q0(e){if(e.length===0)return[];const t=[];let n=e[0];for(let a=1;a<e.length;a++){const s=e[a];s.pitch===n.pitch&&Math.abs(s.freq-n.freq)<1?n.duration+=s.duration:(t.push(n),n=s)}return t.push(n),t}function J0(e,t,n=.01){const a=Math.floor(t/50);let s=-1,i=0,o=0;for(let c=0;c<e.length;c++)o+=e[c]*e[c];if(o=Math.sqrt(o/e.length),o<n)return 0;let l=1;for(let c=50;c<a;c++){let d=0;for(let h=0;h<a;h++)d+=Math.abs(e[h]-e[h+c]);d=1-d/a,d>i&&d>.9&&d>l&&(i=d,s=c),l=d}return s===-1?0:t/s}async function eg(e,t,n){const{signal:a,onProgress:s,rmsThreshold:i,useHanning:o,postPitch:l,postLibrosaPitchTrack:c}=n||{},d=await e.arrayBuffer();if(a!=null&&a.aborted)throw new Error("aborted");const p=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(d),g=p.getChannelData(0),y=p.sampleRate,m=Math.floor(y*.1),x=m,v=[];if(t==="pitchy"){const f=la.PitchDetector.forFloat32Array(m),k=Math.max(1,Math.floor((g.length-m)/x));let b=0;for(let w=0;w<g.length-m;w+=x){if(a!=null&&a.aborted)throw new Error("aborted");const N=g.slice(w,w+m);if(o)for(let A=0;A<N.length;A++)N[A]*=.5*(1-Math.cos(2*Math.PI*A/(N.length-1)));const[$,M]=f.findPitch(N,y),E=dr($);let R=0;for(let A=0;A<N.length;A++)R+=N[A]*N[A];R=Math.sqrt(R/N.length);const L=typeof i=="number"?i:.01;E&&$>50&&$<2e3&&M>.7&&R>L&&v.push({start:w/y,duration:m/y,pitch:E,freq:$}),b++,s&&s(b/k)}}else if(t==="crepe"){if(s&&s(.05),!l)throw new Error("CREPE backend callback (postPitch) is required for crepe algorithm");const f=await l(e);if(a!=null&&a.aborted)throw new Error("aborted");const k=Array.isArray(f.track)?f.track:[];k.length>0&&k.forEach((b,w)=>{var $;const N=dr(b.hz);if(N&&b.hz>50&&b.hz<2e3){const M=(($=k[w+1])==null?void 0:$.t)??b.t+.1;v.push({start:b.t,duration:w<k.length-1?M-b.t:.1,pitch:N,freq:b.hz})}}),s&&s(1)}else if(t==="ultrastar-wp"){const f=Math.max(1,Math.floor((g.length-m)/x));let k=0;for(let b=0;b<g.length-m;b+=x){if(a!=null&&a.aborted)throw new Error("aborted");const w=g.slice(b,b+m);if(o)for(let E=0;E<w.length;E++)w[E]*=.5*(1-Math.cos(2*Math.PI*E/(w.length-1)));const $=J0(w,y,typeof i=="number"?i:.01),M=dr($);M&&$>50&&$<2e3&&v.push({start:b/y,duration:m/y,pitch:M,freq:$}),k++,s&&s(k/f)}}if(t==="librosa"){if(s&&s(.05),!c)throw new Error("Librosa backend callback (postLibrosaPitchTrack) is required for librosa algorithm");const f=await c(e);if(a!=null&&a.aborted)throw new Error("aborted");const k=Array.isArray(f.track)?f.track:[];k.length>0&&k.forEach((b,w)=>{var $;const N=dr(b.hz);if(N&&b.hz>50&&b.hz<2e3){const M=(($=k[w+1])==null?void 0:$.t)??b.t+.1;v.push({start:b.t,duration:w<k.length-1?M-b.t:.1,pitch:N,freq:b.hz})}}),s&&s(1)}return Q0(v)}function tg(e){switch(e){case"pitchy":return`#TITLE:Analyzed Song
|
|
408
408
|
#ARTIST:AI
|
|
409
409
|
#ALGO:Pitchy
|
|
410
410
|
: 0 4 40 Pitchy
|
|
@@ -427,4 +427,4 @@ E`;case"ultrastarws":return`#TITLE:Analyzed Song
|
|
|
427
427
|
E`;default:return`#TITLE:Analyzed Song
|
|
428
428
|
#ARTIST:AI
|
|
429
429
|
: 0 2 40 Test
|
|
430
|
-
E`}}function C0(e,t){return`${e}:${t}`}function j0(e,t,r,a=1){if(t==="off")return e;const s=60/r;if(t==="beat")return Math.round(e/(s/a))*(s/a);if(t==="bar"){const i=s*4;return Math.round(e/i)*i}return e}function M0(e){return e.length===0?[]:e.flat()}function R0(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const gs=[{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 N0(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function Pc(e,t){return t.amount===0?e:e.map(r=>{const a=r.time/t.grid;if(Math.round(a)%2===1){const o=t.grid*t.amount*.5;return{...r,time:r.time+o}}return{...r}})}function Ec(e,t){const r=t.seed!=null?N0(t.seed):Math.random;return e.map(a=>{const s=(r()-.5)*2*t.timingAmount,i=Math.round((r()-.5)*2*t.velocityAmount),o=(r()-.5)*2*t.durationAmount;return{...a,time:Math.max(0,a.time+s),velocity:Math.max(1,Math.min(127,a.velocity+i)),duration:Math.max(.01,a.duration+o)}})}function Ac(e,t,r=1){const a=4/t.stepsPerBar;return e.map(s=>{const i=s.time/a,o=Math.round(i)%t.stepsPerBar,l=t.timingOffsets[o]*a*r,c=1+(t.velocityScales[o]-1)*r,d=1+(t.durationScales[o]-1)*r;return{...s,time:Math.max(0,s.time+l),velocity:Math.max(1,Math.min(127,Math.round(s.velocity*c))),duration:Math.max(.01,s.duration*d)}})}function T0(e,t){let r=[...e.map(a=>({...a}))];return t.template&&t.grooveStrength>0&&(r=Ac(r,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(r=Pc(r,t.swing)),t.humanize&&(r=Ec(r,t.humanize)),r}function $0(e){return gs.find(t=>t.id===e)}function P0(){return gs.map(({id:e,name:t})=>({id:e,name:t}))}function Ic(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 ys(e,t){return Ic(e)*60/t}function Ra(e,t,r){const a=ys(t,r);return Math.round(e/a)*a}function E0(e,t){const{value:r,bpm:a,strength:s=1,quantizeStarts:i=!0,quantizeDurations:o=!1}=t,l=ys(r,a);return e.map(c=>{let{start:d,duration:h}=c;if(i){const f=Math.round(d/l)*l;d=d+(f-d)*s}if(o){const f=Math.max(l,Math.round(h/l)*l);h=h+(f-h)*s}return d===c.start&&h===c.duration?c:{...c,start:d,duration:h}})}function A0(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function I0(e,t={}){const{timingRange:r=.02,velocityRange:a=10,seed:s}=t,i=s!=null?A0(s):Math.random;return e.map(o=>{const l=(i()*2-1)*r,c=Math.round((i()*2-1)*a);return{...o,start:Math.max(0,o.start+l),velocity:o.velocity!=null?Math.max(1,Math.min(127,(o.velocity??100)+c)):void 0}})}function L0(){return{start:0,end:0,enabled:!1}}function D0(e,t){return{...e<t?{start:e,end:t}:{start:t,end:e},enabled:!0}}function z0(e,t,r){return{start:Ra(e.start,t,r),end:Ra(e.end,t,r),enabled:e.enabled}}function _0(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function F0(e,t){if(!t.enabled||t.end<=t.start||e<t.start)return e;if(e>=t.end){const r=t.end-t.start;return t.start+(e-t.start)%r}return e}function Na(e){return e.length===1?e.toLowerCase():e}function Cr(e){var r,a,s,i;const t=[];return(r=e.modifiers)!=null&&r.ctrl&&t.push("Ctrl"),(a=e.modifiers)!=null&&a.shift&&t.push("Shift"),(s=e.modifiers)!=null&&s.alt&&t.push("Alt"),(i=e.modifiers)!=null&&i.meta&&t.push("Meta"),t.push(Na(e.key)),t.join("+")}function O0(e,t){var l,c,d,h;const r=Na(e.key)===Na(t.key),a=!!e.ctrlKey==!!((l=t.modifiers)!=null&&l.ctrl),s=!!e.shiftKey==!!((c=t.modifiers)!=null&&c.shift),i=!!e.altKey==!!((d=t.modifiers)!=null&&d.alt),o=!!e.metaKey==!!((h=t.modifiers)!=null&&h.meta);return r&&a&&s&&i&&o}class Lc{constructor(){this.actions=new Map,this.activeScopes=new Set(["global"]),this.enabled=!0,this.listener=null}register(t){this.actions.set(t.id,{...t,enabled:t.enabled??!0})}unregister(t){this.actions.delete(t)}rebind(t,r){const a=this.actions.get(t);a&&(a.binding=r)}setActiveScopes(t){this.activeScopes.clear(),this.activeScopes.add("global");for(const r of t)this.activeScopes.add(r)}setEnabled(t){this.enabled=t}setActionEnabled(t,r){const a=this.actions.get(t);a&&(a.enabled=r)}findConflicts(){const t=[],r=[...this.actions.values()];for(let a=0;a<r.length;a++)for(let s=a+1;s<r.length;s++){const i=r[a],o=r[s];Cr(i.binding)===Cr(o.binding)&&(i.scope===o.scope||i.scope==="global"||o.scope==="global")&&t.push([i,o])}return t}getGrouped(){const t={};for(const r of this.actions.values())t[r.group]||(t[r.group]=[]),t[r.group].push(r);return t}getAll(){return[...this.actions.values()]}exportConfig(){return[...this.actions.values()].map(t=>({id:t.id,binding:t.binding}))}importConfig(t){for(const r of t)this.rebind(r.id,r.binding)}formatBinding(t){const r=this.actions.get(t);return r?Cr(r.binding):""}handleKeyDown(t){if(!this.enabled)return!1;for(const r of this.actions.values())if(r.enabled&&this.activeScopes.has(r.scope)&&O0(t,r.binding))return t.preventDefault(),t.stopPropagation(),r.callback(),!0;return!1}attach(){this.listener||(this.listener=t=>{const r=t.target;r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.isContentEditable||this.handleKeyDown(t)},window.addEventListener("keydown",this.listener,!0))}detach(){this.listener&&(window.removeEventListener("keydown",this.listener,!0),this.listener=null)}destroy(){this.detach(),this.actions.clear()}}function B0(e={}){const t=new Lc,r=()=>{},a=[{id:"transport.play",label:"Play / Pause",group:"Transport",scope:"global",binding:{key:" "}},{id:"transport.stop",label:"Stop",group:"Transport",scope:"global",binding:{key:"Escape"}},{id:"transport.record",label:"Record",group:"Transport",scope:"global",binding:{key:"r",modifiers:{ctrl:!0}}},{id:"transport.rewind",label:"Rewind",group:"Transport",scope:"global",binding:{key:"Home"}},{id:"transport.forward",label:"Forward",group:"Transport",scope:"global",binding:{key:"End"}},{id:"transport.loopToggle",label:"Toggle Loop",group:"Transport",scope:"global",binding:{key:"l"}},{id:"edit.undo",label:"Undo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0}}},{id:"edit.redo",label:"Redo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0,shift:!0}}},{id:"edit.cut",label:"Cut",group:"Edit",scope:"editor",binding:{key:"x",modifiers:{ctrl:!0}}},{id:"edit.copy",label:"Copy",group:"Edit",scope:"editor",binding:{key:"c",modifiers:{ctrl:!0}}},{id:"edit.paste",label:"Paste",group:"Edit",scope:"editor",binding:{key:"v",modifiers:{ctrl:!0}}},{id:"edit.delete",label:"Delete",group:"Edit",scope:"editor",binding:{key:"Delete"}},{id:"edit.selectAll",label:"Select All",group:"Edit",scope:"editor",binding:{key:"a",modifiers:{ctrl:!0}}},{id:"edit.duplicate",label:"Duplicate",group:"Edit",scope:"editor",binding:{key:"d",modifiers:{ctrl:!0}}},{id:"view.zoomIn",label:"Zoom In",group:"View",scope:"global",binding:{key:"=",modifiers:{ctrl:!0}}},{id:"view.zoomOut",label:"Zoom Out",group:"View",scope:"global",binding:{key:"-",modifiers:{ctrl:!0}}},{id:"view.zoomFit",label:"Zoom to Fit",group:"View",scope:"global",binding:{key:"0",modifiers:{ctrl:!0}}},{id:"view.toggleMixer",label:"Toggle Mixer",group:"View",scope:"global",binding:{key:"m"}},{id:"view.togglePianoRoll",label:"Toggle Piano Roll",group:"View",scope:"global",binding:{key:"p"}},{id:"pianoRoll.quantize",label:"Quantize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"q"}},{id:"pianoRoll.humanize",label:"Humanize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"h"}},{id:"pianoRoll.velocityUp",label:"Velocity +10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{shift:!0}}},{id:"pianoRoll.velocityDown",label:"Velocity -10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{shift:!0}}},{id:"pianoRoll.octaveUp",label:"Octave Up",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{ctrl:!0,shift:!0}}},{id:"pianoRoll.octaveDown",label:"Octave Down",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{ctrl:!0,shift:!0}}},{id:"timeline.split",label:"Split at Cursor",group:"Timeline",scope:"timeline",binding:{key:"s"}},{id:"timeline.mute",label:"Mute Track",group:"Timeline",scope:"timeline",binding:{key:"m",modifiers:{ctrl:!0}}},{id:"timeline.solo",label:"Solo Track",group:"Timeline",scope:"timeline",binding:{key:"s",modifiers:{ctrl:!0}}},{id:"timeline.addTrack",label:"Add Track",group:"Timeline",scope:"timeline",binding:{key:"t",modifiers:{ctrl:!0}}},{id:"mixer.resetFader",label:"Reset Fader",group:"Mixer",scope:"mixer",binding:{key:"0"}},{id:"mixer.bypassFx",label:"Bypass All FX",group:"Mixer",scope:"mixer",binding:{key:"b"}}];for(const s of a)t.register({...s,callback:e[s.id]??r});return t}function G0(e){return Cr(e)}const W0=["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"],U0=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],V0=500*1024*1024,q0=20;function Ot(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function H0(e,t){return!!(e.type&&t.some(r=>e.type.startsWith(r.replace("*","")))||e.type.startsWith("audio/"))}function K0(e,t){const r=Ot(e.name);return r!==""&&t.includes(r)}function bs(e,t={}){const r=t.maxSize??V0,a=t.allowedTypes??W0,s=t.allowedExtensions??U0,i=t.maxFiles??q0,o=[],l=[];for(let c=0;c<e.length;c++){const d=e[c];if(c>=i){l.push({file:d,reason:"limit",message:`Exceeded maximum of ${i} files`});continue}if(d.size>r){l.push({file:d,reason:"size",message:`File exceeds ${Math.round(r/1024/1024)}MB limit`});continue}if(!H0(d,a)&&!K0(d,s)){l.push({file:d,reason:"type",message:`Unsupported file type: ${d.type||Ot(d.name)}`});continue}o.push(d)}return{valid:o,errors:l}}async function Dc(e){const t={file:e,name:e.name.replace(/\.[^.]+$/,""),extension:Ot(e.name),sizeBytes:e.size,mimeType:e.type||`audio/${Ot(e.name)}`};try{const r=await e.arrayBuffer(),s=await new OfflineAudioContext(1,1,44100).decodeAudioData(r);t.duration=s.duration,t.sampleRate=s.sampleRate,t.channels=s.numberOfChannels}catch{}return t}function Y0(e){let t=0;return{onDragEnter:r=>{var a;r.preventDefault(),r.stopPropagation(),t++,t===1&&((a=e.onDragEnter)==null||a.call(e))},onDragOver:r=>{r.preventDefault(),r.stopPropagation(),(r instanceof DragEvent&&r.dataTransfer||"dataTransfer"in r&&r.dataTransfer)&&(r.dataTransfer.dropEffect="copy")},onDragLeave:r=>{var a;r.preventDefault(),r.stopPropagation(),t--,t===0&&((a=e.onDragLeave)==null||a.call(e))},onDrop:async r=>{var d,h;r.preventDefault(),r.stopPropagation(),t=0,(d=e.onDragLeave)==null||d.call(e);const a="dataTransfer"in r?r.dataTransfer:null;if(!((h=a==null?void 0:a.files)!=null&&h.length))return;const s=Array.from(a.files),{valid:i,errors:o}=bs(s,e.validation),l=[],c=[...o];for(const f of i)if(e.probe)try{l.push(await Dc(f))}catch{c.push({file:f,reason:"decode",message:"Failed to decode audio"})}else l.push({file:f,name:f.name.replace(/\.[^.]+$/,""),extension:Ot(f.name),sizeBytes:f.size,mimeType:f.type||`audio/${Ot(f.name)}`});e.onDrop({accepted:l,rejected:c})}}}function Z0(e={}){return new Promise(t=>{const r=document.createElement("input");r.type="file",r.accept="audio/*,.mid,.midi",r.multiple=e.multiple??!0,r.onchange=async()=>{var l;if(!((l=r.files)!=null&&l.length)){t({accepted:[],rejected:[]});return}const a=Array.from(r.files),{valid:s,errors:i}=bs(a,e.validation),o=s.map(c=>({file:c,name:c.name.replace(/\.[^.]+$/,""),extension:Ot(c.name),sizeBytes:c.size,mimeType:c.type||`audio/${Ot(c.name)}`}));t({accepted:o,rejected:i})},r.click()})}var _t=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(_t||{}),zc=(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))(zc||{}),_c=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(_c||{});const X0=["var(--nice-success, #4caf50)","var(--nice-primary, #2196f3)","var(--nice-warning, #ff9800)","var(--nice-color-accent-pink, #e91e63)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-success, #8bc34a)","var(--nice-warning, #ffc107)"],Lr=["off","no function","brak"],Q0=e=>e.segments.some(t=>t.isOff||Lr.some(r=>t.name.toLowerCase().includes(r))),J0=e=>e.segments.find(t=>t.isOff||Lr.some(r=>t.name.toLowerCase().includes(r))),Fc=e=>Math.floor((e.valueFrom+e.valueTo)/2),eg=e=>{const t=J0(e);return t?Fc(t):0},tg=(e,t)=>e.segments.find(r=>t>=r.valueFrom&&t<=r.valueTo),Mn=(e,t=0,r=255)=>Math.max(t,Math.min(r,Math.round(e))),Un=({channel:e,value:t,onChange:r,onCommit:a,showDirectionHint:s})=>{const[i,o]=u.useState(Mn(t)),l=u.useMemo(()=>tg(e,i),[e,i]);u.useEffect(()=>o(Mn(t)),[t]);const c=d=>{const h=Mn(d);o(h),r(h),a==null||a(h)};return n.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:6},children:[n.jsxs("strong",{children:[e.channel,". ",e.name]}),s&&l&&n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:l.name})]}),n.jsx("input",{type:"range",min:0,max:255,value:i,onChange:d=>{const h=Mn(Number(d.target.value));o(h),r(h)},onMouseUp:()=>a==null?void 0:a(i),onTouchEnd:()=>a==null?void 0:a(i),style:{width:"100%"}}),n.jsx("div",{style:{marginTop:6},children:n.jsx("input",{type:"number",min:0,max:255,value:i,onChange:d=>{const h=Mn(Number(d.target.value));o(h),r(h)},onBlur:()=>a==null?void 0:a(i),style:{width:80,padding:6,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:6}})}),Q0(e)&&n.jsx("button",{type:"button",onClick:()=>c(eg(e)),style:{width:"100%",marginTop:8,padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)",cursor:"pointer"},children:"OFF"})]})},vs=({channel:e,value:t,onChange:r,onCommit:a})=>{const s=u.useMemo(()=>{const o=[...e.segments];return o.sort((l,c)=>{const d=(l.isOff?-1:0)+(Lr.some(f=>l.name.toLowerCase().includes(f))?-1:0),h=(c.isOff?-1:0)+(Lr.some(f=>c.name.toLowerCase().includes(f))?-1:0);return d!==h?d-h:l.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),o},[e]),i=o=>{const l=Fc(o);r(l),a==null||a(l)};return n.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[n.jsxs("strong",{children:[e.channel,". ",e.name]}),n.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(120px, 1fr))",gap:8,marginTop:8,maxHeight:220,overflowY:"auto"},children:s.map((o,l)=>{const c=t>=o.valueFrom&&t<=o.valueTo;return n.jsx("button",{type:"button",onClick:()=>i(o),style:{padding:"8px 10px",borderRadius:8,border:c?"2px solid var(--nice-primary-hover, #2563eb)":"1px solid var(--nice-border, #d1d5db)",background:c?"var(--nice-primary-bg, #eff6ff)":"var(--nice-bg, #fff)",textAlign:"left",cursor:"pointer",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:`${o.name} [${o.valueFrom}..${o.valueTo}]`,children:o.name},`${o.name}-${l}`)})})]})},xs=e=>{switch(e.channel.type){case _t.Dimmer:case _t.DimmerWithOff:return n.jsx(Un,{...e});case _t.RotationWithOff:case _t.RotationWithOffAndCcw:return n.jsx(Un,{...e,showDirectionHint:!0});case _t.Options:return n.jsx(vs,{...e});default:return n.jsx(Un,{...e})}},ia=e=>Math.max(0,Math.min(255,Math.round(e))),ng=[{target:".ntd-dmx-editor",titleKey:"tutorial.dmxEditor.intro.title",title:"DMX editor",contentKey:"tutorial.dmxEditor.intro.content",content:"Pick the FTDI device and port, then set each DMX channel’s value with the sliders to control your lighting fixtures live.",placement:"auto"}];function Oc({service:e,channels:t,onChannelChange:r,fixtures:a,...s}){return e?n.jsx(rg,{service:e,...s}):n.jsx("div",{className:s.className,style:s.style,children:n.jsx("small",{children:"Provide a `service` prop (DmxService) to control hardware."})})}function rg({service:e,pollInterval:t=500,className:r,style:a,tutorial:s}){const[i,o]=u.useState([]),[l,c]=u.useState(null),[d,h]=u.useState(()=>Array(513).fill(0)),[f,p]=u.useState(30),[y,m]=u.useState(0),[x,b]=u.useState(!1),g=u.useRef(null);u.useEffect(()=>{let z=!1;return e.getDevices().then(A=>{z||(o(A),A.length>0&&c(A[0]))}).catch(()=>{}),()=>{z=!0}},[e]),u.useEffect(()=>{if(g.current&&window.clearInterval(g.current),!(t<=0))return g.current=window.setInterval(async()=>{try{const z=await e.getState();Array.isArray(z.frontSnapshot)&&z.frontSnapshot.length>=513&&h(z.frontSnapshot.slice(0,513)),typeof z.fps=="number"&&p(z.fps),typeof z.startCode=="number"&&m(z.startCode)}catch{}},t),()=>{g.current&&window.clearInterval(g.current)}},[e,t]);const S=async()=>{l&&(await e.openPort(l.serialNumber||l.description),b(!0))},v=async()=>{await e.closePort(),b(!1)},k=async()=>{await e.blackout(),h(z=>{const A=[...z];for(let $=1;$<A.length;$++)A[$]=0;return A})},M=()=>e.configure(f,y),T=(z,A)=>{const $=ia(A);h(O=>{const I=[...O];return I[z]=$,I})},N=(z,A)=>e.setChannel(z,ia(A)),j=(l==null?void 0:l.deviceInfo)??null,R=u.useMemo(()=>{var z;return(z=j==null?void 0:j.channels)!=null&&z.length?j.channels:Array.from({length:16},(A,$)=>({channel:$+1,name:`Channel ${$+1}`,type:_t.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[j]);return n.jsxs("div",{className:`ntd-dmx-editor ${r??""}`,style:{position:"relative",padding:16,display:"grid",gap:16,...a},children:[n.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:n.jsx(we.NiceTutorialButton,{steps:we.resolveTutorial(s,ng)})}),n.jsxs("section",{style:{display:"grid",gap:12,gridTemplateColumns:"1fr auto auto auto",alignItems:"end"},children:[n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FTDI Device"}),n.jsx("select",{value:(l==null?void 0:l.serialNumber)||"",onChange:z=>c(i.find(A=>A.serialNumber===z.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"},children:i.map(z=>{var A,$;return n.jsxs("option",{value:z.serialNumber,children:[((A=z.deviceInfo)==null?void 0:A.manufacturer)??""," ",(($=z.deviceInfo)==null?void 0:$.model)??z.description," (",z.serialNumber||z.description,")"]},z.serialNumber||z.description)})}),j&&n.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:["Mode: ",n.jsx("b",{children:j.modeName}),", footprint: ",n.jsx("b",{children:j.footprint})]})]}),n.jsx("button",{onClick:S,disabled:!l||x,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-success, #10b981)",background:"var(--nice-success-bg, #ecfdf5)",cursor:"pointer"},children:"Open port"}),n.jsx("button",{onClick:v,disabled:!x,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-danger, #ef4444)",background:"var(--nice-danger-bg, #fef2f2)",cursor:"pointer"},children:"Close port"}),n.jsx("button",{onClick:k,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-border-color, #4b5563)",background:"var(--nice-bg-secondary, #f3f4f6)",cursor:"pointer"},children:"Blackout"})]}),n.jsxs("section",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(160px, 100%), 1fr))",gap:12,alignItems:"end"},children:[n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FPS"}),n.jsx("input",{type:"number",min:10,max:44,value:f,onChange:z=>p(Number(z.target.value)),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"Start Code"}),n.jsx("input",{type:"number",min:0,max:255,value:y,onChange:z=>m(ia(Number(z.target.value))),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),n.jsx("div",{children:n.jsx("button",{onClick:M,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-primary, #3b82f6)",background:"var(--nice-primary-bg, #eff6ff)",cursor:"pointer"},children:"Apply configuration"})})]}),n.jsxs("section",{children:[n.jsx("h3",{style:{margin:"8px 0 12px",fontSize:16},children:"Channels"}),n.jsx("div",{style:{display:"grid",gap:12,gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))"},children:R.map(z=>n.jsx(xs,{channel:z,value:d[z.channel]??0,onChange:A=>T(z.channel,A),onCommit:A=>N(z.channel,A)},z.channel))})]})]})}const Bc=[{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 Gc{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,Bc.forEach(t=>this.profiles.set(t.id,t)),this.createUniverse(1,"Universe 1")}createUniverse(t,r){const a={id:String(t),name:r,channels:new Uint8Array(512)};return this.universes.set(t,a),a}getUniverse(t){return this.universes.get(t)}addFixture(t){this.fixtures.set(t.id,t)}removeFixture(t){this.fixtures.delete(t)}getFixture(t){return this.fixtures.get(t)}getAllFixtures(){return Array.from(this.fixtures.values())}getProfile(t){return this.profiles.get(t)}registerProfile(t){this.profiles.set(t.id,t)}setChannel(t,r,a){const s=this.universes.get(t);s&&r>=1&&r<=512&&(s.channels[r-1]=Math.max(0,Math.min(255,a)))}getChannel(t,r){const a=this.universes.get(t);return a&&r>=1&&r<=512?a.channels[r-1]:0}setFixtureValues(t,r){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);if(s)for(let i=0;i<Math.min(r.length,s.channelCount);i++)a.values[i]=r[i],this.setChannel(a.universe,a.startChannel+i,r[i])}setFixtureColor(t,r,a,s,i=0){const o=this.fixtures.get(t);if(!o)return;const l=this.profiles.get(o.profileId);if(!l)return;const c=[...o.values];l.channels.forEach((d,h)=>{d.name.toLowerCase().includes("red")?c[h]=r:d.name.toLowerCase().includes("green")?c[h]=a:d.name.toLowerCase().includes("blue")?c[h]=s:d.name.toLowerCase().includes("white")&&(c[h]=i)}),this.setFixtureValues(t,c)}setFixtureDimmer(t,r){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);s&&s.channels.forEach((i,o)=>{i.type==="dimmer"&&(a.values[o]=Math.max(0,Math.min(255,Math.round(r*255))),this.setChannel(a.universe,a.startChannel+o,a.values[o]))})}fadeFixture(t,r,a,s="linear"){return new Promise(i=>{const o=this.fixtures.get(t);if(!o){i();return}const l=[...o.values],c=performance.now(),d=()=>{const h=performance.now()-c,f=Math.min(1,h/a);let p=f;switch(s){case"ease-in":p=f*f;break;case"ease-out":p=1-(1-f)*(1-f);break;case"ease-in-out":p=f<.5?2*f*f:1-Math.pow(-2*f+2,2)/2;break}const y=l.map((m,x)=>{const b=r[x]??m;return Math.round(m+(b-m)*p)});this.setFixtureValues(t,y),f<1?requestAnimationFrame(d):i()};d()})}setOutputCallback(t){this.outputCallback=t}start(){this.running||(this.running=!0,this.intervalId=window.setInterval(()=>{this.sendOutput()},1e3/this.frameRate))}stop(){this.running=!1,this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null)}sendOutput(){this.outputCallback&&this.universes.forEach((t,r)=>{this.outputCallback(r,t.channels)})}blackout(){this.universes.forEach(t=>{t.channels.fill(0)}),this.fixtures.forEach(t=>{t.values.fill(0)})}fullOn(){this.fixtures.forEach(t=>{this.setFixtureDimmer(t.id,1)})}}const ag=6454,sg=new Uint8Array([65,114,116,45,78,101,116,0]);function ig(e,t){const r=new Uint8Array(18+t.length);return r.set(sg,0),r[8]=0,r[9]=80,r[10]=0,r[11]=14,r[12]=0,r[13]=0,r[14]=e&255,r[15]=e>>8&255,r[16]=t.length>>8&255,r[17]=t.length&255,r.set(t.slice(0,512),18),r}const og=5568;function lg(e,t,r,a=100,s="Nice2Dev DMX"){const i=Math.min(t.length,512),o=126+i,l=new Uint8Array(o),c=new DataView(l.buffer);c.setUint16(0,16,!1),c.setUint16(2,0,!1);const d=[65,83,67,45,69,49,46,49,55,0,0,0];for(let m=0;m<d.length;m++)l[4+m]=d[m];const h=o-16;c.setUint16(16,28672|h&4095,!1),c.setUint32(18,4,!1);for(let m=0;m<16;m++)l[22+m]=m+1;const f=o-38;c.setUint16(38,28672|f&4095,!1),c.setUint32(40,2,!1);const p=new TextEncoder().encode(s.slice(0,63));l.set(p,44),l[108]=a,c.setUint16(109,0,!1),l[111]=r&255,l[112]=0,c.setUint16(113,e,!1);const y=i+11;return c.setUint16(115,28672|y&4095,!1),l[117]=2,l[118]=161,c.setUint16(119,0,!1),c.setUint16(121,1,!1),c.setUint16(123,i+1,!1),l[125]=0,l.set(t.slice(0,i),126),l}function cg(e){const t=e>>8&255,r=e&255;return`239.255.${t}.${r}`}class dg{constructor(t,r){this.config=t,this.scenes=r,this.currentStep=0,this.direction=1,this.isRunning=!1,this.timer=null,this.fadeStartTime=0,this.fadeFromValues=new Uint8Array(512),this.fadeToValues=new Uint8Array(512),this.onOutput=null}setOutputCallback(t){this.onOutput=t}start(){this.isRunning||(this.isRunning=!0,this.currentStep=this.config.direction==="backward"?this.config.steps.length-1:0,this.direction=this.config.direction==="backward"?-1:1,this.executeStep())}stop(){this.isRunning=!1,this.timer&&(clearTimeout(this.timer),this.timer=null)}executeStep(){var o;if(!this.isRunning)return;const t=this.config.steps[this.currentStep];if(!t)return;const r=this.scenes.get(t.sceneId);if(!r){this.advanceStep();return}const a=new Uint8Array(512);if(r.channels)for(const l of r.channels)l.channel>=1&&l.channel<=512&&(a[l.channel-1]=l.value);this.fadeFromValues.set(this.fadeToValues),this.fadeToValues.set(a),this.fadeStartTime=performance.now();const s=t.fadeTime/this.config.speed,i=t.holdTime/this.config.speed;s>0?this.runFade(s,()=>{var l;(l=this.onOutput)==null||l.call(this,this.fadeToValues),this.timer=setTimeout(()=>this.advanceStep(),i)}):((o=this.onOutput)==null||o.call(this,a),this.timer=setTimeout(()=>this.advanceStep(),i))}runFade(t,r){const a=performance.now(),s=new Uint8Array(512),i=()=>{var c;if(!this.isRunning)return;const o=performance.now()-a,l=Math.min(o/t,1);for(let d=0;d<512;d++)s[d]=Math.round(this.fadeFromValues[d]+(this.fadeToValues[d]-this.fadeFromValues[d])*l);(c=this.onOutput)==null||c.call(this,s),l<1?requestAnimationFrame(i):r()};requestAnimationFrame(i)}advanceStep(){if(!this.isRunning)return;const{steps:t,loop:r,direction:a}=this.config;if(this.currentStep+=this.direction,a==="bounce"){if(this.currentStep>=t.length?(this.direction=-1,this.currentStep=t.length-2):this.currentStep<0&&(this.direction=1,this.currentStep=1),this.currentStep<0||this.currentStep>=t.length){if(!r){this.stop();return}this.currentStep=0,this.direction=1}}else if(this.currentStep>=t.length||this.currentStep<0){if(!r){this.stop();return}this.currentStep=a==="backward"?t.length-1:0}this.executeStep()}}const ug=({engine:e,tracks:t=[],scenes:r=[],duration:a=3e5,currentTime:s=0,bpm:i=120,onTimeChange:o,onCueAdd:l,onCueUpdate:c,onCueDelete:d,onTrackAdd:h,onTrackUpdate:f,onPlay:p,onPause:y,onStop:m,className:x=""})=>{const[b,g]=u.useState(1),[S,v]=u.useState(0),[k,M]=u.useState(!1),[T,N]=u.useState(null),[j,R]=u.useState(null),[z,A]=u.useState(!0),[$,O]=u.useState(1e3),I=u.useRef(null),U=u.useRef(null),J=u.useRef(0),_=u.useMemo(()=>.1*b,[b]),W=u.useCallback(w=>w*_,[_]),K=u.useCallback(w=>w/_,[_]),re=u.useCallback(w=>{if(!z)return w;const D=6e4/i;return Math.round(w/D)*D},[z,i]);u.useEffect(()=>{if(k){const w=performance.now(),D=s,F=()=>{const B=performance.now()-w,V=D+B;if(V>=a){M(!1),o==null||o(0),m==null||m();return}X(V),o==null||o(V),U.current=requestAnimationFrame(F)};U.current=requestAnimationFrame(F),p==null||p()}else U.current!==null&&(cancelAnimationFrame(U.current),U.current=null),y==null||y();return()=>{U.current!==null&&cancelAnimationFrame(U.current)}},[k,s,a,o,p,y,m]);const X=u.useCallback(w=>{t.forEach(D=>{D.muted||D.cues.forEach(F=>{const B=F.startTime,V=B+F.duration;if(w>=B&&w<V&&J.current<B){const Y=r.find(oe=>oe.id===F.sceneId);Y&&Y.fixtures.forEach(oe=>{F.fadeIn&&F.fadeIn>0?e.fadeFixture(oe.fixtureId,oe.values,F.fadeIn):e.setFixtureValues(oe.fixtureId,oe.values)})}if(J.current<V&&w>=V){const Y=r.find(oe=>oe.id===F.sceneId);Y&&Y.fixtures.forEach(oe=>{if(e.getFixture(oe.fixtureId)&&F.fadeOut&&F.fadeOut>0){const ne=new Array(oe.values.length).fill(0);e.fadeFixture(oe.fixtureId,ne,F.fadeOut)}})}})}),J.current=w},[t,r,e]),q=w=>{const D=Math.floor(w/1e3),F=Math.floor(D/60),B=D%60,V=Math.floor(w%1e3/(1e3/30));return`${F}:${B.toString().padStart(2,"0")}:${V.toString().padStart(2,"0")}`},E=u.useCallback(w=>{if(!I.current)return;const D=I.current.getBoundingClientRect(),F=w.clientX-D.left+S,B=re(K(F));o==null||o(Math.max(0,Math.min(a,B)))},[S,K,re,a,o]),P=u.useCallback((w,D,F)=>{const B=t.find(oe=>oe.id===D),V=B==null?void 0:B.cues.find(oe=>oe.id===w);if(!V)return;const Y=re(Math.max(0,V.startTime+K(F)));c==null||c({...V,startTime:Y})},[t,K,re,c]),C=()=>{const w=6e4/i,D=Math.ceil(a/w),F=[];for(let B=0;B<=D;B++){const V=B*w,Y=W(V),oe=B%4===0;F.push(n.jsx("div",{className:`nice-dmx-timeline__beat ${oe?"nice-dmx-timeline__beat--measure":""}`,style:{left:Y},children:oe&&n.jsx("span",{className:"nice-dmx-timeline__beat-label",children:B/4+1})},B))}return F},L=(w,D)=>{const F=W(w.startTime),B=W(w.duration),V=r.find(Y=>Y.id===w.sceneId);return n.jsxs("div",{className:`nice-dmx-timeline__cue ${T===w.id?"nice-dmx-timeline__cue--selected":""}`,style:{left:F,width:B,backgroundColor:(V==null?void 0:V.color)||D.color||"var(--nice-accent, #8b5cf6)"},onClick:Y=>{Y.stopPropagation(),N(w.id)},draggable:!D.locked,onDragEnd:Y=>{var ie;const oe=(ie=Y.target.parentElement)==null?void 0:ie.getBoundingClientRect();oe&&P(w.id,D.id,Y.clientX-oe.left-F)},children:[n.jsx("span",{className:"nice-dmx-timeline__cue-name",children:w.name||(V==null?void 0:V.name)}),w.fadeIn&&w.fadeIn>0&&n.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--in",style:{width:W(w.fadeIn)}}),w.fadeOut&&w.fadeOut>0&&n.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--out",style:{width:W(w.fadeOut)}})]},w.id)};return n.jsxs("div",{className:`nice-dmx-timeline ${x}`,children:[n.jsxs("div",{className:"nice-dmx-timeline__toolbar",children:[n.jsxs("div",{className:"nice-dmx-timeline__transport",children:[n.jsx("button",{type:"button",onClick:()=>o==null?void 0:o(0),title:"Go to start","aria-label":"Go to start",children:n.jsx(G.NtdSkipBack,{size:14})}),n.jsx("button",{type:"button",onClick:()=>M(!k),title:k?"Pause":"Play","aria-label":k?"Pause":"Play",children:k?n.jsx(G.NtdPause,{size:14}):n.jsx(G.NtdPlay,{size:14})}),n.jsx("button",{type:"button",onClick:()=>{M(!1),o==null||o(0),e.blackout(),m==null||m()},title:"Stop","aria-label":"Stop",children:n.jsx(G.NtdStop,{size:14})})]}),n.jsx("div",{className:"nice-dmx-timeline__time",children:q(s)}),n.jsxs("div",{className:"nice-dmx-timeline__tools",children:[n.jsx("button",{type:"button",className:z?"active":"",onClick:()=>A(!z),title:"Snap to grid","aria-label":"Snap to grid",children:n.jsx(G.NtdGrid,{size:14})}),n.jsx("button",{type:"button",onClick:()=>g(Math.max(.25,b-.25)),title:"Zoom out",children:"−"}),n.jsxs("span",{className:"nice-dmx-timeline__zoom",children:[Math.round(b*100),"%"]}),n.jsx("button",{type:"button",onClick:()=>g(Math.min(4,b+.25)),title:"Zoom in",children:"+"})]}),n.jsxs("div",{className:"nice-dmx-timeline__bpm",children:[n.jsx("label",{children:"BPM:"}),n.jsx("span",{children:i})]}),n.jsx("button",{type:"button",className:"nice-dmx-timeline__blackout",onClick:()=>e.blackout(),title:"Blackout","aria-label":"Blackout",children:n.jsx(G.NtdMoon,{size:14})})]}),n.jsxs("div",{className:"nice-dmx-timeline__content",children:[n.jsxs("div",{className:"nice-dmx-timeline__headers",children:[t.map(w=>n.jsxs("div",{className:`nice-dmx-timeline__header ${j===w.id?"nice-dmx-timeline__header--selected":""}`,onClick:()=>R(w.id),children:[n.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:w.color||"var(--nice-accent, #8b5cf6)"}}),n.jsx("span",{className:"nice-dmx-timeline__track-name",children:w.name}),n.jsxs("div",{className:"nice-dmx-timeline__track-controls",children:[n.jsx("button",{type:"button",className:w.muted?"active":"",onClick:D=>{D.stopPropagation(),f==null||f({...w,muted:!w.muted})},title:"Mute",children:"M"}),n.jsx("button",{type:"button",className:w.locked?"active":"",onClick:D=>{D.stopPropagation(),f==null||f({...w,locked:!w.locked})},title:"Lock","aria-label":"Lock",children:n.jsx(G.NtdLock,{size:14})})]})]},w.id)),n.jsx("button",{type:"button",className:"nice-dmx-timeline__add-track",onClick:()=>{h==null||h({id:`track-${Date.now()}`,name:`Track ${t.length+1}`,fixtureIds:[],cues:[]})},children:"+ Add Track"})]}),n.jsxs("div",{className:"nice-dmx-timeline__tracks",ref:I,onClick:E,onScroll:w=>v(w.currentTarget.scrollLeft),children:[n.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:W(a)},children:C()}),t.map(w=>n.jsx("div",{className:`nice-dmx-timeline__track ${w.muted?"nice-dmx-timeline__track--muted":""}`,style:{width:W(a)},children:w.cues.map(D=>L(D,w))},w.id)),n.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:W(s)}})]})]})]})};function hg(){const[e]=u.useState(()=>new Gc);return u.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function pg(e,t,r=120){const[a,s]=u.useState(0),i=u.useRef(0);return u.useEffect(()=>{if(!t)return;const o=60/r,l=()=>{const c=t.currentTime,d=Math.floor(c/o);d!==i.current&&(i.current=d,s(d))};return t.addEventListener("timeupdate",l),()=>t.removeEventListener("timeupdate",l)},[t,r]),{currentBeat:a}}const fg=[],mg=[{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 Wc(){const[e,t]=u.useState(!1),[r,a]=u.useState(.8),[s,i]=u.useState(!1),[o,l]=u.useState(null),[c,d]=u.useState(null),[h,f]=u.useState(null),p=u.useRef(null),y=u.useRef(null),m=u.useRef(null),x=u.useRef(null),b=u.useRef([]),g=u.useRef(null),S=u.useRef(null),v=u.useCallback(()=>{if(y.current)return;const I=new AudioContext;y.current=I;const U=I.createGain();U.gain.value=r,x.current=U;const J=I.createAnalyser();J.fftSize=256,g.current=J,U.connect(J).connect(I.destination)},[]),k=u.useCallback(()=>{const I=p.current,U=y.current,J=x.current;if(!I||!U||!J||m.current)return;const _=U.createMediaElementSource(I);m.current=_,b.current.length>0?(_.connect(b.current[0]),b.current[b.current.length-1].connect(J)):_.connect(J)},[]),M=u.useCallback(()=>{var U;const I=p.current;!I||!S.current||(Bt(),v(),k(),((U=y.current)==null?void 0:U.state)==="suspended"&&y.current.resume(),I.play().catch(J=>d(String(J))))},[v,k]),T=u.useCallback(()=>{var I;(I=p.current)==null||I.pause()},[]),N=u.useCallback(()=>{e?T():M()},[e,M,T]),j=u.useCallback(I=>{const U=Math.max(0,Math.min(1,I));a(U),x.current&&(x.current.gain.value=U),p.current&&(p.current.volume=U)},[]),R=u.useCallback(I=>{S.current=I,d(null),l(null),i(!0),m.current&&(m.current.disconnect(),m.current=null),p.current||(p.current=new Audio,p.current.crossOrigin="anonymous",p.current.addEventListener("playing",()=>{t(!0),i(!1)}),p.current.addEventListener("pause",()=>t(!1)),p.current.addEventListener("waiting",()=>i(!0)),p.current.addEventListener("canplay",()=>i(!1)),p.current.addEventListener("error",()=>d("Failed to load stream"))),p.current.src=I.streamUrl,p.current.load(),l({genre:I.genre,bitrate:I.bitrate})},[]),z=u.useCallback(I=>{y.current||v();const J=y.current;b.current.forEach(W=>W.disconnect());const _=I.bands.map(W=>{const K=J.createBiquadFilter();return K.type="peaking",K.frequency.value=W.frequency,K.gain.value=W.gain,K.Q.value=W.Q??1.4,K});for(let W=0;W<_.length-1;W++)_[W].connect(_[W+1]);b.current=_,m.current&&x.current&&(m.current.disconnect(),m.current.connect(_[0]),_[_.length-1].connect(x.current)),f(I.name)},[v]),A=u.useCallback(()=>{b.current.forEach(I=>I.disconnect()),b.current=[],m.current&&x.current&&(m.current.disconnect(),m.current.connect(x.current)),f(null)},[]);return u.useEffect(()=>()=>{var I,U,J;(I=p.current)==null||I.pause(),p.current=null,b.current.forEach(_=>_.disconnect()),(U=m.current)==null||U.disconnect(),(J=y.current)==null||J.close()},[]),[{isPlaying:e,volume:r,isBuffering:s,metadata:o,error:c,activePreset:h},{play:M,pause:T,toggle:N,setVolume:j,setStation:R,applyEQPreset:z,clearEQ:A}]}function Uc({stations:e,activeStationId:t,onSelect:r,onToggleFavorite:a,className:s}){const{t:i}=Pe(),[o,l]=u.useState(""),[c,d]=u.useState(null),[h,f]=u.useState(!1),p=u.useMemo(()=>[...new Set(e.map(m=>m.genre).filter(Boolean))],[e]),y=u.useMemo(()=>e.filter(m=>{var x,b;if(h&&!m.isFavorite||c&&m.genre!==c)return!1;if(o){const g=o.toLowerCase();return m.name.toLowerCase().includes(g)||(((x=m.genre)==null?void 0:x.toLowerCase().includes(g))??!1)||(((b=m.country)==null?void 0:b.toLowerCase().includes(g))??!1)}return!0}),[e,o,c,h]);return n.jsxs("div",{className:`nice-station-browser${s?` ${s}`:""}`,children:[n.jsxs("div",{className:"nice-station-browser__toolbar",children:[n.jsx("input",{type:"text",className:"nice-station-browser__search",placeholder:(i==null?void 0:i("search_stations"))??"Search stations...",value:o,onChange:m=>l(m.target.value)}),n.jsxs("select",{className:"nice-station-browser__genre-filter",value:c??"",onChange:m=>d(m.target.value||null),children:[n.jsx("option",{value:"",children:(i==null?void 0:i("all_genres"))??"All Genres"}),p.map(m=>n.jsx("option",{value:m,children:m},m))]}),n.jsx("button",{className:`nice-station-browser__fav-toggle${h?" nice-station-browser__fav-toggle--active":""}`,onClick:()=>f(!h),title:(i==null?void 0:i("favorites"))??"Favorites","aria-label":(i==null?void 0:i("favorites"))??"Favorites",children:n.jsx(G.NtdStar,{size:14,style:{color:"var(--nice-warning, #facc15)"}})})]}),n.jsxs("div",{className:"nice-station-browser__list",children:[y.map(m=>n.jsxs("div",{className:`nice-station-browser__item${m.id===t?" nice-station-browser__item--active":""}`,onClick:()=>r(m),role:"button",tabIndex:0,onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&r(m)},children:[m.logoUrl&&n.jsx("img",{className:"nice-station-browser__logo",src:m.logoUrl,alt:m.name,loading:"lazy"}),n.jsxs("div",{className:"nice-station-browser__info",children:[n.jsx("span",{className:"nice-station-browser__name",children:m.name}),m.genre&&n.jsx("span",{className:"nice-station-browser__genre",children:m.genre}),m.country&&n.jsx("span",{className:"nice-station-browser__country",children:m.country})]}),m.bitrate&&n.jsxs("span",{className:"nice-station-browser__bitrate",children:[m.bitrate,"kbps"]}),a&&n.jsx("button",{className:`nice-station-browser__fav${m.isFavorite?" nice-station-browser__fav--active":""}`,onClick:x=>{x.stopPropagation(),a(m.id)},"aria-label":(i==null?void 0:i("favorites"))??"Favorites",children:n.jsx(G.NtdStar,{size:14,style:{color:m.isFavorite?"var(--nice-warning, #facc15)":"var(--nice-text-muted)"}})})]},m.id)),y.length===0&&n.jsx("div",{className:"nice-station-browser__empty",children:(i==null?void 0:i("no_stations_found"))??"No stations found"})]})]})}function gg({stations:e=fg,initialStationId:t,autoPlay:r=!1,eqPresets:a=mg,onStationChange:s,onPlayingChange:i,onMetadata:o,onToggleFavorite:l,onRecordingStart:c,onRecordingStop:d,showBrowser:h=!0,showEqualizer:f=!1,showVisualizer:p=!1,showMetadataHistory:y=!1,showRecording:m=!1,showSleepTimer:x=!1,className:b,style:g}){var L,w;const{t:S}=Pe(),[v,k]=Wc(),[M,T]=u.useState(()=>t?e.find(D=>D.id===t)??null:null),[N,j]=u.useState(f),R=u.useRef(null),z=u.useRef(0),[A,$]=u.useState([]),[O,I]=u.useState(!1),U=u.useRef(null),J=u.useRef([]),[_,W]=u.useState(0),K=u.useRef(null),[re,X]=u.useState(0),[q,E]=u.useState(null),P=u.useRef(null);u.useEffect(()=>{i==null||i(v.isPlaying)},[v.isPlaying,i]),u.useEffect(()=>{v.metadata&&(o==null||o(v.metadata),(v.metadata.title||v.metadata.artist)&&$(D=>[{time:new Date,meta:v.metadata},...D.slice(0,49)]))},[v.metadata,o]);const C=u.useCallback(D=>{T(D),k.setStation(D),s==null||s(D),r&&setTimeout(()=>k.play(),100)},[k,s,r]);return u.useEffect(()=>{if(t&&!M){const D=e.find(F=>F.id===t);D&&C(D)}},[t,e]),u.useEffect(()=>{if(!p||!R.current)return;const D=R.current,F=D.getContext("2d");if(!F)return;const B=()=>{z.current=requestAnimationFrame(B),F.clearRect(0,0,D.width,D.height);const V=F.createLinearGradient(0,D.height,0,0);if(V.addColorStop(0,we.resolveCssColor("var(--nice-accent-tint-80, rgba(99, 102, 241, 0.8))",F.canvas)),V.addColorStop(.5,"rgba(168,85,247,0.6)"),V.addColorStop(1,"rgba(236,72,153,0.4)"),!v.isPlaying){const ne=D.width/32;for(let Z=0;Z<32;Z++){const H=4+Math.sin(Date.now()/1e3+Z*.3)*3;F.fillStyle=V,F.fillRect(Z*ne+1,D.height-H,ne-2,H)}return}const Y=32,oe=D.width/Y;for(let ie=0;ie<Y;ie++){const ne=ie/Y,H=(Math.sin(Date.now()/200+ie*.5)*.3+.5)*D.height*(1-ne*.5)*(.5+Math.random()*.5);F.fillStyle=V,F.fillRect(ie*oe+1,D.height-H,oe-2,H)}};return B(),()=>cancelAnimationFrame(z.current)},[p,v.isPlaying]),u.useCallback(()=>{if(v.isPlaying)try{const F=new AudioContext().createMediaStreamDestination();J.current=[];const B=new MediaRecorder(F.stream,{mimeType:"audio/webm"});B.ondataavailable=V=>{V.data.size>0&&J.current.push(V.data)},B.onstop=()=>{const V=new Blob(J.current,{type:"audio/webm"});d==null||d(V),W(0),K.current&&window.clearInterval(K.current)},B.start(1e3),U.current=B,I(!0),W(0),K.current=window.setInterval(()=>{W(V=>V+1)},1e3),c==null||c()}catch{}},[v.isPlaying,c,d]),u.useCallback(()=>{U.current&&O&&(U.current.stop(),I(!1),K.current&&window.clearInterval(K.current))},[O]),u.useCallback(D=>{P.current&&window.clearInterval(P.current),X(D),E(D*60),P.current=window.setInterval(()=>{E(F=>!F||F<=1?(P.current&&window.clearInterval(P.current),P.current=null,k.pause(),null):F-1)},1e3)},[k]),u.useCallback(()=>{P.current&&window.clearInterval(P.current),P.current=null,E(null),X(0)},[]),u.useEffect(()=>()=>{K.current&&window.clearInterval(K.current),P.current&&window.clearInterval(P.current),cancelAnimationFrame(z.current)},[]),n.jsxs("div",{className:`nice-radio-player${b?` ${b}`:""}`,style:g,children:[n.jsx("div",{className:"nice-radio-player__now-playing",children:M?n.jsxs(n.Fragment,{children:[M.logoUrl&&n.jsx("img",{className:"nice-radio-player__cover",src:M.logoUrl,alt:M.name}),n.jsxs("div",{className:"nice-radio-player__info",children:[n.jsx("span",{className:"nice-radio-player__station-name",children:M.name}),((L=v.metadata)==null?void 0:L.title)&&n.jsx("span",{className:"nice-radio-player__track",children:v.metadata.artist?`${v.metadata.artist} — ${v.metadata.title}`:v.metadata.title}),((w=v.metadata)==null?void 0:w.genre)&&n.jsx("span",{className:"nice-radio-player__genre",children:v.metadata.genre}),v.isBuffering&&n.jsx("span",{className:"nice-radio-player__buffering",children:(S==null?void 0:S("buffering"))??"Buffering..."})]})]}):n.jsx("div",{className:"nice-radio-player__placeholder",children:(S==null?void 0:S("select_station"))??"Select a station"})}),n.jsxs("div",{className:"nice-radio-player__controls",children:[n.jsx("button",{className:"nice-radio-player__play-btn",onClick:k.toggle,disabled:!M,"aria-label":v.isPlaying?"Pause":"Play",children:v.isPlaying?n.jsx(G.NtdPause,{size:16}):n.jsx(G.NtdPlay,{size:16})}),n.jsxs("div",{className:"nice-radio-player__volume",children:[n.jsx("span",{className:"nice-radio-player__volume-icon","aria-hidden":"true",children:n.jsx(G.NtdVolume,{size:16})}),n.jsx("input",{type:"range",min:0,max:1,step:.01,value:v.volume,onChange:D=>k.setVolume(parseFloat(D.target.value)),className:"nice-radio-player__volume-slider","aria-label":"Volume"})]}),n.jsx("button",{className:`nice-radio-player__eq-btn${N?" nice-radio-player__eq-btn--active":""}`,onClick:()=>j(!N),title:"Equalizer",children:"EQ"})]}),v.error&&n.jsx("div",{className:"nice-radio-player__error",children:v.error}),N&&n.jsx("div",{className:"nice-radio-player__equalizer",children:n.jsxs("div",{className:"nice-radio-player__eq-presets",children:[a.map(D=>n.jsx("button",{className:`nice-radio-player__eq-preset${v.activePreset===D.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>k.applyEQPreset(D),children:D.name},D.name)),v.activePreset&&n.jsx("button",{className:"nice-radio-player__eq-preset",onClick:k.clearEQ,children:(S==null?void 0:S("clear"))??"Clear"})]})}),h&&n.jsx(Uc,{stations:e,activeStationId:M==null?void 0:M.id,onSelect:C})]})}const yg=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],bg={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class Vc{constructor(t,r={}){this.localStream=null,this.peers=new Map,this.onRemoteStream=null,this.onPeerStateChange=null,this.onSignalingMessage=null,this.localUserId=t,this.config={iceServers:r.iceServers??yg,audioConstraints:{...bg,echoCancellation:r.echoCancellation??!0,noiseSuppression:r.noiseSuppression??!0,autoGainControl:r.autoGainControl??!0}}}async initialize(){return this.localStream?this.localStream:(this.localStream=await navigator.mediaDevices.getUserMedia({audio:this.config.audioConstraints,video:!1}),this.localStream)}getLocalStream(){return this.localStream}getPeerIds(){return Array.from(this.peers.keys())}getPeerState(t){var r;return((r=this.peers.get(t))==null?void 0:r.state)??null}async createOffer(t){if(!this.localStream)throw new Error("WebRTCAudioManager not initialized. Call initialize() first.");const r=this.createPeerConnection(t),a=await r.createOffer();await r.setLocalDescription(a),this.sendSignalingMessage({type:"offer",from:this.localUserId,to:t,payload:a})}async handleSignalingMessage(t){if(t.to===this.localUserId)switch(t.type){case"offer":await this.handleOffer(t.from,t.payload);break;case"answer":await this.handleAnswer(t.from,t.payload);break;case"ice-candidate":await this.handleIceCandidate(t.from,t.payload);break;case"leave":this.removePeer(t.from);break}}removePeer(t){const r=this.peers.get(t);r&&(r.pc.close(),this.peers.delete(t))}disconnect(){for(const t of this.peers.keys())this.sendSignalingMessage({type:"leave",from:this.localUserId,to:t,payload:null});for(const t of this.peers.values())t.pc.close();this.peers.clear(),this.localStream&&(this.localStream.getTracks().forEach(t=>t.stop()),this.localStream=null)}setMuted(t){this.localStream&&this.localStream.getAudioTracks().forEach(r=>{r.enabled=!t})}isMuted(){if(!this.localStream)return!0;const t=this.localStream.getAudioTracks()[0];return t?!t.enabled:!0}createPeerConnection(t){const r=new RTCPeerConnection({iceServers:this.config.iceServers}),a={id:t,pc:r,remoteStream:null,state:r.connectionState};return this.peers.set(t,a),this.localStream&&this.localStream.getTracks().forEach(s=>{r.addTrack(s,this.localStream)}),r.onicecandidate=s=>{s.candidate&&this.sendSignalingMessage({type:"ice-candidate",from:this.localUserId,to:t,payload:s.candidate.toJSON()})},r.ontrack=s=>{var o;const[i]=s.streams;i&&(a.remoteStream=i,(o=this.onRemoteStream)==null||o.call(this,t,i))},r.onconnectionstatechange=()=>{var s;a.state=r.connectionState,(s=this.onPeerStateChange)==null||s.call(this,t,r.connectionState),(r.connectionState==="failed"||r.connectionState==="disconnected")&&this.removePeer(t)},r}async handleOffer(t,r){this.localStream||await this.initialize();const a=this.createPeerConnection(t);await a.setRemoteDescription(new RTCSessionDescription(r));const s=await a.createAnswer();await a.setLocalDescription(s),this.sendSignalingMessage({type:"answer",from:this.localUserId,to:t,payload:s})}async handleAnswer(t,r){const a=this.peers.get(t);a&&await a.pc.setRemoteDescription(new RTCSessionDescription(r))}async handleIceCandidate(t,r){const a=this.peers.get(t);a&&r&&await a.pc.addIceCandidate(new RTCIceCandidate(r))}sendSignalingMessage(t){var r;(r=this.onSignalingMessage)==null||r.call(this,t)}}function vg(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function xg(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function Sg(){return new AudioContext({sampleRate:48e3,latencyHint:"interactive"})}const Ss=u.forwardRef(function(t,r){const{mode:a="bars",width:s=300,height:i=100,barCount:o=32,barColor:l="var(--nice-primary, #3b82f6)",backgroundColor:c="transparent",fftSize:d=256,smoothing:h=.8,minDecibels:f=-90,maxDecibels:p=-10,deviceId:y,autoStart:m=!1,onStart:x,onStop:b,onAudioLevel:g,onError:S,className:v,style:k,barBorderRadius:M=2,barGap:T=2,lineWidth:N=2}=t,j=u.useRef(null),R=u.useRef(null),z=u.useRef(null),A=u.useRef(null),$=u.useRef(0),O=u.useRef(null),I=u.useRef(0),[U,J]=u.useState(!1),_=Array.isArray(l)?l.join("|"):l,W=u.useMemo(()=>_.split("|").map(w=>we.resolveCssColor(w,j.current)),[_]),K=u.useCallback((w,D,F=!0)=>{const B=F?w.createLinearGradient(0,i,0,0):w.createLinearGradient(0,0,s,0);return D.forEach((V,Y)=>{B.addColorStop(Y/(D.length-1),V)}),B},[s,i]),re=u.useCallback((w,D)=>{const B=(s-(o-1)*T)/o,V=Math.floor(D.length/o),Y=W,oe=Y.length>1?K(w,Y):Y[0];w.fillStyle=oe;for(let ie=0;ie<o;ie++){const Z=D[ie*V]/255*i,H=ie*(B+T),se=i-Z;M>0?(w.beginPath(),w.roundRect(H,se,B,Z,M),w.fill()):w.fillRect(H,se,B,Z)}},[o,W,T,M,s,i,K]),X=u.useCallback((w,D)=>{const F=i/2,V=(s-(o-1)*T)/o,Y=Math.floor(D.length/o),oe=W,ie=oe.length>1?K(w,oe):oe[0];w.fillStyle=ie;for(let ne=0;ne<o;ne++){const H=D[ne*Y]/255*F,se=ne*(V+T);M>0?(w.beginPath(),w.roundRect(se,F-H,V,H,M),w.fill(),w.beginPath(),w.roundRect(se,F,V,H,M),w.fill()):(w.fillRect(se,F-H,V,H),w.fillRect(se,F,V,H))}},[o,W,T,M,s,i,K]),q=u.useCallback((w,D)=>{const F=W;w.strokeStyle=F.length>1?K(w,F,!1):F[0],w.lineWidth=N,w.lineCap="round",w.lineJoin="round",w.beginPath();const B=s/D.length;let V=0;for(let Y=0;Y<D.length;Y++){const ie=D[Y]/128*i/2;Y===0?w.moveTo(V,ie):w.lineTo(V,ie),V+=B}w.stroke()},[W,N,s,i,K]),E=u.useCallback((w,D)=>{const F=s/2,B=i/2,V=Math.min(s,i)/3,Y=W;w.strokeStyle=Y.length>1?K(w,Y):Y[0],w.lineWidth=N;const oe=Math.floor(D.length/64),ie=Math.PI*2/64;w.beginPath();for(let ne=0;ne<64;ne++){const Z=D[ne*oe]/255,H=V+Z*V*.5,se=ne*ie-Math.PI/2,ae=F+Math.cos(se)*H,ue=B+Math.sin(se)*H;ne===0?w.moveTo(ae,ue):w.lineTo(ae,ue)}w.closePath(),w.stroke()},[W,N,s,i,K]),P=u.useCallback(()=>{const w=j.current,D=z.current,F=O.current;if(!w||!D||!F)return;const B=w.getContext("2d");if(!B)return;a==="waveform"?D.getByteTimeDomainData(F):D.getByteFrequencyData(F);let V=0;for(let Y=0;Y<F.length;Y++)V+=F[Y];switch(I.current=V/(F.length*255),g==null||g(I.current),B.clearRect(0,0,s,i),c!=="transparent"&&(B.fillStyle=we.resolveCssColor(c,B.canvas),B.fillRect(0,0,s,i)),a){case"bars":re(B,F);break;case"mirror-bars":X(B,F);break;case"waveform":q(B,F);break;case"circle":E(B,F);break}$.current=requestAnimationFrame(P)},[a,s,i,c,re,X,q,E,g]),C=u.useCallback(async()=>{try{if(U)return;const w=await navigator.mediaDevices.getUserMedia({audio:y?{deviceId:{exact:y}}:!0,video:!1});A.current=w;const D=new AudioContext;R.current=D;const F=D.createMediaStreamSource(w),B=D.createAnalyser();B.fftSize=d,B.smoothingTimeConstant=h,B.minDecibels=f,B.maxDecibels=p,F.connect(B),z.current=B,O.current=new Uint8Array(B.frequencyBinCount),J(!0),x==null||x(),P()}catch(w){S==null||S(w instanceof Error?w:new Error(String(w)))}},[U,y,d,h,f,p,x,S,P]),L=u.useCallback(()=>{cancelAnimationFrame($.current),A.current&&(A.current.getTracks().forEach(D=>D.stop()),A.current=null),R.current&&(R.current.close(),R.current=null),z.current=null,O.current=null,I.current=0,J(!1),b==null||b();const w=j.current;if(w){const D=w.getContext("2d");D&&(D.clearRect(0,0,s,i),c!=="transparent"&&(D.fillStyle=we.resolveCssColor(c,D.canvas),D.fillRect(0,0,s,i)))}},[s,i,c,b]);return u.useImperativeHandle(r,()=>({start:C,stop:L,isCapturing:()=>U,getAudioLevel:()=>I.current}),[C,L,U]),u.useEffect(()=>(m&&C(),()=>{L()}),[m]),n.jsx("canvas",{ref:j,width:s,height:i,className:v,style:{display:"block",...k},"aria-label":"Audio visualizer"})}),$i=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}}},kg={position:"fixed",display:"flex",flexDirection:"column",gap:8,padding:12,borderRadius:12,boxShadow:"0 4px 20px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:14,minWidth:200,maxWidth:280,transition:"all 0.2s ease"},wg={background:"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",text:"var(--nice-overlay-85, rgba(0, 0, 0, 0.85))",textSecondary:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",border:"var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-bg, #fee2e2)",mutedIcon:"var(--nice-danger, #ef4444)",activeBg:"var(--nice-success-bg, #dcfce7)",activeIcon:"var(--nice-success, #22c55e)",hoverBg:"var(--nice-overlay-5, rgba(0, 0, 0, 0.05))"},Cg={background:"var(--nice-overlay-90, rgba(30, 30, 30, 0.95))",text:"var(--nice-text-on-primary, #fff)",textSecondary:"var(--nice-text-muted, #a0a0a0)",border:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-dark, #7f1d1d)",mutedIcon:"var(--nice-danger-light, #fca5a5)",activeBg:"var(--nice-success, #14532d)",activeIcon:"var(--nice-success-light, #86efac)",hoverBg:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))"},qc=u.forwardRef(function(t,r){const{userId:a,userName:s,userAvatarUrl:i,participants:o=[],rtcConfig:l,position:c="bottom-right",expanded:d=!0,onSignalingMessage:h,onMuteToggle:f,onLeave:p,onSpeakingChange:y,speakingThreshold:m=.1,theme:x="auto",className:b,style:g,zIndex:S=1e3}=t,v=u.useRef(null),k=u.useRef(null),M=u.useRef(new Map);u.useRef(new Map);const[T,N]=u.useState(!1),[j,R]=u.useState(!1),[z,A]=u.useState(!1),[$,O]=u.useState(d),U=u.useMemo(()=>x==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":x,[x])==="dark"?Cg:wg;u.useEffect(()=>{const q=new Vc(a,l);return q.onRemoteStream=(E,P)=>{let C=M.current.get(E);C||(C=new Audio,C.autoplay=!0,M.current.set(E,C)),C.srcObject=P},q.onSignalingMessage=E=>{h==null||h(E)},q.onPeerStateChange=(E,P)=>{P==="connected"&&R(!0)},v.current=q,q.initialize().then(()=>{var E;(E=k.current)==null||E.start()}),()=>{q.disconnect();const E=M.current;E.forEach(P=>{P.srcObject=null}),E.clear()}},[a,l,h]);const J=u.useCallback(()=>{var E;const q=!T;N(q),(E=v.current)==null||E.setMuted(q),f==null||f(q)},[T,f]),_=u.useCallback(()=>{var q,E;(q=v.current)==null||q.disconnect(),(E=k.current)==null||E.stop(),R(!1),p==null||p()},[p]),W=u.useCallback(q=>{const E=q>m;E!==z&&(A(E),y==null||y(a,E))},[m,z,a,y]),K=u.useCallback(async q=>{var E;await((E=v.current)==null?void 0:E.createOffer(q))},[]),re=u.useCallback(async q=>{var E;await((E=v.current)==null?void 0:E.handleSignalingMessage(q))},[]);u.useImperativeHandle(r,()=>({connectToPeer:K,handleSignalingMessage:re,toggleMute:J,isMuted:()=>T,leave:_,getManager:()=>v.current}),[K,re,J,T,_]);const X=({participant:q,isLocal:E,isSpeaking:P})=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 0"},children:[n.jsx("div",{style:{width:32,height:32,borderRadius:"50%",backgroundColor:U.hoverBg,border:`2px solid ${P?U.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:U.text,transition:"border-color 0.15s ease"},children:q.avatarUrl?n.jsx("img",{src:q.avatarUrl,alt:q.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):q.name.charAt(0).toUpperCase()}),n.jsx("div",{style:{flex:1,minWidth:0},children:n.jsxs("div",{style:{color:U.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[q.name,E&&n.jsx("span",{style:{color:U.textSecondary,fontWeight:400},children:" (You)"})]})}),q.isMuted&&n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:U.mutedIcon,strokeWidth:"2",children:[n.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),n.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),n.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),n.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),n.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})]});return $?n.jsxs("div",{className:b,style:{...kg,...$i(c),backgroundColor:U.background,border:`1px solid ${U.border}`,zIndex:S,...g},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${U.border}`},children:[n.jsx("span",{style:{color:U.text,fontWeight:600},children:"Voice Chat"}),n.jsx("button",{onClick:()=>O(!1),style:{background:"none",border:"none",cursor:"pointer",padding:4,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:4},"aria-label":"Collapse",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:U.textSecondary,strokeWidth:"2",children:[n.jsx("polyline",{points:"4 14 10 14 10 20"}),n.jsx("polyline",{points:"20 10 14 10 14 4"}),n.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),n.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[n.jsx(X,{participant:{id:a,name:s,avatarUrl:i,isMuted:T},isLocal:!0,isSpeaking:z&&!T}),o.map(q=>n.jsx(X,{participant:q,isSpeaking:q.isSpeaking},q.id))]}),n.jsx(Ss,{ref:k,mode:"bars",width:256,height:32,barCount:24,barColor:T?"var(--nice-text-muted, #9ca3af)":["var(--nice-primary, #3b82f6)","var(--nice-accent, #8b5cf6)"],barGap:3,barBorderRadius:2,autoStart:!1,onAudioLevel:W,style:{borderRadius:4,opacity:T?.5:1}}),n.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[n.jsx("button",{onClick:J,style:{flex:1,padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:T?U.mutedBg:U.activeBg,color:T?U.mutedIcon:U.activeIcon,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":T?"Unmute":"Mute",children:T?n.jsxs(n.Fragment,{children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),n.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),n.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),n.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),n.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Muted"]}):n.jsxs(n.Fragment,{children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),n.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),n.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),n.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Mic On"]})}),n.jsx("button",{onClick:_,style:{padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:"var(--nice-danger-bg, #fef2f2)",color:"var(--nice-danger-dark, #dc2626)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":"Leave voice chat",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),n.jsx("polyline",{points:"16 17 21 12 16 7"}),n.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]})]}):n.jsx("div",{className:b,style:{position:"fixed",...$i(c),zIndex:S,...g},children:n.jsxs("button",{onClick:()=>O(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:U.background,boxShadow:"0 4px 12px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":"Expand voice chat",children:[n.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:U.text,strokeWidth:"2",children:[n.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),n.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),n.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),n.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),o.length>0&&n.jsx("span",{style:{position:"absolute",top:-4,right:-4,width:20,height:20,borderRadius:"50%",backgroundColor:U.speakingRing,color:"var(--nice-text-on-primary, #fff)",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:o.length+1})]})})});function jg(e,t){const r={...t,id:`op_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now()},a=e.operations.slice(0,e.undoIndex+1);return a.push(r),{...e,operations:a,undoIndex:a.length-1}}function Mg(e){return e.undoIndex<0?e:{...e,undoIndex:e.undoIndex-1}}function Rg(e){return e.undoIndex>=e.operations.length-1?e:{...e,undoIndex:e.undoIndex+1}}function Ng(e,t,r){const s=({"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":.6666666666666666,"1/8T":.3333333333333333,"1/16T":.16666666666666666,"1/4D":1.5,"1/8D":.75}[t.grid]??1)*r,i=t.strength/100;return e.map(o=>{const l=Math.round(o.startTick/s)*s,c=o.startTick+(l-o.startTick)*i,d=(Math.random()-.5)*2*t.humanize;return{...o,startTick:Math.max(0,Math.round(c+d))}})}function Tg(e){if(e.length<2)return null;const t=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],r=[...new Set(e.map(s=>s%12))].sort((s,i)=>s-i),a=[{intervals:[0,4,7],quality:"maj"},{intervals:[0,3,7],quality:"min"},{intervals:[0,4,7,11],quality:"maj7"},{intervals:[0,3,7,10],quality:"min7"},{intervals:[0,4,7,10],quality:"7"},{intervals:[0,3,6],quality:"dim"},{intervals:[0,4,8],quality:"aug"},{intervals:[0,3,6,9],quality:"dim7"},{intervals:[0,2,7],quality:"sus2"},{intervals:[0,5,7],quality:"sus4"},{intervals:[0,4,7,9],quality:"6"},{intervals:[0,3,7,9],quality:"min6"}];for(const s of r){const i=r.map(o=>(o-s+12)%12).sort((o,l)=>o-l);for(const o of a)if(o.intervals.length===i.length&&o.intervals.every((l,c)=>l===i[c])){const l=t[s],c=t[e[0]%12];return{root:l,quality:o.quality,bass:c!==l?c:void 0,symbol:`${l}${o.quality==="maj"?"":o.quality}${c!==l?`/${c}`:""}`,intervals:o.intervals}}}return null}const Hc={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 $g(e,t,r){const a=Hc[r],s=(e-t+120)%12;let i=a[0],o=999;for(const c of a){const d=Math.min(Math.abs(s-c),12-Math.abs(s-c));d<o&&(o=d,i=c)}const l=Math.floor((e-t)/12);return t+l*12+i}function Pg(e,t){switch(t.type){case"transpose":return e.map(r=>({...r,pitch:Math.max(0,Math.min(127,r.pitch+(t.params.semitones??0)))}));case"invert":{const r=t.params.axis??60;return e.map(a=>({...a,pitch:Math.max(0,Math.min(127,Math.round(2*r-a.pitch)))}))}case"retrograde":{if(e.length===0)return e;const r=Math.max(...e.map(a=>a.startTick+a.durationTicks));return e.map(a=>({...a,startTick:r-a.startTick-a.durationTicks}))}case"randomize-velocity":return e.map(r=>({...r,velocity:Math.max(1,Math.min(127,r.velocity+Math.round((Math.random()-.5)*2*(t.params.range??20))))}));default:return e}}function Eg(e){return e>=95?"S":e>=85?"A":e>=70?"B":e>=55?"C":e>=40?"D":"F"}const Ag={"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]}},Ig={"Bass Drum":{staffLine:4,noteHead:"normal",stem:"down"},Snare:{staffLine:2,noteHead:"normal",stem:"up"},"Hi-Hat Closed":{staffLine:0,noteHead:"x",stem:"up"},"Hi-Hat Open":{staffLine:0,noteHead:"diamond",stem:"up"},Ride:{staffLine:-1,noteHead:"x",stem:"up"},Crash:{staffLine:-2,noteHead:"x",stem:"up"},"High Tom":{staffLine:1,noteHead:"normal",stem:"up"},"Mid Tom":{staffLine:2,noteHead:"normal",stem:"down"},"Low Tom":{staffLine:3,noteHead:"normal",stem:"down"}};exports.ALL_CAP_STYLES=Wn;exports.ALL_EFFECTS=Ol;exports.ALL_TEXTURES=vo;exports.ARTNET_PORT=ag;exports.ASYMMETRIC_CAPS=co;exports.ArpeggiatorPanel=Yi;exports.AudioEffectType=zc;exports.AudioPitchAnalyzer=So;exports.AudioPlaybackEngine=Pm;exports.AudioRecorder=Da;exports.AudioTimeline=Ea;exports.AutoSavePanel=Di;exports.BarFillEditor=xo;exports.CCAutomationLaneEditor=Ui;exports.CCLane=Ei;exports.CONTROLLER_PROFILES=Ql;exports.ChaseRunner=dg;exports.CollaboratorPermission=_c;exports.DEFAULT_ARP_CONFIG=ca;exports.DEFAULT_AUDIO_INPUT_SETTINGS=Gl;exports.DEFAULT_BAR_FILL=Gt;exports.DEFAULT_CAP_STYLE=ho;exports.DEFAULT_EMPTY_BAR_FILL=_r;exports.DEFAULT_FONT_SETTINGS=Br;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=Fr;exports.DEFAULT_GOLD_FILLED_BAR_FILL=Or;exports.DEFAULT_KARAOKE_SETTINGS=po;exports.DEFAULT_PLAYER_BAR_STYLE=pn;exports.DEFAULT_SEED_CONFIG=Ul;exports.DMXEngine=Gc;exports.DRUM_PATTERN_NAMES=Vm;exports.DefaultScoringPresets=Oa;exports.DmxChannelControl=xs;exports.DmxChannelType=_t;exports.DmxEditor=Oc;exports.DmxOptionsControl=vs;exports.DmxSliderControl=Un;exports.DynamicRuleEditor=vl;exports.DynamicRuleField=ot;exports.DynamicRuleOperator=lt;exports.EditorTrackProvider=za;exports.EditorUndoManager=Cu;exports.FIXTURE_PROFILES=Bc;exports.GENERIC_PROFILE=hs;exports.GM_DRUM_MAP=Ig;exports.GRADIENT_PRESETS=tl;exports.GROOVE_TEMPLATES=gs;exports.GenericPlayer=Qa;exports.GenericPlayerControls=il;exports.GenericPlayerStage=ol;exports.GenericPlayerStageVisualizer=ll;exports.GenericPlaylist=ul;exports.GenericPlaylistItem=ss;exports.KARAOKE_FONT_OPTIONS=lp;exports.KEY_MAPS=Io;exports.KaraokeEditorManager=al;exports.KaraokeFormat=es;exports.KaraokeLyrics=Fa;exports.KaraokePhaserRenderer=sl;exports.KaraokeSummaryOverlay=Xa;exports.KaraokeTimeline=Ya;exports.LANE_COLORS=In;exports.LAUNCH_CONTROL_PROFILE=Xl;exports.LAYER_COLORS=X0;exports.LFOPanel=Zi;exports.MINILAB_PROFILE=Zl;exports.MPK_MINI_PROFILE=Yl;exports.MasterFXPanel=_i;exports.MidiCCMapper=Hm;exports.ModeSwitcher=rs;exports.NOTE_NAMES=Fm;exports.NiceArpeggiatorPanel=Yi;exports.NiceAudioEffectsRack=Mm;exports.NiceAudioErrorBoundary=rd;exports.NiceAudioInputPicker=$m;exports.NiceAudioPitchAnalyzer=So;exports.NiceAudioStudio=eu;exports.NiceAudioTimeline=Ea;exports.NiceAutoSavePanel=Di;exports.NiceBarFillEditor=xo;exports.NiceCCAutomationLaneEditor=Ui;exports.NiceCCLane=Ei;exports.NiceDMXTimeline=ug;exports.NiceDmxChannelControl=xs;exports.NiceDmxEditor=Oc;exports.NiceDmxOptionsControl=vs;exports.NiceDmxSliderControl=Un;exports.NiceDynamicRuleEditor=vl;exports.NiceEditorTrackProvider=za;exports.NiceGenericPlayer=Qa;exports.NiceGenericPlayerControls=il;exports.NiceGenericPlayerStage=ol;exports.NiceGenericPlayerStageVisualizer=ll;exports.NiceGenericPlaylist=ul;exports.NiceGenericPlaylistItem=ss;exports.NiceI18nProvider=nd;exports.NiceKaraokeEditorManager=al;exports.NiceKaraokeLyrics=Fa;exports.NiceKaraokeManager=Vh;exports.NiceKaraokePhaserRenderer=sl;exports.NiceKaraokeSelectionMode=el;exports.NiceKaraokeSessionJoin=ip;exports.NiceKaraokeSetupPanel=Jo;exports.NiceKaraokeSongBrowser=Qh;exports.NiceKaraokeSummaryOverlay=Xa;exports.NiceKaraokeTimeline=Ya;exports.NiceKaraokeUploader=Eo;exports.NiceLFOPanel=Zi;exports.NiceLatencyCalibrator=ep;exports.NiceMasterFXPanel=_i;exports.NiceModeSwitcher=rs;exports.NiceMusicLibraryExplorer=nf;exports.NiceNoteParticles=zl;exports.NiceNoteRiver=Dl;exports.NicePadKaraokeOverlay=Ao;exports.NicePianoRoll=Pa;exports.NicePlaylistBrowser=wl;exports.NicePlaylistDualPane=xl;exports.NicePlaylistGridView=Ml;exports.NicePlaylistImportWizard=$l;exports.NicePlaylistList=cs;exports.NicePlaylistOverview=Rl;exports.NicePlaylistSearchBar=Nl;exports.NicePlaylistSidebar=jl;exports.NicePlaylistTagEditor=pl;exports.NicePlaylistTrackList=os;exports.NiceRadioPlayer=gg;exports.NiceRecordingOptionsPanel=Fi;exports.NiceStageVisualizer=as;exports.NiceStationBrowser=Uc;exports.NiceStepSequencerPanel=Xi;exports.NiceStreamingVisualizer=Ss;exports.NiceUndoRedoPanel=zi;exports.NiceVocalEffectsRack=Nm;exports.NiceVocalPerformanceReport=Yh;exports.NiceVoiceChatOverlay=qc;exports.NiceWaveform=$a;exports.NiceYouTubePlayer=cl;exports.NiceZoomSnapControls=Aa;exports.NoteParticles=zl;exports.NoteRiver=Dl;exports.OVERLAY_PATTERNS=$r;exports.OXYGEN25_PROFILE=Kl;exports.PLAYER_COLORS=et;exports.PLAYER_COLOR_VARS=ur;exports.PROGRESSION_NAMES=Um;exports.PadNotePlayer=_o;exports.PaneSide=ml;exports.PianoRoll=Pa;exports.PlaylistBrowser=wl;exports.PlaylistDualPane=xl;exports.PlaylistGridView=Ml;exports.PlaylistImportWizard=$l;exports.PlaylistList=cs;exports.PlaylistOverview=Rl;exports.PlaylistSearchBar=Nl;exports.PlaylistSidebar=jl;exports.PlaylistTagEditor=pl;exports.PlaylistTrackList=os;exports.PlaylistType=is;exports.RecordingOptionsPanel=Fi;exports.SACN_PORT=og;exports.SCALE_INTERVALS=Hc;exports.SCALE_NAMES=Wm;exports.SKEW_CAPS=uo;exports.STANDARD_TUNINGS=Ag;exports.SYMMETRIC_CAPS=qa;exports.ShortcutManager=Lc;exports.SimpleSynth=Wl;exports.SortDirection=ln;exports.SortField=gl;exports.StageVisualizer=as;exports.StepSequencerPanel=Xi;exports.StreamingVisualizer=Ss;exports.TEXTURE_CATEGORIES=Za;exports.TrackSource=St;exports.UndoRedoPanel=zi;exports.ViewMode=fl;exports.VocalEffectsEngine=Bl;exports.VoiceChatOverlay=qc;exports.Waveform=$a;exports.WebRTCAudioManager=Vc;exports.YouTubePlayer=cl;exports.ZoomSnapControls=Aa;exports.addEffectToLayer=c0;exports.addMidiNote=p0;exports.analyzeAudioFileWithAlgorithm=k0;exports.applyGroove=T0;exports.applyGrooveTemplate=Ac;exports.applyHumanize=Ec;exports.applyKaraokeDisplayVars=ns;exports.applyMidiTransform=Pg;exports.applySwing=Pc;exports.arrow_L=Ft;exports.arrow_R=Nt;exports.autoCorrelate=jo;exports.bracket_L=Ga;exports.bracket_R=oo;exports.buildArpSequence=qi;exports.buildLanes=Lo;exports.buildNoteDescriptors=Ja;exports.buildPadNoteEvents=zo;exports.buildSegmentScores=Mo;exports.canRedo=ac;exports.canUndo=rc;exports.chamfer_L=Mr;exports.chamfer_R=hn;exports.clearMidiNotes=m0;exports.clearPattern=kc;exports.computeGrade=Eg;exports.computeTheoreticalMax=Uo;exports.computeVocalPerformanceReport=Yo;exports.convertBrowserSongToKaraokeSongFile=Ih;exports.copyCCEvents=Ma;exports.createAnalyserNode=Rc;exports.createArpPattern=e0;exports.createArtNetPacket=ig;exports.createBasslinePattern=t0;exports.createCCHistory=Jl;exports.createCompressorNode=Tc;exports.createDefaultLFO=Dr;exports.createDefaultShortcuts=B0;exports.createDropZoneHandlers=Y0;exports.createEmptyPattern=Yt;exports.createEmptyStep=ps;exports.createGainNode=Nc;exports.createHiHatPattern=Jm;exports.createKickPattern=Xm;exports.createLoopRegion=L0;exports.createSACNPacket=lg;exports.createSnarePattern=Qm;exports.createVocoderNode=$c;exports.createVoiceChatAudioContext=Sg;exports.cutCCEvents=ic;exports.deleteCCEventsInRange=oc;exports.deserializeLFO=du;exports.deserializePattern=r0;exports.detectChord=Tg;exports.downsampleAndQuantizePitchPoints=Ro;exports.drawGlossyBarOnCanvas=Tn;exports.drawTimeline=pa;exports.estimateLatencyMs=No;exports.estimateLatencyMsFromRecording=Qo;exports.evaluateLFO=Ia;exports.evaluateLFOAsCC=La;exports.exportCCLane=dc;exports.extractBpmFromNotes=no;exports.findTextureByUrl=ph;exports.formatShortcut=G0;exports.generateArpEvents=pu;exports.generatePlaceholderWaveform=R0;exports.generateSeed=Hl;exports.generateUltrastarText=w0;exports.getActiveGradient=rl;exports.getActiveLyrics=$u;exports.getActiveWords=Pu;exports.getAlgorithmColor=Eh;exports.getAlgorithmCssVar=Ah;exports.getAlgorithmLabel=Ph;exports.getArpModes=Hi;exports.getArpRates=Ki;exports.getAudioContext=yn;exports.getAudioInputDevices=xg;exports.getAudioWorkletProcessorCode=jc;exports.getBackgroundUrl=$h;exports.getCachedImage=dh;exports.getCapStyleByName=Rn;exports.getComboMultiplier=Go;exports.getCoverUrl=Th;exports.getGrooveTemplate=$0;exports.getGrooveTemplateNames=P0;exports.getLaneForPitch=Do;exports.getNextPlayerColor=Sd;exports.getNextPlayerColorCss=kd;exports.getOverlayCanvasPattern=An;exports.getPatternByName=Nn;exports.getSACNMulticastAddress=cg;exports.getScoringPreset=zr;exports.getTexturePattern=Pn;exports.getVerseRatingLabel=Bo;exports.handleAddCCEvent=y0;exports.handleRedo=wu;exports.handleRemoveCCEvent=v0;exports.handleSelectCCLane=g0;exports.handleUndo=ku;exports.handleUpdateCCEvent=b0;exports.hexToHsl=Pr;exports.humanizeMidiNotes=I0;exports.hydrateKaraokeDisplayFromBackend=cp;exports.hydratePlayerKaraokeSettingsFromBackend=Gu;exports.hzToUltrastarPitch=ro;exports.importCCLane=uc;exports.initKaraokeDisplaySettings=up;exports.instrumentPresets=Em;exports.isAudioContextRunning=Ai;exports.isInLoopRegion=_0;exports.isWebRTCSupported=vg;exports.loadAllKaraokeSettings=Wu;exports.loadAudioWorkletModule=Mc;exports.loadKaraokeDisplaySettings=nl;exports.loadKaraokeSettings=Ha;exports.loadPlayerBarStyle=fo;exports.loadPlayerBarStyles=Vu;exports.loadRemoteScoringPresets=Fu;exports.makeClickReference=Xo;exports.makeClipSelectionId=C0;exports.mergeWaveforms=M0;exports.midiSeedGenerator=qm;exports.midiToHz=fa;exports.normalizeHex=Er;exports.openAudioFilePicker=Z0;exports.ornate_L=Ua;exports.ornate_R=Tr;exports.parseLyrics=Nu;exports.parseNotes=Hn;exports.parseUltraStarText=Po;exports.parseVersesWithSyllables=to;exports.parseVersesWithWords=Tu;exports.parseVideoMetadata=Co;exports.pasteCCEvents=sc;exports.pill_L=qt;exports.pill_R=zt;exports.preloadTexture=Ka;exports.preloadTextures=uh;exports.probeAudioFile=Dc;exports.pushCCState=ec;exports.pushOperation=jg;exports.quantizeMidiNotes=E0;exports.quantizeNotes=Ng;exports.quantizeStepInBeats=Ic;exports.quantizeStepInSeconds=ys;exports.randomizeVelocity=Sc;exports.recordCCEvent=lc;exports.redoCC=nc;exports.redoOperation=Rg;exports.removeEffectFromLayer=d0;exports.removeMidiNote=f0;exports.renderGlossyBarSvg=mo;exports.resumeAudioContext=Bt;exports.reversePattern=vc;exports.sampleLFOForDisplay=Wi;exports.sampleLFOToCCEvents=Gi;exports.saveKaraokeDisplaySettings=dp;exports.saveKaraokeSettings=Bu;exports.savePlayerBarStyle=Uu;exports.scaleResult=qo;exports.scaleTo10k=Vo;exports.scoreNotesWithPitchPoints=Wo;exports.selectCCEventsInRange=Km;exports.serializeLFO=cu;exports.serializePattern=n0;exports.setLoopFromSelection=D0;exports.setProjectWithUndo=Ji;exports.setStepGate=mc;exports.setStepNote=pc;exports.setStepProbability=gc;exports.setStepVelocity=fc;exports.sharp_L=dn;exports.sharp_R=un;exports.shield_L=Rr;exports.shield_R=io;exports.shiftPattern=xc;exports.shouldTrigger=Cc;exports.skewTL_L=hr;exports.skewTL_R=ha;exports.skewTR_L=ua;exports.skewTR_R=pr;exports.snapLoopToGrid=z0;exports.snapTimeToQuantize=Ra;exports.snapToGrid=j0;exports.snapToScale=$g;exports.soft_L=Ba;exports.soft_R=so;exports.stepDuration=fs;exports.stepTimeOffset=wc;exports.syncDivisionToHz=Oi;exports.tab_L=Wa;exports.tab_R=lo;exports.thinCCEvents=cc;exports.toTrack=$o;exports.toggleEffectBypass=u0;exports.toggleStep=hc;exports.toggleStepSlide=yc;exports.transposePattern=bc;exports.undoCC=tc;exports.undoOperation=Mg;exports.updateEffectParams=h0;exports.useAudioWorklet=l0;exports.useAutoSave=bu;exports.useCCAutomation=Zm;exports.useCanPickSong=sp;exports.useDMXAudioSync=pg;exports.useDMXEngine=hg;exports.useEditorTrack=Ru;exports.useKaraokePitch=Oo;exports.useKaraokeScoring=Ho;exports.useLocalPlaylists=ls;exports.useMPE=Dm;exports.useMidiLearn=Im;exports.useNiceTranslation=Pe;exports.useOxygen25=_m;exports.usePitchWorker=s0;exports.usePlaybackEngine=vu;exports.useProjectCRUD=Mu;exports.useRadioStream=Wc;exports.useRecording=xu;exports.useScoringWorker=i0;exports.useStepSequencer=a0;exports.useWebMidi=Ur;exports.useWorker=ms;exports.validateAudioFiles=bs;exports.wave_L=Nr;exports.wave_R=Va;exports.waveformValue=Bi;exports.wrapTimeInLoop=F0;
|
|
430
|
+
E`}}function ng(e,t){return`${e}:${t}`}function rg(e,t,n,a=1){if(t==="off")return e;const s=60/n;if(t==="beat")return Math.round(e/(s/a))*(s/a);if(t==="bar"){const i=s*4;return Math.round(e/i)*i}return e}function ag(e){return e.length===0?[]:e.flat()}function sg(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const ls=[{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 ig(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function fc(e,t){return t.amount===0?e:e.map(n=>{const a=n.time/t.grid;if(Math.round(a)%2===1){const o=t.grid*t.amount*.5;return{...n,time:n.time+o}}return{...n}})}function mc(e,t){const n=t.seed!=null?ig(t.seed):Math.random;return e.map(a=>{const s=(n()-.5)*2*t.timingAmount,i=Math.round((n()-.5)*2*t.velocityAmount),o=(n()-.5)*2*t.durationAmount;return{...a,time:Math.max(0,a.time+s),velocity:Math.max(1,Math.min(127,a.velocity+i)),duration:Math.max(.01,a.duration+o)}})}function gc(e,t,n=1){const a=4/t.stepsPerBar;return e.map(s=>{const i=s.time/a,o=Math.round(i)%t.stepsPerBar,l=t.timingOffsets[o]*a*n,c=1+(t.velocityScales[o]-1)*n,d=1+(t.durationScales[o]-1)*n;return{...s,time:Math.max(0,s.time+l),velocity:Math.max(1,Math.min(127,Math.round(s.velocity*c))),duration:Math.max(.01,s.duration*d)}})}function og(e,t){let n=[...e.map(a=>({...a}))];return t.template&&t.grooveStrength>0&&(n=gc(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=fc(n,t.swing)),t.humanize&&(n=mc(n,t.humanize)),n}function lg(e){return ls.find(t=>t.id===e)}function cg(){return ls.map(({id:e,name:t})=>({id:e,name:t}))}function yc(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 cs(e,t){return yc(e)*60/t}function Na(e,t,n){const a=cs(t,n);return Math.round(e/a)*a}function dg(e,t){const{value:n,bpm:a,strength:s=1,quantizeStarts:i=!0,quantizeDurations:o=!1}=t,l=cs(n,a);return e.map(c=>{let{start:d,duration:h}=c;if(i){const p=Math.round(d/l)*l;d=d+(p-d)*s}if(o){const p=Math.max(l,Math.round(h/l)*l);h=h+(p-h)*s}return d===c.start&&h===c.duration?c:{...c,start:d,duration:h}})}function ug(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function hg(e,t={}){const{timingRange:n=.02,velocityRange:a=10,seed:s}=t,i=s!=null?ug(s):Math.random;return e.map(o=>{const l=(i()*2-1)*n,c=Math.round((i()*2-1)*a);return{...o,start:Math.max(0,o.start+l),velocity:o.velocity!=null?Math.max(1,Math.min(127,(o.velocity??100)+c)):void 0}})}function pg(){return{start:0,end:0,enabled:!1}}function fg(e,t){return{...e<t?{start:e,end:t}:{start:t,end:e},enabled:!0}}function mg(e,t,n){return{start:Na(e.start,t,n),end:Na(e.end,t,n),enabled:e.enabled}}function gg(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function yg(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 Ta(e){return e.length===1?e.toLowerCase():e}function Cr(e){var n,a,s,i;const t=[];return(n=e.modifiers)!=null&&n.ctrl&&t.push("Ctrl"),(a=e.modifiers)!=null&&a.shift&&t.push("Shift"),(s=e.modifiers)!=null&&s.alt&&t.push("Alt"),(i=e.modifiers)!=null&&i.meta&&t.push("Meta"),t.push(Ta(e.key)),t.join("+")}function vg(e,t){var l,c,d,h;const n=Ta(e.key)===Ta(t.key),a=!!e.ctrlKey==!!((l=t.modifiers)!=null&&l.ctrl),s=!!e.shiftKey==!!((c=t.modifiers)!=null&&c.shift),i=!!e.altKey==!!((d=t.modifiers)!=null&&d.alt),o=!!e.metaKey==!!((h=t.modifiers)!=null&&h.meta);return n&&a&&s&&i&&o}class vc{constructor(){this.actions=new Map,this.activeScopes=new Set(["global"]),this.enabled=!0,this.listener=null}register(t){this.actions.set(t.id,{...t,enabled:t.enabled??!0})}unregister(t){this.actions.delete(t)}rebind(t,n){const a=this.actions.get(t);a&&(a.binding=n)}setActiveScopes(t){this.activeScopes.clear(),this.activeScopes.add("global");for(const n of t)this.activeScopes.add(n)}setEnabled(t){this.enabled=t}setActionEnabled(t,n){const a=this.actions.get(t);a&&(a.enabled=n)}findConflicts(){const t=[],n=[...this.actions.values()];for(let a=0;a<n.length;a++)for(let s=a+1;s<n.length;s++){const i=n[a],o=n[s];Cr(i.binding)===Cr(o.binding)&&(i.scope===o.scope||i.scope==="global"||o.scope==="global")&&t.push([i,o])}return t}getGrouped(){const t={};for(const 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?Cr(n.binding):""}handleKeyDown(t){if(!this.enabled)return!1;for(const n of this.actions.values())if(n.enabled&&this.activeScopes.has(n.scope)&&vg(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 bg(e={}){const t=new vc,n=()=>{},a=[{id:"transport.play",label:"Play / Pause",group:"Transport",scope:"global",binding:{key:" "}},{id:"transport.stop",label:"Stop",group:"Transport",scope:"global",binding:{key:"Escape"}},{id:"transport.record",label:"Record",group:"Transport",scope:"global",binding:{key:"r",modifiers:{ctrl:!0}}},{id:"transport.rewind",label:"Rewind",group:"Transport",scope:"global",binding:{key:"Home"}},{id:"transport.forward",label:"Forward",group:"Transport",scope:"global",binding:{key:"End"}},{id:"transport.loopToggle",label:"Toggle Loop",group:"Transport",scope:"global",binding:{key:"l"}},{id:"edit.undo",label:"Undo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0}}},{id:"edit.redo",label:"Redo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0,shift:!0}}},{id:"edit.cut",label:"Cut",group:"Edit",scope:"editor",binding:{key:"x",modifiers:{ctrl:!0}}},{id:"edit.copy",label:"Copy",group:"Edit",scope:"editor",binding:{key:"c",modifiers:{ctrl:!0}}},{id:"edit.paste",label:"Paste",group:"Edit",scope:"editor",binding:{key:"v",modifiers:{ctrl:!0}}},{id:"edit.delete",label:"Delete",group:"Edit",scope:"editor",binding:{key:"Delete"}},{id:"edit.selectAll",label:"Select All",group:"Edit",scope:"editor",binding:{key:"a",modifiers:{ctrl:!0}}},{id:"edit.duplicate",label:"Duplicate",group:"Edit",scope:"editor",binding:{key:"d",modifiers:{ctrl:!0}}},{id:"view.zoomIn",label:"Zoom In",group:"View",scope:"global",binding:{key:"=",modifiers:{ctrl:!0}}},{id:"view.zoomOut",label:"Zoom Out",group:"View",scope:"global",binding:{key:"-",modifiers:{ctrl:!0}}},{id:"view.zoomFit",label:"Zoom to Fit",group:"View",scope:"global",binding:{key:"0",modifiers:{ctrl:!0}}},{id:"view.toggleMixer",label:"Toggle Mixer",group:"View",scope:"global",binding:{key:"m"}},{id:"view.togglePianoRoll",label:"Toggle Piano Roll",group:"View",scope:"global",binding:{key:"p"}},{id:"pianoRoll.quantize",label:"Quantize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"q"}},{id:"pianoRoll.humanize",label:"Humanize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"h"}},{id:"pianoRoll.velocityUp",label:"Velocity +10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{shift:!0}}},{id:"pianoRoll.velocityDown",label:"Velocity -10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{shift:!0}}},{id:"pianoRoll.octaveUp",label:"Octave Up",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{ctrl:!0,shift:!0}}},{id:"pianoRoll.octaveDown",label:"Octave Down",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{ctrl:!0,shift:!0}}},{id:"timeline.split",label:"Split at Cursor",group:"Timeline",scope:"timeline",binding:{key:"s"}},{id:"timeline.mute",label:"Mute Track",group:"Timeline",scope:"timeline",binding:{key:"m",modifiers:{ctrl:!0}}},{id:"timeline.solo",label:"Solo Track",group:"Timeline",scope:"timeline",binding:{key:"s",modifiers:{ctrl:!0}}},{id:"timeline.addTrack",label:"Add Track",group:"Timeline",scope:"timeline",binding:{key:"t",modifiers:{ctrl:!0}}},{id:"mixer.resetFader",label:"Reset Fader",group:"Mixer",scope:"mixer",binding:{key:"0"}},{id:"mixer.bypassFx",label:"Bypass All FX",group:"Mixer",scope:"mixer",binding:{key:"b"}}];for(const s of a)t.register({...s,callback:e[s.id]??n});return t}function xg(e){return Cr(e)}const Sg=["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"],kg=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],wg=500*1024*1024,Cg=20;function Bt(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function jg(e,t){return!!(e.type&&t.some(n=>e.type.startsWith(n.replace("*","")))||e.type.startsWith("audio/"))}function Mg(e,t){const n=Bt(e.name);return n!==""&&t.includes(n)}function ds(e,t={}){const n=t.maxSize??wg,a=t.allowedTypes??Sg,s=t.allowedExtensions??kg,i=t.maxFiles??Cg,o=[],l=[];for(let c=0;c<e.length;c++){const d=e[c];if(c>=i){l.push({file:d,reason:"limit",message:`Exceeded maximum of ${i} files`});continue}if(d.size>n){l.push({file:d,reason:"size",message:`File exceeds ${Math.round(n/1024/1024)}MB limit`});continue}if(!jg(d,a)&&!Mg(d,s)){l.push({file:d,reason:"type",message:`Unsupported file type: ${d.type||Bt(d.name)}`});continue}o.push(d)}return{valid:o,errors:l}}async function bc(e){const t={file:e,name:e.name.replace(/\.[^.]+$/,""),extension:Bt(e.name),sizeBytes:e.size,mimeType:e.type||`audio/${Bt(e.name)}`};try{const n=await e.arrayBuffer(),s=await new OfflineAudioContext(1,1,44100).decodeAudioData(n);t.duration=s.duration,t.sampleRate=s.sampleRate,t.channels=s.numberOfChannels}catch{}return t}function Rg(e){let t=0;return{onDragEnter:n=>{var a;n.preventDefault(),n.stopPropagation(),t++,t===1&&((a=e.onDragEnter)==null||a.call(e))},onDragOver:n=>{n.preventDefault(),n.stopPropagation(),(n instanceof DragEvent&&n.dataTransfer||"dataTransfer"in n&&n.dataTransfer)&&(n.dataTransfer.dropEffect="copy")},onDragLeave:n=>{var a;n.preventDefault(),n.stopPropagation(),t--,t===0&&((a=e.onDragLeave)==null||a.call(e))},onDrop:async n=>{var d,h;n.preventDefault(),n.stopPropagation(),t=0,(d=e.onDragLeave)==null||d.call(e);const a="dataTransfer"in n?n.dataTransfer:null;if(!((h=a==null?void 0:a.files)!=null&&h.length))return;const s=Array.from(a.files),{valid:i,errors:o}=ds(s,e.validation),l=[],c=[...o];for(const p of i)if(e.probe)try{l.push(await bc(p))}catch{c.push({file:p,reason:"decode",message:"Failed to decode audio"})}else l.push({file:p,name:p.name.replace(/\.[^.]+$/,""),extension:Bt(p.name),sizeBytes:p.size,mimeType:p.type||`audio/${Bt(p.name)}`});e.onDrop({accepted:l,rejected:c})}}}function Ng(e={}){return new Promise(t=>{const n=document.createElement("input");n.type="file",n.accept="audio/*,.mid,.midi",n.multiple=e.multiple??!0,n.onchange=async()=>{var l;if(!((l=n.files)!=null&&l.length)){t({accepted:[],rejected:[]});return}const a=Array.from(n.files),{valid:s,errors:i}=ds(a,e.validation),o=s.map(c=>({file:c,name:c.name.replace(/\.[^.]+$/,""),extension:Bt(c.name),sizeBytes:c.size,mimeType:c.type||`audio/${Bt(c.name)}`}));t({accepted:o,rejected:i})},n.click()})}var Ft=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(Ft||{}),xc=(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))(xc||{}),Sc=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(Sc||{});const Tg=["var(--nice-success, #4caf50)","var(--nice-primary, #2196f3)","var(--nice-warning, #ff9800)","var(--nice-color-accent-pink, #e91e63)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-success, #8bc34a)","var(--nice-warning, #ffc107)"],Lr=["off","no function","brak"],Pg=e=>e.segments.some(t=>t.isOff||Lr.some(n=>t.name.toLowerCase().includes(n))),$g=e=>e.segments.find(t=>t.isOff||Lr.some(n=>t.name.toLowerCase().includes(n))),kc=e=>Math.floor((e.valueFrom+e.valueTo)/2),Eg=e=>{const t=$g(e);return t?kc(t):0},Ag=(e,t)=>e.segments.find(n=>t>=n.valueFrom&&t<=n.valueTo),Mn=(e,t=0,n=255)=>Math.max(t,Math.min(n,Math.round(e))),Vn=({channel:e,value:t,onChange:n,onCommit:a,showDirectionHint:s})=>{const[i,o]=u.useState(Mn(t)),l=u.useMemo(()=>Ag(e,i),[e,i]);u.useEffect(()=>o(Mn(t)),[t]);const c=d=>{const h=Mn(d);o(h),n(h),a==null||a(h)};return r.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:6},children:[r.jsxs("strong",{children:[e.channel,". ",e.name]}),s&&l&&r.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:l.name})]}),r.jsx("input",{type:"range",min:0,max:255,value:i,onChange:d=>{const h=Mn(Number(d.target.value));o(h),n(h)},onMouseUp:()=>a==null?void 0:a(i),onTouchEnd:()=>a==null?void 0:a(i),style:{width:"100%"}}),r.jsx("div",{style:{marginTop:6},children:r.jsx("input",{type:"number",min:0,max:255,value:i,onChange:d=>{const h=Mn(Number(d.target.value));o(h),n(h)},onBlur:()=>a==null?void 0:a(i),style:{width:80,padding:6,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:6}})}),Pg(e)&&r.jsx("button",{type:"button",onClick:()=>c(Eg(e)),style:{width:"100%",marginTop:8,padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)",cursor:"pointer"},children:"OFF"})]})},us=({channel:e,value:t,onChange:n,onCommit:a})=>{const s=u.useMemo(()=>{const o=[...e.segments];return o.sort((l,c)=>{const d=(l.isOff?-1:0)+(Lr.some(p=>l.name.toLowerCase().includes(p))?-1:0),h=(c.isOff?-1:0)+(Lr.some(p=>c.name.toLowerCase().includes(p))?-1:0);return d!==h?d-h:l.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),o},[e]),i=o=>{const l=kc(o);n(l),a==null||a(l)};return r.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[r.jsxs("strong",{children:[e.channel,". ",e.name]}),r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(120px, 1fr))",gap:8,marginTop:8,maxHeight:220,overflowY:"auto"},children:s.map((o,l)=>{const c=t>=o.valueFrom&&t<=o.valueTo;return r.jsx("button",{type:"button",onClick:()=>i(o),style:{padding:"8px 10px",borderRadius:8,border:c?"2px solid var(--nice-primary-hover, #2563eb)":"1px solid var(--nice-border, #d1d5db)",background:c?"var(--nice-primary-bg, #eff6ff)":"var(--nice-bg, #fff)",textAlign:"left",cursor:"pointer",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:`${o.name} [${o.valueFrom}..${o.valueTo}]`,children:o.name},`${o.name}-${l}`)})})]})},hs=e=>{switch(e.channel.type){case Ft.Dimmer:case Ft.DimmerWithOff:return r.jsx(Vn,{...e});case Ft.RotationWithOff:case Ft.RotationWithOffAndCcw:return r.jsx(Vn,{...e,showDirectionHint:!0});case Ft.Options:return r.jsx(us,{...e});default:return r.jsx(Vn,{...e})}},oa=e=>Math.max(0,Math.min(255,Math.round(e))),Ig=[{target:".ntd-dmx-editor",titleKey:"tutorial.dmxEditor.intro.title",title:"DMX editor",contentKey:"tutorial.dmxEditor.intro.content",content:"Pick the FTDI device and port, then set each DMX channel’s value with the sliders to control your lighting fixtures live.",placement:"auto"}];function wc({service:e,...t}){return e?r.jsx(Lg,{service:e,...t}):r.jsx("div",{className:t.className,style:t.style,children:r.jsx("small",{children:"Provide a `service` prop (DmxService) to control hardware."})})}function Lg({service:e,pollInterval:t=500,className:n,style:a,tutorial:s}){const{t:i}=be(),[o,l]=u.useState([]),[c,d]=u.useState(null),[h,p]=u.useState(()=>Array(513).fill(0)),[g,y]=u.useState(30),[m,x]=u.useState(0),[v,f]=u.useState(!1),k=u.useRef(null);u.useEffect(()=>{let A=!1;return e.getDevices().then(z=>{A||(l(z),z.length>0&&d(z[0]))}).catch(()=>{}),()=>{A=!0}},[e]),u.useEffect(()=>{if(k.current&&window.clearInterval(k.current),!(t<=0))return k.current=window.setInterval(async()=>{try{const A=await e.getState();Array.isArray(A.frontSnapshot)&&A.frontSnapshot.length>=513&&p(A.frontSnapshot.slice(0,513)),typeof A.fps=="number"&&y(A.fps),typeof A.startCode=="number"&&x(A.startCode)}catch{}},t),()=>{k.current&&window.clearInterval(k.current)}},[e,t]);const b=async()=>{c&&(await e.openPort(c.serialNumber||c.description),f(!0))},w=async()=>{await e.closePort(),f(!1)},N=async()=>{await e.blackout(),p(A=>{const z=[...A];for(let j=1;j<z.length;j++)z[j]=0;return z})},$=()=>e.configure(g,m),M=(A,z)=>{const j=oa(z);p(I=>{const Y=[...I];return Y[A]=j,Y})},E=(A,z)=>e.setChannel(A,oa(z)),R=(c==null?void 0:c.deviceInfo)??null,L=u.useMemo(()=>{var A;return(A=R==null?void 0:R.channels)!=null&&A.length?R.channels:Array.from({length:16},(z,j)=>({channel:j+1,name:`Channel ${j+1}`,type:Ft.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[R]);return r.jsxs("div",{className:`ntd-dmx-editor ${n??""}`,style:{position:"relative",padding:16,display:"grid",gap:16,...a},children:[r.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:r.jsx(we.NiceTutorialButton,{steps:we.resolveTutorial(s,Ig)})}),r.jsxs("section",{style:{display:"grid",gap:12,gridTemplateColumns:"1fr auto auto auto",alignItems:"end"},children:[r.jsxs("div",{children:[r.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:i("dmxEditor.ftdiDevice","FTDI Device")}),r.jsx("select",{value:(c==null?void 0:c.serialNumber)||"",onChange:A=>d(o.find(z=>z.serialNumber===A.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"},children:o.map(A=>{var z,j;return r.jsxs("option",{value:A.serialNumber,children:[((z=A.deviceInfo)==null?void 0:z.manufacturer)??""," ",((j=A.deviceInfo)==null?void 0:j.model)??A.description," (",A.serialNumber||A.description,")"]},A.serialNumber||A.description)})}),R&&r.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:["Mode: ",r.jsx("b",{children:R.modeName}),", footprint: ",r.jsx("b",{children:R.footprint})]})]}),r.jsx("button",{onClick:b,disabled:!c||v,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-success, #10b981)",background:"var(--nice-success-bg, #ecfdf5)",cursor:"pointer"},children:i("dmxEditor.openPort","Open port")}),r.jsx("button",{onClick:w,disabled:!v,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-danger, #ef4444)",background:"var(--nice-danger-bg, #fef2f2)",cursor:"pointer"},children:i("dmxEditor.closePort","Close port")}),r.jsx("button",{onClick:N,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-border-color, #4b5563)",background:"var(--nice-bg-secondary, #f3f4f6)",cursor:"pointer"},children:i("dmxEditor.blackout","Blackout")})]}),r.jsxs("section",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(160px, 100%), 1fr))",gap:12,alignItems:"end"},children:[r.jsxs("div",{children:[r.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FPS"}),r.jsx("input",{type:"number",min:10,max:44,value:g,onChange:A=>y(Number(A.target.value)),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),r.jsxs("div",{children:[r.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:i("dmxEditor.startCode","Start Code")}),r.jsx("input",{type:"number",min:0,max:255,value:m,onChange:A=>x(oa(Number(A.target.value))),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),r.jsx("div",{children:r.jsx("button",{onClick:$,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-primary, #3b82f6)",background:"var(--nice-primary-bg, #eff6ff)",cursor:"pointer"},children:i("dmxEditor.applyConfiguration","Apply configuration")})})]}),r.jsxs("section",{children:[r.jsx("h3",{style:{margin:"8px 0 12px",fontSize:16},children:i("dmxEditor.channels","Channels")}),r.jsx("div",{style:{display:"grid",gap:12,gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))"},children:L.map(A=>r.jsx(hs,{channel:A,value:h[A.channel]??0,onChange:z=>M(A.channel,z),onCommit:z=>E(A.channel,z)},A.channel))})]})]})}const Cc=[{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 jc{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,Cc.forEach(t=>this.profiles.set(t.id,t)),this.createUniverse(1,"Universe 1")}createUniverse(t,n){const a={id:String(t),name:n,channels:new Uint8Array(512)};return this.universes.set(t,a),a}getUniverse(t){return this.universes.get(t)}addFixture(t){this.fixtures.set(t.id,t)}removeFixture(t){this.fixtures.delete(t)}getFixture(t){return this.fixtures.get(t)}getAllFixtures(){return Array.from(this.fixtures.values())}getProfile(t){return this.profiles.get(t)}registerProfile(t){this.profiles.set(t.id,t)}setChannel(t,n,a){const s=this.universes.get(t);s&&n>=1&&n<=512&&(s.channels[n-1]=Math.max(0,Math.min(255,a)))}getChannel(t,n){const a=this.universes.get(t);return a&&n>=1&&n<=512?a.channels[n-1]:0}setFixtureValues(t,n){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);if(s)for(let i=0;i<Math.min(n.length,s.channelCount);i++)a.values[i]=n[i],this.setChannel(a.universe,a.startChannel+i,n[i])}setFixtureColor(t,n,a,s,i=0){const o=this.fixtures.get(t);if(!o)return;const l=this.profiles.get(o.profileId);if(!l)return;const c=[...o.values];l.channels.forEach((d,h)=>{d.name.toLowerCase().includes("red")?c[h]=n:d.name.toLowerCase().includes("green")?c[h]=a:d.name.toLowerCase().includes("blue")?c[h]=s:d.name.toLowerCase().includes("white")&&(c[h]=i)}),this.setFixtureValues(t,c)}setFixtureDimmer(t,n){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);s&&s.channels.forEach((i,o)=>{i.type==="dimmer"&&(a.values[o]=Math.max(0,Math.min(255,Math.round(n*255))),this.setChannel(a.universe,a.startChannel+o,a.values[o]))})}fadeFixture(t,n,a,s="linear"){return new Promise(i=>{const o=this.fixtures.get(t);if(!o){i();return}const l=[...o.values],c=performance.now(),d=()=>{const h=performance.now()-c,p=Math.min(1,h/a);let g=p;switch(s){case"ease-in":g=p*p;break;case"ease-out":g=1-(1-p)*(1-p);break;case"ease-in-out":g=p<.5?2*p*p:1-Math.pow(-2*p+2,2)/2;break}const y=l.map((m,x)=>{const v=n[x]??m;return Math.round(m+(v-m)*g)});this.setFixtureValues(t,y),p<1?requestAnimationFrame(d):i()};d()})}setOutputCallback(t){this.outputCallback=t}start(){this.running||(this.running=!0,this.intervalId=window.setInterval(()=>{this.sendOutput()},1e3/this.frameRate))}stop(){this.running=!1,this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null)}sendOutput(){this.outputCallback&&this.universes.forEach((t,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 _g=6454,zg=new Uint8Array([65,114,116,45,78,101,116,0]);function Dg(e,t){const n=new Uint8Array(18+t.length);return n.set(zg,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 Fg=5568;function Og(e,t,n,a=100,s="Nice2Dev DMX"){const i=Math.min(t.length,512),o=126+i,l=new Uint8Array(o),c=new DataView(l.buffer);c.setUint16(0,16,!1),c.setUint16(2,0,!1);const d=[65,83,67,45,69,49,46,49,55,0,0,0];for(let m=0;m<d.length;m++)l[4+m]=d[m];const h=o-16;c.setUint16(16,28672|h&4095,!1),c.setUint32(18,4,!1);for(let m=0;m<16;m++)l[22+m]=m+1;const p=o-38;c.setUint16(38,28672|p&4095,!1),c.setUint32(40,2,!1);const g=new TextEncoder().encode(s.slice(0,63));l.set(g,44),l[108]=a,c.setUint16(109,0,!1),l[111]=n&255,l[112]=0,c.setUint16(113,e,!1);const y=i+11;return c.setUint16(115,28672|y&4095,!1),l[117]=2,l[118]=161,c.setUint16(119,0,!1),c.setUint16(121,1,!1),c.setUint16(123,i+1,!1),l[125]=0,l.set(t.slice(0,i),126),l}function Bg(e){const t=e>>8&255,n=e&255;return`239.255.${t}.${n}`}class Gg{constructor(t,n){this.config=t,this.scenes=n,this.currentStep=0,this.direction=1,this.isRunning=!1,this.timer=null,this.fadeStartTime=0,this.fadeFromValues=new Uint8Array(512),this.fadeToValues=new Uint8Array(512),this.onOutput=null}setOutputCallback(t){this.onOutput=t}start(){this.isRunning||(this.isRunning=!0,this.currentStep=this.config.direction==="backward"?this.config.steps.length-1:0,this.direction=this.config.direction==="backward"?-1:1,this.executeStep())}stop(){this.isRunning=!1,this.timer&&(clearTimeout(this.timer),this.timer=null)}executeStep(){var o;if(!this.isRunning)return;const t=this.config.steps[this.currentStep];if(!t)return;const n=this.scenes.get(t.sceneId);if(!n){this.advanceStep();return}const a=new Uint8Array(512);if(n.channels)for(const l of n.channels)l.channel>=1&&l.channel<=512&&(a[l.channel-1]=l.value);this.fadeFromValues.set(this.fadeToValues),this.fadeToValues.set(a),this.fadeStartTime=performance.now();const s=t.fadeTime/this.config.speed,i=t.holdTime/this.config.speed;s>0?this.runFade(s,()=>{var l;(l=this.onOutput)==null||l.call(this,this.fadeToValues),this.timer=setTimeout(()=>this.advanceStep(),i)}):((o=this.onOutput)==null||o.call(this,a),this.timer=setTimeout(()=>this.advanceStep(),i))}runFade(t,n){const a=performance.now(),s=new Uint8Array(512),i=()=>{var c;if(!this.isRunning)return;const o=performance.now()-a,l=Math.min(o/t,1);for(let d=0;d<512;d++)s[d]=Math.round(this.fadeFromValues[d]+(this.fadeToValues[d]-this.fadeFromValues[d])*l);(c=this.onOutput)==null||c.call(this,s),l<1?requestAnimationFrame(i):n()};requestAnimationFrame(i)}advanceStep(){if(!this.isRunning)return;const{steps:t,loop:n,direction:a}=this.config;if(this.currentStep+=this.direction,a==="bounce"){if(this.currentStep>=t.length?(this.direction=-1,this.currentStep=t.length-2):this.currentStep<0&&(this.direction=1,this.currentStep=1),this.currentStep<0||this.currentStep>=t.length){if(!n){this.stop();return}this.currentStep=0,this.direction=1}}else if(this.currentStep>=t.length||this.currentStep<0){if(!n){this.stop();return}this.currentStep=a==="backward"?t.length-1:0}this.executeStep()}}const Wg=({engine:e,tracks:t=[],scenes:n=[],duration:a=3e5,currentTime:s=0,bpm:i=120,onTimeChange:o,onCueAdd:l,onCueUpdate:c,onCueDelete:d,onTrackAdd:h,onTrackUpdate:p,onPlay:g,onPause:y,onStop:m,className:x=""})=>{const{t:v}=be(),[f,k]=u.useState(1),[b,w]=u.useState(0),[N,$]=u.useState(!1),[M,E]=u.useState(null),[R,L]=u.useState(null),[A,z]=u.useState(!0),[j,I]=u.useState(1e3),Y=u.useRef(null),H=u.useRef(null),D=u.useRef(0),V=u.useMemo(()=>.1*f,[f]),Z=u.useCallback(P=>P*V,[V]),X=u.useCallback(P=>P/V,[V]),q=u.useCallback(P=>{if(!A)return P;const B=6e4/i;return Math.round(P/B)*B},[A,i]);u.useEffect(()=>{if(N){const P=performance.now(),B=s,_=()=>{const U=performance.now()-P,J=B+U;if(J>=a){$(!1),o==null||o(0),m==null||m();return}G(J),o==null||o(J),H.current=requestAnimationFrame(_)};H.current=requestAnimationFrame(_),g==null||g()}else H.current!==null&&(cancelAnimationFrame(H.current),H.current=null),y==null||y();return()=>{H.current!==null&&cancelAnimationFrame(H.current)}},[N,s,a,o,g,y,m]);const G=u.useCallback(P=>{t.forEach(B=>{B.muted||B.cues.forEach(_=>{const U=_.startTime,J=U+_.duration;if(P>=U&&P<J&&D.current<U){const se=n.find(oe=>oe.id===_.sceneId);se&&se.fixtures.forEach(oe=>{_.fadeIn&&_.fadeIn>0?e.fadeFixture(oe.fixtureId,oe.values,_.fadeIn):e.setFixtureValues(oe.fixtureId,oe.values)})}if(D.current<J&&P>=J){const se=n.find(oe=>oe.id===_.sceneId);se&&se.fixtures.forEach(oe=>{if(e.getFixture(oe.fixtureId)&&_.fadeOut&&_.fadeOut>0){const W=new Array(oe.values.length).fill(0);e.fadeFixture(oe.fixtureId,W,_.fadeOut)}})}})}),D.current=P},[t,n,e]),C=P=>{const B=Math.floor(P/1e3),_=Math.floor(B/60),U=B%60,J=Math.floor(P%1e3/(1e3/30));return`${_}:${U.toString().padStart(2,"0")}:${J.toString().padStart(2,"0")}`},T=u.useCallback(P=>{if(!Y.current)return;const B=Y.current.getBoundingClientRect(),_=P.clientX-B.left+b,U=q(X(_));o==null||o(Math.max(0,Math.min(a,U)))},[b,X,q,a,o]),S=u.useCallback((P,B,_)=>{const U=t.find(oe=>oe.id===B),J=U==null?void 0:U.cues.find(oe=>oe.id===P);if(!J)return;const se=q(Math.max(0,J.startTime+X(_)));c==null||c({...J,startTime:se})},[t,X,q,c]),F=()=>{const P=6e4/i,B=Math.ceil(a/P),_=[];for(let U=0;U<=B;U++){const J=U*P,se=Z(J),oe=U%4===0;_.push(r.jsx("div",{className:`nice-dmx-timeline__beat ${oe?"nice-dmx-timeline__beat--measure":""}`,style:{left:se},children:oe&&r.jsx("span",{className:"nice-dmx-timeline__beat-label",children:U/4+1})},U))}return _},K=(P,B)=>{const _=Z(P.startTime),U=Z(P.duration),J=n.find(se=>se.id===P.sceneId);return r.jsxs("div",{className:`nice-dmx-timeline__cue ${M===P.id?"nice-dmx-timeline__cue--selected":""}`,style:{left:_,width:U,backgroundColor:(J==null?void 0:J.color)||B.color||"var(--nice-accent, #8b5cf6)"},onClick:se=>{se.stopPropagation(),E(P.id)},draggable:!B.locked,onDragEnd:se=>{var re;const oe=(re=se.target.parentElement)==null?void 0:re.getBoundingClientRect();oe&&S(P.id,B.id,se.clientX-oe.left-_)},children:[r.jsx("span",{className:"nice-dmx-timeline__cue-name",children:P.name||(J==null?void 0:J.name)}),P.fadeIn&&P.fadeIn>0&&r.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--in",style:{width:Z(P.fadeIn)}}),P.fadeOut&&P.fadeOut>0&&r.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--out",style:{width:Z(P.fadeOut)}})]},P.id)};return r.jsxs("div",{className:`nice-dmx-timeline ${x}`,children:[r.jsxs("div",{className:"nice-dmx-timeline__toolbar",children:[r.jsxs("div",{className:"nice-dmx-timeline__transport",children:[r.jsx("button",{type:"button",onClick:()=>o==null?void 0:o(0),title:v("dmxTimeline.goToStart","Go to start"),"aria-label":v("dmxTimeline.goToStart","Go to start"),children:r.jsx(O.NtdSkipBack,{size:14})}),r.jsx("button",{type:"button",onClick:()=>$(!N),title:N?"Pause":"Play","aria-label":N?"Pause":"Play",children:N?r.jsx(O.NtdPause,{size:14}):r.jsx(O.NtdPlay,{size:14})}),r.jsx("button",{type:"button",onClick:()=>{$(!1),o==null||o(0),e.blackout(),m==null||m()},title:v("dmxTimeline.stop","Stop"),"aria-label":v("dmxTimeline.stop","Stop"),children:r.jsx(O.NtdStop,{size:14})})]}),r.jsx("div",{className:"nice-dmx-timeline__time",children:C(s)}),r.jsxs("div",{className:"nice-dmx-timeline__tools",children:[r.jsx("button",{type:"button",className:`nice-dmx-timeline__tool ${A?"nice-dmx-timeline__tool--active":""}`,onClick:()=>z(!A),title:v("dmxTimeline.snapToGrid","Snap to grid"),"aria-label":v("dmxTimeline.snapToGrid","Snap to grid"),children:r.jsx(O.NtdGrid,{size:14})}),r.jsx("button",{type:"button",onClick:()=>k(Math.max(.25,f-.25)),title:v("dmxTimeline.zoomOut","Zoom out"),children:"−"}),r.jsxs("span",{className:"nice-dmx-timeline__zoom",children:[Math.round(f*100),"%"]}),r.jsx("button",{type:"button",onClick:()=>k(Math.min(4,f+.25)),title:v("dmxTimeline.zoomIn","Zoom in"),children:"+"})]}),r.jsxs("div",{className:"nice-dmx-timeline__bpm",children:[r.jsx("label",{children:"BPM:"}),r.jsx("span",{children:i})]}),r.jsx("button",{type:"button",className:"nice-dmx-timeline__blackout",onClick:()=>e.blackout(),title:v("dmxTimeline.blackout","Blackout"),"aria-label":v("dmxTimeline.blackout","Blackout"),children:r.jsx(O.NtdMoon,{size:14})})]}),r.jsxs("div",{className:"nice-dmx-timeline__content",children:[r.jsxs("div",{className:"nice-dmx-timeline__headers",children:[t.map(P=>r.jsxs("div",{className:`nice-dmx-timeline__header ${R===P.id?"nice-dmx-timeline__header--selected":""}`,onClick:()=>L(P.id),children:[r.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:P.color||"var(--nice-accent, #8b5cf6)"}}),r.jsx("span",{className:"nice-dmx-timeline__track-name",children:P.name}),r.jsxs("div",{className:"nice-dmx-timeline__track-controls",children:[r.jsx("button",{type:"button",className:`nice-dmx-timeline__track-toggle ${P.muted?"nice-dmx-timeline__track-toggle--active":""}`,onClick:B=>{B.stopPropagation(),p==null||p({...P,muted:!P.muted})},title:v("dmxTimeline.mute","Mute"),children:"M"}),r.jsx("button",{type:"button",className:`nice-dmx-timeline__track-toggle ${P.locked?"nice-dmx-timeline__track-toggle--active":""}`,onClick:B=>{B.stopPropagation(),p==null||p({...P,locked:!P.locked})},title:v("dmxTimeline.lock","Lock"),"aria-label":v("dmxTimeline.lock","Lock"),children:r.jsx(O.NtdLock,{size:14})})]})]},P.id)),r.jsx("button",{type:"button",className:"nice-dmx-timeline__add-track",onClick:()=>{h==null||h({id:`track-${Date.now()}`,name:`Track ${t.length+1}`,fixtureIds:[],cues:[]})},children:"+ Add Track"})]}),r.jsxs("div",{className:"nice-dmx-timeline__tracks",ref:Y,onClick:T,onScroll:P=>w(P.currentTarget.scrollLeft),children:[r.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:Z(a)},children:F()}),t.map(P=>r.jsx("div",{className:`nice-dmx-timeline__track ${P.muted?"nice-dmx-timeline__track--muted":""}`,style:{width:Z(a)},children:P.cues.map(B=>K(B,P))},P.id)),r.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:Z(s)}})]})]})]})};function Vg(){const[e]=u.useState(()=>new jc);return u.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function Ug(e,t,n=120){const[a,s]=u.useState(0),i=u.useRef(0);return u.useEffect(()=>{if(!t)return;const o=60/n,l=()=>{const c=t.currentTime,d=Math.floor(c/o);d!==i.current&&(i.current=d,s(d))};return t.addEventListener("timeupdate",l),()=>t.removeEventListener("timeupdate",l)},[t,n]),{currentBeat:a}}const qg=[],Hg=[],Kg=[{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 Mc(){const[e,t]=u.useState(!1),[n,a]=u.useState(.8),[s,i]=u.useState(!1),[o,l]=u.useState(null),[c,d]=u.useState(null),[h,p]=u.useState(null),g=u.useRef(null),y=u.useRef(null),m=u.useRef(null),x=u.useRef(null),v=u.useRef([]),f=u.useRef(null),k=u.useRef(null),b=u.useCallback(()=>{if(y.current)return;const I=new AudioContext;y.current=I;const Y=I.createGain();Y.gain.value=n,x.current=Y;const H=I.createAnalyser();H.fftSize=256,f.current=H,Y.connect(H).connect(I.destination)},[]),w=u.useCallback(()=>{const I=g.current,Y=y.current,H=x.current;if(!I||!Y||!H||m.current)return;const D=Y.createMediaElementSource(I);m.current=D,v.current.length>0?(D.connect(v.current[0]),v.current[v.current.length-1].connect(H)):D.connect(H)},[]),N=u.useCallback(()=>{var Y;const I=g.current;!I||!k.current||(Yt(),b(),w(),((Y=y.current)==null?void 0:Y.state)==="suspended"&&y.current.resume(),I.play().catch(H=>d(String(H))))},[b,w]),$=u.useCallback(()=>{var I;(I=g.current)==null||I.pause()},[]),M=u.useCallback(()=>{e?$():N()},[e,N,$]),E=u.useCallback(I=>{const Y=Math.max(0,Math.min(1,I));a(Y),x.current&&(x.current.gain.value=Y),g.current&&(g.current.volume=Y)},[]),R=u.useCallback(I=>{k.current=I,d(null),l(null),i(!0),m.current&&(m.current.disconnect(),m.current=null),g.current||(g.current=new Audio,g.current.crossOrigin="anonymous",g.current.addEventListener("playing",()=>{t(!0),i(!1)}),g.current.addEventListener("pause",()=>t(!1)),g.current.addEventListener("waiting",()=>i(!0)),g.current.addEventListener("canplay",()=>i(!1)),g.current.addEventListener("error",()=>d("Failed to load stream"))),g.current.src=I.streamUrl,g.current.load(),l({genre:I.genre,bitrate:I.bitrate})},[]),L=u.useCallback(I=>{y.current||b();const H=y.current;v.current.forEach(V=>V.disconnect());const D=I.bands.map(V=>{const Z=H.createBiquadFilter();return Z.type="peaking",Z.frequency.value=V.frequency,Z.gain.value=V.gain,Z.Q.value=V.Q??1.4,Z});for(let V=0;V<D.length-1;V++)D[V].connect(D[V+1]);v.current=D,m.current&&x.current&&(m.current.disconnect(),m.current.connect(D[0]),D[D.length-1].connect(x.current)),p(I.name)},[b]),A=u.useCallback(()=>{v.current.forEach(I=>I.disconnect()),v.current=[],m.current&&x.current&&(m.current.disconnect(),m.current.connect(x.current)),p(null)},[]);return u.useEffect(()=>()=>{var I,Y,H;(I=g.current)==null||I.pause(),g.current=null,v.current.forEach(D=>D.disconnect()),(Y=m.current)==null||Y.disconnect(),(H=y.current)==null||H.close()},[]),[{isPlaying:e,volume:n,isBuffering:s,metadata:o,error:c,activePreset:h},{play:N,pause:$,toggle:M,setVolume:E,setStation:R,applyEQPreset:L,clearEQ:A}]}function Rc({stations:e=qg,activeStationId:t,onSelect:n,onToggleFavorite:a,className:s}){const{t:i}=be(),[o,l]=u.useState(""),[c,d]=u.useState(null),[h,p]=u.useState(!1),g=u.useMemo(()=>[...new Set(e.map(m=>m.genre).filter(Boolean))],[e]),y=u.useMemo(()=>e.filter(m=>{var x,v;if(h&&!m.isFavorite||c&&m.genre!==c)return!1;if(o){const f=o.toLowerCase();return m.name.toLowerCase().includes(f)||(((x=m.genre)==null?void 0:x.toLowerCase().includes(f))??!1)||(((v=m.country)==null?void 0:v.toLowerCase().includes(f))??!1)}return!0}),[e,o,c,h]);return r.jsxs("div",{className:`nice-station-browser${s?` ${s}`:""}`,children:[r.jsxs("div",{className:"nice-station-browser__toolbar",children:[r.jsx("input",{type:"text",className:"nice-station-browser__search",placeholder:i("radioPlayer.searchStations","Search stations…"),value:o,onChange:m=>l(m.target.value)}),r.jsxs("select",{className:"nice-station-browser__genre-filter",value:c??"",onChange:m=>d(m.target.value||null),children:[r.jsx("option",{value:"",children:i("radioPlayer.allGenres","All Genres")}),g.map(m=>r.jsx("option",{value:m,children:m},m))]}),r.jsx("button",{className:`nice-station-browser__fav-toggle${h?" nice-station-browser__fav-toggle--active":""}`,onClick:()=>p(!h),title:i("radioPlayer.favorites","Favorites"),"aria-label":i("radioPlayer.favorites","Favorites"),children:r.jsx(O.NtdStar,{size:14,style:{color:"var(--nice-warning, #facc15)"}})})]}),r.jsxs("div",{className:"nice-station-browser__list",children:[y.map(m=>r.jsxs("div",{className:`nice-station-browser__item${m.id===t?" nice-station-browser__item--active":""}`,onClick:()=>n(m),role:"button",tabIndex:0,onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&n(m)},children:[m.logoUrl&&r.jsx("img",{className:"nice-station-browser__logo",src:m.logoUrl,alt:m.name,loading:"lazy"}),r.jsxs("div",{className:"nice-station-browser__info",children:[r.jsx("span",{className:"nice-station-browser__name",children:m.name}),m.genre&&r.jsx("span",{className:"nice-station-browser__genre",children:m.genre}),m.country&&r.jsx("span",{className:"nice-station-browser__country",children:m.country})]}),m.bitrate&&r.jsxs("span",{className:"nice-station-browser__bitrate",children:[m.bitrate,"kbps"]}),a&&r.jsx("button",{className:`nice-station-browser__fav${m.isFavorite?" nice-station-browser__fav--active":""}`,onClick:x=>{x.stopPropagation(),a(m.id)},"aria-label":i("radioPlayer.favorites","Favorites"),children:r.jsx(O.NtdStar,{size:14,style:{color:m.isFavorite?"var(--nice-warning, #facc15)":"var(--nice-text-muted)"}})})]},m.id)),y.length===0&&r.jsx("div",{className:"nice-station-browser__empty",children:i("radioPlayer.noStationsFound","No stations found")})]})]})}function Yg({stations:e=Hg,initialStationId:t,autoPlay:n=!1,eqPresets:a=Kg,onStationChange:s,onPlayingChange:i,onMetadata:o,onToggleFavorite:l,onRecordingStart:c,onRecordingStop:d,showBrowser:h=!0,showEqualizer:p=!1,showVisualizer:g=!1,showMetadataHistory:y=!1,showRecording:m=!1,showSleepTimer:x=!1,className:v,style:f}){var F,K;const{t:k}=be(),[b,w]=Mc(),[N,$]=u.useState(()=>t?e.find(P=>P.id===t)??null:null),[M,E]=u.useState(p),R=u.useRef(null),L=u.useRef(0),[A,z]=u.useState([]),[j,I]=u.useState(!1),Y=u.useRef(null),H=u.useRef([]),[D,V]=u.useState(0),Z=u.useRef(null),[X,q]=u.useState(0),[G,C]=u.useState(null),T=u.useRef(null);u.useEffect(()=>{i==null||i(b.isPlaying)},[b.isPlaying,i]),u.useEffect(()=>{b.metadata&&(o==null||o(b.metadata),(b.metadata.title||b.metadata.artist)&&z(P=>[{time:new Date,meta:b.metadata},...P.slice(0,49)]))},[b.metadata,o]);const S=u.useCallback(P=>{$(P),w.setStation(P),s==null||s(P),n&&setTimeout(()=>w.play(),100)},[w,s,n]);return u.useEffect(()=>{if(t&&!N){const P=e.find(B=>B.id===t);P&&S(P)}},[t,e]),u.useEffect(()=>{if(!g||!R.current)return;const P=R.current,B=P.getContext("2d");if(!B)return;const _=()=>{L.current=requestAnimationFrame(_),B.clearRect(0,0,P.width,P.height);const U=B.createLinearGradient(0,P.height,0,0);if(U.addColorStop(0,we.resolveCssColor("var(--nice-accent-tint-80, rgba(99, 102, 241, 0.8))",B.canvas)),U.addColorStop(.5,we.resolveCssColor("var(--nice-accent-tint-50, rgba(168,85,247,0.6))",B.canvas)),U.addColorStop(1,"rgba(236,72,153,0.4)"),!b.isPlaying){const re=P.width/32;for(let W=0;W<32;W++){const ee=4+Math.sin(Date.now()/1e3+W*.3)*3;B.fillStyle=U,B.fillRect(W*re+1,P.height-ee,re-2,ee)}return}const J=32,se=P.width/J;for(let oe=0;oe<J;oe++){const re=oe/J,ee=(Math.sin(Date.now()/200+oe*.5)*.3+.5)*P.height*(1-re*.5)*(.5+Math.random()*.5);B.fillStyle=U,B.fillRect(oe*se+1,P.height-ee,se-2,ee)}};return _(),()=>cancelAnimationFrame(L.current)},[g,b.isPlaying]),u.useCallback(()=>{if(b.isPlaying)try{const B=new AudioContext().createMediaStreamDestination();H.current=[];const _=new MediaRecorder(B.stream,{mimeType:"audio/webm"});_.ondataavailable=U=>{U.data.size>0&&H.current.push(U.data)},_.onstop=()=>{const U=new Blob(H.current,{type:"audio/webm"});d==null||d(U),V(0),Z.current&&window.clearInterval(Z.current)},_.start(1e3),Y.current=_,I(!0),V(0),Z.current=window.setInterval(()=>{V(U=>U+1)},1e3),c==null||c()}catch{}},[b.isPlaying,c,d]),u.useCallback(()=>{Y.current&&j&&(Y.current.stop(),I(!1),Z.current&&window.clearInterval(Z.current))},[j]),u.useCallback(P=>{T.current&&window.clearInterval(T.current),q(P),C(P*60),T.current=window.setInterval(()=>{C(B=>!B||B<=1?(T.current&&window.clearInterval(T.current),T.current=null,w.pause(),null):B-1)},1e3)},[w]),u.useCallback(()=>{T.current&&window.clearInterval(T.current),T.current=null,C(null),q(0)},[]),u.useEffect(()=>()=>{Z.current&&window.clearInterval(Z.current),T.current&&window.clearInterval(T.current),cancelAnimationFrame(L.current)},[]),r.jsxs("div",{className:`nice-radio-player${v?` ${v}`:""}`,style:f,children:[r.jsx("div",{className:"nice-radio-player__now-playing",children:N?r.jsxs(r.Fragment,{children:[N.logoUrl&&r.jsx("img",{className:"nice-radio-player__cover",src:N.logoUrl,alt:N.name}),r.jsxs("div",{className:"nice-radio-player__info",children:[r.jsx("span",{className:"nice-radio-player__station-name",children:N.name}),((F=b.metadata)==null?void 0:F.title)&&r.jsx("span",{className:"nice-radio-player__track",children:b.metadata.artist?`${b.metadata.artist} — ${b.metadata.title}`:b.metadata.title}),((K=b.metadata)==null?void 0:K.genre)&&r.jsx("span",{className:"nice-radio-player__genre",children:b.metadata.genre}),b.isBuffering&&r.jsx("span",{className:"nice-radio-player__buffering",children:k("radioPlayer.buffering","Buffering…")})]})]}):r.jsx("div",{className:"nice-radio-player__placeholder",children:k("radioPlayer.selectStation","Select a station")})}),r.jsxs("div",{className:"nice-radio-player__controls",children:[r.jsx("button",{className:"nice-radio-player__play-btn",onClick:w.toggle,disabled:!N,"aria-label":b.isPlaying?"Pause":"Play",children:b.isPlaying?r.jsx(O.NtdPause,{size:16}):r.jsx(O.NtdPlay,{size:16})}),r.jsxs("div",{className:"nice-radio-player__volume",children:[r.jsx("span",{className:"nice-radio-player__volume-icon","aria-hidden":"true",children:r.jsx(O.NtdVolume,{size:16})}),r.jsx("input",{type:"range",min:0,max:1,step:.01,value:b.volume,onChange:P=>w.setVolume(parseFloat(P.target.value)),className:"nice-radio-player__volume-slider","aria-label":k("radioPlayer.volume","Volume")})]}),r.jsx("button",{className:`nice-radio-player__eq-btn${M?" nice-radio-player__eq-btn--active":""}`,onClick:()=>E(!M),title:k("radioPlayer.equalizer","Equalizer"),children:"EQ"})]}),b.error&&r.jsx("div",{className:"nice-radio-player__error",children:b.error}),M&&r.jsx("div",{className:"nice-radio-player__equalizer",children:r.jsxs("div",{className:"nice-radio-player__eq-presets",children:[a.map(P=>r.jsx("button",{className:`nice-radio-player__eq-preset${b.activePreset===P.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>w.applyEQPreset(P),children:P.name},P.name)),b.activePreset&&r.jsx("button",{className:"nice-radio-player__eq-preset",onClick:w.clearEQ,children:k("clear","Clear")})]})}),h&&r.jsx(Rc,{stations:e,activeStationId:N==null?void 0:N.id,onSelect:S})]})}const Zg=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],Xg={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class Nc{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??Zg,audioConstraints:{...Xg,echoCancellation:n.echoCancellation??!0,noiseSuppression:n.noiseSuppression??!0,autoGainControl:n.autoGainControl??!0}}}async initialize(){return this.localStream?this.localStream:(this.localStream=await navigator.mediaDevices.getUserMedia({audio:this.config.audioConstraints,video:!1}),this.localStream)}getLocalStream(){return this.localStream}getPeerIds(){return Array.from(this.peers.keys())}getPeerState(t){var n;return((n=this.peers.get(t))==null?void 0:n.state)??null}async createOffer(t){if(!this.localStream)throw new Error("WebRTCAudioManager not initialized. Call initialize() first.");const n=this.createPeerConnection(t),a=await n.createOffer();await n.setLocalDescription(a),this.sendSignalingMessage({type:"offer",from:this.localUserId,to:t,payload:a})}async handleSignalingMessage(t){if(t.to===this.localUserId)switch(t.type){case"offer":await this.handleOffer(t.from,t.payload);break;case"answer":await this.handleAnswer(t.from,t.payload);break;case"ice-candidate":await this.handleIceCandidate(t.from,t.payload);break;case"leave":this.removePeer(t.from);break}}removePeer(t){const n=this.peers.get(t);n&&(n.pc.close(),this.peers.delete(t))}disconnect(){for(const t of this.peers.keys())this.sendSignalingMessage({type:"leave",from:this.localUserId,to:t,payload:null});for(const t of this.peers.values())t.pc.close();this.peers.clear(),this.localStream&&(this.localStream.getTracks().forEach(t=>t.stop()),this.localStream=null)}setMuted(t){this.localStream&&this.localStream.getAudioTracks().forEach(n=>{n.enabled=!t})}isMuted(){if(!this.localStream)return!0;const t=this.localStream.getAudioTracks()[0];return t?!t.enabled:!0}createPeerConnection(t){const n=new RTCPeerConnection({iceServers:this.config.iceServers}),a={id:t,pc:n,remoteStream:null,state:n.connectionState};return this.peers.set(t,a),this.localStream&&this.localStream.getTracks().forEach(s=>{n.addTrack(s,this.localStream)}),n.onicecandidate=s=>{s.candidate&&this.sendSignalingMessage({type:"ice-candidate",from:this.localUserId,to:t,payload:s.candidate.toJSON()})},n.ontrack=s=>{var o;const[i]=s.streams;i&&(a.remoteStream=i,(o=this.onRemoteStream)==null||o.call(this,t,i))},n.onconnectionstatechange=()=>{var s;a.state=n.connectionState,(s=this.onPeerStateChange)==null||s.call(this,t,n.connectionState),(n.connectionState==="failed"||n.connectionState==="disconnected")&&this.removePeer(t)},n}async handleOffer(t,n){this.localStream||await this.initialize();const a=this.createPeerConnection(t);await a.setRemoteDescription(new RTCSessionDescription(n));const s=await a.createAnswer();await a.setLocalDescription(s),this.sendSignalingMessage({type:"answer",from:this.localUserId,to:t,payload:s})}async handleAnswer(t,n){const a=this.peers.get(t);a&&await a.pc.setRemoteDescription(new RTCSessionDescription(n))}async handleIceCandidate(t,n){const a=this.peers.get(t);a&&n&&await a.pc.addIceCandidate(new RTCIceCandidate(n))}sendSignalingMessage(t){var n;(n=this.onSignalingMessage)==null||n.call(this,t)}}function Qg(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function Jg(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function ey(){return new AudioContext({sampleRate:48e3,latencyHint:"interactive"})}const ps=u.forwardRef(function(t,n){const{t:a}=be(),{mode:s="bars",width:i=300,height:o=100,barCount:l=32,barColor:c="var(--nice-primary, #3b82f6)",backgroundColor:d="transparent",fftSize:h=256,smoothing:p=.8,minDecibels:g=-90,maxDecibels:y=-10,deviceId:m,autoStart:x=!1,onStart:v,onStop:f,onAudioLevel:k,onError:b,className:w,style:N,barBorderRadius:$=2,barGap:M=2,lineWidth:E=2}=t,R=u.useRef(null),L=u.useRef(null),A=u.useRef(null),z=u.useRef(null),j=u.useRef(0),I=u.useRef(null),Y=u.useRef(0),[H,D]=u.useState(!1),V=Array.isArray(c)?c.join("|"):c,Z=u.useMemo(()=>V.split("|").map(P=>we.resolveCssColor(P,R.current)),[V]),X=u.useCallback((P,B,_=!0)=>{const U=_?P.createLinearGradient(0,o,0,0):P.createLinearGradient(0,0,i,0);return B.forEach((J,se)=>{U.addColorStop(se/(B.length-1),J)}),U},[i,o]),q=u.useCallback((P,B)=>{const U=(i-(l-1)*M)/l,J=Math.floor(B.length/l),se=Z,oe=se.length>1?X(P,se):se[0];P.fillStyle=oe;for(let re=0;re<l;re++){const ee=B[re*J]/255*o,ae=re*(U+M),le=o-ee;$>0?(P.beginPath(),P.roundRect(ae,le,U,ee,$),P.fill()):P.fillRect(ae,le,U,ee)}},[l,Z,M,$,i,o,X]),G=u.useCallback((P,B)=>{const _=o/2,J=(i-(l-1)*M)/l,se=Math.floor(B.length/l),oe=Z,re=oe.length>1?X(P,oe):oe[0];P.fillStyle=re;for(let W=0;W<l;W++){const ae=B[W*se]/255*_,le=W*(J+M);$>0?(P.beginPath(),P.roundRect(le,_-ae,J,ae,$),P.fill(),P.beginPath(),P.roundRect(le,_,J,ae,$),P.fill()):(P.fillRect(le,_-ae,J,ae),P.fillRect(le,_,J,ae))}},[l,Z,M,$,i,o,X]),C=u.useCallback((P,B)=>{const _=Z;P.strokeStyle=_.length>1?X(P,_,!1):_[0],P.lineWidth=E,P.lineCap="round",P.lineJoin="round",P.beginPath();const U=i/B.length;let J=0;for(let se=0;se<B.length;se++){const re=B[se]/128*o/2;se===0?P.moveTo(J,re):P.lineTo(J,re),J+=U}P.stroke()},[Z,E,i,o,X]),T=u.useCallback((P,B)=>{const _=i/2,U=o/2,J=Math.min(i,o)/3,se=Z;P.strokeStyle=se.length>1?X(P,se):se[0],P.lineWidth=E;const oe=Math.floor(B.length/64),re=Math.PI*2/64;P.beginPath();for(let W=0;W<64;W++){const ee=B[W*oe]/255,ae=J+ee*J*.5,le=W*re-Math.PI/2,ce=_+Math.cos(le)*ae,te=U+Math.sin(le)*ae;W===0?P.moveTo(ce,te):P.lineTo(ce,te)}P.closePath(),P.stroke()},[Z,E,i,o,X]),S=u.useCallback(()=>{const P=R.current,B=A.current,_=I.current;if(!P||!B||!_)return;const U=P.getContext("2d");if(!U)return;s==="waveform"?B.getByteTimeDomainData(_):B.getByteFrequencyData(_);let J=0;for(let se=0;se<_.length;se++)J+=_[se];switch(Y.current=J/(_.length*255),k==null||k(Y.current),U.clearRect(0,0,i,o),d!=="transparent"&&(U.fillStyle=we.resolveCssColor(d,U.canvas),U.fillRect(0,0,i,o)),s){case"bars":q(U,_);break;case"mirror-bars":G(U,_);break;case"waveform":C(U,_);break;case"circle":T(U,_);break}j.current=requestAnimationFrame(S)},[s,i,o,d,q,G,C,T,k]),F=u.useCallback(async()=>{try{if(H)return;const P=await navigator.mediaDevices.getUserMedia({audio:m?{deviceId:{exact:m}}:!0,video:!1});z.current=P;const B=new AudioContext;L.current=B;const _=B.createMediaStreamSource(P),U=B.createAnalyser();U.fftSize=h,U.smoothingTimeConstant=p,U.minDecibels=g,U.maxDecibels=y,_.connect(U),A.current=U,I.current=new Uint8Array(U.frequencyBinCount),D(!0),v==null||v(),S()}catch(P){b==null||b(P instanceof Error?P:new Error(String(P)))}},[H,m,h,p,g,y,v,b,S]),K=u.useCallback(()=>{cancelAnimationFrame(j.current),z.current&&(z.current.getTracks().forEach(B=>B.stop()),z.current=null),L.current&&(L.current.close(),L.current=null),A.current=null,I.current=null,Y.current=0,D(!1),f==null||f();const P=R.current;if(P){const B=P.getContext("2d");B&&(B.clearRect(0,0,i,o),d!=="transparent"&&(B.fillStyle=we.resolveCssColor(d,B.canvas),B.fillRect(0,0,i,o)))}},[i,o,d,f]);return u.useImperativeHandle(n,()=>({start:F,stop:K,isCapturing:()=>H,getAudioLevel:()=>Y.current}),[F,K,H]),u.useEffect(()=>(x&&F(),()=>{K()}),[x]),r.jsx("canvas",{ref:R,width:i,height:o,className:w,style:{display:"block",...N},"aria-label":a("streamingVisualizer.audioVisualizer","Audio visualizer")})}),Ni=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}}},ty={position:"fixed",display:"flex",flexDirection:"column",gap:8,padding:12,borderRadius:12,boxShadow:"0 4px 20px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:14,minWidth:200,maxWidth:280,transition:"all 0.2s ease"},ny={background:"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",text:"var(--nice-overlay-85, rgba(0, 0, 0, 0.85))",textSecondary:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",border:"var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-bg, #fee2e2)",mutedIcon:"var(--nice-danger, #ef4444)",activeBg:"var(--nice-success-bg, #dcfce7)",activeIcon:"var(--nice-success, #22c55e)",hoverBg:"var(--nice-overlay-5, rgba(0, 0, 0, 0.05))"},ry={background:"var(--nice-overlay-90, rgba(30, 30, 30, 0.95))",text:"var(--nice-color-white, #fff)",textSecondary:"var(--nice-text-muted, #a0a0a0)",border:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-dark, #7f1d1d)",mutedIcon:"var(--nice-danger-light, #fca5a5)",activeBg:"var(--nice-success, #14532d)",activeIcon:"var(--nice-success-light, #86efac)",hoverBg:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))"},Tc=u.forwardRef(function(t,n){const{t:a}=be(),{userId:s,userName:i,userAvatarUrl:o,participants:l=[],rtcConfig:c,position:d="bottom-right",expanded:h=!0,onSignalingMessage:p,onMuteToggle:g,onLeave:y,onSpeakingChange:m,speakingThreshold:x=.1,theme:v="auto",className:f,style:k,zIndex:b=1e3}=t,w=u.useRef(null),N=u.useRef(null),$=u.useRef(new Map);u.useRef(new Map);const[M,E]=u.useState(!1),[R,L]=u.useState(!1),[A,z]=u.useState(!1),[j,I]=u.useState(h),H=u.useMemo(()=>v==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":v,[v])==="dark"?ry:ny;u.useEffect(()=>{const C=new Nc(s,c);return C.onRemoteStream=(T,S)=>{let F=$.current.get(T);F||(F=new Audio,F.autoplay=!0,$.current.set(T,F)),F.srcObject=S},C.onSignalingMessage=T=>{p==null||p(T)},C.onPeerStateChange=(T,S)=>{S==="connected"&&L(!0)},w.current=C,C.initialize().then(()=>{var T;(T=N.current)==null||T.start()}),()=>{C.disconnect();const T=$.current;T.forEach(S=>{S.srcObject=null}),T.clear()}},[s,c,p]);const D=u.useCallback(()=>{var T;const C=!M;E(C),(T=w.current)==null||T.setMuted(C),g==null||g(C)},[M,g]),V=u.useCallback(()=>{var C,T;(C=w.current)==null||C.disconnect(),(T=N.current)==null||T.stop(),L(!1),y==null||y()},[y]),Z=u.useCallback(C=>{const T=C>x;T!==A&&(z(T),m==null||m(s,T))},[x,A,s,m]),X=u.useCallback(async C=>{var T;await((T=w.current)==null?void 0:T.createOffer(C))},[]),q=u.useCallback(async C=>{var T;await((T=w.current)==null?void 0:T.handleSignalingMessage(C))},[]);u.useImperativeHandle(n,()=>({connectToPeer:X,handleSignalingMessage:q,toggleMute:D,isMuted:()=>M,leave:V,getManager:()=>w.current}),[X,q,D,M,V]);const G=({participant:C,isLocal:T,isSpeaking:S})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 0"},children:[r.jsx("div",{style:{width:32,height:32,borderRadius:"50%",backgroundColor:H.hoverBg,border:`2px solid ${S?H.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:H.text,transition:"border-color 0.15s ease"},children:C.avatarUrl?r.jsx("img",{src:C.avatarUrl,alt:C.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):C.name.charAt(0).toUpperCase()}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsxs("div",{style:{color:H.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[C.name,T&&r.jsx("span",{style:{color:H.textSecondary,fontWeight:400},children:" (You)"})]})}),C.isMuted&&r.jsx(O.NtdMicrophoneOff,{size:16,variant:"outline",primaryColor:H.mutedIcon})]});return j?r.jsxs("div",{className:f,style:{...ty,...Ni(d),backgroundColor:H.background,border:`1px solid ${H.border}`,zIndex:b,...k},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${H.border}`},children:[r.jsx("span",{style:{color:H.text,fontWeight:600},children:a("voiceChatOverlay.voiceChat","Voice Chat")}),r.jsx("button",{onClick:()=>I(!1),style:{background:"none",border:"none",cursor:"pointer",padding:4,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:4},"aria-label":a("voiceChatOverlay.collapse","Collapse"),children:r.jsx(O.NtdMinimize,{size:16,variant:"outline",primaryColor:H.textSecondary})})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[r.jsx(G,{participant:{id:s,name:i,avatarUrl:o,isMuted:M},isLocal:!0,isSpeaking:A&&!M}),l.map(C=>r.jsx(G,{participant:C,isSpeaking:C.isSpeaking},C.id))]}),r.jsx(ps,{ref:N,mode:"bars",width:256,height:32,barCount:24,barColor:M?"var(--nice-text-muted, #9ca3af)":["var(--nice-primary, #3b82f6)","var(--nice-accent, #8b5cf6)"],barGap:3,barBorderRadius:2,autoStart:!1,onAudioLevel:Z,style:{borderRadius:4,opacity:M?.5:1}}),r.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[r.jsx("button",{onClick:D,style:{flex:1,padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:M?H.mutedBg:H.activeBg,color:M?H.mutedIcon:H.activeIcon,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":M?"Unmute":"Mute",children:M?r.jsxs(r.Fragment,{children:[r.jsx(O.NtdMicrophoneOff,{size:16,variant:"outline"}),a("voiceChatOverlay.muted","Muted")]}):r.jsxs(r.Fragment,{children:[r.jsx(O.NtdMicrophone,{size:16,variant:"outline"}),a("voiceChatOverlay.micOn","Mic On")]})}),r.jsx("button",{onClick:V,style:{padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:"var(--nice-danger-bg, #fef2f2)",color:"var(--nice-danger-dark, #dc2626)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":a("voiceChatOverlay.leaveVoiceChat","Leave voice chat"),children:r.jsx(O.NtdLogOut,{size:16,variant:"outline"})})]})]}):r.jsx("div",{className:f,style:{position:"fixed",...Ni(d),zIndex:b,...k},children:r.jsxs("button",{onClick:()=>I(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:H.background,boxShadow:"0 4px 12px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":a("voiceChatOverlay.expandVoiceChat","Expand voice chat"),children:[r.jsx(O.NtdMicrophone,{size:24,variant:"outline",primaryColor:H.text}),l.length>0&&r.jsx("span",{style:{position:"absolute",top:-4,right:-4,width:20,height:20,borderRadius:"50%",backgroundColor:H.speakingRing,color:"var(--nice-color-white, #fff)",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:l.length+1})]})})});function ay(e,t){const n={...t,id:`op_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now()},a=e.operations.slice(0,e.undoIndex+1);return a.push(n),{...e,operations:a,undoIndex:a.length-1}}function sy(e){return e.undoIndex<0?e:{...e,undoIndex:e.undoIndex-1}}function iy(e){return e.undoIndex>=e.operations.length-1?e:{...e,undoIndex:e.undoIndex+1}}function oy(e,t,n){const s=({"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":.6666666666666666,"1/8T":.3333333333333333,"1/16T":.16666666666666666,"1/4D":1.5,"1/8D":.75}[t.grid]??1)*n,i=t.strength/100;return e.map(o=>{const l=Math.round(o.startTick/s)*s,c=o.startTick+(l-o.startTick)*i,d=(Math.random()-.5)*2*t.humanize;return{...o,startTick:Math.max(0,Math.round(c+d))}})}function ly(e){if(e.length<2)return null;const t=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],n=[...new Set(e.map(s=>s%12))].sort((s,i)=>s-i),a=[{intervals:[0,4,7],quality:"maj"},{intervals:[0,3,7],quality:"min"},{intervals:[0,4,7,11],quality:"maj7"},{intervals:[0,3,7,10],quality:"min7"},{intervals:[0,4,7,10],quality:"7"},{intervals:[0,3,6],quality:"dim"},{intervals:[0,4,8],quality:"aug"},{intervals:[0,3,6,9],quality:"dim7"},{intervals:[0,2,7],quality:"sus2"},{intervals:[0,5,7],quality:"sus4"},{intervals:[0,4,7,9],quality:"6"},{intervals:[0,3,7,9],quality:"min6"}];for(const s of n){const i=n.map(o=>(o-s+12)%12).sort((o,l)=>o-l);for(const o of a)if(o.intervals.length===i.length&&o.intervals.every((l,c)=>l===i[c])){const l=t[s],c=t[e[0]%12];return{root:l,quality:o.quality,bass:c!==l?c:void 0,symbol:`${l}${o.quality==="maj"?"":o.quality}${c!==l?`/${c}`:""}`,intervals:o.intervals}}}return null}const Pc={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 cy(e,t,n){const a=Pc[n],s=(e-t+120)%12;let i=a[0],o=999;for(const c of a){const d=Math.min(Math.abs(s-c),12-Math.abs(s-c));d<o&&(o=d,i=c)}const l=Math.floor((e-t)/12);return t+l*12+i}function dy(e,t){switch(t.type){case"transpose":return e.map(n=>({...n,pitch:Math.max(0,Math.min(127,n.pitch+(t.params.semitones??0)))}));case"invert":{const n=t.params.axis??60;return e.map(a=>({...a,pitch:Math.max(0,Math.min(127,Math.round(2*n-a.pitch)))}))}case"retrograde":{if(e.length===0)return e;const n=Math.max(...e.map(a=>a.startTick+a.durationTicks));return e.map(a=>({...a,startTick:n-a.startTick-a.durationTicks}))}case"randomize-velocity":return e.map(n=>({...n,velocity:Math.max(1,Math.min(127,n.velocity+Math.round((Math.random()-.5)*2*(t.params.range??20))))}));default:return e}}function uy(e){return e>=95?"S":e>=85?"A":e>=70?"B":e>=55?"C":e>=40?"D":"F"}const hy={"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]}},py={"Bass Drum":{staffLine:4,noteHead:"normal",stem:"down"},Snare:{staffLine:2,noteHead:"normal",stem:"up"},"Hi-Hat Closed":{staffLine:0,noteHead:"x",stem:"up"},"Hi-Hat Open":{staffLine:0,noteHead:"diamond",stem:"up"},Ride:{staffLine:-1,noteHead:"x",stem:"up"},Crash:{staffLine:-2,noteHead:"x",stem:"up"},"High Tom":{staffLine:1,noteHead:"normal",stem:"up"},"Mid Tom":{staffLine:2,noteHead:"normal",stem:"down"},"Low Tom":{staffLine:3,noteHead:"normal",stem:"down"}};exports.ALL_CAP_STYLES=Wn;exports.ALL_EFFECTS=_l;exports.ALL_TEXTURES=$o;exports.ARTNET_PORT=_g;exports.ASYMMETRIC_CAPS=ko;exports.AudioEffectType=xc;exports.AudioPlaybackEngine=h0;exports.AudioRecorder=La;exports.AutoSavePanel=Li;exports.CONTROLLER_PROFILES=Kl;exports.ChaseRunner=Gg;exports.CollaboratorPermission=Sc;exports.DEFAULT_ARP_CONFIG=ua;exports.DEFAULT_AUDIO_INPUT_SETTINGS=Dl;exports.DEFAULT_BAR_FILL=Gt;exports.DEFAULT_CAP_STYLE=Co;exports.DEFAULT_EMPTY_BAR_FILL=Dr;exports.DEFAULT_FONT_SETTINGS=Br;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=Fr;exports.DEFAULT_GOLD_FILLED_BAR_FILL=Or;exports.DEFAULT_KARAOKE_SETTINGS=jo;exports.DEFAULT_SEED_CONFIG=Ol;exports.DMXEngine=jc;exports.DRUM_PATTERN_NAMES=M0;exports.DefaultScoringPresets=Da;exports.DmxChannelControl=hs;exports.DmxChannelType=Ft;exports.DmxEditor=wc;exports.DmxOptionsControl=us;exports.DmxSliderControl=Vn;exports.DynamicRuleField=lt;exports.DynamicRuleOperator=ct;exports.EditorTrackProvider=_a;exports.EditorUndoManager=wu;exports.FIXTURE_PROFILES=Cc;exports.GENERIC_PROFILE=as;exports.GM_DRUM_MAP=py;exports.GRADIENT_PRESETS=hl;exports.GROOVE_TEMPLATES=ls;exports.GenericPlaylistItem=Qa;exports.KARAOKE_FONT_OPTIONS=fp;exports.KEY_MAPS=qo;exports.KaraokeFormat=Ya;exports.LANE_COLORS=In;exports.LAUNCH_CONTROL_PROFILE=Hl;exports.LAYER_COLORS=Tg;exports.MINILAB_PROFILE=ql;exports.MPK_MINI_PROFILE=Ul;exports.MasterFXPanel=zi;exports.MidiCCMapper=N0;exports.NOTE_NAMES=x0;exports.NiceArpeggiatorPanel=cu;exports.NiceAudioEffectsRack=o0;exports.NiceAudioErrorBoundary=Oc;exports.NiceAudioInputPicker=u0;exports.NiceAudioPitchAnalyzer=ph;exports.NiceAudioStudio=Gd;exports.NiceAudioTimeline=Ii;exports.NiceAutoSavePanel=Li;exports.NiceBarFillEditor=hh;exports.NiceCCAutomationLaneEditor=iu;exports.NiceCCLane=Qc;exports.NiceDMXTimeline=Wg;exports.NiceDmxChannelControl=hs;exports.NiceDmxEditor=wc;exports.NiceDmxOptionsControl=us;exports.NiceDmxSliderControl=Vn;exports.NiceDynamicRuleEditor=Of;exports.NiceEditorTrackProvider=_a;exports.NiceGenericPlayer=Io;exports.NiceGenericPlayerControls=Mp;exports.NiceGenericPlayerStage=af;exports.NiceGenericPlaylist=vf;exports.NiceGenericPlaylistItem=Qa;exports.NiceI18nProvider=Dc;exports.NiceKaraokeEditorManager=xp;exports.NiceKaraokeLyrics=po;exports.NiceKaraokeManager=Kh;exports.NiceKaraokePhaserRenderer=wp;exports.NiceKaraokeSelectionMode=ul;exports.NiceKaraokeSessionJoin=hp;exports.NiceKaraokeSetupPanel=dl;exports.NiceKaraokeSongBrowser=rp;exports.NiceKaraokeSummaryOverlay=Eo;exports.NiceKaraokeTimeline=To;exports.NiceKaraokeUploader=Vo;exports.NiceLFOPanel=hu;exports.NiceLatencyCalibrator=sp;exports.NiceMasterFXPanel=zi;exports.NiceModeSwitcher=ml;exports.NiceMusicLibraryExplorer=uf;exports.NiceNoteParticles=Wm;exports.NiceNoteRiver=_m;exports.NicePadKaraokeOverlay=Uo;exports.NicePianoRoll=$a;exports.NicePlaylistBrowser=Xf;exports.NicePlaylistDualPane=Wf;exports.NicePlaylistGridView=tm;exports.NicePlaylistImportWizard=um;exports.NicePlaylistList=ts;exports.NicePlaylistOverview=rm;exports.NicePlaylistSearchBar=am;exports.NicePlaylistSidebar=Jf;exports.NicePlaylistTagEditor=xf;exports.NicePlaylistTrackList=Cl;exports.NiceRadioPlayer=Yg;exports.NiceRecordingOptionsPanel=Di;exports.NiceSampleBrowser=Vd;exports.NiceStageVisualizer=gl;exports.NiceStationBrowser=Rc;exports.NiceStepSequencerPanel=gu;exports.NiceStreamingVisualizer=ps;exports.NiceUndoRedoPanel=_i;exports.NiceVocalEffectsRack=c0;exports.NiceVocalPerformanceReport=Qh;exports.NiceVoiceChatOverlay=Tc;exports.NiceWaveform=Pi;exports.NiceYouTubePlayer=sf;exports.NiceZoomSnapControls=Ea;exports.OVERLAY_PATTERNS=Pr;exports.OXYGEN25_PROFILE=Vl;exports.PLAYER_COLORS=et;exports.PLAYER_COLOR_VARS=ur;exports.PROGRESSION_NAMES=j0;exports.PadNotePlayer=Zo;exports.PaneSide=xl;exports.PianoRoll=$a;exports.PlaylistList=ts;exports.PlaylistType=Ja;exports.RecordingOptionsPanel=Di;exports.SACN_PORT=Fg;exports.SCALE_INTERVALS=Pc;exports.SCALE_NAMES=C0;exports.SKEW_CAPS=wo;exports.STANDARD_TUNINGS=hy;exports.SYMMETRIC_CAPS=Va;exports.ShortcutManager=vc;exports.SimpleSynth=Fl;exports.SortDirection=dn;exports.SortField=Sl;exports.StreamingVisualizer=ps;exports.TEXTURE_CATEGORIES=Ha;exports.TrackSource=St;exports.UndoRedoPanel=_i;exports.ViewMode=bl;exports.VocalEffectsEngine=zl;exports.VoiceChatOverlay=Tc;exports.WebRTCAudioManager=Nc;exports.ZoomSnapControls=Ea;exports.addEffectToLayer=B0;exports.addMidiNote=U0;exports.analyzeAudioFileWithAlgorithm=eg;exports.applyGroove=og;exports.applyGrooveTemplate=gc;exports.applyHumanize=mc;exports.applyKaraokeDisplayVars=Xa;exports.applyMidiTransform=dy;exports.applySwing=fc;exports.arrow_L=Ot;exports.arrow_R=Tt;exports.autoCorrelate=zo;exports.bracket_L=Oa;exports.bracket_R=xo;exports.buildArpSequence=so;exports.buildLanes=Ho;exports.buildNoteDescriptors=Ka;exports.buildPadNoteEvents=Yo;exports.buildSegmentScores=Do;exports.canRedo=Ui;exports.canUndo=Vi;exports.chamfer_L=Mr;exports.chamfer_R=fn;exports.clearMidiNotes=H0;exports.clearPattern=sc;exports.computeGrade=uy;exports.computeTheoreticalMax=nl;exports.computeVocalPerformanceReport=ol;exports.convertBrowserSongToKaraokeSongFile=Eh;exports.copyCCEvents=da;exports.createAnalyserNode=dc;exports.createArpPattern=E0;exports.createArtNetPacket=Dg;exports.createBasslinePattern=A0;exports.createCCHistory=Oi;exports.createCompressorNode=hc;exports.createDefaultLFO=_r;exports.createDefaultShortcuts=bg;exports.createDropZoneHandlers=Rg;exports.createEmptyPattern=Zt;exports.createEmptyStep=ss;exports.createGainNode=uc;exports.createHiHatPattern=$0;exports.createKickPattern=T0;exports.createLoopRegion=pg;exports.createSACNPacket=Og;exports.createSnarePattern=P0;exports.createVocoderNode=pc;exports.createVoiceChatAudioContext=ey;exports.cutCCEvents=Hi;exports.deleteCCEventsInRange=Ki;exports.deserializeLFO=nu;exports.deserializePattern=L0;exports.detectChord=ly;exports.downsampleAndQuantizePitchPoints=Fo;exports.drawGlossyBarOnCanvas=Tn;exports.drawTimeline=ma;exports.estimateLatencyMs=Oo;exports.estimateLatencyMsFromRecording=cl;exports.evaluateLFO=Aa;exports.evaluateLFOAsCC=Ia;exports.exportCCLane=Xi;exports.extractBpmFromNotes=fo;exports.findTextureByUrl=ch;exports.formatShortcut=xg;exports.generateArpEvents=lu;exports.generatePlaceholderWaveform=sg;exports.generateSeed=Wl;exports.generateUltrastarText=tg;exports.getActiveGradient=fl;exports.getActiveLyrics=Tu;exports.getActiveWords=Pu;exports.getAlgorithmColor=Ph;exports.getAlgorithmCssVar=$h;exports.getAlgorithmLabel=Th;exports.getArpModes=io;exports.getArpRates=oo;exports.getAudioContext=qn;exports.getAudioInputDevices=Jg;exports.getAudioWorkletProcessorCode=lc;exports.getBackgroundUrl=Nh;exports.getCachedImage=ih;exports.getCapStyleByName=Rn;exports.getComboMultiplier=el;exports.getCoverUrl=Rh;exports.getGrooveTemplate=lg;exports.getGrooveTemplateNames=cg;exports.getLaneForPitch=Ko;exports.getNextPlayerColor=sd;exports.getNextPlayerColorCss=id;exports.getOverlayCanvasPattern=An;exports.getPatternByName=Nn;exports.getSACNMulticastAddress=Bg;exports.getScoringPreset=zr;exports.getTexturePattern=$n;exports.getVerseRatingLabel=Jo;exports.handleAddCCEvent=Y0;exports.handleRedo=ku;exports.handleRemoveCCEvent=X0;exports.handleSelectCCLane=K0;exports.handleUndo=Su;exports.handleUpdateCCEvent=Z0;exports.hexToHsl=$r;exports.humanizeMidiNotes=hg;exports.hydrateKaraokeDisplayFromBackend=mp;exports.hydratePlayerKaraokeSettingsFromBackend=Ou;exports.hzToUltrastarPitch=mo;exports.importCCLane=Qi;exports.initKaraokeDisplaySettings=yp;exports.instrumentPresets=p0;exports.isAudioContextRunning=$i;exports.isInLoopRegion=gg;exports.isWebRTCSupported=Qg;exports.loadAllKaraokeSettings=Bu;exports.loadAudioWorkletModule=cc;exports.loadKaraokeDisplaySettings=pl;exports.loadKaraokeSettings=Ua;exports.loadRemoteScoringPresets=zu;exports.makeClickReference=ll;exports.makeClipSelectionId=ng;exports.mergeWaveforms=ag;exports.midiSeedGenerator=R0;exports.midiToHz=ga;exports.normalizeHex=Er;exports.openAudioFilePicker=Ng;exports.ornate_L=Ga;exports.ornate_R=Tr;exports.parseLyrics=Ru;exports.parseNotes=Hn;exports.parseUltraStarText=Wo;exports.parseVersesWithSyllables=ho;exports.parseVersesWithWords=Nu;exports.parseVideoMetadata=_o;exports.pasteCCEvents=qi;exports.pill_L=qt;exports.pill_R=Dt;exports.preloadTexture=qa;exports.preloadTextures=oh;exports.probeAudioFile=bc;exports.pushCCState=Bi;exports.pushOperation=ay;exports.quantizeMidiNotes=dg;exports.quantizeNotes=oy;exports.quantizeStepInBeats=yc;exports.quantizeStepInSeconds=cs;exports.randomizeVelocity=ac;exports.recordCCEvent=Yi;exports.redoCC=Wi;exports.redoOperation=iy;exports.removeEffectFromLayer=G0;exports.removeMidiNote=q0;exports.renderGlossyBarSvg=Mo;exports.resumeAudioContext=Yt;exports.reversePattern=nc;exports.sampleLFOForDisplay=ro;exports.sampleLFOToCCEvents=no;exports.saveKaraokeDisplaySettings=gp;exports.saveKaraokeSettings=Fu;exports.scaleResult=al;exports.scaleTo10k=rl;exports.scoreNotesWithPitchPoints=tl;exports.selectCCEventsInRange=Ud;exports.serializeLFO=tu;exports.serializePattern=I0;exports.setLoopFromSelection=fg;exports.setProjectWithUndo=co;exports.setStepGate=Ql;exports.setStepNote=Zl;exports.setStepProbability=Jl;exports.setStepVelocity=Xl;exports.sharp_L=hn;exports.sharp_R=pn;exports.shield_L=Rr;exports.shield_R=bo;exports.shiftPattern=rc;exports.shouldTrigger=oc;exports.skewTL_L=hr;exports.skewTL_R=fa;exports.skewTR_L=pa;exports.skewTR_R=pr;exports.snapLoopToGrid=mg;exports.snapTimeToQuantize=Na;exports.snapToGrid=rg;exports.snapToScale=cy;exports.soft_L=Fa;exports.soft_R=vo;exports.stepDuration=is;exports.stepTimeOffset=ic;exports.syncDivisionToHz=eo;exports.tab_L=Ba;exports.tab_R=So;exports.thinCCEvents=Zi;exports.toTrack=Go;exports.toggleEffectBypass=W0;exports.toggleStep=Yl;exports.toggleStepSlide=ec;exports.transposePattern=tc;exports.undoCC=Gi;exports.undoOperation=sy;exports.updateEffectParams=V0;exports.useAudioWorklet=O0;exports.useAutoSave=yu;exports.useCCAutomation=Ji;exports.useCanPickSong=up;exports.useDMXAudioSync=Ug;exports.useDMXEngine=Vg;exports.useEditorTrack=Mu;exports.useKaraokePitch=Qo;exports.useKaraokeScoring=sl;exports.useLocalPlaylists=es;exports.useMPE=y0;exports.useMidiLearn=m0;exports.useNiceTranslation=be;exports.useOxygen25=b0;exports.usePitchWorker=z0;exports.usePlaybackEngine=vu;exports.useProjectCRUD=ju;exports.useRadioStream=Mc;exports.useRecording=bu;exports.useScoringWorker=D0;exports.useStepSequencer=_0;exports.useWebMidi=Vr;exports.useWorker=os;exports.validateAudioFiles=ds;exports.wave_L=Nr;exports.wave_R=Wa;exports.waveformValue=to;exports.wrapTimeInLoop=yg;
|