@nice2dev/ui-audio 1.4.1 → 1.4.2
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 +41 -0
- package/dist/index.cjs +12 -12
- package/dist/index.mjs +2156 -2134
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var Ac=Object.create;var vs=Object.defineProperty;var Ic=Object.getOwnPropertyDescriptor;var Lc=Object.getOwnPropertyNames;var _c=Object.getPrototypeOf,Dc=Object.prototype.hasOwnProperty;var zc=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Lc(t))!Dc.call(e,s)&&s!==n&&vs(e,s,{get:()=>t[s],enumerable:!(a=Ic(t,s))||a.enumerable});return e};var Yr=(e,t,n)=>(n=e!=null?Ac(_c(e)):{},zc(t||!e||!e.__esModule?vs(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),ve=require("@nice2dev/ui-core"),d=require("react"),ie=require("@nice2dev/ui"),B=require("@nice2dev/icons"),da=require("pitchy"),$a=require("react-youtube");var vt=typeof document<"u"?document.currentScript:null;const Ei=d.createContext(null),Fc=({t:e,children:t})=>r.jsx(Ei.Provider,{value:e,children:t});function xe(){const e=d.useContext(Ei),{t}=ve.useNiceTranslation();return{t:d.useMemo(()=>e??((a,s)=>t(a,s??a)),[e,t])}}function Oc({componentName:e,error:t,onReset:n}){const{t:a}=xe();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 Bc extends d.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){var s,i;const a=this.props.componentName?`[${this.props.componentName}]`:"[AudioErrorBoundary]";console.error(`${a} Caught error:`,t,n),(i=(s=this.props).onError)==null||i.call(s,t,n)}render(){return this.state.hasError&&this.state.error?typeof this.props.fallback=="function"?this.props.fallback(this.state.error,this.reset):this.props.fallback?this.props.fallback:r.jsx(Oc,{componentName:this.props.componentName,error:this.state.error,onReset:this.reset}):this.props.children}}function Gc(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 Zr={},ua={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function Wc(){const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:vt&&vt.tagName.toUpperCase()==="SCRIPT"&&vt.src||new URL("index.cjs",document.baseURI).href}<"u"?Zr==null?void 0:Zr.VITE_LOG_LEVEL:void 0;return e&&e in ua?e:"WARN"}const Uc=Wc();function Xn(e){return ua[e]>=ua[Uc]}function Qn(e){return`[${e}]`}const st=(function(){return{debug(e,t,...n){Xn("DEBUG")&&console.debug(Qn(e),t,...n)},info(e,t,...n){Xn("INFO")&&console.info(Qn(e),t,...n)},warn(e,t,...n){Xn("WARN")&&console.warn(Qn(e),t,...n)},error(e,t,...n){Xn("ERROR")&&console.error(Qn(e),t,...n)},scoped(e){return{debug:(t,...n)=>st.debug(e,t,...n),info:(t,...n)=>st.info(e,t,...n),warn:(t,...n)=>st.warn(e,t,...n),error:(t,...n)=>st.error(e,t,...n)}}}})(),bs=st.scoped("Waveform"),Vc=["audio/","video/"],$i=({audioBlob:e,currentTime:t,duration:n,width:a=600,height:s=200,zoom:i=1,onSeek:o,onRegionSelect:l,markers:c=[],regions:u=[],displayMode:h="waveform",multiChannel:p=!1,waveColor: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:b=!0,showPeakMeter:f=!1,className:j})=>{const{t:v}=xe(),C=d.useRef(null),T=d.useRef(null),[M,k]=d.useState(null),[R,P]=d.useState(0),[I,A]=d.useState(!1),[L,E]=d.useState(null),[D,Z]=d.useState(null),[G,F]=d.useState(0),q=Math.max(a,a*i),V=x?24:0;d.useEffect(()=>{if(!e||e.size===0){k(null);return}e.type&&!Vc.some(N=>e.type.startsWith(N))&&bs.warn("Unexpected blob MIME type:",e.type);let w=!1;return(async()=>{let N=null;try{const S=await e.arrayBuffer();if(S.byteLength===0||w)return;N=new AudioContext;const O=await N.decodeAudioData(S);w||k(O)}catch(S){bs.error("Failed to decode audio:",S)}finally{N==null||N.close().catch(()=>{})}})(),()=>{w=!0}},[e]),d.useEffect(()=>{if(i>1&&n>0){const w=t/n*q;(w<R||w>R+a)&&P(Math.max(0,w-a/2))}},[t,n,i,a,q,R]),d.useEffect(()=>{const w=C.current,N=M;if(!w||!n||n===1/0)return;const S=w.getContext("2d");if(!S)return;const O=q,Y=s;if(w.width=O,w.height=Y+V,S.clearRect(0,0,O,Y+V),m!=="transparent"&&(S.fillStyle=ve.resolveCssColor(m),S.fillRect(0,0,O,Y+V)),x){const _=ve.resolveCssColor("var(--nice-text-secondary, #888)");S.fillStyle=ve.resolveCssColor("var(--nice-bg-secondary, rgba(128,128,128,0.15))"),S.fillRect(0,0,O,V),S.fillStyle=_,S.font="10px monospace",S.textAlign="center";const U=Math.max(1,Math.floor(n/(q/80)));for(let $=0;$<=n;$+=U){const H=$/n*O;S.fillText(Yc($),H,V-4),S.fillStyle=ve.resolveCssColor("var(--nice-border-color, rgba(128,128,128,0.3))"),S.fillRect(H,V,1,Y),S.fillStyle=_}}for(const _ of u){const U=_.start/n*O,$=_.end/n*O;S.fillStyle=ve.resolveCssColor(_.color??"var(--nice-accent-tint-15, rgba(99, 102, 241, 0.15))"),S.fillRect(U,V,$-U,Y),_.label&&(S.fillStyle=ve.resolveCssColor(_.color??"var(--nice-info, #6366f1)"),S.font="10px sans-serif",S.textAlign="left",S.fillText(_.label,U+2,V+12))}if(L!==null&&D!==null){const _=Math.min(L,D),U=Math.max(L,D);S.fillStyle=ve.resolveCssColor("var(--nice-warning-tint-20, rgba(255,200,0,0.2))"),S.fillRect(_,V,U-_,Y)}if(N){const _=p?N.numberOfChannels:1,U=Y/_,$=ve.resolveCssColor(g);let H=0;for(let X=0;X<_;X++){const re=N.getChannelData(X),oe=V+X*U;if(h==="waveform"?qc(S,re,O,U,oe,$):h==="bars"?Hc(S,re,O,U,oe,$):h==="spectrogram"&&Kc(S,re,O,U,oe,N.sampleRate),f&&n>0){const se=Math.floor(t/n*re.length),z=Math.floor(N.sampleRate*.05);let ee=0;for(let ce=Math.max(0,se-z);ce<Math.min(re.length,se+z);ce++)ee+=re[ce]*re[ce];const ae=Math.sqrt(ee/(z*2));H=Math.max(H,ae)}p&&b&&_>1&&(S.fillStyle=ve.resolveCssColor("var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"),S.font="bold 11px sans-serif",S.textAlign="left",S.fillText(X===0?"L":X===1?"R":`Ch${X+1}`,4,oe+14))}F(H)}if(n>0){const _=Math.max(0,Math.min(t/n*O,O));S.beginPath(),S.strokeStyle=ve.resolveCssColor(y),S.lineWidth=2,S.moveTo(_,V),S.lineTo(_,Y+V),S.stroke()}for(const _ of c){const U=_.time/n*O,$=ve.resolveCssColor(_.color??"var(--nice-warning, #f59e0b)");S.beginPath(),S.strokeStyle=$,S.lineWidth=2,S.setLineDash([4,4]),S.moveTo(U,V),S.lineTo(U,Y+V),S.stroke(),S.setLineDash([]),_.label&&(S.fillStyle=$,S.font="bold 10px sans-serif",S.textAlign="center",S.fillText(_.label,U,V+Y-4))}},[M,t,n,q,s,i,h,p,g,y,m,x,c,u,L,D,f,b,V]);const K=d.useCallback(w=>{var O;if(!n)return;const N=(O=C.current)==null?void 0:O.getBoundingClientRect();if(!N)return;const S=w.clientX-N.left+R;A(!0),E(S),Z(S)},[n,R]),W=d.useCallback(w=>{if(!I||!C.current)return;const N=C.current.getBoundingClientRect(),S=w.clientX-N.left+R;Z(S)},[I,R]),Q=d.useCallback(()=>{if(!I||L===null||D===null||!n){A(!1),E(null),Z(null);return}const w=Math.min(L,D),N=Math.max(L,D),S=(N-w)/q*n;if(A(!1),E(null),Z(null),S<.2){const O=w/q*n;o==null||o(O)}else{const O=w/q*n,Y=N/q*n;l==null||l({start:O,end:Y})}},[I,L,D,n,q,o,l]);return r.jsxs("div",{ref:T,className:`nice-waveform${j?` ${j}`:""}`,style:{position:"relative",width:a,overflow:i>1?"auto":"hidden",cursor:o?"crosshair":"default"},onScroll:w=>P(w.target.scrollLeft),children:[r.jsx("canvas",{ref:C,width:q,height:s+V,style:{display:"block"},role:"img","aria-label":v("waveform.waveformCanvas","Waveform canvas"),onMouseDown:K,onMouseMove:W,onMouseUp:Q,onMouseLeave:Q}),f&&r.jsx("div",{style:{position:"absolute",right:4,top:V+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,G*300)}%`,background:G>.8?"var(--nice-danger, #ef4444)":G>.5?"var(--nice-warning, #f59e0b)":"var(--nice-success, #22c55e)",borderRadius:4,transition:"height 50ms"}})})]})};function qc(e,t,n,a,s,i){const o=Math.floor(t.length/n),l=s+a/2;e.beginPath(),e.strokeStyle=i,e.lineWidth=1;for(let c=0;c<n;c++){const u=c*o,h=t.subarray(u,u+o);let p=0,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 Hc(e,t,n,a,s,i){const o=Math.max(2,Math.floor(n/128)),l=Math.floor(n/o),c=Math.floor(t.length/l);for(let u=0;u<l;u++){const h=u*c,p=t.subarray(h,h+c);let g=0;for(let b=0;b<p.length;b++)g+=Math.abs(p[b]);const m=g/p.length*a*.9,x=u*o;e.fillStyle=i,e.fillRect(x+1,s+a-m,o-2,m)}}function Kc(e,t,n,a,s,i){const l=Math.min(n,512),c=Math.floor(t.length/l),u=n/l;for(let h=0;h<l;h++){const p=h*c,g=new Float32Array(256/2);for(let m=0;m<256/2;m++){let x=0,b=0;for(let f=0;f<256&&p+f<t.length;f++){const j=2*Math.PI*m*f/256;x+=t[p+f]*Math.cos(j),b-=t[p+f]*Math.sin(j)}g[m]=Math.sqrt(x*x+b*b)/256}const y=a/g.length;for(let m=0;m<g.length;m++){const x=Math.min(1,g[m]*10),b=Math.floor(x*255),f=Math.floor(x*100),j=Math.floor((1-x)*200);e.fillStyle=`rgb(${b},${f},${j})`,e.fillRect(h*u,s+a-(m+1)*y,u+1,y+1)}}}function Yc(e){const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const xs=88,tn=16,Jn=16,Zc=320;function Xc(e){return e-21}function Qc(e){return e+21}const Aa=({notes:e,onAddNote:t,onRemoveNote:n,selectedNoteId:a,setSelectedNoteId:s,duration:i=4,zoom:o=1})=>{const l=d.useRef(null),c=Zc*o,u=xs*tn,h=d.useRef(null);d.useEffect(()=>{},[e,o,i]);const p=y=>{const m=l.current;if(!m)return;const x=m.getBoundingClientRect(),b=y.clientX-x.left,f=y.clientY-x.top,j=Math.floor(f/tn),v=Qc(j),C=b/c*i;h.current={drawing:!0,startX:b,key:j},t(v,C,i/Jn)},g=(y,m)=>{m.stopPropagation(),s==null||s(y)};return r.jsxs("svg",{ref:l,width:c,height:u,style:{background:"var(--nice-bg-secondary, #f8fafc)",border:"1px solid var(--nice-border-color, #cbd5e1)",userSelect:"none",display:"block"},onMouseDown:p,children:[[...Array(xs)].map((y,m)=>r.jsx("rect",{x:0,y:m*tn,width:c,height:tn,fill:m%2===0?"var(--nice-bg-secondary, #f8fafc)":"var(--nice-bg-tertiary, #f1f5f9)"},m)),[...Array(Jn+1)].map((y,m)=>r.jsx("line",{x1:m*c/Jn,y1:0,x2:m*c/Jn,y2:u,stroke:"var(--nice-border-muted, #ccc)",strokeWidth:m%4===0?2:1},m)),e.map(y=>{const m=Xc(y.pitch),x=y.start/i*c,b=y.duration/i*c;return r.jsx("rect",{x,y:m*tn,width:Math.max(6,b),height:tn-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)})]})},Jc=({ccEvents:e,onAddEvent:t,onUpdateEvent:n,onRemoveEvent:a,ccType:s,duration:i,width:o,height:l=60,curveType:c})=>{const u=d.useRef(null),{t:h}=xe(),[p,g]=d.useState(null),[y,m]=d.useState(null),[x,b]=d.useState(null),f=[...e].sort((E,D)=>E.time-D.time),j=E=>[E.time/i*o,(127-E.value)/127*l],v=(E,D,Z)=>Math.max(D,Math.min(Z,E)),C=E=>{var V;if(E.target instanceof SVGCircleElement)return;const D=(V=u.current)==null?void 0:V.getBoundingClientRect();if(!D)return;const Z=E.clientX-D.left,G=E.clientY-D.top,F=v(Z/o*i,0,i),q=v(127-Math.round(G/l*127),0,127);t(s,q,F)},T=(E,D)=>{var q;D.stopPropagation(),g(E.id),b(E.id);const[Z,G]=j(E),F=(q=u.current)==null?void 0:q.getBoundingClientRect();F&&m({dx:D.clientX-F.left-Z,dy:D.clientY-F.top-G})},M=E=>{var V;if(p==null||!y)return;const D=(V=u.current)==null?void 0:V.getBoundingClientRect();if(!D)return;const Z=v(E.clientX-D.left-y.dx,0,o),G=v(E.clientY-D.top-y.dy,0,l),F=v(Z/o*i,0,i),q=v(127-Math.round(G/l*127),0,127);n(p,q,F)},k=()=>{g(null),m(null)};d.useEffect(()=>{const E=D=>{(D.key==="Delete"||D.key==="Backspace")&&x!=null&&(a(x),b(null))};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[x,a]),d.useEffect(()=>{if(p!=null)return window.addEventListener("mousemove",M),window.addEventListener("mouseup",k),()=>{window.removeEventListener("mousemove",M),window.removeEventListener("mouseup",k)}});const[R,P]=d.useState(null),I=(E,D)=>{const[Z,G]=j(E);P({x:Z+10,y:G-10,text:h("ccLane.valTimeS","Val: {value}, Time: {time}s").replace("{value}",String(E.value)).replace("{time}",String(E.time.toFixed(2)))})},A=()=>P(null),L=E=>{var V;const D=(V=u.current)==null?void 0:V.getBoundingClientRect();if(!D)return;const Z=E.clientX-D.left,G=E.clientY-D.top,F=v(Z/o*i,0,i),q=v(127-Math.round(G/l*127),0,127);t(s,q,F)};return r.jsxs("svg",{ref:u,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:C,onDoubleClick:L,tabIndex:0,children:[[...Array(9)].map((E,D)=>r.jsx("line",{x1:0,y1:D*l/8,x2:o,y2:D*l/8,stroke:"var(--nice-border-muted, #ddd)",strokeWidth:D===0||D===8?2:1},D)),f.length>1&&r.jsx("polyline",{fill:"none",stroke:"var(--nice-color-accent, #1976d2)",strokeWidth:2,points:f.map(E=>j(E).join(",")).join(" ")}),f.map(E=>{const[D,Z]=j(E);return r.jsxs("g",{children:[r.jsx("circle",{cx:D,cy:Z,r:x===E.id?8:6,fill:x===E.id?"var(--nice-color-accent, #1976d2)":"var(--nice-color-accent-light, #90caf9)",stroke:"var(--nice-color-accent, #1976d2)",strokeWidth:x===E.id?3:2,style:{cursor:"pointer"},onMouseDown:G=>T(E,G),onContextMenu:G=>{G.preventDefault(),a(E.id)},onClick:G=>{G.stopPropagation(),b(E.id)},onMouseOver:G=>I(E),onMouseOut:A}),x===E.id&&r.jsx("foreignObject",{x:D+10,y:Z-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:E.handleType||c||"linear",onChange:G=>{n(E.id,E.value,E.time,G.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")})]})]})})]},E.id)}),R&&r.jsxs("g",{pointerEvents:"none",children:[r.jsx("rect",{x:R.x,y:R.y-18,width:90,height:20,fill:"var(--nice-color-surface, #fff)",stroke:"var(--nice-color-accent, #1976d2)",rx:4}),r.jsx("text",{x:R.x+6,y:R.y-4,fontSize:13,fill:"var(--nice-color-accent, #1976d2)",children:R.text})]}),r.jsxs("text",{x:6,y:16,fontSize:14,fill:"var(--nice-color-accent, #1976d2)",children:["CC",s]})]})},ed=st.scoped("audioContext");let Un=null;function Yn(){if(!Un)try{Un=new(window.AudioContext||window.webkitAudioContext)}catch(e){ed.error("Error initializing AudioContext:",e)}return Un}async function Xt(){const e=Yn();e&&e.state==="suspended"&&await e.resume()}function Ai(){return!!Un&&Un.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 td(e,t){if(!t.snapEnabled)return e;const n=Ii(t);return Math.round(e/n)*n}function nd(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 rd(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 Li(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=ve.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=ve.resolveCssColor("var(--nice-border-secondary, #ddd)",a.canvas),a.lineWidth=1;for(let c=0;c<=t.duration;c+=l){const u=c/t.duration*s,h=c%1===0;if(a.strokeStyle=ve.resolveCssColor(h?"var(--nice-border-secondary, #ccc)":"var(--nice-border-muted, #eee)",a.canvas),a.lineWidth=h?1.5:.5,a.beginPath(),a.moveTo(u,0),a.lineTo(u,i),a.stroke(),h&&o>40){a.fillStyle=ve.resolveCssColor("var(--nice-text-muted, #666)",a.canvas),a.font="10px monospace",a.textAlign="center";const p=n?rd(c,t.bpm):nd(c);a.fillText(p,u,12)}}if(t.snapEnabled){const c=Ii(t);a.strokeStyle=ve.resolveCssColor("var(--nice-color-accent, #ffeb3b)",a.canvas),a.lineWidth=.5;for(let u=0;u<=t.duration;u+=c){const h=u/t.duration*s;a.beginPath(),a.moveTo(h,i-5),a.lineTo(h,i),a.stroke()}}}function ad(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;Li(e,t),s.strokeStyle=ve.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=ve.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 sd(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=ve.resolveCssColor(a,s.canvas),s.lineWidth=1,s.beginPath(),n.forEach((u,h)=>{const p=h/(n.length-1)*i,g=l-u*c;h===0?s.moveTo(p,g):s.lineTo(p,g)}),s.stroke(),s.restore()}const _i=({zoom:e=1,duration:t=4,isPlaying:n,isRecording:a,currentTime:s,bpm:i=120,snapEnabled:o=!1,snapMode:l="beat",waveform:c,waveformColor:u,onCurrentTimeChange:h,onZoomChange:p})=>{const{t:g}=xe(),y=d.useRef(null),[m,x]=d.useState(!1),b=d.useRef(s);b.current=s;const f=d.useRef(t);f.current=t;const j=d.useRef(h);j.current=h;const v={bpm:i,snapEnabled:o,snapMode:l};d.useEffect(()=>{Xt();const P=y.current;if(!P)return;const I={zoom:e,duration:t,bpm:i,snapEnabled:o,snapMode:l};Li(P,I),c!=null&&c.length&&sd(P,I,c,u),ad(P,I,s,a)},[e,t,s,a,i,o,l,c,u]),d.useEffect(()=>{if(!n)return;let P=performance.now(),I=0;const A=L=>{const E=Math.max(0,L-P)/1e3;P=L;const D=Math.min(b.current+E,f.current);b.current=D,j.current(D),D<f.current&&(I=requestAnimationFrame(A))};return I=requestAnimationFrame(A),()=>cancelAnimationFrame(I)},[n]);const C=P=>{x(!0),k(P)},T=P=>{m&&k(P)},M=()=>{x(!1)},k=P=>{if(!y.current)return;const I=y.current.getBoundingClientRect();let L=(P.clientX-I.left)/I.width*t;L=td(L,v),h(Math.min(Math.max(L,0),t))},R=P=>{if(!p)return;P.preventDefault();const I=P.deltaY>0?-.1:.1,A=Math.max(.5,Math.min(5,e+I));p(A)};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:C,onMouseMove:T,onMouseUp:M,onMouseLeave:M,onWheel:R,role:"img","aria-label":g("audioTimeline.audioTimelineCanvas","Audio timeline canvas")})})},Xe=["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 id(e){for(const t of Xe)if(!e.includes(t))return t;return Xe[Math.floor(Math.random()*Xe.length)]}const pr=Xe.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function od(e){for(let t=0;t<Xe.length;t++){const n=Xe[t],a=pr[t];if(!e.includes(n)&&!e.includes(a))return a}return pr[Math.floor(Math.random()*pr.length)]}const ld="_panel_3bj7x_3",cd="_panelCompact_3bj7x_19",dd="_panelNarrow_3bj7x_25",ud="_panelWide_3bj7x_31",hd="_heading_3bj7x_37",pd="_row_3bj7x_53",fd="_field_3bj7x_65",md="_buttonRow_3bj7x_71",gd="_sliderW200_3bj7x_83",yd="_sliderW240_3bj7x_89",vd="_selectW160_3bj7x_95",bd="_inputW120_3bj7x_101",xd="_inputW160_3bj7x_107",Sd="_inputW200_3bj7x_113",kd="_noteText_3bj7x_123",wd="_noteTextMargin_3bj7x_131",Cd="_presetDivider_3bj7x_145",jd="_presetLabel_3bj7x_159",Md="_countInAlert_3bj7x_173",Rd="_levelLabel_3bj7x_181",Nd="_levelMeter_3bj7x_189",Td="_levelBar_3bj7x_205",Pd="_panelInactive_3bj7x_225",Ed="_header_3bj7x_231",$d="_title_3bj7x_245",Ad="_grid2_3bj7x_257",Id="_full_3bj7x_267",Ld="_label_3bj7x_275",_d="_grow_3bj7x_291",Dd="_pushRight_3bj7x_299",zd="_alignStart_3bj7x_305",Fd="_toolbar_3bj7x_311",Od="_subPanel_3bj7x_325",ye={panel:ld,panelCompact:cd,panelNarrow:dd,panelWide:ud,heading:hd,row:pd,field:fd,buttonRow:md,sliderW200:gd,sliderW240:yd,selectW160:vd,inputW120:bd,inputW160:xd,inputW200:Sd,noteText:kd,noteTextMargin:wd,presetDivider:Cd,presetLabel:jd,countInAlert:Md,levelLabel:Rd,levelMeter:Nd,levelBar:Td,panelInactive:Pd,header:Ed,title:$d,grid2:Ad,full:Id,label:Ld,grow:_d,pushRight:Dd,alignStart:zd,toolbar:Fd,subPanel:Od},Tt=e=>Array.isArray(e)?e[0]??"":e,Di=({autoSaveMode:e,setAutoSaveMode:t,autoSaveInterval:n,setAutoSaveInterval:a})=>{const{t:s}=xe();return r.jsxs("div",{className:`${ye.panel} ${ye.panelNarrow}`,children:[r.jsx("h6",{className:ye.heading,children:s("editorPanels.autoSaveTitle","Project auto-save")}),r.jsx("div",{className:ye.field,children:r.jsx(ie.NiceSelect,{label:s("editorPanels.autoSaveMode","Auto-save mode"),size:"sm",value:e,onChange:i=>t(Tt(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:ye.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:ye.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.")]})]})},zi=({undoCount:e,redoCount:t,onUndo:n,onRedo:a})=>{const{t:s}=xe();return r.jsxs("div",{className:`${ye.panel} ${ye.panelNarrow}`,children:[r.jsx("h6",{className:ye.heading,children:s("editorPanels.changeHistory","Project change history")}),r.jsxs("div",{className:ye.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(B.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(B.NtdRedo,{size:14})," ",s("editorPanels.redo","Redo")]})]}),r.jsx("div",{className:ye.noteTextMargin,children:s("editorPanels.undoRedoNote","Undo/Redo works on the entire project (all editor changes). After each change Redo is cleared.")})]})},Ss=e=>`${e.toFixed(1)}x`,Ia=({zoom:e,setZoom:t,uiZoom:n,setUiZoom:a,snapEnabled:s,onToggleSnap:i,snapMode:o,onSnapModeChange:l,bpm:c,setBpm:u})=>{const{t:h}=xe();return r.jsx("div",{className:`${ye.panel} ${ye.panelCompact} ${ye.panelNarrow}`,children:r.jsxs("div",{className:ye.row,children:[r.jsx("div",{className:ye.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:Ss})}),r.jsx("div",{className:ye.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:Ss})}),r.jsx(ie.NiceCheckbox,{label:h("editorPanels.snap","Snap"),size:"sm",checked:s,onChange:()=>i()}),s&&r.jsx("div",{className:ye.selectW160,children:r.jsx(ie.NiceSelect,{size:"sm","aria-label":h("editorPanels.snapTo","Snap to"),value:o,onChange:p=>l(Tt(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:ye.inputW120,children:r.jsx(ie.NiceNumberInput,{label:h("editorPanels.bpm","BPM"),size:"sm",min:20,max:300,value:c,onChange:p=>u(p??c)})})]})})},Bd=[["peaking","Peaking"],["lowpass","Low-pass"],["highpass","High-pass"],["lowshelf","Low shelf"],["highshelf","High shelf"],["notch","Notch"],["bandpass","Band-pass"]],Fi=({masterVolume:e,onMasterVolumeChange:t,filterType:n,filterFreq:a,filterQ:s,filterGain:i,onFilterChange:o,masterEQPresets:l,customPresets:c,onLoadPreset:u,onSavePreset:h,onDeletePreset:p})=>{const{t:g}=xe(),[y,m]=d.useState(""),x=()=>{y.trim()&&(h(y.trim()),m(""))};return r.jsxs("div",{className:`${ye.panel} ${ye.panelCompact} ${ye.panelWide}`,children:[r.jsxs("div",{className:ye.row,children:[r.jsx("div",{className:ye.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:b=>`${Math.round(b*100)}%`})}),r.jsx("div",{className:ye.selectW160,children:r.jsx(ie.NiceSelect,{label:g("editorPanels.filter","Filter"),size:"sm",value:n,onChange:b=>o({type:Tt(b)}),options:Bd.map(([b,f])=>({value:b,label:g(`editorPanels.filter.${b}`,f)}))})}),r.jsx("div",{className:ye.sliderW240,children:r.jsx(ie.NiceSlider,{label:g("editorPanels.frequency","Freq"),size:"sm",min:40,max:12e3,step:10,value:a,onChange:b=>o({frequency:b}),showValue:!0,formatValue:b=>`${Math.round(b)} Hz`})}),r.jsx("div",{className:ye.sliderW200,children:r.jsx(ie.NiceSlider,{label:"Q",size:"sm",min:.1,max:12,step:.1,value:s,onChange:b=>o({q:b}),showValue:!0,formatValue:b=>b.toFixed(1)})}),(n==="peaking"||n==="lowshelf"||n==="highshelf")&&r.jsx("div",{className:ye.sliderW200,children:r.jsx(ie.NiceSlider,{label:g("editorPanels.gain","Gain"),size:"sm",min:-18,max:18,step:.5,value:i,onChange:b=>o({gain:b}),showValue:!0,formatValue:b=>`${b.toFixed(1)} dB`})})]}),r.jsxs("div",{className:ye.presetDivider,children:[r.jsxs("div",{className:ye.row,children:[r.jsxs("span",{className:ye.presetLabel,children:[g("editorPanels.eqPresets","EQ Presets"),":"]}),[...l,...c].map(b=>r.jsx(ie.NiceButton,{variant:"outline",size:"xs",onClick:()=>u(b),children:b.name},b.name)),c.length>0&&r.jsx("div",{className:ye.selectW160,children:r.jsx(ie.NiceSelect,{size:"sm","aria-label":g("editorPanels.deletePreset","Delete preset..."),placeholder:g("editorPanels.deletePreset","Delete preset..."),value:"",onChange:b=>{const f=Tt(b);f&&p(f)},options:c.map(b=>({value:b.name,label:b.name}))})})]}),r.jsxs("div",{className:ye.row,children:[r.jsx("div",{className:ye.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:b=>b.key==="Enter"&&x()})}),r.jsx(ie.NiceButton,{variant:"success",size:"xs",onClick:x,disabled:!y.trim(),children:g("editorPanels.saveCurrent","Save Current")})]})]})]})},Oi=({countInBars:e,setCountInBars:t,isCountIn:n,countInRemaining:a,overdubEnabled:s,setOverdubEnabled:i,punchIn:o,setPunchIn:l,punchOut:c,setPunchOut:u,monitorLevel:h})=>{const{t:p}=xe();return r.jsx("div",{className:`${ye.panel} ${ye.panelCompact} ${ye.panelWide}`,children:r.jsxs("div",{className:ye.row,children:[r.jsx("div",{className:ye.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:ye.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:ye.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:ye.inputW160,children:r.jsx(ie.NiceNumberInput,{label:p("editorPanels.punchOut","Punch Out (s)"),size:"sm",min:0,step:.1,value:c,onChange:u})}),r.jsx(ie.NiceButton,{variant:"outline",size:"xs",onClick:()=>{l(null),u(null)},children:p("editorPanels.clearPunch","Clear punch")}),r.jsx("div",{className:ye.levelLabel,children:p("editorPanels.level","Level")}),r.jsx("div",{className:ye.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:ye.levelBar,style:{width:`${Math.min(1,h*2)*100}%`,background:h>.7?"var(--nice-danger, #f44336)":"var(--nice-success, #4caf50)"}})})]})})},Gd=[{id:1,name:"Audio 1",type:"audio",color:Xe[0],volume:.8,audioBlob:null},{id:2,name:"MIDI 1",type:"midi",color:Xe[1],volume:.8,notes:[]}],Wd=({initialTracks:e,tracks:t,onTracksChange:n,initialBpm:a=120,duration:s=30,height:i=480,title:o,displayMode:l="standard",onNew:c,onOpen:u,onSave:h,onExport:p,t:g})=>{var ae,ce;const{t:y}=xe(),m=g??y,x=o??m("audioStudio.untitledProject","Untitled project"),[b,f]=d.useState(l),j=b==="advanced",v=b!=="basic",[C,T]=d.useState(e??Gd),M=t??C,k=d.useCallback(le=>{t===void 0&&T(le),n==null||n(le)},[t,n]),[R,P]=d.useState(!1),[I,A]=d.useState(0),[L,E]=d.useState(1),[D,Z]=d.useState(2),[G,F]=d.useState(!0),[q,V]=d.useState("beat"),[K,W]=d.useState(a),[Q,w]=d.useState(80),[N,S]=d.useState(((ae=M[0])==null?void 0:ae.id)??null),O=d.useRef(0),Y=d.useRef(0);d.useEffect(()=>{if(!R)return;Y.current=performance.now();const le=ne=>{const pe=(ne-Y.current)/1e3;Y.current=ne,A(fe=>{const ge=fe+pe;return ge>=s?(P(!1),s):ge}),O.current=requestAnimationFrame(le)};return O.current=requestAnimationFrame(le),()=>cancelAnimationFrame(O.current)},[R,s]);const _=d.useCallback((le,ne)=>k(M.map(pe=>pe.id===le?{...pe,...ne}:pe)),[M,k]),U=d.useCallback(le=>{const ne=M.reduce((fe,ge)=>Math.max(fe,ge.id),0)+1,pe=M.filter(fe=>fe.type===le).length+1;k([...M,{id:ne,name:`${le==="audio"?"Audio":"MIDI"} ${pe}`,type:le,color:Xe[M.length%Xe.length],volume:.8,...le==="audio"?{audioBlob:null}:{notes:[]}}]),S(ne)},[M,k]),$=d.useCallback(le=>k(M.filter(ne=>ne.id!==le)),[M,k]),H=d.useCallback(()=>{if(c){c();return}k([]),A(0),P(!1)},[c,k]),X=d.useCallback((le,ne,pe,fe)=>{const ge=M.find(je=>je.id===le),he=(ge==null?void 0:ge.notes)??[],we=he.reduce((je,Pe)=>Math.max(je,Pe.id),0)+1;_(le,{notes:[...he,{id:we,pitch:ne,start:pe,duration:fe,velocity:100}]})},[M,_]),re=d.useCallback((le,ne)=>{const pe=M.find(fe=>fe.id===le);_(le,{notes:((pe==null?void 0:pe.notes)??[]).filter(fe=>fe.id!==ne)})},[M,_]),oe=d.useMemo(()=>{const le=Math.floor(I/60),ne=Math.floor(I%60),pe=Math.floor(I%1*100);return`${le}:${ne.toString().padStart(2,"0")}.${pe.toString().padStart(2,"0")}`},[I]),se=d.useMemo(()=>{const le=(pe,fe)=>({id:`mode-${pe}`,label:`${b===pe?"• ":" "}${fe}`,onClick:()=>f(pe)}),ne=[{id:"file",label:m("studio.menu.file","File"),children:[{id:"new",label:m("studio.menu.new","New"),onClick:H},...u?[{id:"open",label:m("studio.menu.open","Open…"),onClick:u}]:[],{id:"save",label:m("studio.menu.save","Save"),onClick:()=>h==null?void 0:h(M)},{id:"export",label:m("studio.menu.export","Export…"),onClick:()=>p==null?void 0:p(M)}]}];return v&&ne.push({id:"edit",label:m("studio.menu.edit","Edit"),children:[{id:"add-audio",label:m("studio.addAudio","Add audio track"),onClick:()=>U("audio")},{id:"add-midi",label:m("studio.addMidi","Add MIDI track"),onClick:()=>U("midi")}]}),ne.push({id:"view",label:m("studio.menu.view","View"),children:[{id:"modes",label:m("studio.menu.modes","Display mode"),divider:!1,disabled:!0},le("basic",m("studio.mode.basic","Basic")),le("standard",m("studio.mode.standard","Standard")),le("advanced",m("studio.mode.advanced","Advanced")),{id:"d1",divider:!0},{id:"snap",label:`${G?"• ":" "}${m("studio.snap","Snap to grid")}`,onClick:()=>F(pe=>!pe)}]}),ne.push({id:"help",label:m("studio.menu.help","Help"),children:[{id:"about",label:m("studio.menu.about","About NiceAudioStudio"),disabled:!0}]}),ne},[m,b,v,G,H,u,h,p,M,U]),z=r.jsxs(r.Fragment,{children:[r.jsxs(ie.NiceButton,{variant:"primary",size:"sm",onClick:()=>P(le=>!le),children:[R?r.jsx(B.NtdPause,{size:14}):r.jsx(B.NtdPlay,{size:14})," ",R?m("studio.pause","Pause"):m("studio.play","Play")]}),r.jsxs(ie.NiceButton,{variant:"secondary",size:"sm",onClick:()=>{P(!1),A(0)},children:[r.jsx(B.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:()=>U("audio"),children:[r.jsx(B.NtdPlus,{size:14})," ",m("studio.addAudioShort","Audio")]}),v&&r.jsxs(ie.NiceButton,{variant:"outline",size:"sm",onClick:()=>U("midi"),children:[r.jsx(B.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:Q,onChange:w,min:0,max:100})})]}),ee=r.jsxs(r.Fragment,{children:[r.jsxs("span",{children:[K," BPM"]}),r.jsx("span",{children:"·"}),r.jsx("span",{style:{fontVariantNumeric:"tabular-nums"},children:oe}),r.jsx("span",{children:"·"}),r.jsxs("span",{children:[M.length," ",m("studio.tracks","tracks")]}),j&&N!=null&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"·"}),r.jsxs("span",{children:[m("studio.active","Active"),": ",((ce=M.find(le=>le.id===N))==null?void 0:ce.name)??"—"]})]}),r.jsx("span",{style:{flex:1}}),r.jsx("span",{style:{textTransform:"capitalize"},children:b})]});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:se,orientation:"horizontal"}),r.jsx("span",{style:{color:"var(--nice-text-secondary)",fontSize:13},children:x})]}),toolbar:z,statusBar:ee,children:[v&&r.jsx("div",{style:{padding:"6px 12px",borderBottom:"1px solid var(--nice-border-color)"},children:r.jsx(Ia,{zoom:L,setZoom:E,uiZoom:D,setUiZoom:Z,snapEnabled:G,onToggleSnap:()=>F(le=>!le),snapMode:q,onSnapModeChange:V,bpm:K,setBpm:W})}),r.jsx("div",{style:{padding:8},children:r.jsx(_i,{zoom:L,duration:s,isPlaying:R,isRecording:!1,currentTime:I,bpm:K,snapEnabled:G,snapMode:q,onCurrentTimeChange:A,onZoomChange:E})}),M.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.")}):M.map(le=>r.jsxs("div",{role:"presentation",onFocus:()=>S(le.id),style:{display:"flex",gap:8,padding:8,borderTop:"1px solid var(--nice-border-color)",background:N===le.id?"color-mix(in srgb, var(--nice-color-primary) 8%, transparent)":"transparent"},onClick:()=>S(le.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:le.color||Xe[0],flex:"0 0 auto"}}),r.jsx("div",{style:{flex:1},children:r.jsx(ie.NiceTextInput,{value:le.name,onChange:ne=>_(le.id,{name:ne}),size:"sm"})})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[r.jsx(ie.NiceButton,{variant:le.muted?"danger":"ghost",size:"sm",onClick:()=>_(le.id,{muted:!le.muted}),children:"M"}),v&&r.jsx(ie.NiceButton,{variant:le.solo?"warning":"ghost",size:"sm",onClick:()=>_(le.id,{solo:!le.solo}),children:"S"}),r.jsx("div",{style:{flex:1},children:r.jsx(ie.NiceSlider,{value:Math.round((le.volume??.8)*100),onChange:ne=>_(le.id,{volume:ne/100}),min:0,max:100})}),r.jsx(ie.NiceButton,{variant:"ghost",size:"sm",onClick:()=>$(le.id),children:r.jsx(B.NtdClose,{size:14})})]})]}),r.jsx("div",{style:{flex:1,minWidth:0,opacity:le.muted?.5:1},children:le.type==="audio"?r.jsx($i,{audioBlob:le.audioBlob??null,currentTime:I,duration:s,zoom:L,height:80,waveColor:le.color,onSeek:A}):r.jsx(Aa,{notes:le.notes??[],onAddNote:(ne,pe,fe)=>X(le.id,ne,pe,fe),onRemoveNote:ne=>re(le.id,ne),duration:s,zoom:L})})]},le.id))]})},Bi=({data:e,width:t=200,height:n=40,color:a="var(--nice-accent, #8b5cf6)",progress:s=0,onClick:i})=>{const o=d.useRef(null);d.useEffect(()=>{const c=o.current;if(!c||!e)return;const u=c.getContext("2d");if(!u)return;const h=window.devicePixelRatio||1;c.width=t*h,c.height=n*h,u.scale(h,h),u.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,b=y/e.length<s;u.fillStyle=b?a:`${a}66`,u.fillRect(m,g-x/2,Math.max(1,p-1),x)}s>0&&s<1&&(u.strokeStyle=ve.resolveCssColor("var(--nice-bg, #fff)",u.canvas),u.lineWidth=2,u.beginPath(),u.moveTo(s*t,0),u.lineTo(s*t,n),u.stroke())},[e,t,n,a,s]);const l=d.useCallback(c=>{if(!i)return;const u=c.currentTarget.getBoundingClientRect(),h=c.clientX-u.left;i(h/u.width)},[i]);return r.jsx("canvas",{ref:o,className:"nice-sample-waveform",width:t,height:n,style:{width:t,height:n},onClick:l})},Ud=({sample:e,isSelected:t,isPlaying:n,playProgress:a,showWaveform:s,showAnalysis:i,onSelect:o,onPlay:l,onStop:c,onDragStart:u,onFavorite:h})=>{const{t:p}=xe(),g=m=>{const x=Math.floor(m/60),b=Math.floor(m%60);return`${x}:${b.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",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,className:`nice-sample-row ${t?"nice-sample-row--selected":""} ${n?"nice-sample-row--playing":""}`,onClick:o,draggable:!0,onDragStart:u,children:[r.jsx("button",{type:"button",className:"nice-sample-row__play",onClick:m=>{m.stopPropagation(),n?c():l()},"aria-label":n?p("sampleBrowser.stop","Stop"):p("sampleBrowser.play","Play"),title:n?p("sampleBrowser.stop","Stop"):p("sampleBrowser.play","Play"),children:n?r.jsx(B.NtdStop,{size:14}):r.jsx(B.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(B.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(Bi,{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:u="name",sortDirection:h="asc",filterTags:p,searchQuery:g="",className:y=""})=>{const{t:m}=xe(),[x,b]=d.useState(null),[f,j]=d.useState(null),[v,C]=d.useState(null),[T,M]=d.useState(0),[k,R]=d.useState(new Map),[P,I]=d.useState(t),A=d.useRef(null),L=d.useRef(null);d.useEffect(()=>(A.current=new Audio,A.current.addEventListener("ended",()=>{C(null),M(0)}),()=>{A.current&&(A.current.pause(),A.current=null),L.current&&clearInterval(L.current)}),[]);const E=d.useMemo(()=>{let K=[...P];if(g){const W=g.toLowerCase();K=K.filter(Q=>{var w;return Q.name.toLowerCase().includes(W)||((w=Q.tags)==null?void 0:w.some(N=>N.toLowerCase().includes(W)))})}return p&&p.length>0&&(K=K.filter(W=>{var Q;return(Q=W.tags)==null?void 0:Q.some(w=>p.includes(w))})),f&&(K=f.samples||[]),K.sort((W,Q)=>{var N,S;let w=0;switch(u){case"name":w=W.name.localeCompare(Q.name);break;case"duration":w=W.duration-Q.duration;break;case"bpm":w=(W.bpm||0)-(Q.bpm||0);break;case"key":w=(W.key||"").localeCompare(Q.key||"");break;case"date":w=(((N=W.dateAdded)==null?void 0:N.getTime())||0)-(((S=Q.dateAdded)==null?void 0:S.getTime())||0);break}return h==="asc"?w:-w}),K},[P,g,p,f,u,h]),D=d.useCallback(K=>{b(K),n==null||n(K)},[n]),Z=d.useCallback(async K=>{if(A.current&&(A.current.pause(),L.current&&clearInterval(L.current),A.current.src=K.url||K.path,A.current.play(),C(K.id),M(0),L.current=window.setInterval(()=>{A.current&&M(A.current.currentTime/A.current.duration)},50),c&&!k.has(K.id)&&i))try{const W=await i(K);R(Q=>new Map(Q).set(K.id,W)),I(Q=>Q.map(w=>w.id===K.id?{...w,bpm:W.bpm,key:W.key,waveformData:W.waveformData}:w))}catch(W){console.error("Failed to analyze sample:",W)}},[c,k,i]),G=d.useCallback(()=>{A.current&&(A.current.pause(),A.current.currentTime=0),L.current&&clearInterval(L.current),C(null),M(0)},[]),F=d.useCallback(K=>{I(W=>W.map(Q=>Q.id===K?{...Q,favorite:!Q.favorite}:Q))},[]),q=d.useCallback((K,W)=>{W.dataTransfer.setData("application/json",JSON.stringify(K)),W.dataTransfer.effectAllowed="copy",a==null||a(K,W)},[a]),V=(K,W=0)=>{var Q;return r.jsxs("div",{className:"nice-sample-folder",style:{paddingLeft:W*16},children:[r.jsxs("button",{type:"button",className:`nice-sample-folder__btn ${(f==null?void 0:f.id)===K.id?"nice-sample-folder__btn--selected":""}`,onClick:()=>{j(K),s==null||s(K)},children:[r.jsx("span",{className:"nice-sample-folder__icon","aria-hidden":"true",children:r.jsx(B.NtdFolder,{size:14})}),r.jsx("span",{className:"nice-sample-folder__name",children:K.name}),K.samples&&r.jsx("span",{className:"nice-sample-folder__count",children:K.samples.length})]}),(Q=K.children)==null?void 0:Q.map(w=>V(w,W+1))]},K.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:()=>j(null),children:[r.jsx("span",{className:"nice-sample-folder__icon","aria-hidden":"true",children:r.jsx(B.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:P.length})]}),e.map(K=>V(K))]})}),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:m("sampleBrowser.key2","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:E.length===0?r.jsx("div",{className:"nice-sample-browser__empty",children:m("sampleBrowser.noSamplesFound","No samples found")}):E.map(K=>r.jsx(Ud,{sample:K,isSelected:(x==null?void 0:x.id)===K.id,isPlaying:v===K.id,playProgress:v===K.id?T:0,showWaveform:l,showAnalysis:c,onSelect:()=>D(K),onPlay:()=>Z(K),onStop:G,onDragStart:W=>q(K,W),onFavorite:()=>F(K.id)},K.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(Bi,{data:x.waveformData,width:300,height:80,progress:v===x.id?T:0}),r.jsxs("div",{className:"nice-sample-browser__preview-info",children:[r.jsx("div",{children:m("sampleBrowser.durationS","Duration: {duration}s").replace("{duration}",String(x.duration.toFixed(2)))}),r.jsx("div",{children:m("sampleBrowser.sampleRateHz","Sample Rate: {sampleRate} Hz").replace("{sampleRate}",String(x.sampleRate))}),r.jsx("div",{children:m("sampleBrowser.channels","Channels: {channels}").replace("{channels}",String(x.channels))}),x.bpm&&r.jsx("div",{children:m("sampleBrowser.bpm","BPM: {bpm}").replace("{bpm}",String(x.bpm))}),x.key&&r.jsx("div",{children:m("sampleBrowser.key","Key: {key}").replace("{key}",String(x.key))})]})]})]})};function Gi(e){return{past:[],present:e,future:[]}}function Wi(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function Ui(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 Vi(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 qi(e){return e.past.length>0}function Hi(e){return e.future.length>0}function ha(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>({...n}))}function Ki(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 Yi(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 Zi(e,t){return e.filter(n=>n.time<t.start||n.time>t.end)}function qd(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>n.id)}function Xi(e,t,n,a){const s={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:a};return[...e,s]}function Qi(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 Ji(e){return JSON.stringify(e,null,2)}function eo(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 gt(e,t){var n;return((n=e.find(a=>a.layerId===t))==null?void 0:n.events)??[]}function jt(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 Hd(e,t){switch(t.type){case"UNDO":return Ui(e);case"REDO":return Vi(e);default:{let n=e.present;switch(t.type){case"ADD_EVENT":{const a=[...gt(n,t.layerId),t.event];n=jt(n,t.layerId,a);break}case"UPDATE_EVENT":{const a=gt(n,t.layerId).map(s=>s.id===t.id?{...s,value:t.value,time:t.time,handleType:t.handleType??s.handleType}:s);n=jt(n,t.layerId,a);break}case"REMOVE_EVENT":{const a=gt(n,t.layerId).filter(s=>s.id!==t.id);n=jt(n,t.layerId,a);break}case"SET_EVENTS":n=jt(n,t.layerId,t.events);break;case"PASTE":{const a=gt(n,t.layerId),s=Ki(a,t.clipboard,t.targetTime);n=jt(n,t.layerId,s);break}case"CUT":{const a=gt(n,t.layerId),{remaining:s}=Yi(a,t.range);n=jt(n,t.layerId,s);break}case"DELETE_RANGE":{const a=gt(n,t.layerId),s=Zi(a,t.range);n=jt(n,t.layerId,s);break}case"RECORD":{const a=gt(n,t.layerId),s=Xi(a,t.cc,t.value,t.time);n=jt(n,t.layerId,s);break}case"THIN":{const a=gt(n,t.layerId),s=Qi(a,t.keepEveryN);n=jt(n,t.layerId,s);break}case"IMPORT":{const a=eo(t.json);a.length>0&&(n=jt(n,t.layerId,a));break}}return Wi(e,n)}}}function to(e=[]){const[t,n]=d.useReducer(Hd,Gi(e)),a=d.useRef([]),s=d.useCallback(v=>gt(t.present,v),[t.present]),i=d.useCallback((v,C)=>n({type:"ADD_EVENT",layerId:v,event:C}),[]),o=d.useCallback((v,C,T,M,k)=>n({type:"UPDATE_EVENT",layerId:v,id:C,value:T,time:M,handleType:k}),[]),l=d.useCallback((v,C)=>n({type:"REMOVE_EVENT",layerId:v,id:C}),[]),c=d.useCallback((v,C)=>n({type:"SET_EVENTS",layerId:v,events:C}),[]),u=d.useCallback(()=>n({type:"UNDO"}),[]),h=d.useCallback(()=>n({type:"REDO"}),[]),p=d.useCallback((v,C)=>{a.current=ha(gt(t.present,v),C)},[t.present]),g=d.useCallback((v,C)=>{a.current=ha(gt(t.present,v),C),n({type:"CUT",layerId:v,range:C})},[t.present]),y=d.useCallback((v,C)=>{a.current.length>0&&n({type:"PASTE",layerId:v,clipboard:a.current,targetTime:C})},[]),m=d.useCallback((v,C)=>n({type:"DELETE_RANGE",layerId:v,range:C}),[]),x=d.useCallback((v,C,T,M)=>n({type:"RECORD",layerId:v,cc:C,value:T,time:M}),[]),b=d.useCallback((v,C)=>n({type:"THIN",layerId:v,keepEveryN:C}),[]),f=d.useCallback(v=>Ji(gt(t.present,v)),[t.present]),j=d.useCallback((v,C)=>n({type:"IMPORT",layerId:v,json:C}),[]);return{snapshots:t.present,getEvents:s,addEvent:i,updateEvent:o,removeEvent:l,setEvents:c,undo:u,redo:h,canUndo:qi(t),canRedo:Hi(t),copy:p,cut:g,paste:y,clipboard:a.current,deleteRange:m,record:x,thin:b,exportLane:f,importLane:j}}let Kd=Date.now();function vn(){return Kd++}function Yd(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:vn(),cc:t,value:bn(i.value),time:i.time}),s=i.time);return a}function ks(e,t,n,a=32){const s=[];for(let i=0;i<=a;i++){const o=i/a;s.push({id:vn(),cc:n,value:bn(Rr(e.value,t.value,o)),time:Rr(e.time,t.time,o)})}return s}function Zd(e,t,n,a,s=48){const i=[];for(let o=0;o<=s;o++){const l=o/s,c=ws(e.time,t.time,n.time,l),u=ws(e.value,t.value,n.value,l);i.push({id:vn(),cc:a,value:bn(u),time:c})}return i}function Xd(e,t,n,a=8){const s=[],i=(t.time-e.time)/a,o=(t.value-e.value)/a;for(let l=0;l<a;l++){const c=e.time+l*i,u=bn(e.value+l*o);s.push({id:vn(),cc:n,value:u,time:c}),s.push({id:vn(),cc:n,value:u,time:c+i-.001})}return s}function Qd(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:vn(),cc:n,value:bn(Rr(e.value,t.value,c)),time:Rr(e.time,t.time,l)})}return i}function Jd(e,t=3){if(e.length<t)return e;const n=[...e].sort((a,s)=>a.time-s.time);return n.map((a,s)=>{const i=Math.max(0,s-Math.floor(t/2)),o=Math.min(n.length,i+t),l=n.slice(i,o),c=l.reduce((u,h)=>u+h.value,0)/l.length;return{...a,value:bn(Math.round(c))}})}function eu(e,t){let n;switch(e.mode){case"pencil":n=Yd(t,e.cc,e.resolution);break;case"line":n=t.length>=2?ks(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?n=Zd(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?n=ks(t[0],t[t.length-1],e.cc):n=[];break;case"step":n=t.length>=2?Xd(t[0],t[t.length-1],e.cc):[];break;case"ramp":n=t.length>=2?Qd(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=Jd(n,a)}return n}function bn(e){return Math.max(0,Math.min(127,Math.round(e)))}function Rr(e,t,n){return e+(t-e)*n}function ws(e,t,n,a){const s=1-a;return s*s*e+2*s*a*t+a*a*n}function zr(){return{waveform:"sine",rate:1,depth:.5,phase:0,center:.5,syncToBpm:!1,syncDivision:"1/4",enabled:!0}}const tu={"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 no(e,t){return e/60*tu[t]/4}function ro(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 La(e,t,n){if(!e.enabled)return e.center;const a=e.syncToBpm&&n?no(n,e.syncDivision):e.rate,s=t*a+e.phase/(2*Math.PI),i=ro(e.waveform,s),o=e.center+i*e.depth*.5;return Math.max(0,Math.min(1,o))}function _a(e,t,n){return Math.round(La(e,t,n)*127)}function ao(e,t,n,a,s=30,i){const o=n-t,l=Math.max(2,Math.ceil(o*s)),c=[];for(let u=0;u<=l;u++){const h=t+u/l*o,p=_a(e,h,i);c.push({time:h,value:p,cc:a})}return c}function so(e,t,n,a=2,s,i=200){const o=[];for(let l=0;l<=i;l++){const c=l/i*a,u=La(e,c,s);o.push({x:l/i*t,y:(1-u)*n})}return o}function nu(e){return JSON.stringify(e,null,2)}function ru(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const Xr=140,xn=24,au=[{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"}],su=[{mode:"pencil",label:"Pencil"},{mode:"line",label:"Line"},{mode:"curve",label:"Curve"},{mode:"step",label:"Step"},{mode:"ramp",label:"Ramp"}],iu=["sine","triangle","sawtooth","square","random","sample-hold"],ou=({layerId:e=0,ccNumber:t,duration:n=8,zoom:a=1,automation:s,onChangeCCNumber:i})=>{const o=to(),l=s??o,[c,u]=ve.useControllableState({value:t,fallbackValue:1,onChange:i,componentName:"NiceCCAutomationLaneEditor"}),{t:h}=xe(),p=d.useRef(null),[g,y]=d.useState("pencil"),[m,x]=d.useState(!1),b=d.useRef([]),[f,j]=d.useState(null),[v,C]=d.useState(!1),[T,M]=d.useState(zr()),k=d.useRef(null),R=l.getEvents(e),P=R.filter(w=>w.cc===c),I=Math.max(400,n*30*a),A=d.useCallback(w=>w/I*n,[I,n]),L=d.useCallback(w=>Math.round(Math.max(0,Math.min(127,127-(w-xn)/Xr*127))),[]),E=d.useCallback(w=>w/n*I,[I,n]),D=d.useCallback(w=>xn+(127-w)/127*Xr,[]),Z=d.useCallback(()=>{const w=p.current;if(!w)return;const N=w.getContext("2d");if(!N)return;const S=w.width,O=w.height;N.clearRect(0,0,S,O),N.fillStyle=ve.resolveCssColor("var(--nice-bg, #1a1a2e)",N.canvas),N.fillRect(0,0,S,O);const Y=ve.resolveCssColor("var(--nice-border-color, #cbd5e1)",N.canvas);N.strokeStyle=Y,N.lineWidth=1,N.globalAlpha=.5;for(let $=0;$<=127;$+=16){const H=D($);N.beginPath(),N.moveTo(0,H),N.lineTo(S,H),N.stroke()}N.globalAlpha=1,N.fillStyle=ve.resolveCssColor("var(--nice-text-muted, #64748b)",N.canvas),N.font="10px monospace",N.textBaseline="middle";for(const $ of[0,32,64,96,127])N.fillText(String($),2,D($));N.strokeStyle=Y,N.globalAlpha=.3;for(let $=0;$<=n;$++){const H=E($);N.beginPath(),N.moveTo(H,0),N.lineTo(H,O),N.stroke()}N.globalAlpha=1;const _=[...P].sort(($,H)=>$.time-H.time);if(_.length>0){N.beginPath(),N.moveTo(E(_[0].time),O-xn);for(const $ of _)N.lineTo(E($.time),D($.value));N.lineTo(E(_[_.length-1].time),O-xn),N.closePath(),N.fillStyle=ve.resolveCssColor("var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",N.canvas),N.fill(),N.beginPath(),N.strokeStyle=ve.resolveCssColor("var(--nice-primary, #3b82f6)",N.canvas),N.lineWidth=2;for(let $=0;$<_.length;$++){const H=E(_[$].time),X=D(_[$].value);$===0?N.moveTo(H,X):((_[$].handleType??"linear")==="step"&&N.lineTo(H,D(_[$-1].value)),N.lineTo(H,X))}N.stroke();for(const $ of _){const H=E($.time),X=D($.value),re=f===$.id;N.beginPath(),N.arc(H,X,re?6:4,0,Math.PI*2),N.fillStyle=ve.resolveCssColor(re?"var(--nice-primary-light, #60a5fa)":"var(--nice-primary, #3b82f6)",N.canvas),N.fill(),N.strokeStyle=ve.resolveCssColor("var(--nice-bg, #fff)",N.canvas),N.lineWidth=1.5,N.stroke()}}N.strokeStyle=Y,N.lineWidth=1,N.setLineDash([4,4]);const U=D(0);N.beginPath(),N.moveTo(0,U),N.lineTo(S,U),N.stroke(),N.setLineDash([])},[P,n,E,D,f]);d.useEffect(()=>{Z()},[Z]);const G=w=>{var Y;const N=(Y=p.current)==null?void 0:Y.getBoundingClientRect();if(!N)return;const S=w.clientX-N.left,O=w.clientY-N.top;g==="pencil"?(x(!0),b.current=[{time:A(S),value:L(O)}]):(x(!0),b.current=[{time:A(S),value:L(O)}])},F=w=>{var U;const N=(U=p.current)==null?void 0:U.getBoundingClientRect();if(!N)return;const S=w.clientX-N.left,O=w.clientY-N.top;m&&b.current.push({time:A(S),value:L(O)});const Y=[...P].sort(($,H)=>$.time-H.time);let _=null;for(const $ of Y){const H=E($.time),X=D($.value);if(Math.abs(S-H)<8&&Math.abs(O-X)<8){_=$.id;break}}j(_)},q=()=>{if(!m)return;x(!1);const w=b.current;if(w.length===0)return;const N=eu({mode:g,cc:c,resolution:.02,smoothing:g==="pencil"?.3:0},w);N.length>0&&l.setEvents(e,[...R,...N]),b.current=[]},V=w=>{var Y;const N=(Y=p.current)==null?void 0:Y.getBoundingClientRect();if(!N)return;const S=w.clientX-N.left,O=w.clientY-N.top;for(const _ of P){const U=E(_.time),$=D(_.value);if(Math.abs(S-U)<8&&Math.abs(O-$)<8){l.removeEvent(e,_.id);return}}l.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:c,value:L(O),time:A(S)})},K=()=>{const N=ao(T,0,n,c,Math.ceil(n*20),120).map((S,O)=>({...S,id:Date.now()+O}));l.setEvents(e,[...R,...N]),C(!1)},W=()=>{const w=l.exportLane(e),N=new Blob([w],{type:"application/json"}),S=URL.createObjectURL(N),O=document.createElement("a");O.href=S,O.download=`cc-lane-${c}-layer-${e}.json`,document.body.appendChild(O),O.click(),O.remove(),URL.revokeObjectURL(S)},Q=w=>{var S;const N=(S=w.target.files)==null?void 0:S[0];N&&(N.text().then(O=>{l.importLane(e,O)}),k.current&&(k.current.value=""))};return r.jsxs("div",{className:ye.panel,children:[r.jsxs("div",{className:ye.header,children:[r.jsx("h6",{className:ye.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:w=>u(Number(Tt(w))),options:au.map(w=>({value:String(w.cc),label:h("ccLane.cc2","{label} (CC{cc})").replace("{label}",String(h(`ccLane.preset.${w.key}`,w.label))).replace("{cc}",String(w.cc))}))}),r.jsx(ie.NiceSegmentedControl,{size:"sm",value:g,onChange:y,options:su.map(w=>({value:w.mode,label:h(`ccLane.mode.${w.mode}`,w.label)}))}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(B.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(B.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:ye.toolbar,children:[r.jsx(ie.NiceButton,{size:"sm",variant:v?"primary":"outline","aria-pressed":v,onClick:()=>C(!v),title:h("ccLane.lfoHint","Apply LFO modulation"),children:h("ccLane.lfo","LFO")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:W,title:h("ccLane.exportHint","Export CC lane as JSON"),children:h("ccLane.export","Export")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:()=>{var w;return(w=k.current)==null?void 0:w.click()},title:h("ccLane.importHint","Import CC lane from JSON"),children:h("ccLane.import","Import")}),r.jsx("input",{ref:k,type:"file",accept:".json",hidden:!0,onChange:Q}),r.jsx(ie.NiceButton,{size:"sm",variant:"danger",onClick:()=>l.setEvents(e,R.filter(w=>w.cc!==c)),title:h("ccLane.clearHint","Clear all CC events for this lane"),children:h("ccLane.clear","Clear")}),r.jsxs("span",{className:`${ye.noteText} ${ye.pushRight}`,children:[P.length," ",h("ccLane.events","events")]})]}),v&&r.jsxs("div",{className:ye.subPanel,children:[r.jsxs("div",{className:`${ye.row} ${ye.alignStart} ${ye.field}`,children:[r.jsx(ie.NiceSelect,{size:"sm",controlWidth:130,label:h("ccLane.lfoWave","Wave"),value:T.waveform,onChange:w=>M(N=>({...N,waveform:Tt(w)})),options:iu.map(w=>({value:w,label:w}))}),r.jsx(ie.NiceNumberInput,{size:"sm",className:ye.inputW120,label:h("ccLane.lfoRate","Rate (Hz)"),min:.01,max:20,step:.1,precision:2,value:T.rate,onChange:w=>{w!==null&&M(N=>({...N,rate:w}))}}),r.jsx("div",{className:ye.sliderW200,children:r.jsx(ie.NiceSlider,{size:"sm",label:h("ccLane.lfoDepth","Depth"),min:0,max:1,step:.01,value:T.depth,onChange:w=>M(N=>({...N,depth:w})),showValue:!0,formatValue:w=>w.toFixed(2)})}),r.jsx("div",{className:ye.sliderW200,children:r.jsx(ie.NiceSlider,{size:"sm",label:h("ccLane.lfoCenter","Center"),min:0,max:1,step:.01,value:T.center,onChange:w=>M(N=>({...N,center:w})),showValue:!0,formatValue:w=>w.toFixed(2)})})]}),r.jsxs("div",{className:ye.buttonRow,children:[r.jsx(ie.NiceButton,{size:"sm",variant:"primary",onClick:K,children:h("ccLane.applyLfo","Apply LFO")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:()=>C(!1),children:h("ccLane.cancel","Cancel")})]})]}),r.jsx("div",{style:{overflowX:"auto",borderRadius:6},children:r.jsx("canvas",{ref:p,width:I,height:Xr+xn*2,style:{cursor:m?"crosshair":f?"pointer":"crosshair",display:"block",borderRadius:6},onMouseDown:G,onMouseMove:F,onMouseUp:q,onMouseLeave:()=>{m&&q()},onDoubleClick:V,role:"img","aria-label":h("ccLane.canvas","CC automation lane")})}),r.jsx("div",{className:ye.noteTextMargin,children:h("ccLane.hint","Click to draw. Double-click to add/remove points. Drag to draw curves.")})]})},io={"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},pa={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function lu(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 oo(e,t){if(e.length===0)return[];const n=lu(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 cu(e,t,n,a=0,s=1){const i=oo(e,t);if(i.length===0)return[];const o=60/n,l=io[t.rate]*o,c=l*t.gate,u=[],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 b=t.velocityPattern?t.velocityPattern[g%t.velocityPattern.length]:x.velocity;u.push({pitch:x.pitch,velocity:b,startTime:m,duration:c,step:g})}else{const x=g%i.length,b=i[x],f=t.velocityPattern?t.velocityPattern[g%t.velocityPattern.length]:b.velocity;u.push({pitch:b.pitch,velocity:f,startTime:m,duration:c,step:g})}}return u}function lo(){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 co(){return Object.keys(io)}const Cs=e=>`${Math.round(e*100)}%`,du=({config:e=pa,onChange:t=()=>{},active:n=!1,onToggleActive:a=()=>{}})=>{const{t:s}=xe(),i=lo(),o=co(),l=c=>t({...e,...c});return r.jsxs("div",{className:`${ye.panel} ${n?"":ye.panelInactive}`,children:[r.jsxs("div",{className:ye.header,children:[r.jsx("h6",{className:ye.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(pa),title:s("arp.resetHint","Reset to defaults"),children:s("arp.reset","Reset")})]}),r.jsxs("div",{className:ye.grid2,children:[r.jsxs("div",{className:ye.full,children:[r.jsx("span",{className:ye.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:Tt(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:Cs}),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:Cs}),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})]})]})},js=e=>`${Math.round(e*100)}%`,uu=["sine","triangle","sawtooth","square","random","sample-hold"],hu=["1/1","1/2","1/4","1/8","1/16","1/32"],Sn=200,nn=48,pu=({config:e,onChange:t,index:n,onRemove:a})=>{const{t:s}=xe(),i=d.useRef(null),o=c=>t({...e,...c}),l=d.useCallback(()=>{const c=i.current;if(!c)return;const u=c.getContext("2d");if(!u)return;u.clearRect(0,0,Sn,nn),u.fillStyle=ve.resolveCssColor("var(--nice-bg-secondary, #161b22)",u.canvas),u.fillRect(0,0,Sn,nn),u.strokeStyle=ve.resolveCssColor("var(--nice-border-color, #cbd5e1)",u.canvas),u.lineWidth=1,u.setLineDash([3,3]),u.beginPath(),u.moveTo(0,nn/2),u.lineTo(Sn,nn/2),u.stroke(),u.setLineDash([]);const h=so(e,Sn,nn);if(h.length>0){u.beginPath(),u.strokeStyle=ve.resolveCssColor(e.enabled?"var(--nice-primary, #3b82f6)":"var(--nice-text-secondary, #484f58)",u.canvas),u.lineWidth=1.5;for(let p=0;p<h.length;p++){const g=h[p].x,y=h[p].y;p===0?u.moveTo(g,y):u.lineTo(g,y)}u.stroke()}},[e]);return d.useEffect(()=>{l()},[l]),r.jsxs("div",{className:`${ye.panel} ${ye.panelCompact} ${e.enabled?"":ye.panelInactive}`,children:[r.jsxs("div",{className:ye.header,children:[r.jsxs("h6",{className:ye.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(zr()),title:s("lfo.resetHint","Reset to defaults"),children:s("lfo.reset","Reset")}),a&&r.jsx("span",{className:ye.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(B.NtdClose,{size:12})})})]}),r.jsxs("div",{className:`${ye.row} ${ye.alignStart}`,children:[r.jsx("canvas",{ref:i,width:Sn,height:nn,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:ye.grow,children:[r.jsx("div",{className:ye.field,children:r.jsx(ie.NiceSegmentedControl,{size:"xs",block:!0,value:e.waveform,onChange:c=>o({waveform:c}),options:uu.map(c=>({value:c,label:r.jsx("span",{title:c,children:c==="sample-hold"?"S&H":c.slice(0,3)})}))})}),r.jsxs("div",{className:ye.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:js}),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:js}),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:ye.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:Tt(c)}),options:hu.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})})]})]})]})]})},fu=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],mu=[16,32,64],gu=e=>`${Math.round(e*100)}%`;function Ms(e){const t=Math.floor(e/12)-1;return`${fu[e%12]}${t}`}const yu=({seq:e})=>{const{t}=xe(),n=e==null?void 0:e.pattern,a=d.useMemo(()=>n?n.steps.slice(0,n.length):[],[n]);if(!e||!n)return r.jsxs("div",{className:ye.panel,children:[r.jsx("h6",{className:ye.title,children:t("stepSeq.title","Step Sequencer")}),r.jsx("div",{className:ye.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 u=c.currentTarget,h=u.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=()=>{u.removeEventListener("pointermove",g),u.removeEventListener("pointerup",y),u.removeEventListener("pointercancel",y)};(m=u.setPointerCapture)==null||m.call(u,c.pointerId),u.addEventListener("pointermove",g),u.addEventListener("pointerup",y),u.addEventListener("pointercancel",y),p(c.clientY)};return r.jsxs("div",{className:ye.panel,children:[r.jsxs("div",{className:ye.header,children:[r.jsx("h6",{className:ye.title,children:t("stepSeq.title","Step Sequencer")}),r.jsx(ie.NiceButton,{size:"sm",variant:i?"danger":"success",leftIcon:i?r.jsx(B.NtdStop,{size:12}):r.jsx(B.NtdPlay,{size:12}),onClick:e.togglePlayback,children:i?t("stepSeq.stop","Stop"):t("stepSeq.play","Play")})]}),r.jsxs("div",{className:`${ye.row} ${ye.alignStart} ${ye.field}`,children:[r.jsx(ie.NiceNumberInput,{size:"sm",className:ye.inputW120,label:t("stepSeq.bpm","BPM"),min:20,max:300,value:n.bpm,onChange:l=>{l!==null&&e.setBpm(l)}}),r.jsx("div",{className:ye.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:gu})}),r.jsxs("div",{children:[r.jsx("span",{className:ye.label,children:t("stepSeq.length","Steps")}),r.jsx(ie.NiceSegmentedControl,{size:"sm",value:n.length,onChange:e.setLength,options:mu.map(l=>({value:l,label:String(l)}))})]})]}),r.jsxs("div",{className:ye.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(B.NtdArrowRight,{size:12}),onClick:()=>e.shift(1),children:t("stepSeq.shift","Shift")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(B.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 u=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":u,"aria-label":`${t("stepSeq.step","Step")} ${c+1}${u?`, ${Ms(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:u?`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:u?"var(--nice-color-white, #ffffff)":"var(--nice-text-secondary, #484f58)",fontSize:8,fontWeight:600,transition:"background 0.1s"},children:u?Ms(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:u?"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"}})}),u&&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 vu(e,t,n){const{t:a}=xe(),[s,i]=d.useState("interval"),[o,l]=d.useState(30),c=d.useRef(null),u=d.useCallback(()=>{if(e)try{localStorage.setItem("audioEditor.autoSave",JSON.stringify(e)),t(a("useAutoSave.projectAutoSavedLocally","Project auto-saved locally")),n("success"),setTimeout(()=>t(""),2e3)}catch(h){t(a("useAutoSave.autoSaveError","Auto-save error:")+" "+h.message),n("error")}},[e,t,n,a]);return d.useEffect(()=>{(s==="onChange"||s==="both")&&u()},[e,s,u]),d.useEffect(()=>(c.current&&(clearInterval(c.current),c.current=null),(s==="interval"||s==="both")&&o>0&&(c.current=window.setInterval(u,o*1e3)),()=>{c.current&&(clearInterval(c.current),c.current=null)}),[s,o,u]),{autoSaveMode:s,setAutoSaveMode:i,autoSaveInterval:o,setAutoSaveInterval:l}}function bu(e,t,n){const a=d.useRef(null),[s,i]=d.useState(!1),[o,l]=d.useState(0),[c,u]=d.useState(10),[h,p]=d.useState(!1),[g,y]=d.useState(120),m=d.useCallback((k,R)=>`L${k}-C${R}`,[]),x=d.useCallback((k,R)=>{if(!a.current||!R.audioBuffer)return;const P=m(k,R.id),I=e[k];a.current.addClip({id:P,buffer:R.audioBuffer,startTime:R.start,offset:0,duration:R.duration,layerId:k,volume:(I==null?void 0:I.volume)??1,pan:(I==null?void 0:I.pan)??0,stretchFactor:R.stretchFactor||1,effectChain:(I==null?void 0:I.effectChain)||[]})},[e,m]),b=d.useCallback((k,R)=>{var P;(P=a.current)==null||P.removeClip(m(k,R))},[m]);d.useEffect(()=>{Object.entries(t).forEach(([k,R])=>{const P=Number(k);R==null||R.forEach(I=>x(P,I))})},[t,e,x]),d.useEffect(()=>{a.current&&Object.entries(n).forEach(([k,R])=>{const P=Number(k);a.current.setMidiCCEvents(P,R)})},[n]);const f=d.useCallback(()=>{a.current&&(s?a.current.pause():a.current.play())},[s]),j=d.useCallback(()=>{var k;(k=a.current)==null||k.stop()},[]),v=d.useCallback(k=>{var R;(R=a.current)==null||R.seek(k)},[]),C=d.useCallback(()=>{if(!a.current)return;const k=!h;p(k),a.current.setLoopRegion(0,c,k)},[h,c]),T=d.useCallback(k=>{var P;const R=Math.max(1,c+k);u(R),(P=a.current)==null||P.setLoopRegion(0,R,h)},[c,h]),M=d.useCallback(async(k,R=1024)=>{const P=await k.arrayBuffer(),I=new(window.AudioContext||window.webkitAudioContext),A=await I.decodeAudioData(P.slice(0)),L=A.getChannelData(0),E=L.length,D=Math.max(1,Math.floor(E/R)),Z=[];for(let G=0;G<R;G++){const F=G*D;if(F>=E)break;Z.push(L[F])}return I.close(),{waveform:Z.map(G=>Math.max(-1,Math.min(1,G))),duration:A.duration,buffer:A}},[]);return{engineRef:a,isPlaying:s,setIsPlaying:i,currentTime:o,setCurrentTime:l,duration:c,setDuration:u,isLooping:h,setIsLooping:p,bpm:g,setBpm:y,handlePlayPause:f,handleStop:j,handleSeek:v,handleToggleLoop:C,handleAdjustDuration:T,upsertEngineClip:x,removeEngineClip:b,makeEngineClipId:m,blobToWaveform:M}}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 n=t.mimeType||"audio/webm";this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:n}),this.audioChunks=[],this.audioContext=new(window.AudioContext||window.webkitAudioContext);let s=this.audioContext.createMediaStreamSource(this.stream);t.gain!==void 0&&t.gain>0&&(this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=t.gain,s.connect(this.gainNode),s=this.gainNode),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,s.connect(this.analyser),t.monitorEnabled&&(this.monitorGain=this.audioContext.createGain(),this.monitorGain.gain.value=(t.monitorVolume??100)/100,s.connect(this.monitorGain),this.monitorGain.connect(this.audioContext.destination));const i=()=>{if(!this.analyser)return;const o=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(o);let l=0;for(let u=0;u<o.length;u++){const h=(o[u]-128)/128;l+=h*h}const c=Math.sqrt(l/o.length);this.levelCallback&&this.levelCallback(c),this.isRecording&&(this.levelRaf=requestAnimationFrame(i))};this.mediaRecorder.ondataavailable=o=>{o.data&&o.data.size>0&&this.audioChunks.push(o.data)},this.mediaRecorder.start(),this.isRecording=!0,this.levelRaf=requestAnimationFrame(i)}getStream(){return this.stream}async stopRecording(){return!this.isRecording||!this.mediaRecorder?null:new Promise(t=>{const n=this.mediaRecorder;n.onstop=()=>{const a=new Blob(this.audioChunks,{type:n.mimeType});this.cleanup(),t(a)},n.stop(),this.isRecording=!1})}cleanup(){this.levelRaf&&(cancelAnimationFrame(this.levelRaf),this.levelRaf=null),this.levelCallback=void 0,this.monitorGain&&(this.monitorGain.disconnect(),this.monitorGain=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.analyser&&(this.analyser.disconnect(),this.analyser=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.stream&&(this.stream.getTracks().forEach(t=>t.stop()),this.stream=null),this.mediaRecorder=null,this.audioChunks=[]}}function xu(e){const{t}=xe(),[n,a]=d.useState(!1),[s,i]=d.useState(!1),[o,l]=d.useState(0),[c,u]=d.useState(0),[h,p]=d.useState(null),g=d.useRef(null),y=d.useRef(null),m=d.useRef(0),x=d.useRef(null),b=d.useRef(null),f=d.useCallback(()=>{x.current&&(clearInterval(x.current),x.current=null),b.current&&(clearTimeout(b.current),b.current=null)},[]),j=d.useCallback(async()=>{if(!e.activeLayer){e.showToast("Select a layer to record.","error");return}n||(g.current||(g.current=new Da),m.current=y.current??e.currentTime,a(!0),l(0),await g.current.startRecording({onLevel:l}))},[e,n]),v=d.useCallback(async()=>{var E;if(f(),i(!1),u(0),y.current=null,!g.current){a(!1),l(0);return}const M=await g.current.stopRecording();if(a(!1),l(0),!M||!e.activeLayer)return;const{waveform:k,duration:R,buffer:P}=await e.blobToWaveform(M),I=e.activeLayer.id;e.setWaveforms(D=>({...D,[I]:k}));const A=Math.max(0,m.current||0),L={id:Date.now(),label:t("useRecording.recording","Recording"),start:A,duration:R,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:(E=e.layerSettings[I])==null?void 0:E.color,blob:M,blobUrl:URL.createObjectURL(M),audioBuffer:P};e.setLayerClips(D=>({...D,[I]:[...D[I]||[],L]})),e.upsertEngineClip(I,L),e.setSelectedClip({layerId:I,clipId:L.id})},[e,f,t]),C=d.useCallback(M=>{if(M<=0){j();return}i(!0),u(M);const k=performance.now();x.current=window.setInterval(()=>{const R=(performance.now()-k)/1e3;u(Math.max(0,M-R))},100),b.current=window.setTimeout(()=>{f(),i(!1),u(0),y.current||j()},M*1e3)},[j,f]),T=d.useCallback(async()=>{if(n||s){await v();return}if(!e.activeLayer){e.showToast("Select a layer before recording","error");return}const M=Math.max(0,e.countInBars)*4*(60/e.bpm),k=e.punchIn!=null&&e.punchIn>e.currentTime?e.punchIn:null;k&&(y.current=k),e.overdubEnabled&&!e.isPlaying&&e.playEngine(),k?M>0&&C(M):C(M)},[n,s,e,v,C]);return{isRecording:n,isCountIn:s,monitorLevel:o,countInRemaining:c,punchOut:h,setPunchOut:p,armedPunchInRef:y,recorderRef:g,clearCountInTimers:f,startRecordingNow:j,stopRecordingFlow:v,handleRecord:T}}var uo=(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))(uo||{});const Su={};class er{constructor(t,n,a,s={}){this.type=t,this.name=n,this.component=Su[t]??(()=>null),this.audioType=a,this.parameters=s}}new er("Recorder","Recorder","vocal",{deviceId:"",gain:1,sensitivity:"high"}),new er("Audio Clip","Audio Clip","instrumental",{clipId:null,octave:"4"}),new er("Speech Synth","Speech Synth","vocal",{text:"",voice:"default"}),new er("Keyboard/Pads","Keyboard","instrumental",{instrument:"piano",preset:"default",velocity:100});function ho(e,t,n,a,s){n(i=>t?[...i,t]:i),a([]),s(e)}function ku(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 wu(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 Cu{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 ju=st.scoped("useProjectCRUD");function Mu(e){const{t}=xe(),{project:n,activeSection:a,setProject:s,setActiveSection:i,setLayers:o,setActiveLayer:l,setUndoStack:c,setRedoStack:u,addSection:h,addLayer:p}=e,g=d.useCallback(v=>ho(v,n,c,u,s),[n,c,u,s]),y=d.useCallback(async()=>{var k;if(!n)return;const v=(((k=n.sections)==null?void 0:k.length)??0)+1,C=t("useProjectCRUD.section","Section"),M={id:await h(n.id,C,v),projectId:n.id,name:C,orderNumber:v,layers:[]};g({...n,sections:[...n.sections||[],M]}),i(M)},[n,g,i,h,t]),m=d.useCallback(async v=>{var M,k,R;if(!n||!await e.confirm(t("useProjectCRUD.deleteSectionConfirm","Delete this section?")))return;await e.deleteSection(v);const T=(n.sections??[]).filter(P=>P.id!==v);g({...n,sections:T}),i(T[0]??null),o(((M=T[0])==null?void 0:M.layers)??[]),l(((R=(k=T[0])==null?void 0:k.layers)==null?void 0:R[0])??null)},[n,g,i,o,l,e,t]),x=d.useCallback(async()=>{var C;if(!a)return;const v={id:-Date.now(),name:t("useProjectCRUD.newLayer","New Layer"),sectionId:a.id,audioSource:uo.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};o(T=>[...T,v]),l(v);try{const T=await p(a.id,v.name,v.audioSource,v.audioSourceParameters);o(M=>M.map(k=>k.id===v.id?{...v,id:T}:k)),n&&g({...n,sections:((C=n.sections)==null?void 0:C.map(M=>M.id===a.id?{...M,layers:[...(M.layers??[]).filter(k=>k.id!==T),{...v,id:T}]}:M))??[]})}catch(T){o(M=>M.filter(k=>k.id!==v.id)),ju.error("Failed to add layer:",T)}},[a,n,g,o,l,p,t]),b=d.useCallback(async v=>{var T,M;if((T=e.layerSettings[v])!=null&&T.locked){e.showToast(t("useProjectCRUD.layerLocked","Layer is locked. Unlock to delete."),"error");return}await e.confirm(t("useProjectCRUD.deleteLayerConfirm","Delete this layer?"))&&((e.layerClips[v]||[]).forEach(k=>e.removeEngineClip(v,k.id)),e.setLayerMidiNotes(k=>{const R={...k};return delete R[v],R}),await e.deleteLayer(v),o(k=>k.filter(R=>R.id!==v)),l(k=>(k==null?void 0:k.id)===v?null:k),n&&g({...n,sections:((M=n.sections)==null?void 0:M.map(k=>k.id===(a==null?void 0:a.id)?{...k,layers:(k.layers??[]).filter(R=>R.id!==v)}:k))??[]}))},[n,a,g,o,l,e,t]),f=d.useCallback(async()=>{if(!n)return;const v=e.projectVolume===""?void 0:Number(e.projectVolume);if(Number.isNaN(v)){e.setStatusType("error"),e.setStatusMessage(t("useProjectCRUD.volumeNotNumber","Volume must be a number"));return}if(!e.projectName.trim()){e.setStatusType("error"),e.setStatusMessage(t("useProjectCRUD.projectNameEmpty","Project name cannot be empty"));return}await e.updateProject(n.id,{name:e.projectName||n.name,isTemplate:e.projectIsTemplate,volume:v}),g({...n,name:e.projectName||n.name,isTemplate:e.projectIsTemplate,volume:v}),e.setStatusType("success"),e.setStatusMessage(t("useProjectCRUD.projectSaved","Project saved"))},[n,e,g,t]),j=d.useCallback(async()=>{var T;if(!a)return;const v=e.sectionName||a.name,C=e.sectionOrder===""?a.orderNumber:Number(e.sectionOrder);if(!v.trim()){e.setStatusType("error"),e.setStatusMessage(t("useProjectCRUD.sectionNameEmpty","Section name cannot be empty"));return}if(Number.isNaN(C)){e.setStatusType("error"),e.setStatusMessage(t("useProjectCRUD.orderNotNumber","Order must be a number"));return}await e.updateSection(a.id,{name:v,orderNumber:C}),i({...a,name:v,orderNumber:C}),n&&g({...n,sections:((T=n.sections)==null?void 0:T.map(M=>M.id===a.id?{...M,name:v,orderNumber:C}:M))??[]}),e.setStatusType("success"),e.setStatusMessage(t("useProjectCRUD.sectionSaved","Section saved"))},[a,n,e,g,i,t]);return{handleAddSection:y,handleDeleteSection:m,handleAddLayer:x,handleDeleteLayer:b,handleSaveProject:f,handleSaveSection:j}}const po=d.createContext(null);function Ru(){const e=d.useContext(po);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const za=({value:e,children:t})=>r.jsx(po.Provider,{value:e,children:t});process.env.NODE_ENV!=="production"&&(za.displayName="EditorTrackProvider");const hn=(e,t)=>t&&t>0?e*15/t:e/10,Fa=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},Nu=(e,t)=>{const n=t??Fa(e),a=[];let s="",i=0,o="",l=!0;function c(){o.trim()!==""&&(s.length>0&&(s+=" "),s+=o.trim()),o=""}return e.forEach(u=>{if(!(u.startsWith("#")||u.startsWith("E"))){if(u.startsWith("-"))c(),s.trim().length>0&&(a.push({text:s.trim(),timestamp:i}),s=""),l=!0;else if(u.startsWith(":")||u.startsWith("*")){const h=u.indexOf(" "),p=u.indexOf(" ",h+1),g=u.indexOf(" ",p+1),y=u.indexOf(" ",g+1);if(y===-1)return;const m=hn(parseFloat(u.substring(h+1,p)),n);s===""&&(i=m);const x=u.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 n=t??Fa(e),a=[];let s=[],i="",o=0,l=!0,c=null,u="";function h(){c&&u.trim()!==""&&(c.text=u.trim(),s.push({...c}),i.length>0&&(i+=" "),i+=c.text),c=null,u=""}return e.forEach(p=>{if(!(p.startsWith("#")||p.startsWith("E"))){if(p.startsWith("-"))h(),i.trim().length>0&&(a.push({text:i.trim(),timestamp:o,words:s}),i="",s=[]),l=!0;else if(p.startsWith(":")||p.startsWith("*")){const g=p.startsWith("*"),y=p.indexOf(" "),m=p.indexOf(" ",y+1),x=p.indexOf(" ",m+1),b=p.indexOf(" ",x+1);if(b===-1)return;const f=hn(parseFloat(p.substring(y+1,m)),n),j=hn(parseFloat(p.substring(m+1,x)),n),v=f+j;i===""&&(o=f);const C=p.substring(b+1);if(C.trim()==="~"){c&&(c.endTime=v);return}let T=C;T.startsWith("~")&&(T=T.substring(1)),l?(h(),u=T.trimEnd(),c={text:"",startTime:f,endTime:v,isGolden:g}):c?(u+=T.trimEnd(),c.endTime=v,g&&(c.isGolden=!0)):(u=T.trimEnd(),c={text:"",startTime:f,endTime:v,isGolden:g}),l=C.endsWith(" ")}}}),h(),i.trim().length>0&&a.push({text:i.trim(),timestamp:o,words:s}),a},fo=(e,t)=>{const n=t??Fa(e),a=[];let s=[],i=0;function o(){s.length>0&&(a.push({timestamp:i,syllables:[...s]}),s=[])}return e.forEach(l=>{if(!(l.startsWith("#")||l.startsWith("E"))){if(l.startsWith("-")){o();const c=l.trim().split(/\s+/);if(c.length>=2){const u=parseFloat(c[1]);isFinite(u)&&(i=hn(u,n))}}else if(l.startsWith(":")||l.startsWith("*")){const c=l.startsWith("*"),u=l.indexOf(" "),h=l.indexOf(" ",u+1),p=l.indexOf(" ",h+1),g=l.indexOf(" ",p+1);if(g===-1)return;const y=parseFloat(l.substring(u+1,h)),m=parseFloat(l.substring(h+1,p)),x=hn(y,n),b=x+hn(m,n);s.length===0&&(i=x);const f=l.substring(g+1);if(f.trim()==="~"){s.length>0&&(s[s.length-1].endTime=b);return}let j=f;j.startsWith("~")&&(j=j.substring(1));const v=f.endsWith(" "),C=v?j.slice(0,-1):j;s.push({text:C,startTime:x,endTime:b,isGolden:c,hasTrailingSpace:v})}}}),o(),a},Pu=(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},Eu=(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},Rs="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",Ns="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))",Au="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",Iu=({song:e,currentTime:t=0})=>{const{t:n}=xe(),a=d.useMemo(()=>!e||!e.notes.length?[]:fo(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 u=a[c].timestamp,h=c+1<a.length?a[c+1].timestamp:u+30;if(s>=u&&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,u)=>{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},u):h>=1?r.jsx("span",{style:{background:m?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Rs,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:m?`drop-shadow(${Ns})`:"none",transition:"filter 0.2s ease"},children:g},u):r.jsxs("span",{style:{position:"relative",display:"inline",filter:y?m?`drop-shadow(${Ns})`:`drop-shadow(${Au})`:"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))":Rs,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",clipPath:`inset(0 ${100-p}% 0 0)`,pointerEvents:"none"},children:g})]},u)})}),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,u)=>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?" ":"")},u))})]}):a.length>0?r.jsx("p",{style:{color:"var(--karaoke-waiting-text, #999)"},children:r.jsx(B.NtdMusic,{size:20})}):r.jsxs("p",{style:{color:"var(--karaoke-waiting-text, #999)",display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(B.NtdMicrophone,{size:18})," ",n("karaokeLyrics.waitingForLyrics","Waiting for lyrics...")]})})},mo=d.memo(Iu),Lu=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Lt(e){return 12*Math.log2(e/440)+69}function _t(e){const t=Math.round(e);return`${Lu[(t%12+12)%12]}${Math.floor(t/12)-1}`}function Vn(e,t){const n=e-t;return n-12*Math.round(n/12)}const _u="var(--nice-color-success, #22c55e)",Du="var(--nice-color-error, #ef4444)",zu="var(--nice-color-primary, #3b82f6)",kn=e=>typeof e=="number"&&e>0,Fu=({pitch:e,target:t,history:n,showTarget:a=!0,showHistory:s=!0,historyLength:i=100,tolerance:o=1,range:l=6,hitColor:c=_u,missColor:u=Du,targetColor:h=zu,height:p=120,idleText:g,className:y,style:m,"aria-label":x,"data-testid":b})=>{const{t:f}=xe(),j=d.useRef(null),v=d.useRef(null),[C,T]=d.useState(0),M=d.useRef([]),[,k]=d.useState(0);d.useEffect(()=>{n||(M.current=[...M.current,kn(e)?e:null].slice(-i),k(Z=>Z+1))},[e,n,i]);const R=(n??M.current).slice(-i),P=typeof t=="number",I=!kn(e)&&!P&&!R.some(kn),A=kn(e)?Lt(e):void 0;d.useEffect(()=>{const Z=v.current;if(!Z||I||(T(Z.clientWidth),typeof ResizeObserver>"u"))return;const G=new ResizeObserver(()=>T(Z.clientWidth));return G.observe(Z),()=>G.disconnect()},[I]),d.useEffect(()=>{const Z=j.current,G=Z==null?void 0:Z.getContext("2d");if(!Z||!G||C<=0)return;const F=typeof window<"u"&&window.devicePixelRatio||1;Z.width=Math.round(C*F),Z.height=Math.round(p*F),G.setTransform(F,0,0,F,0,0),G.clearRect(0,0,C,p);const q=_=>ve.resolveCssColor(_,Z),V=q(c),K=q(u),W=q(h),Q=q("var(--nice-border-color, rgba(127, 127, 127, 0.25))"),w=q("var(--nice-text-secondary, #888)"),N=P?t:A??69,S=l*2,O=_=>{const U=P?Vn(_,N):_-N;return p/2-Math.max(-l,Math.min(l,U))/S*p};G.strokeStyle=Q,G.lineWidth=1;for(let _=-l;_<=l;_++){const U=p/2-_/S*p;G.beginPath(),G.moveTo(0,U),G.lineTo(C,U),G.stroke()}if(P&&a){const _=o/S*p;G.globalAlpha=.25,G.fillStyle=W,G.fillRect(0,p/2-_,C,_*2),G.globalAlpha=1,G.strokeStyle=W,G.lineWidth=2,G.beginPath(),G.moveTo(0,p/2),G.lineTo(C,p/2),G.stroke()}const Y=_=>!P||Math.abs(Vn(_,t))<=o;if(s&&R.length>1){const _=C/Math.max(1,i-1),U=C-(R.length-1)*_;R.forEach(($,H)=>{if(!kn($))return;const X=Lt($);G.fillStyle=Y(X)?V:K,G.beginPath(),G.arc(U+H*_,O(X),2,0,Math.PI*2),G.fill()})}if(A!==void 0&&(G.fillStyle=Y(A)?V:K,G.beginPath(),G.arc(C-7,O(A),6,0,Math.PI*2),G.fill()),G.font="11px sans-serif",G.fillStyle=w,G.textBaseline="top",P&&G.fillText(_t(t),4,4),A!==void 0){const _=_t(A);G.fillText(_,C-18-G.measureText(_).width,4)}},[C,p,R,A,t,P,a,s,i,o,l,c,u,h]);const L=`nice-pitch-meter${I?" nice-pitch-meter--idle":""}${y?` ${y}`:""}`;if(I)return r.jsxs("div",{className:L,style:{height:p,...m},role:"status","data-testid":b,children:[r.jsx(B.NtdMicrophone,{size:18}),r.jsx("span",{children:g??f("pitchMeter.waiting","Waiting for a voice…")})]});const E=A!==void 0&&P?Vn(A,t):void 0,D=x??[P?f("pitchMeter.target","Target {note}").replace("{note}",_t(t)):"",A!==void 0?f("pitchMeter.sung","sung {note}").replace("{note}",_t(A)):f("pitchMeter.silent","silent"),E!==void 0?f("pitchMeter.offset","{n} semitones").replace("{n}",(E>0?"+":"")+E.toFixed(1)):""].filter(Boolean).join(", ");return r.jsx("div",{ref:v,className:L,style:{height:p,...m},"data-testid":b,children:r.jsx("canvas",{ref:j,role:"img","aria-label":D,style:{width:"100%",height:p}})})},Qr={},Ou=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:vt&&vt.tagName.toUpperCase()==="SCRIPT"&&vt.src||new URL("index.cjs",document.baseURI).href}<"u"&&(Qr==null?void 0:Qr.VITE_DEBUG_KARAOKE)==="true";function fa(e,t,...n){(Ou||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 go=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},Ts=(e,t)=>t&&t>0?e*15/t:e/10,Zn=(e,t)=>{const n=t??go(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:Ts(parseFloat(o[1]),n),duration:Ts(parseFloat(o[2]),n),pitch:parseInt(o[3],10),isGold:c})}}),s.length>0&&a.push(s),a},yo=(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},vo=st.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}},Bu="karaoke.scoringPresets";function Gu(){try{const e=localStorage.getItem(Bu);return e?JSON.parse(e):null}catch(e){return vo.warn("Failed to parse scoring presets overrides",e),null}}function bo(e){const t={...Oa},n=Gu();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=bo();const Wu=async e=>{try{let t=null;if(e?t=await e.getKaraokeScoringConfig():(vo.debug("No fetcher provided, using defaults"),t=null),t&&t.presets)return exports.ScoringPresets=bo(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},Fr=(e="normal")=>exports.ScoringPresets[e]||Oa.normal,Uu=3,te=Uu;function Kt(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 pn(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,n=t+2,a=Math.max(t-te,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${te+a} ${te}H${n}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 Nr(e){const t=e*.3|0,n=t+2,a=Math.max(t-te,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e-t}V${t}Z`,inn:`M${te+a} ${te}H${n}V${e-te}H${te+a}L${te} ${e-te-a}V${te+a}Z`}}function Gt(e){const t=e*.42|0,n=t+2,a=Math.max(t-(te*1.4|0),2);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e/2}Z`,inn:`M${te+a} ${te}H${n}V${e-te}H${te+a}L${te} ${e/2}Z`}}function Tr(e){const t=e*.3|0,n=t+4,a=Math.max(t-te,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${te+a} ${te}H${n}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,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${te+(t*1.2|0)} ${te}H${n}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,n=t+3,a=Math.max(t-te,1);return{w:n,out:`M0 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}Z`,inn:`M${te} ${te}H${n}V${e-te}H${te+a}Q${te} ${e-te} ${te} ${e-te-a}Z`}}function Pr(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${te+(t*1.8|0)} ${te}H${n}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,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${te+(t*2.5|0)} ${te}H${n}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 fr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M${t} 0H${n}V${e}H0Z`,inn:`M${te+t-(te*1.3|0)} ${te}H${n}V${e-te}H${te+1}Z`}}function ma(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}V${e}H${t}Z`,inn:`M${te} ${te}H${n}V${e-te}H${te+t-(te*1.3|0)+1}Z`}}function Ot(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 fn(e){return{w:te+1,out:`M0 0H${te+1}V${e}H0Z`,inn:`M0 ${te}H1V${e-te}H0Z`}}function xo(e){const t=Math.min(14,e*.22)|0,n=t+2,a=Math.max(t-te,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 ${te}H${n-te-a}Q${n-te} ${te} ${n-te} ${te+a}V${e-te-a}Q${n-te} ${e-te} ${n-te-a} ${e-te}H0Z`}}function mn(e){const t=e*.3|0,n=t+2,a=Math.max(t-te,1);return{w:n,out:`M0 0H${n-t}L${n} ${t}V${e-t}L${n-t} ${e}H0Z`,inn:`M0 ${te}H${n-te-a}L${n-te} ${te+a}V${e-te-a}L${n-te-a} ${e-te}H0Z`}}function Nt(e){const t=e*.42|0,n=t+2,a=Math.max(t-(te*1.4|0),2);return{w:n,out:`M0 0H${n-t}L${n} ${e/2}L${n-t} ${e}H0Z`,inn:`M0 ${te}H${n-te-a}L${n-te} ${e/2}L${n-te-a} ${e-te}H0Z`}}function So(e){const t=e*.3|0,n=t+4,a=Math.max(t-te,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 ${te}H${n-te-a}Q${n-te} ${te} ${n-te} ${te+a}V${e-te-a}L${n-te-(a*.6|0)} ${e-te}H0Z`}}function ko(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 ${te}H${n-te-(t*1.2|0)}C${n-te-(t*2.2|0)} ${e*.37|0} ${n-te-(t*2.2|0)} ${e*.63|0} ${n-te-(t*1.2|0)} ${e-te}H0Z`}}function wo(e){const t=e*.32|0,n=t+3,a=Math.max(t-te,1);return{w:n,out:`M0 0H${n}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${te}H${n-te}V${e-te-a}Q${n-te} ${e-te} ${n-te-a} ${e-te}H0Z`}}function Va(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 ${te}H${n-te-(t*1.8|0)}C${n-te-(t*.9|0)} ${te} ${n-te+(t*.1|0)} ${e*.22|0} ${n-te-(t*.4|0)} ${e*.37|0}S${n-te-(t*.4|0)} ${e*.78|0} ${n-te-(t*1.8|0)} ${e-te}H0Z`}}function Er(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 ${te}H${n-te-(t*2.5|0)}L${n-te-(t*.7|0)} ${te+(t*1.6|0)}L${n-te-(t*1.7|0)} ${e*.36|0}L${n-te} ${e/2|0}L${n-te-(t*1.7|0)} ${e*.64|0}L${n-te-(t*.7|0)} ${e-te-(t*1.6|0)}L${n-te-(t*2.5|0)} ${e-te}H0Z`}}function ga(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}L${n-t} ${e}H0Z`,inn:`M0 ${te}H${n-te}L${n-te-t+(te*1.3|0)} ${e-te}H0Z`}}function mr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n-t}L${n} ${e}H0Z`,inn:`M0 ${te}H${n-te-t+(te*1.3|0)}L${n-te} ${e-te}H0Z`}}const qa=[{name:"Pill",L:Kt,R:Ot},{name:"Sharp",L:pn,R:fn},{name:"Soft",L:Ba,R:xo},{name:"Chamfer",L:Nr,R:mn},{name:"Arrow",L:Gt,R:Nt},{name:"Shield",L:Tr,R:So},{name:"Bracket",L:Ga,R:ko},{name:"Tab",L:Wa,R:wo},{name:"Wave",L:Pr,R:Va},{name:"Ornate",L:Ua,R:Er}],Co=[{name:"Pill→Arrow",L:Kt,R:Nt},{name:"Arrow→Pill",L:Gt,R:Ot},{name:"Pill→Sharp",L:Kt,R:fn},{name:"Sharp→Pill",L:pn,R:Ot},{name:"Pill→Chamfer",L:Kt,R:mn},{name:"Chamfer→Pill",L:Nr,R:Ot},{name:"Arrow→Sharp",L:Gt,R:fn},{name:"Sharp→Arrow",L:pn,R:Nt},{name:"Arrow→Chamfer",L:Gt,R:mn},{name:"Chamfer→Arrow",L:Nr,R:Nt},{name:"Soft→Arrow",L:Ba,R:Nt},{name:"Shield→Chamfer",L:Tr,R:mn},{name:"Pill→Wave",L:Kt,R:Va},{name:"Wave→Arrow",L:Pr,R:Nt},{name:"Tab→Pill",L:Wa,R:Ot},{name:"Ornate→Sharp",L:Ua,R:fn},{name:"Sharp→Ornate",L:pn,R:Er},{name:"Bracket→Arrow",L:Ga,R:Nt},{name:"Shield→Pill",L:Tr,R:Ot},{name:"Wave→Ornate",L:Pr,R:Er}],jo=[{name:"Skew ╲",L:fr,R:ga},{name:"Skew ╱",L:ma,R:mr},{name:"◇ Romb",L:Gt,R:Nt},{name:"╲→Pill",L:fr,R:Ot},{name:"Pill→╲",L:Kt,R:ga},{name:"╱→Sharp",L:ma,R:fn},{name:"Sharp→╱",L:pn,R:mr},{name:"╲→Arrow",L:fr,R:Nt},{name:"Arrow→╱",L:Gt,R:mr},{name:"◇→Chamfer",L:Gt,R:mn}],qn=(function(){return[...qa,...Co,...jo]})(),Mo=qa[0];function Tn(e){return qn.find(t=>t.name===e)||Mo}const $r=[{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 Pn(e){return $r.find(t=>t.name===e)||null}const Ut={color:null,capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,glass:0,textureUrl:null,textureScale:1},Or=(function(){return{...Ut,glass:85}})(),Br=(function(){return{...Ut,patternName:"Stars"}})(),Gr=(function(){return{...Ut,patternName:"Stars"}})(),Wr={fontFamily:null,fontSize:18,fontColor:null,outlineColor:null,outlineWidth:0,shadow:null},Ro=(function(){return{filledBar:{...Ut},emptyBar:{...Or},goldFilledBar:{...Gr},goldEmptyBar:{...Br},font:{...Wr},disableGoldNotes:!1}})(),Ps={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",$s="nice2dev-player-karaoke-settings";function gn(e){return e!=null?`${$s}-${e}`:$s}function As(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=Ro,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 Ha(e){try{const t=localStorage.getItem(gn(e));if(t){const a=JSON.parse(t);return Ls(a)}const n=localStorage.getItem(As(e));if(n){const a=JSON.parse(n),s=Is({...Ps,...a});return localStorage.setItem(gn(e),JSON.stringify(s)),s}if(e!=null){const a=localStorage.getItem(gn());if(a)return Ls(JSON.parse(a));const s=localStorage.getItem(As());if(s)return Is({...Ps,...JSON.parse(s)})}}catch{}return{filledBar:{...Ut},emptyBar:{...Or},goldFilledBar:{...Gr},goldEmptyBar:{...Br},font:{...Wr}}}function Vu(e,t){const n=JSON.stringify(e);localStorage.setItem(gn(t),n)}let _s=!1;async function qu(e){if(_s||(_s=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(gn())||localStorage.setItem(gn(),t)}catch{}}function Hu(e){const t=new Map;for(const n of e)t.set(n,Ha(n));return t}const Ku={"&":"&","<":"<",">":">",'"':""","'":"'"},Yu=/[&<>"']/g;function Zu(e){return e.replace(Yu,t=>Ku[t])}function Xu(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,Ze=Qu;function Ar(e){const t=parseInt(e.slice(1,3),16)/255,n=parseInt(e.slice(3,5),16)/255,a=parseInt(e.slice(5,7),16)/255,s=Math.max(t,n,a),i=Math.min(t,n,a);let o=0,l=0;const c=(s+i)/2;if(s!==i){const u=s-i;switch(l=c>.5?u/(2-s-i):u/(s+i),s){case t:o=((n-a)/u+(n<a?6:0))/6;break;case n:o=((a-t)/u+2)/6;break;case a:o=((t-n)/u+4)/6;break}}return[Math.round(o*360),Math.round(l*100),Math.round(c*100)]}function Ir(e){let t=e.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),"#"+t.toLowerCase()}function dt(e,t){return e.replace(/([MLHVCSQTAZ])/gi,`
|
|
1
|
+
"use strict";var Ic=Object.create;var bs=Object.defineProperty;var Lc=Object.getOwnPropertyDescriptor;var _c=Object.getOwnPropertyNames;var Dc=Object.getPrototypeOf,zc=Object.prototype.hasOwnProperty;var Fc=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of _c(t))!zc.call(e,s)&&s!==n&&bs(e,s,{get:()=>t[s],enumerable:!(a=Lc(t,s))||a.enumerable});return e};var Zr=(e,t,n)=>(n=e!=null?Ic(Dc(e)):{},Fc(t||!e||!e.__esModule?bs(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),ve=require("@nice2dev/ui-core"),d=require("react"),ie=require("@nice2dev/ui"),B=require("@nice2dev/icons"),ua=require("pitchy"),Aa=require("react-youtube");var yt=typeof document<"u"?document.currentScript:null;const $i=d.createContext(null),Oc=({t:e,children:t})=>r.jsx($i.Provider,{value:e,children:t});function xe(){const e=d.useContext($i),{t}=ve.useNiceTranslation();return{t:d.useMemo(()=>e??((a,s)=>t(a,s??a)),[e,t])}}function Bc({componentName:e,error:t,onReset:n}){const{t:a}=xe();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 Gc extends d.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){var s,i;const a=this.props.componentName?`[${this.props.componentName}]`:"[AudioErrorBoundary]";console.error(`${a} Caught error:`,t,n),(i=(s=this.props).onError)==null||i.call(s,t,n)}render(){return this.state.hasError&&this.state.error?typeof this.props.fallback=="function"?this.props.fallback(this.state.error,this.reset):this.props.fallback?this.props.fallback:r.jsx(Bc,{componentName:this.props.componentName,error:this.state.error,onReset:this.reset}):this.props.children}}function Wc(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 Xr={},ha={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function Uc(){const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:yt&&yt.tagName.toUpperCase()==="SCRIPT"&&yt.src||new URL("index.cjs",document.baseURI).href}<"u"?Xr==null?void 0:Xr.VITE_LOG_LEVEL:void 0;return e&&e in ha?e:"WARN"}const Vc=Uc();function Xn(e){return ha[e]>=ha[Vc]}function Qn(e){return`[${e}]`}const st=(function(){return{debug(e,t,...n){Xn("DEBUG")&&console.debug(Qn(e),t,...n)},info(e,t,...n){Xn("INFO")&&console.info(Qn(e),t,...n)},warn(e,t,...n){Xn("WARN")&&console.warn(Qn(e),t,...n)},error(e,t,...n){Xn("ERROR")&&console.error(Qn(e),t,...n)},scoped(e){return{debug:(t,...n)=>st.debug(e,t,...n),info:(t,...n)=>st.info(e,t,...n),warn:(t,...n)=>st.warn(e,t,...n),error:(t,...n)=>st.error(e,t,...n)}}}})(),xs=st.scoped("Waveform"),qc=["audio/","video/"],Ai=({audioBlob:e,currentTime:t,duration:n,width:a=600,height:s=200,zoom:i=1,onSeek:o,onRegionSelect:l,markers:c=[],regions:u=[],displayMode:h="waveform",multiChannel:p=!1,waveColor: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:b=!0,showPeakMeter:f=!1,className:j})=>{const{t:v}=xe(),C=d.useRef(null),T=d.useRef(null),[M,k]=d.useState(null),[R,P]=d.useState(0),[I,A]=d.useState(!1),[L,E]=d.useState(null),[D,Z]=d.useState(null),[G,F]=d.useState(0),q=Math.max(a,a*i),V=x?24:0;d.useEffect(()=>{if(!e||e.size===0){k(null);return}e.type&&!qc.some(N=>e.type.startsWith(N))&&xs.warn("Unexpected blob MIME type:",e.type);let w=!1;return(async()=>{let N=null;try{const S=await e.arrayBuffer();if(S.byteLength===0||w)return;N=new AudioContext;const O=await N.decodeAudioData(S);w||k(O)}catch(S){xs.error("Failed to decode audio:",S)}finally{N==null||N.close().catch(()=>{})}})(),()=>{w=!0}},[e]),d.useEffect(()=>{if(i>1&&n>0){const w=t/n*q;(w<R||w>R+a)&&P(Math.max(0,w-a/2))}},[t,n,i,a,q,R]),d.useEffect(()=>{const w=C.current,N=M;if(!w||!n||n===1/0)return;const S=w.getContext("2d");if(!S)return;const O=q,Y=s;if(w.width=O,w.height=Y+V,S.clearRect(0,0,O,Y+V),m!=="transparent"&&(S.fillStyle=ve.resolveCssColor(m),S.fillRect(0,0,O,Y+V)),x){const _=ve.resolveCssColor("var(--nice-text-secondary, #888)");S.fillStyle=ve.resolveCssColor("var(--nice-bg-secondary, rgba(128,128,128,0.15))"),S.fillRect(0,0,O,V),S.fillStyle=_,S.font="10px monospace",S.textAlign="center";const U=Math.max(1,Math.floor(n/(q/80)));for(let $=0;$<=n;$+=U){const H=$/n*O;S.fillText(Zc($),H,V-4),S.fillStyle=ve.resolveCssColor("var(--nice-border-color, rgba(128,128,128,0.3))"),S.fillRect(H,V,1,Y),S.fillStyle=_}}for(const _ of u){const U=_.start/n*O,$=_.end/n*O;S.fillStyle=ve.resolveCssColor(_.color??"var(--nice-accent-tint-15, rgba(99, 102, 241, 0.15))"),S.fillRect(U,V,$-U,Y),_.label&&(S.fillStyle=ve.resolveCssColor(_.color??"var(--nice-info, #6366f1)"),S.font="10px sans-serif",S.textAlign="left",S.fillText(_.label,U+2,V+12))}if(L!==null&&D!==null){const _=Math.min(L,D),U=Math.max(L,D);S.fillStyle=ve.resolveCssColor("var(--nice-warning-tint-20, rgba(255,200,0,0.2))"),S.fillRect(_,V,U-_,Y)}if(N){const _=p?N.numberOfChannels:1,U=Y/_,$=ve.resolveCssColor(g);let H=0;for(let X=0;X<_;X++){const re=N.getChannelData(X),oe=V+X*U;if(h==="waveform"?Hc(S,re,O,U,oe,$):h==="bars"?Kc(S,re,O,U,oe,$):h==="spectrogram"&&Yc(S,re,O,U,oe,N.sampleRate),f&&n>0){const se=Math.floor(t/n*re.length),z=Math.floor(N.sampleRate*.05);let ee=0;for(let ce=Math.max(0,se-z);ce<Math.min(re.length,se+z);ce++)ee+=re[ce]*re[ce];const ae=Math.sqrt(ee/(z*2));H=Math.max(H,ae)}p&&b&&_>1&&(S.fillStyle=ve.resolveCssColor("var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"),S.font="bold 11px sans-serif",S.textAlign="left",S.fillText(X===0?"L":X===1?"R":`Ch${X+1}`,4,oe+14))}F(H)}if(n>0){const _=Math.max(0,Math.min(t/n*O,O));S.beginPath(),S.strokeStyle=ve.resolveCssColor(y),S.lineWidth=2,S.moveTo(_,V),S.lineTo(_,Y+V),S.stroke()}for(const _ of c){const U=_.time/n*O,$=ve.resolveCssColor(_.color??"var(--nice-warning, #f59e0b)");S.beginPath(),S.strokeStyle=$,S.lineWidth=2,S.setLineDash([4,4]),S.moveTo(U,V),S.lineTo(U,Y+V),S.stroke(),S.setLineDash([]),_.label&&(S.fillStyle=$,S.font="bold 10px sans-serif",S.textAlign="center",S.fillText(_.label,U,V+Y-4))}},[M,t,n,q,s,i,h,p,g,y,m,x,c,u,L,D,f,b,V]);const K=d.useCallback(w=>{var O;if(!n)return;const N=(O=C.current)==null?void 0:O.getBoundingClientRect();if(!N)return;const S=w.clientX-N.left+R;A(!0),E(S),Z(S)},[n,R]),W=d.useCallback(w=>{if(!I||!C.current)return;const N=C.current.getBoundingClientRect(),S=w.clientX-N.left+R;Z(S)},[I,R]),Q=d.useCallback(()=>{if(!I||L===null||D===null||!n){A(!1),E(null),Z(null);return}const w=Math.min(L,D),N=Math.max(L,D),S=(N-w)/q*n;if(A(!1),E(null),Z(null),S<.2){const O=w/q*n;o==null||o(O)}else{const O=w/q*n,Y=N/q*n;l==null||l({start:O,end:Y})}},[I,L,D,n,q,o,l]);return r.jsxs("div",{ref:T,className:`nice-waveform${j?` ${j}`:""}`,style:{position:"relative",width:a,overflow:i>1?"auto":"hidden",cursor:o?"crosshair":"default"},onScroll:w=>P(w.target.scrollLeft),children:[r.jsx("canvas",{ref:C,width:q,height:s+V,style:{display:"block"},role:"img","aria-label":v("waveform.waveformCanvas","Waveform canvas"),onMouseDown:K,onMouseMove:W,onMouseUp:Q,onMouseLeave:Q}),f&&r.jsx("div",{style:{position:"absolute",right:4,top:V+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,G*300)}%`,background:G>.8?"var(--nice-danger, #ef4444)":G>.5?"var(--nice-warning, #f59e0b)":"var(--nice-success, #22c55e)",borderRadius:4,transition:"height 50ms"}})})]})};function Hc(e,t,n,a,s,i){const o=Math.floor(t.length/n),l=s+a/2;e.beginPath(),e.strokeStyle=i,e.lineWidth=1;for(let c=0;c<n;c++){const u=c*o,h=t.subarray(u,u+o);let p=0,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 Kc(e,t,n,a,s,i){const o=Math.max(2,Math.floor(n/128)),l=Math.floor(n/o),c=Math.floor(t.length/l);for(let u=0;u<l;u++){const h=u*c,p=t.subarray(h,h+c);let g=0;for(let b=0;b<p.length;b++)g+=Math.abs(p[b]);const m=g/p.length*a*.9,x=u*o;e.fillStyle=i,e.fillRect(x+1,s+a-m,o-2,m)}}function Yc(e,t,n,a,s,i){const l=Math.min(n,512),c=Math.floor(t.length/l),u=n/l;for(let h=0;h<l;h++){const p=h*c,g=new Float32Array(256/2);for(let m=0;m<256/2;m++){let x=0,b=0;for(let f=0;f<256&&p+f<t.length;f++){const j=2*Math.PI*m*f/256;x+=t[p+f]*Math.cos(j),b-=t[p+f]*Math.sin(j)}g[m]=Math.sqrt(x*x+b*b)/256}const y=a/g.length;for(let m=0;m<g.length;m++){const x=Math.min(1,g[m]*10),b=Math.floor(x*255),f=Math.floor(x*100),j=Math.floor((1-x)*200);e.fillStyle=`rgb(${b},${f},${j})`,e.fillRect(h*u,s+a-(m+1)*y,u+1,y+1)}}}function Zc(e){const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const Ss=88,tn=16,Jn=16,Xc=320;function Qc(e){return e-21}function Jc(e){return e+21}const Ia=({notes:e,onAddNote:t,onRemoveNote:n,selectedNoteId:a,setSelectedNoteId:s,duration:i=4,zoom:o=1})=>{const l=d.useRef(null),c=Xc*o,u=Ss*tn,h=d.useRef(null);d.useEffect(()=>{},[e,o,i]);const p=y=>{const m=l.current;if(!m)return;const x=m.getBoundingClientRect(),b=y.clientX-x.left,f=y.clientY-x.top,j=Math.floor(f/tn),v=Jc(j),C=b/c*i;h.current={drawing:!0,startX:b,key:j},t(v,C,i/Jn)},g=(y,m)=>{m.stopPropagation(),s==null||s(y)};return r.jsxs("svg",{ref:l,width:c,height:u,style:{background:"var(--nice-bg-secondary, #f8fafc)",border:"1px solid var(--nice-border-color, #cbd5e1)",userSelect:"none",display:"block"},onMouseDown:p,children:[[...Array(Ss)].map((y,m)=>r.jsx("rect",{x:0,y:m*tn,width:c,height:tn,fill:m%2===0?"var(--nice-bg-secondary, #f8fafc)":"var(--nice-bg-tertiary, #f1f5f9)"},m)),[...Array(Jn+1)].map((y,m)=>r.jsx("line",{x1:m*c/Jn,y1:0,x2:m*c/Jn,y2:u,stroke:"var(--nice-border-muted, #ccc)",strokeWidth:m%4===0?2:1},m)),e.map(y=>{const m=Qc(y.pitch),x=y.start/i*c,b=y.duration/i*c;return r.jsx("rect",{x,y:m*tn,width:Math.max(6,b),height:tn-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)})]})},ed=({ccEvents:e,onAddEvent:t,onUpdateEvent:n,onRemoveEvent:a,ccType:s,duration:i,width:o,height:l=60,curveType:c})=>{const u=d.useRef(null),{t:h}=xe(),[p,g]=d.useState(null),[y,m]=d.useState(null),[x,b]=d.useState(null),f=[...e].sort((E,D)=>E.time-D.time),j=E=>[E.time/i*o,(127-E.value)/127*l],v=(E,D,Z)=>Math.max(D,Math.min(Z,E)),C=E=>{var V;if(E.target instanceof SVGCircleElement)return;const D=(V=u.current)==null?void 0:V.getBoundingClientRect();if(!D)return;const Z=E.clientX-D.left,G=E.clientY-D.top,F=v(Z/o*i,0,i),q=v(127-Math.round(G/l*127),0,127);t(s,q,F)},T=(E,D)=>{var q;D.stopPropagation(),g(E.id),b(E.id);const[Z,G]=j(E),F=(q=u.current)==null?void 0:q.getBoundingClientRect();F&&m({dx:D.clientX-F.left-Z,dy:D.clientY-F.top-G})},M=E=>{var V;if(p==null||!y)return;const D=(V=u.current)==null?void 0:V.getBoundingClientRect();if(!D)return;const Z=v(E.clientX-D.left-y.dx,0,o),G=v(E.clientY-D.top-y.dy,0,l),F=v(Z/o*i,0,i),q=v(127-Math.round(G/l*127),0,127);n(p,q,F)},k=()=>{g(null),m(null)};d.useEffect(()=>{const E=D=>{(D.key==="Delete"||D.key==="Backspace")&&x!=null&&(a(x),b(null))};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[x,a]),d.useEffect(()=>{if(p!=null)return window.addEventListener("mousemove",M),window.addEventListener("mouseup",k),()=>{window.removeEventListener("mousemove",M),window.removeEventListener("mouseup",k)}});const[R,P]=d.useState(null),I=(E,D)=>{const[Z,G]=j(E);P({x:Z+10,y:G-10,text:h("ccLane.valTimeS","Val: {value}, Time: {time}s").replace("{value}",String(E.value)).replace("{time}",String(E.time.toFixed(2)))})},A=()=>P(null),L=E=>{var V;const D=(V=u.current)==null?void 0:V.getBoundingClientRect();if(!D)return;const Z=E.clientX-D.left,G=E.clientY-D.top,F=v(Z/o*i,0,i),q=v(127-Math.round(G/l*127),0,127);t(s,q,F)};return r.jsxs("svg",{ref:u,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:C,onDoubleClick:L,tabIndex:0,children:[[...Array(9)].map((E,D)=>r.jsx("line",{x1:0,y1:D*l/8,x2:o,y2:D*l/8,stroke:"var(--nice-border-muted, #ddd)",strokeWidth:D===0||D===8?2:1},D)),f.length>1&&r.jsx("polyline",{fill:"none",stroke:"var(--nice-color-accent, #1976d2)",strokeWidth:2,points:f.map(E=>j(E).join(",")).join(" ")}),f.map(E=>{const[D,Z]=j(E);return r.jsxs("g",{children:[r.jsx("circle",{cx:D,cy:Z,r:x===E.id?8:6,fill:x===E.id?"var(--nice-color-accent, #1976d2)":"var(--nice-color-accent-light, #90caf9)",stroke:"var(--nice-color-accent, #1976d2)",strokeWidth:x===E.id?3:2,style:{cursor:"pointer"},onMouseDown:G=>T(E,G),onContextMenu:G=>{G.preventDefault(),a(E.id)},onClick:G=>{G.stopPropagation(),b(E.id)},onMouseOver:G=>I(E),onMouseOut:A}),x===E.id&&r.jsx("foreignObject",{x:D+10,y:Z-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:E.handleType||c||"linear",onChange:G=>{n(E.id,E.value,E.time,G.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")})]})]})})]},E.id)}),R&&r.jsxs("g",{pointerEvents:"none",children:[r.jsx("rect",{x:R.x,y:R.y-18,width:90,height:20,fill:"var(--nice-color-surface, #fff)",stroke:"var(--nice-color-accent, #1976d2)",rx:4}),r.jsx("text",{x:R.x+6,y:R.y-4,fontSize:13,fill:"var(--nice-color-accent, #1976d2)",children:R.text})]}),r.jsxs("text",{x:6,y:16,fontSize:14,fill:"var(--nice-color-accent, #1976d2)",children:["CC",s]})]})},td=st.scoped("audioContext");let Un=null;function Yn(){if(!Un)try{Un=new(window.AudioContext||window.webkitAudioContext)}catch(e){td.error("Error initializing AudioContext:",e)}return Un}async function Xt(){const e=Yn();e&&e.state==="suspended"&&await e.resume()}function Ii(){return!!Un&&Un.state==="running"}function Li(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 nd(e,t){if(!t.snapEnabled)return e;const n=Li(t);return Math.round(e/n)*n}function rd(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 ad(e,t){const n=t/60,a=e*n,s=Math.floor(a/4),i=Math.floor(a%4);return`${s+1}:${i+1}`}function _i(e,t,n=!0){const a=e.getContext("2d");if(!a)return;const s=30*t.zoom*t.duration,i=Math.max(80,30*t.zoom);e.width=s,e.height=i,a.clearRect(0,0,s,i),a.fillStyle=ve.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=ve.resolveCssColor("var(--nice-border-secondary, #ddd)",a.canvas),a.lineWidth=1;for(let c=0;c<=t.duration;c+=l){const u=c/t.duration*s,h=c%1===0;if(a.strokeStyle=ve.resolveCssColor(h?"var(--nice-border-secondary, #ccc)":"var(--nice-border-muted, #eee)",a.canvas),a.lineWidth=h?1.5:.5,a.beginPath(),a.moveTo(u,0),a.lineTo(u,i),a.stroke(),h&&o>40){a.fillStyle=ve.resolveCssColor("var(--nice-text-muted, #666)",a.canvas),a.font="10px monospace",a.textAlign="center";const p=n?ad(c,t.bpm):rd(c);a.fillText(p,u,12)}}if(t.snapEnabled){const c=Li(t);a.strokeStyle=ve.resolveCssColor("var(--nice-color-accent, #ffeb3b)",a.canvas),a.lineWidth=.5;for(let u=0;u<=t.duration;u+=c){const h=u/t.duration*s;a.beginPath(),a.moveTo(h,i-5),a.lineTo(h,i),a.stroke()}}}function sd(e,t,n,a){const s=e.getContext("2d");if(!s)return;const i=30*t.zoom*t.duration,o=Math.max(80,30*t.zoom),l=n/t.duration*i;_i(e,t),s.strokeStyle=ve.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=ve.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 id(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=ve.resolveCssColor(a,s.canvas),s.lineWidth=1,s.beginPath(),n.forEach((u,h)=>{const p=h/(n.length-1)*i,g=l-u*c;h===0?s.moveTo(p,g):s.lineTo(p,g)}),s.stroke(),s.restore()}const Di=({zoom:e=1,duration:t=4,isPlaying:n,isRecording:a,currentTime:s,bpm:i=120,snapEnabled:o=!1,snapMode:l="beat",waveform:c,waveformColor:u,onCurrentTimeChange:h,onZoomChange:p})=>{const{t:g}=xe(),y=d.useRef(null),[m,x]=d.useState(!1),b=d.useRef(s);b.current=s;const f=d.useRef(t);f.current=t;const j=d.useRef(h);j.current=h;const v={bpm:i,snapEnabled:o,snapMode:l};d.useEffect(()=>{Xt();const P=y.current;if(!P)return;const I={zoom:e,duration:t,bpm:i,snapEnabled:o,snapMode:l};_i(P,I),c!=null&&c.length&&id(P,I,c,u),sd(P,I,s,a)},[e,t,s,a,i,o,l,c,u]),d.useEffect(()=>{if(!n)return;let P=performance.now(),I=0;const A=L=>{const E=Math.max(0,L-P)/1e3;P=L;const D=Math.min(b.current+E,f.current);b.current=D,j.current(D),D<f.current&&(I=requestAnimationFrame(A))};return I=requestAnimationFrame(A),()=>cancelAnimationFrame(I)},[n]);const C=P=>{x(!0),k(P)},T=P=>{m&&k(P)},M=()=>{x(!1)},k=P=>{if(!y.current)return;const I=y.current.getBoundingClientRect();let L=(P.clientX-I.left)/I.width*t;L=nd(L,v),h(Math.min(Math.max(L,0),t))},R=P=>{if(!p)return;P.preventDefault();const I=P.deltaY>0?-.1:.1,A=Math.max(.5,Math.min(5,e+I));p(A)};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:C,onMouseMove:T,onMouseUp:M,onMouseLeave:M,onWheel:R,role:"img","aria-label":g("audioTimeline.audioTimelineCanvas","Audio timeline canvas")})})},Xe=["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 od(e){for(const t of Xe)if(!e.includes(t))return t;return Xe[Math.floor(Math.random()*Xe.length)]}const fr=Xe.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function ld(e){for(let t=0;t<Xe.length;t++){const n=Xe[t],a=fr[t];if(!e.includes(n)&&!e.includes(a))return a}return fr[Math.floor(Math.random()*fr.length)]}const cd="_panel_3bj7x_3",dd="_panelCompact_3bj7x_19",ud="_panelNarrow_3bj7x_25",hd="_panelWide_3bj7x_31",pd="_heading_3bj7x_37",fd="_row_3bj7x_53",md="_field_3bj7x_65",gd="_buttonRow_3bj7x_71",yd="_sliderW200_3bj7x_83",vd="_sliderW240_3bj7x_89",bd="_selectW160_3bj7x_95",xd="_inputW120_3bj7x_101",Sd="_inputW160_3bj7x_107",kd="_inputW200_3bj7x_113",wd="_noteText_3bj7x_123",Cd="_noteTextMargin_3bj7x_131",jd="_presetDivider_3bj7x_145",Md="_presetLabel_3bj7x_159",Rd="_countInAlert_3bj7x_173",Nd="_levelLabel_3bj7x_181",Td="_levelMeter_3bj7x_189",Pd="_levelBar_3bj7x_205",Ed="_panelInactive_3bj7x_225",$d="_header_3bj7x_231",Ad="_title_3bj7x_245",Id="_grid2_3bj7x_257",Ld="_full_3bj7x_267",_d="_label_3bj7x_275",Dd="_grow_3bj7x_291",zd="_pushRight_3bj7x_299",Fd="_alignStart_3bj7x_305",Od="_toolbar_3bj7x_311",Bd="_subPanel_3bj7x_325",ye={panel:cd,panelCompact:dd,panelNarrow:ud,panelWide:hd,heading:pd,row:fd,field:md,buttonRow:gd,sliderW200:yd,sliderW240:vd,selectW160:bd,inputW120:xd,inputW160:Sd,inputW200:kd,noteText:wd,noteTextMargin:Cd,presetDivider:jd,presetLabel:Md,countInAlert:Rd,levelLabel:Nd,levelMeter:Td,levelBar:Pd,panelInactive:Ed,header:$d,title:Ad,grid2:Id,full:Ld,label:_d,grow:Dd,pushRight:zd,alignStart:Fd,toolbar:Od,subPanel:Bd},Nt=e=>Array.isArray(e)?e[0]??"":e,zi=({autoSaveMode:e,setAutoSaveMode:t,autoSaveInterval:n,setAutoSaveInterval:a})=>{const{t:s}=xe();return r.jsxs("div",{className:`${ye.panel} ${ye.panelNarrow}`,children:[r.jsx("h6",{className:ye.heading,children:s("editorPanels.autoSaveTitle","Project auto-save")}),r.jsx("div",{className:ye.field,children:r.jsx(ie.NiceSelect,{label:s("editorPanels.autoSaveMode","Auto-save mode"),size:"sm",value:e,onChange:i=>t(Nt(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:ye.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:ye.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.")]})]})},Fi=({undoCount:e,redoCount:t,onUndo:n,onRedo:a})=>{const{t:s}=xe();return r.jsxs("div",{className:`${ye.panel} ${ye.panelNarrow}`,children:[r.jsx("h6",{className:ye.heading,children:s("editorPanels.changeHistory","Project change history")}),r.jsxs("div",{className:ye.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(B.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(B.NtdRedo,{size:14})," ",s("editorPanels.redo","Redo")]})]}),r.jsx("div",{className:ye.noteTextMargin,children:s("editorPanels.undoRedoNote","Undo/Redo works on the entire project (all editor changes). After each change Redo is cleared.")})]})},ks=e=>`${e.toFixed(1)}x`,La=({zoom:e,setZoom:t,uiZoom:n,setUiZoom:a,snapEnabled:s,onToggleSnap:i,snapMode:o,onSnapModeChange:l,bpm:c,setBpm:u})=>{const{t:h}=xe();return r.jsx("div",{className:`${ye.panel} ${ye.panelCompact} ${ye.panelNarrow}`,children:r.jsxs("div",{className:ye.row,children:[r.jsx("div",{className:ye.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:ks})}),r.jsx("div",{className:ye.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:ks})}),r.jsx(ie.NiceCheckbox,{label:h("editorPanels.snap","Snap"),size:"sm",checked:s,onChange:()=>i()}),s&&r.jsx("div",{className:ye.selectW160,children:r.jsx(ie.NiceSelect,{size:"sm","aria-label":h("editorPanels.snapTo","Snap to"),value:o,onChange:p=>l(Nt(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:ye.inputW120,children:r.jsx(ie.NiceNumberInput,{label:h("editorPanels.bpm","BPM"),size:"sm",min:20,max:300,value:c,onChange:p=>u(p??c)})})]})})},Gd=[["peaking","Peaking"],["lowpass","Low-pass"],["highpass","High-pass"],["lowshelf","Low shelf"],["highshelf","High shelf"],["notch","Notch"],["bandpass","Band-pass"]],Oi=({masterVolume:e,onMasterVolumeChange:t,filterType:n,filterFreq:a,filterQ:s,filterGain:i,onFilterChange:o,masterEQPresets:l,customPresets:c,onLoadPreset:u,onSavePreset:h,onDeletePreset:p})=>{const{t:g}=xe(),[y,m]=d.useState(""),x=()=>{y.trim()&&(h(y.trim()),m(""))};return r.jsxs("div",{className:`${ye.panel} ${ye.panelCompact} ${ye.panelWide}`,children:[r.jsxs("div",{className:ye.row,children:[r.jsx("div",{className:ye.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:b=>`${Math.round(b*100)}%`})}),r.jsx("div",{className:ye.selectW160,children:r.jsx(ie.NiceSelect,{label:g("editorPanels.filter","Filter"),size:"sm",value:n,onChange:b=>o({type:Nt(b)}),options:Gd.map(([b,f])=>({value:b,label:g(`editorPanels.filter.${b}`,f)}))})}),r.jsx("div",{className:ye.sliderW240,children:r.jsx(ie.NiceSlider,{label:g("editorPanels.frequency","Freq"),size:"sm",min:40,max:12e3,step:10,value:a,onChange:b=>o({frequency:b}),showValue:!0,formatValue:b=>`${Math.round(b)} Hz`})}),r.jsx("div",{className:ye.sliderW200,children:r.jsx(ie.NiceSlider,{label:"Q",size:"sm",min:.1,max:12,step:.1,value:s,onChange:b=>o({q:b}),showValue:!0,formatValue:b=>b.toFixed(1)})}),(n==="peaking"||n==="lowshelf"||n==="highshelf")&&r.jsx("div",{className:ye.sliderW200,children:r.jsx(ie.NiceSlider,{label:g("editorPanels.gain","Gain"),size:"sm",min:-18,max:18,step:.5,value:i,onChange:b=>o({gain:b}),showValue:!0,formatValue:b=>`${b.toFixed(1)} dB`})})]}),r.jsxs("div",{className:ye.presetDivider,children:[r.jsxs("div",{className:ye.row,children:[r.jsxs("span",{className:ye.presetLabel,children:[g("editorPanels.eqPresets","EQ Presets"),":"]}),[...l,...c].map(b=>r.jsx(ie.NiceButton,{variant:"outline",size:"xs",onClick:()=>u(b),children:b.name},b.name)),c.length>0&&r.jsx("div",{className:ye.selectW160,children:r.jsx(ie.NiceSelect,{size:"sm","aria-label":g("editorPanels.deletePreset","Delete preset..."),placeholder:g("editorPanels.deletePreset","Delete preset..."),value:"",onChange:b=>{const f=Nt(b);f&&p(f)},options:c.map(b=>({value:b.name,label:b.name}))})})]}),r.jsxs("div",{className:ye.row,children:[r.jsx("div",{className:ye.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:b=>b.key==="Enter"&&x()})}),r.jsx(ie.NiceButton,{variant:"success",size:"xs",onClick:x,disabled:!y.trim(),children:g("editorPanels.saveCurrent","Save Current")})]})]})]})},Bi=({countInBars:e,setCountInBars:t,isCountIn:n,countInRemaining:a,overdubEnabled:s,setOverdubEnabled:i,punchIn:o,setPunchIn:l,punchOut:c,setPunchOut:u,monitorLevel:h})=>{const{t:p}=xe();return r.jsx("div",{className:`${ye.panel} ${ye.panelCompact} ${ye.panelWide}`,children:r.jsxs("div",{className:ye.row,children:[r.jsx("div",{className:ye.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:ye.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:ye.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:ye.inputW160,children:r.jsx(ie.NiceNumberInput,{label:p("editorPanels.punchOut","Punch Out (s)"),size:"sm",min:0,step:.1,value:c,onChange:u})}),r.jsx(ie.NiceButton,{variant:"outline",size:"xs",onClick:()=>{l(null),u(null)},children:p("editorPanels.clearPunch","Clear punch")}),r.jsx("div",{className:ye.levelLabel,children:p("editorPanels.level","Level")}),r.jsx("div",{className:ye.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:ye.levelBar,style:{width:`${Math.min(1,h*2)*100}%`,background:h>.7?"var(--nice-danger, #f44336)":"var(--nice-success, #4caf50)"}})})]})})},Wd=[{id:1,name:"Audio 1",type:"audio",color:Xe[0],volume:.8,audioBlob:null},{id:2,name:"MIDI 1",type:"midi",color:Xe[1],volume:.8,notes:[]}],Ud=({initialTracks:e,tracks:t,onTracksChange:n,initialBpm:a=120,duration:s=30,height:i=480,title:o,displayMode:l="standard",onNew:c,onOpen:u,onSave:h,onExport:p,t:g})=>{var ae,ce;const{t:y}=xe(),m=g??y,x=o??m("audioStudio.untitledProject","Untitled project"),[b,f]=d.useState(l),j=b==="advanced",v=b!=="basic",[C,T]=d.useState(e??Wd),M=t??C,k=d.useCallback(le=>{t===void 0&&T(le),n==null||n(le)},[t,n]),[R,P]=d.useState(!1),[I,A]=d.useState(0),[L,E]=d.useState(1),[D,Z]=d.useState(2),[G,F]=d.useState(!0),[q,V]=d.useState("beat"),[K,W]=d.useState(a),[Q,w]=d.useState(80),[N,S]=d.useState(((ae=M[0])==null?void 0:ae.id)??null),O=d.useRef(0),Y=d.useRef(0);d.useEffect(()=>{if(!R)return;Y.current=performance.now();const le=ne=>{const pe=(ne-Y.current)/1e3;Y.current=ne,A(fe=>{const ge=fe+pe;return ge>=s?(P(!1),s):ge}),O.current=requestAnimationFrame(le)};return O.current=requestAnimationFrame(le),()=>cancelAnimationFrame(O.current)},[R,s]);const _=d.useCallback((le,ne)=>k(M.map(pe=>pe.id===le?{...pe,...ne}:pe)),[M,k]),U=d.useCallback(le=>{const ne=M.reduce((fe,ge)=>Math.max(fe,ge.id),0)+1,pe=M.filter(fe=>fe.type===le).length+1;k([...M,{id:ne,name:`${le==="audio"?"Audio":"MIDI"} ${pe}`,type:le,color:Xe[M.length%Xe.length],volume:.8,...le==="audio"?{audioBlob:null}:{notes:[]}}]),S(ne)},[M,k]),$=d.useCallback(le=>k(M.filter(ne=>ne.id!==le)),[M,k]),H=d.useCallback(()=>{if(c){c();return}k([]),A(0),P(!1)},[c,k]),X=d.useCallback((le,ne,pe,fe)=>{const ge=M.find(je=>je.id===le),he=(ge==null?void 0:ge.notes)??[],we=he.reduce((je,Pe)=>Math.max(je,Pe.id),0)+1;_(le,{notes:[...he,{id:we,pitch:ne,start:pe,duration:fe,velocity:100}]})},[M,_]),re=d.useCallback((le,ne)=>{const pe=M.find(fe=>fe.id===le);_(le,{notes:((pe==null?void 0:pe.notes)??[]).filter(fe=>fe.id!==ne)})},[M,_]),oe=d.useMemo(()=>{const le=Math.floor(I/60),ne=Math.floor(I%60),pe=Math.floor(I%1*100);return`${le}:${ne.toString().padStart(2,"0")}.${pe.toString().padStart(2,"0")}`},[I]),se=d.useMemo(()=>{const le=(pe,fe)=>({id:`mode-${pe}`,label:`${b===pe?"• ":" "}${fe}`,onClick:()=>f(pe)}),ne=[{id:"file",label:m("studio.menu.file","File"),children:[{id:"new",label:m("studio.menu.new","New"),onClick:H},...u?[{id:"open",label:m("studio.menu.open","Open…"),onClick:u}]:[],{id:"save",label:m("studio.menu.save","Save"),onClick:()=>h==null?void 0:h(M)},{id:"export",label:m("studio.menu.export","Export…"),onClick:()=>p==null?void 0:p(M)}]}];return v&&ne.push({id:"edit",label:m("studio.menu.edit","Edit"),children:[{id:"add-audio",label:m("studio.addAudio","Add audio track"),onClick:()=>U("audio")},{id:"add-midi",label:m("studio.addMidi","Add MIDI track"),onClick:()=>U("midi")}]}),ne.push({id:"view",label:m("studio.menu.view","View"),children:[{id:"modes",label:m("studio.menu.modes","Display mode"),divider:!1,disabled:!0},le("basic",m("studio.mode.basic","Basic")),le("standard",m("studio.mode.standard","Standard")),le("advanced",m("studio.mode.advanced","Advanced")),{id:"d1",divider:!0},{id:"snap",label:`${G?"• ":" "}${m("studio.snap","Snap to grid")}`,onClick:()=>F(pe=>!pe)}]}),ne.push({id:"help",label:m("studio.menu.help","Help"),children:[{id:"about",label:m("studio.menu.about","About NiceAudioStudio"),disabled:!0}]}),ne},[m,b,v,G,H,u,h,p,M,U]),z=r.jsxs(r.Fragment,{children:[r.jsxs(ie.NiceButton,{variant:"primary",size:"sm",onClick:()=>P(le=>!le),children:[R?r.jsx(B.NtdPause,{size:14}):r.jsx(B.NtdPlay,{size:14})," ",R?m("studio.pause","Pause"):m("studio.play","Play")]}),r.jsxs(ie.NiceButton,{variant:"secondary",size:"sm",onClick:()=>{P(!1),A(0)},children:[r.jsx(B.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:()=>U("audio"),children:[r.jsx(B.NtdPlus,{size:14})," ",m("studio.addAudioShort","Audio")]}),v&&r.jsxs(ie.NiceButton,{variant:"outline",size:"sm",onClick:()=>U("midi"),children:[r.jsx(B.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:Q,onChange:w,min:0,max:100})})]}),ee=r.jsxs(r.Fragment,{children:[r.jsxs("span",{children:[K," BPM"]}),r.jsx("span",{children:"·"}),r.jsx("span",{style:{fontVariantNumeric:"tabular-nums"},children:oe}),r.jsx("span",{children:"·"}),r.jsxs("span",{children:[M.length," ",m("studio.tracks","tracks")]}),j&&N!=null&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"·"}),r.jsxs("span",{children:[m("studio.active","Active"),": ",((ce=M.find(le=>le.id===N))==null?void 0:ce.name)??"—"]})]}),r.jsx("span",{style:{flex:1}}),r.jsx("span",{style:{textTransform:"capitalize"},children:b})]});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:se,orientation:"horizontal"}),r.jsx("span",{style:{color:"var(--nice-text-secondary)",fontSize:13},children:x})]}),toolbar:z,statusBar:ee,children:[v&&r.jsx("div",{style:{padding:"6px 12px",borderBottom:"1px solid var(--nice-border-color)"},children:r.jsx(La,{zoom:L,setZoom:E,uiZoom:D,setUiZoom:Z,snapEnabled:G,onToggleSnap:()=>F(le=>!le),snapMode:q,onSnapModeChange:V,bpm:K,setBpm:W})}),r.jsx("div",{style:{padding:8},children:r.jsx(Di,{zoom:L,duration:s,isPlaying:R,isRecording:!1,currentTime:I,bpm:K,snapEnabled:G,snapMode:q,onCurrentTimeChange:A,onZoomChange:E})}),M.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.")}):M.map(le=>r.jsxs("div",{role:"presentation",onFocus:()=>S(le.id),style:{display:"flex",gap:8,padding:8,borderTop:"1px solid var(--nice-border-color)",background:N===le.id?"color-mix(in srgb, var(--nice-color-primary) 8%, transparent)":"transparent"},onClick:()=>S(le.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:le.color||Xe[0],flex:"0 0 auto"}}),r.jsx("div",{style:{flex:1},children:r.jsx(ie.NiceTextInput,{value:le.name,onChange:ne=>_(le.id,{name:ne}),size:"sm"})})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[r.jsx(ie.NiceButton,{variant:le.muted?"danger":"ghost",size:"sm",onClick:()=>_(le.id,{muted:!le.muted}),children:"M"}),v&&r.jsx(ie.NiceButton,{variant:le.solo?"warning":"ghost",size:"sm",onClick:()=>_(le.id,{solo:!le.solo}),children:"S"}),r.jsx("div",{style:{flex:1},children:r.jsx(ie.NiceSlider,{value:Math.round((le.volume??.8)*100),onChange:ne=>_(le.id,{volume:ne/100}),min:0,max:100})}),r.jsx(ie.NiceButton,{variant:"ghost",size:"sm",onClick:()=>$(le.id),children:r.jsx(B.NtdClose,{size:14})})]})]}),r.jsx("div",{style:{flex:1,minWidth:0,opacity:le.muted?.5:1},children:le.type==="audio"?r.jsx(Ai,{audioBlob:le.audioBlob??null,currentTime:I,duration:s,zoom:L,height:80,waveColor:le.color,onSeek:A}):r.jsx(Ia,{notes:le.notes??[],onAddNote:(ne,pe,fe)=>X(le.id,ne,pe,fe),onRemoveNote:ne=>re(le.id,ne),duration:s,zoom:L})})]},le.id))]})},Gi=({data:e,width:t=200,height:n=40,color:a="var(--nice-accent, #8b5cf6)",progress:s=0,onClick:i})=>{const o=d.useRef(null);d.useEffect(()=>{const c=o.current;if(!c||!e)return;const u=c.getContext("2d");if(!u)return;const h=window.devicePixelRatio||1;c.width=t*h,c.height=n*h,u.scale(h,h),u.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,b=y/e.length<s;u.fillStyle=b?a:`${a}66`,u.fillRect(m,g-x/2,Math.max(1,p-1),x)}s>0&&s<1&&(u.strokeStyle=ve.resolveCssColor("var(--nice-bg, #fff)",u.canvas),u.lineWidth=2,u.beginPath(),u.moveTo(s*t,0),u.lineTo(s*t,n),u.stroke())},[e,t,n,a,s]);const l=d.useCallback(c=>{if(!i)return;const u=c.currentTarget.getBoundingClientRect(),h=c.clientX-u.left;i(h/u.width)},[i]);return r.jsx("canvas",{ref:o,className:"nice-sample-waveform",width:t,height:n,style:{width:t,height:n},onClick:l})},Vd=({sample:e,isSelected:t,isPlaying:n,playProgress:a,showWaveform:s,showAnalysis:i,onSelect:o,onPlay:l,onStop:c,onDragStart:u,onFavorite:h})=>{const{t:p}=xe(),g=m=>{const x=Math.floor(m/60),b=Math.floor(m%60);return`${x}:${b.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",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,className:`nice-sample-row ${t?"nice-sample-row--selected":""} ${n?"nice-sample-row--playing":""}`,onClick:o,draggable:!0,onDragStart:u,children:[r.jsx("button",{type:"button",className:"nice-sample-row__play",onClick:m=>{m.stopPropagation(),n?c():l()},"aria-label":n?p("sampleBrowser.stop","Stop"):p("sampleBrowser.play","Play"),title:n?p("sampleBrowser.stop","Stop"):p("sampleBrowser.play","Play"),children:n?r.jsx(B.NtdStop,{size:14}):r.jsx(B.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(B.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(Gi,{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))})]})},qd=({folders:e=[],samples:t=[],onSampleSelect:n,onSampleDragStart:a,onFolderSelect:s,onAnalyze:i,audioContext:o,showWaveform:l=!0,showAnalysis:c=!0,sortBy:u="name",sortDirection:h="asc",filterTags:p,searchQuery:g="",className:y=""})=>{const{t:m}=xe(),[x,b]=d.useState(null),[f,j]=d.useState(null),[v,C]=d.useState(null),[T,M]=d.useState(0),[k,R]=d.useState(new Map),[P,I]=d.useState(t),A=d.useRef(null),L=d.useRef(null);d.useEffect(()=>(A.current=new Audio,A.current.addEventListener("ended",()=>{C(null),M(0)}),()=>{A.current&&(A.current.pause(),A.current=null),L.current&&clearInterval(L.current)}),[]);const E=d.useMemo(()=>{let K=[...P];if(g){const W=g.toLowerCase();K=K.filter(Q=>{var w;return Q.name.toLowerCase().includes(W)||((w=Q.tags)==null?void 0:w.some(N=>N.toLowerCase().includes(W)))})}return p&&p.length>0&&(K=K.filter(W=>{var Q;return(Q=W.tags)==null?void 0:Q.some(w=>p.includes(w))})),f&&(K=f.samples||[]),K.sort((W,Q)=>{var N,S;let w=0;switch(u){case"name":w=W.name.localeCompare(Q.name);break;case"duration":w=W.duration-Q.duration;break;case"bpm":w=(W.bpm||0)-(Q.bpm||0);break;case"key":w=(W.key||"").localeCompare(Q.key||"");break;case"date":w=(((N=W.dateAdded)==null?void 0:N.getTime())||0)-(((S=Q.dateAdded)==null?void 0:S.getTime())||0);break}return h==="asc"?w:-w}),K},[P,g,p,f,u,h]),D=d.useCallback(K=>{b(K),n==null||n(K)},[n]),Z=d.useCallback(async K=>{if(A.current&&(A.current.pause(),L.current&&clearInterval(L.current),A.current.src=K.url||K.path,A.current.play(),C(K.id),M(0),L.current=window.setInterval(()=>{A.current&&M(A.current.currentTime/A.current.duration)},50),c&&!k.has(K.id)&&i))try{const W=await i(K);R(Q=>new Map(Q).set(K.id,W)),I(Q=>Q.map(w=>w.id===K.id?{...w,bpm:W.bpm,key:W.key,waveformData:W.waveformData}:w))}catch(W){console.error("Failed to analyze sample:",W)}},[c,k,i]),G=d.useCallback(()=>{A.current&&(A.current.pause(),A.current.currentTime=0),L.current&&clearInterval(L.current),C(null),M(0)},[]),F=d.useCallback(K=>{I(W=>W.map(Q=>Q.id===K?{...Q,favorite:!Q.favorite}:Q))},[]),q=d.useCallback((K,W)=>{W.dataTransfer.setData("application/json",JSON.stringify(K)),W.dataTransfer.effectAllowed="copy",a==null||a(K,W)},[a]),V=(K,W=0)=>{var Q;return r.jsxs("div",{className:"nice-sample-folder",style:{paddingLeft:W*16},children:[r.jsxs("button",{type:"button",className:`nice-sample-folder__btn ${(f==null?void 0:f.id)===K.id?"nice-sample-folder__btn--selected":""}`,onClick:()=>{j(K),s==null||s(K)},children:[r.jsx("span",{className:"nice-sample-folder__icon","aria-hidden":"true",children:r.jsx(B.NtdFolder,{size:14})}),r.jsx("span",{className:"nice-sample-folder__name",children:K.name}),K.samples&&r.jsx("span",{className:"nice-sample-folder__count",children:K.samples.length})]}),(Q=K.children)==null?void 0:Q.map(w=>V(w,W+1))]},K.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:()=>j(null),children:[r.jsx("span",{className:"nice-sample-folder__icon","aria-hidden":"true",children:r.jsx(B.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:P.length})]}),e.map(K=>V(K))]})}),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:m("sampleBrowser.key2","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:E.length===0?r.jsx("div",{className:"nice-sample-browser__empty",children:m("sampleBrowser.noSamplesFound","No samples found")}):E.map(K=>r.jsx(Vd,{sample:K,isSelected:(x==null?void 0:x.id)===K.id,isPlaying:v===K.id,playProgress:v===K.id?T:0,showWaveform:l,showAnalysis:c,onSelect:()=>D(K),onPlay:()=>Z(K),onStop:G,onDragStart:W=>q(K,W),onFavorite:()=>F(K.id)},K.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(Gi,{data:x.waveformData,width:300,height:80,progress:v===x.id?T:0}),r.jsxs("div",{className:"nice-sample-browser__preview-info",children:[r.jsx("div",{children:m("sampleBrowser.durationS","Duration: {duration}s").replace("{duration}",String(x.duration.toFixed(2)))}),r.jsx("div",{children:m("sampleBrowser.sampleRateHz","Sample Rate: {sampleRate} Hz").replace("{sampleRate}",String(x.sampleRate))}),r.jsx("div",{children:m("sampleBrowser.channels","Channels: {channels}").replace("{channels}",String(x.channels))}),x.bpm&&r.jsx("div",{children:m("sampleBrowser.bpm","BPM: {bpm}").replace("{bpm}",String(x.bpm))}),x.key&&r.jsx("div",{children:m("sampleBrowser.key","Key: {key}").replace("{key}",String(x.key))})]})]})]})};function Wi(e){return{past:[],present:e,future:[]}}function Ui(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function Vi(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 qi(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 Hi(e){return e.past.length>0}function Ki(e){return e.future.length>0}function pa(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>({...n}))}function Yi(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 Zi(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 Xi(e,t){return e.filter(n=>n.time<t.start||n.time>t.end)}function Hd(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>n.id)}function Qi(e,t,n,a){const s={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:a};return[...e,s]}function Ji(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 eo(e){return JSON.stringify(e,null,2)}function to(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 gt(e,t){var n;return((n=e.find(a=>a.layerId===t))==null?void 0:n.events)??[]}function Ct(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 Kd(e,t){switch(t.type){case"UNDO":return Vi(e);case"REDO":return qi(e);default:{let n=e.present;switch(t.type){case"ADD_EVENT":{const a=[...gt(n,t.layerId),t.event];n=Ct(n,t.layerId,a);break}case"UPDATE_EVENT":{const a=gt(n,t.layerId).map(s=>s.id===t.id?{...s,value:t.value,time:t.time,handleType:t.handleType??s.handleType}:s);n=Ct(n,t.layerId,a);break}case"REMOVE_EVENT":{const a=gt(n,t.layerId).filter(s=>s.id!==t.id);n=Ct(n,t.layerId,a);break}case"SET_EVENTS":n=Ct(n,t.layerId,t.events);break;case"PASTE":{const a=gt(n,t.layerId),s=Yi(a,t.clipboard,t.targetTime);n=Ct(n,t.layerId,s);break}case"CUT":{const a=gt(n,t.layerId),{remaining:s}=Zi(a,t.range);n=Ct(n,t.layerId,s);break}case"DELETE_RANGE":{const a=gt(n,t.layerId),s=Xi(a,t.range);n=Ct(n,t.layerId,s);break}case"RECORD":{const a=gt(n,t.layerId),s=Qi(a,t.cc,t.value,t.time);n=Ct(n,t.layerId,s);break}case"THIN":{const a=gt(n,t.layerId),s=Ji(a,t.keepEveryN);n=Ct(n,t.layerId,s);break}case"IMPORT":{const a=to(t.json);a.length>0&&(n=Ct(n,t.layerId,a));break}}return Ui(e,n)}}}function no(e=[]){const[t,n]=d.useReducer(Kd,Wi(e)),a=d.useRef([]),s=d.useCallback(v=>gt(t.present,v),[t.present]),i=d.useCallback((v,C)=>n({type:"ADD_EVENT",layerId:v,event:C}),[]),o=d.useCallback((v,C,T,M,k)=>n({type:"UPDATE_EVENT",layerId:v,id:C,value:T,time:M,handleType:k}),[]),l=d.useCallback((v,C)=>n({type:"REMOVE_EVENT",layerId:v,id:C}),[]),c=d.useCallback((v,C)=>n({type:"SET_EVENTS",layerId:v,events:C}),[]),u=d.useCallback(()=>n({type:"UNDO"}),[]),h=d.useCallback(()=>n({type:"REDO"}),[]),p=d.useCallback((v,C)=>{a.current=pa(gt(t.present,v),C)},[t.present]),g=d.useCallback((v,C)=>{a.current=pa(gt(t.present,v),C),n({type:"CUT",layerId:v,range:C})},[t.present]),y=d.useCallback((v,C)=>{a.current.length>0&&n({type:"PASTE",layerId:v,clipboard:a.current,targetTime:C})},[]),m=d.useCallback((v,C)=>n({type:"DELETE_RANGE",layerId:v,range:C}),[]),x=d.useCallback((v,C,T,M)=>n({type:"RECORD",layerId:v,cc:C,value:T,time:M}),[]),b=d.useCallback((v,C)=>n({type:"THIN",layerId:v,keepEveryN:C}),[]),f=d.useCallback(v=>eo(gt(t.present,v)),[t.present]),j=d.useCallback((v,C)=>n({type:"IMPORT",layerId:v,json:C}),[]);return{snapshots:t.present,getEvents:s,addEvent:i,updateEvent:o,removeEvent:l,setEvents:c,undo:u,redo:h,canUndo:Hi(t),canRedo:Ki(t),copy:p,cut:g,paste:y,clipboard:a.current,deleteRange:m,record:x,thin:b,exportLane:f,importLane:j}}let Yd=Date.now();function vn(){return Yd++}function Zd(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:vn(),cc:t,value:bn(i.value),time:i.time}),s=i.time);return a}function ws(e,t,n,a=32){const s=[];for(let i=0;i<=a;i++){const o=i/a;s.push({id:vn(),cc:n,value:bn(Nr(e.value,t.value,o)),time:Nr(e.time,t.time,o)})}return s}function Xd(e,t,n,a,s=48){const i=[];for(let o=0;o<=s;o++){const l=o/s,c=Cs(e.time,t.time,n.time,l),u=Cs(e.value,t.value,n.value,l);i.push({id:vn(),cc:a,value:bn(u),time:c})}return i}function Qd(e,t,n,a=8){const s=[],i=(t.time-e.time)/a,o=(t.value-e.value)/a;for(let l=0;l<a;l++){const c=e.time+l*i,u=bn(e.value+l*o);s.push({id:vn(),cc:n,value:u,time:c}),s.push({id:vn(),cc:n,value:u,time:c+i-.001})}return s}function Jd(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:vn(),cc:n,value:bn(Nr(e.value,t.value,c)),time:Nr(e.time,t.time,l)})}return i}function eu(e,t=3){if(e.length<t)return e;const n=[...e].sort((a,s)=>a.time-s.time);return n.map((a,s)=>{const i=Math.max(0,s-Math.floor(t/2)),o=Math.min(n.length,i+t),l=n.slice(i,o),c=l.reduce((u,h)=>u+h.value,0)/l.length;return{...a,value:bn(Math.round(c))}})}function tu(e,t){let n;switch(e.mode){case"pencil":n=Zd(t,e.cc,e.resolution);break;case"line":n=t.length>=2?ws(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?n=Xd(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?n=ws(t[0],t[t.length-1],e.cc):n=[];break;case"step":n=t.length>=2?Qd(t[0],t[t.length-1],e.cc):[];break;case"ramp":n=t.length>=2?Jd(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=eu(n,a)}return n}function bn(e){return Math.max(0,Math.min(127,Math.round(e)))}function Nr(e,t,n){return e+(t-e)*n}function Cs(e,t,n,a){const s=1-a;return s*s*e+2*s*a*t+a*a*n}function Fr(){return{waveform:"sine",rate:1,depth:.5,phase:0,center:.5,syncToBpm:!1,syncDivision:"1/4",enabled:!0}}const nu={"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 ro(e,t){return e/60*nu[t]/4}function ao(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 _a(e,t,n){if(!e.enabled)return e.center;const a=e.syncToBpm&&n?ro(n,e.syncDivision):e.rate,s=t*a+e.phase/(2*Math.PI),i=ao(e.waveform,s),o=e.center+i*e.depth*.5;return Math.max(0,Math.min(1,o))}function Da(e,t,n){return Math.round(_a(e,t,n)*127)}function so(e,t,n,a,s=30,i){const o=n-t,l=Math.max(2,Math.ceil(o*s)),c=[];for(let u=0;u<=l;u++){const h=t+u/l*o,p=Da(e,h,i);c.push({time:h,value:p,cc:a})}return c}function io(e,t,n,a=2,s,i=200){const o=[];for(let l=0;l<=i;l++){const c=l/i*a,u=_a(e,c,s);o.push({x:l/i*t,y:(1-u)*n})}return o}function ru(e){return JSON.stringify(e,null,2)}function au(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const Qr=140,xn=24,su=[{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"}],iu=[{mode:"pencil",label:"Pencil"},{mode:"line",label:"Line"},{mode:"curve",label:"Curve"},{mode:"step",label:"Step"},{mode:"ramp",label:"Ramp"}],ou=["sine","triangle","sawtooth","square","random","sample-hold"],lu=({layerId:e=0,ccNumber:t,duration:n=8,zoom:a=1,automation:s,onChangeCCNumber:i})=>{const o=no(),l=s??o,[c,u]=ve.useControllableState({value:t,fallbackValue:1,onChange:i,componentName:"NiceCCAutomationLaneEditor"}),{t:h}=xe(),p=d.useRef(null),[g,y]=d.useState("pencil"),[m,x]=d.useState(!1),b=d.useRef([]),[f,j]=d.useState(null),[v,C]=d.useState(!1),[T,M]=d.useState(Fr()),k=d.useRef(null),R=l.getEvents(e),P=R.filter(w=>w.cc===c),I=Math.max(400,n*30*a),A=d.useCallback(w=>w/I*n,[I,n]),L=d.useCallback(w=>Math.round(Math.max(0,Math.min(127,127-(w-xn)/Qr*127))),[]),E=d.useCallback(w=>w/n*I,[I,n]),D=d.useCallback(w=>xn+(127-w)/127*Qr,[]),Z=d.useCallback(()=>{const w=p.current;if(!w)return;const N=w.getContext("2d");if(!N)return;const S=w.width,O=w.height;N.clearRect(0,0,S,O),N.fillStyle=ve.resolveCssColor("var(--nice-bg, #1a1a2e)",N.canvas),N.fillRect(0,0,S,O);const Y=ve.resolveCssColor("var(--nice-border-color, #cbd5e1)",N.canvas);N.strokeStyle=Y,N.lineWidth=1,N.globalAlpha=.5;for(let $=0;$<=127;$+=16){const H=D($);N.beginPath(),N.moveTo(0,H),N.lineTo(S,H),N.stroke()}N.globalAlpha=1,N.fillStyle=ve.resolveCssColor("var(--nice-text-muted, #64748b)",N.canvas),N.font="10px monospace",N.textBaseline="middle";for(const $ of[0,32,64,96,127])N.fillText(String($),2,D($));N.strokeStyle=Y,N.globalAlpha=.3;for(let $=0;$<=n;$++){const H=E($);N.beginPath(),N.moveTo(H,0),N.lineTo(H,O),N.stroke()}N.globalAlpha=1;const _=[...P].sort(($,H)=>$.time-H.time);if(_.length>0){N.beginPath(),N.moveTo(E(_[0].time),O-xn);for(const $ of _)N.lineTo(E($.time),D($.value));N.lineTo(E(_[_.length-1].time),O-xn),N.closePath(),N.fillStyle=ve.resolveCssColor("var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",N.canvas),N.fill(),N.beginPath(),N.strokeStyle=ve.resolveCssColor("var(--nice-primary, #3b82f6)",N.canvas),N.lineWidth=2;for(let $=0;$<_.length;$++){const H=E(_[$].time),X=D(_[$].value);$===0?N.moveTo(H,X):((_[$].handleType??"linear")==="step"&&N.lineTo(H,D(_[$-1].value)),N.lineTo(H,X))}N.stroke();for(const $ of _){const H=E($.time),X=D($.value),re=f===$.id;N.beginPath(),N.arc(H,X,re?6:4,0,Math.PI*2),N.fillStyle=ve.resolveCssColor(re?"var(--nice-primary-light, #60a5fa)":"var(--nice-primary, #3b82f6)",N.canvas),N.fill(),N.strokeStyle=ve.resolveCssColor("var(--nice-bg, #fff)",N.canvas),N.lineWidth=1.5,N.stroke()}}N.strokeStyle=Y,N.lineWidth=1,N.setLineDash([4,4]);const U=D(0);N.beginPath(),N.moveTo(0,U),N.lineTo(S,U),N.stroke(),N.setLineDash([])},[P,n,E,D,f]);d.useEffect(()=>{Z()},[Z]);const G=w=>{var Y;const N=(Y=p.current)==null?void 0:Y.getBoundingClientRect();if(!N)return;const S=w.clientX-N.left,O=w.clientY-N.top;g==="pencil"?(x(!0),b.current=[{time:A(S),value:L(O)}]):(x(!0),b.current=[{time:A(S),value:L(O)}])},F=w=>{var U;const N=(U=p.current)==null?void 0:U.getBoundingClientRect();if(!N)return;const S=w.clientX-N.left,O=w.clientY-N.top;m&&b.current.push({time:A(S),value:L(O)});const Y=[...P].sort(($,H)=>$.time-H.time);let _=null;for(const $ of Y){const H=E($.time),X=D($.value);if(Math.abs(S-H)<8&&Math.abs(O-X)<8){_=$.id;break}}j(_)},q=()=>{if(!m)return;x(!1);const w=b.current;if(w.length===0)return;const N=tu({mode:g,cc:c,resolution:.02,smoothing:g==="pencil"?.3:0},w);N.length>0&&l.setEvents(e,[...R,...N]),b.current=[]},V=w=>{var Y;const N=(Y=p.current)==null?void 0:Y.getBoundingClientRect();if(!N)return;const S=w.clientX-N.left,O=w.clientY-N.top;for(const _ of P){const U=E(_.time),$=D(_.value);if(Math.abs(S-U)<8&&Math.abs(O-$)<8){l.removeEvent(e,_.id);return}}l.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:c,value:L(O),time:A(S)})},K=()=>{const N=so(T,0,n,c,Math.ceil(n*20),120).map((S,O)=>({...S,id:Date.now()+O}));l.setEvents(e,[...R,...N]),C(!1)},W=()=>{const w=l.exportLane(e),N=new Blob([w],{type:"application/json"}),S=URL.createObjectURL(N),O=document.createElement("a");O.href=S,O.download=`cc-lane-${c}-layer-${e}.json`,document.body.appendChild(O),O.click(),O.remove(),URL.revokeObjectURL(S)},Q=w=>{var S;const N=(S=w.target.files)==null?void 0:S[0];N&&(N.text().then(O=>{l.importLane(e,O)}),k.current&&(k.current.value=""))};return r.jsxs("div",{className:ye.panel,children:[r.jsxs("div",{className:ye.header,children:[r.jsx("h6",{className:ye.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:w=>u(Number(Nt(w))),options:su.map(w=>({value:String(w.cc),label:h("ccLane.cc2","{label} (CC{cc})").replace("{label}",String(h(`ccLane.preset.${w.key}`,w.label))).replace("{cc}",String(w.cc))}))}),r.jsx(ie.NiceSegmentedControl,{size:"sm",value:g,onChange:y,options:iu.map(w=>({value:w.mode,label:h(`ccLane.mode.${w.mode}`,w.label)}))}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(B.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(B.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:ye.toolbar,children:[r.jsx(ie.NiceButton,{size:"sm",variant:v?"primary":"outline","aria-pressed":v,onClick:()=>C(!v),title:h("ccLane.lfoHint","Apply LFO modulation"),children:h("ccLane.lfo","LFO")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:W,title:h("ccLane.exportHint","Export CC lane as JSON"),children:h("ccLane.export","Export")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:()=>{var w;return(w=k.current)==null?void 0:w.click()},title:h("ccLane.importHint","Import CC lane from JSON"),children:h("ccLane.import","Import")}),r.jsx("input",{ref:k,type:"file",accept:".json",hidden:!0,onChange:Q}),r.jsx(ie.NiceButton,{size:"sm",variant:"danger",onClick:()=>l.setEvents(e,R.filter(w=>w.cc!==c)),title:h("ccLane.clearHint","Clear all CC events for this lane"),children:h("ccLane.clear","Clear")}),r.jsxs("span",{className:`${ye.noteText} ${ye.pushRight}`,children:[P.length," ",h("ccLane.events","events")]})]}),v&&r.jsxs("div",{className:ye.subPanel,children:[r.jsxs("div",{className:`${ye.row} ${ye.alignStart} ${ye.field}`,children:[r.jsx(ie.NiceSelect,{size:"sm",controlWidth:130,label:h("ccLane.lfoWave","Wave"),value:T.waveform,onChange:w=>M(N=>({...N,waveform:Nt(w)})),options:ou.map(w=>({value:w,label:w}))}),r.jsx(ie.NiceNumberInput,{size:"sm",className:ye.inputW120,label:h("ccLane.lfoRate","Rate (Hz)"),min:.01,max:20,step:.1,precision:2,value:T.rate,onChange:w=>{w!==null&&M(N=>({...N,rate:w}))}}),r.jsx("div",{className:ye.sliderW200,children:r.jsx(ie.NiceSlider,{size:"sm",label:h("ccLane.lfoDepth","Depth"),min:0,max:1,step:.01,value:T.depth,onChange:w=>M(N=>({...N,depth:w})),showValue:!0,formatValue:w=>w.toFixed(2)})}),r.jsx("div",{className:ye.sliderW200,children:r.jsx(ie.NiceSlider,{size:"sm",label:h("ccLane.lfoCenter","Center"),min:0,max:1,step:.01,value:T.center,onChange:w=>M(N=>({...N,center:w})),showValue:!0,formatValue:w=>w.toFixed(2)})})]}),r.jsxs("div",{className:ye.buttonRow,children:[r.jsx(ie.NiceButton,{size:"sm",variant:"primary",onClick:K,children:h("ccLane.applyLfo","Apply LFO")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:()=>C(!1),children:h("ccLane.cancel","Cancel")})]})]}),r.jsx("div",{style:{overflowX:"auto",borderRadius:6},children:r.jsx("canvas",{ref:p,width:I,height:Qr+xn*2,style:{cursor:m?"crosshair":f?"pointer":"crosshair",display:"block",borderRadius:6},onMouseDown:G,onMouseMove:F,onMouseUp:q,onMouseLeave:()=>{m&&q()},onDoubleClick:V,role:"img","aria-label":h("ccLane.canvas","CC automation lane")})}),r.jsx("div",{className:ye.noteTextMargin,children:h("ccLane.hint","Click to draw. Double-click to add/remove points. Drag to draw curves.")})]})},oo={"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},fa={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function cu(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 lo(e,t){if(e.length===0)return[];const n=cu(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 du(e,t,n,a=0,s=1){const i=lo(e,t);if(i.length===0)return[];const o=60/n,l=oo[t.rate]*o,c=l*t.gate,u=[],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 b=t.velocityPattern?t.velocityPattern[g%t.velocityPattern.length]:x.velocity;u.push({pitch:x.pitch,velocity:b,startTime:m,duration:c,step:g})}else{const x=g%i.length,b=i[x],f=t.velocityPattern?t.velocityPattern[g%t.velocityPattern.length]:b.velocity;u.push({pitch:b.pitch,velocity:f,startTime:m,duration:c,step:g})}}return u}function co(){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 uo(){return Object.keys(oo)}const js=e=>`${Math.round(e*100)}%`,uu=({config:e=fa,onChange:t=()=>{},active:n=!1,onToggleActive:a=()=>{}})=>{const{t:s}=xe(),i=co(),o=uo(),l=c=>t({...e,...c});return r.jsxs("div",{className:`${ye.panel} ${n?"":ye.panelInactive}`,children:[r.jsxs("div",{className:ye.header,children:[r.jsx("h6",{className:ye.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(fa),title:s("arp.resetHint","Reset to defaults"),children:s("arp.reset","Reset")})]}),r.jsxs("div",{className:ye.grid2,children:[r.jsxs("div",{className:ye.full,children:[r.jsx("span",{className:ye.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:Nt(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:js}),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:js}),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})]})]})},Ms=e=>`${Math.round(e*100)}%`,hu=["sine","triangle","sawtooth","square","random","sample-hold"],pu=["1/1","1/2","1/4","1/8","1/16","1/32"],Sn=200,nn=48,fu=({config:e,onChange:t,index:n,onRemove:a})=>{const{t:s}=xe(),i=d.useRef(null),o=c=>t({...e,...c}),l=d.useCallback(()=>{const c=i.current;if(!c)return;const u=c.getContext("2d");if(!u)return;u.clearRect(0,0,Sn,nn),u.fillStyle=ve.resolveCssColor("var(--nice-bg-secondary, #161b22)",u.canvas),u.fillRect(0,0,Sn,nn),u.strokeStyle=ve.resolveCssColor("var(--nice-border-color, #cbd5e1)",u.canvas),u.lineWidth=1,u.setLineDash([3,3]),u.beginPath(),u.moveTo(0,nn/2),u.lineTo(Sn,nn/2),u.stroke(),u.setLineDash([]);const h=io(e,Sn,nn);if(h.length>0){u.beginPath(),u.strokeStyle=ve.resolveCssColor(e.enabled?"var(--nice-primary, #3b82f6)":"var(--nice-text-secondary, #484f58)",u.canvas),u.lineWidth=1.5;for(let p=0;p<h.length;p++){const g=h[p].x,y=h[p].y;p===0?u.moveTo(g,y):u.lineTo(g,y)}u.stroke()}},[e]);return d.useEffect(()=>{l()},[l]),r.jsxs("div",{className:`${ye.panel} ${ye.panelCompact} ${e.enabled?"":ye.panelInactive}`,children:[r.jsxs("div",{className:ye.header,children:[r.jsxs("h6",{className:ye.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(Fr()),title:s("lfo.resetHint","Reset to defaults"),children:s("lfo.reset","Reset")}),a&&r.jsx("span",{className:ye.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(B.NtdClose,{size:12})})})]}),r.jsxs("div",{className:`${ye.row} ${ye.alignStart}`,children:[r.jsx("canvas",{ref:i,width:Sn,height:nn,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:ye.grow,children:[r.jsx("div",{className:ye.field,children:r.jsx(ie.NiceSegmentedControl,{size:"xs",block:!0,value:e.waveform,onChange:c=>o({waveform:c}),options:hu.map(c=>({value:c,label:r.jsx("span",{title:c,children:c==="sample-hold"?"S&H":c.slice(0,3)})}))})}),r.jsxs("div",{className:ye.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:Ms}),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:Ms}),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:ye.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:Nt(c)}),options:pu.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})})]})]})]})]})},mu=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],gu=[16,32,64],yu=e=>`${Math.round(e*100)}%`;function Rs(e){const t=Math.floor(e/12)-1;return`${mu[e%12]}${t}`}const vu=({seq:e})=>{const{t}=xe(),n=e==null?void 0:e.pattern,a=d.useMemo(()=>n?n.steps.slice(0,n.length):[],[n]);if(!e||!n)return r.jsxs("div",{className:ye.panel,children:[r.jsx("h6",{className:ye.title,children:t("stepSeq.title","Step Sequencer")}),r.jsx("div",{className:ye.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 u=c.currentTarget,h=u.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=()=>{u.removeEventListener("pointermove",g),u.removeEventListener("pointerup",y),u.removeEventListener("pointercancel",y)};(m=u.setPointerCapture)==null||m.call(u,c.pointerId),u.addEventListener("pointermove",g),u.addEventListener("pointerup",y),u.addEventListener("pointercancel",y),p(c.clientY)};return r.jsxs("div",{className:ye.panel,children:[r.jsxs("div",{className:ye.header,children:[r.jsx("h6",{className:ye.title,children:t("stepSeq.title","Step Sequencer")}),r.jsx(ie.NiceButton,{size:"sm",variant:i?"danger":"success",leftIcon:i?r.jsx(B.NtdStop,{size:12}):r.jsx(B.NtdPlay,{size:12}),onClick:e.togglePlayback,children:i?t("stepSeq.stop","Stop"):t("stepSeq.play","Play")})]}),r.jsxs("div",{className:`${ye.row} ${ye.alignStart} ${ye.field}`,children:[r.jsx(ie.NiceNumberInput,{size:"sm",className:ye.inputW120,label:t("stepSeq.bpm","BPM"),min:20,max:300,value:n.bpm,onChange:l=>{l!==null&&e.setBpm(l)}}),r.jsx("div",{className:ye.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:yu})}),r.jsxs("div",{children:[r.jsx("span",{className:ye.label,children:t("stepSeq.length","Steps")}),r.jsx(ie.NiceSegmentedControl,{size:"sm",value:n.length,onChange:e.setLength,options:gu.map(l=>({value:l,label:String(l)}))})]})]}),r.jsxs("div",{className:ye.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(B.NtdArrowRight,{size:12}),onClick:()=>e.shift(1),children:t("stepSeq.shift","Shift")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(B.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 u=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":u,"aria-label":`${t("stepSeq.step","Step")} ${c+1}${u?`, ${Rs(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:u?`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:u?"var(--nice-color-white, #ffffff)":"var(--nice-text-secondary, #484f58)",fontSize:8,fontWeight:600,transition:"background 0.1s"},children:u?Rs(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:u?"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"}})}),u&&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 bu(e,t,n){const{t:a}=xe(),[s,i]=d.useState("interval"),[o,l]=d.useState(30),c=d.useRef(null),u=d.useCallback(()=>{if(e)try{localStorage.setItem("audioEditor.autoSave",JSON.stringify(e)),t(a("useAutoSave.projectAutoSavedLocally","Project auto-saved locally")),n("success"),setTimeout(()=>t(""),2e3)}catch(h){t(a("useAutoSave.autoSaveError","Auto-save error:")+" "+h.message),n("error")}},[e,t,n,a]);return d.useEffect(()=>{(s==="onChange"||s==="both")&&u()},[e,s,u]),d.useEffect(()=>(c.current&&(clearInterval(c.current),c.current=null),(s==="interval"||s==="both")&&o>0&&(c.current=window.setInterval(u,o*1e3)),()=>{c.current&&(clearInterval(c.current),c.current=null)}),[s,o,u]),{autoSaveMode:s,setAutoSaveMode:i,autoSaveInterval:o,setAutoSaveInterval:l}}function xu(e,t,n){const a=d.useRef(null),[s,i]=d.useState(!1),[o,l]=d.useState(0),[c,u]=d.useState(10),[h,p]=d.useState(!1),[g,y]=d.useState(120),m=d.useCallback((k,R)=>`L${k}-C${R}`,[]),x=d.useCallback((k,R)=>{if(!a.current||!R.audioBuffer)return;const P=m(k,R.id),I=e[k];a.current.addClip({id:P,buffer:R.audioBuffer,startTime:R.start,offset:0,duration:R.duration,layerId:k,volume:(I==null?void 0:I.volume)??1,pan:(I==null?void 0:I.pan)??0,stretchFactor:R.stretchFactor||1,effectChain:(I==null?void 0:I.effectChain)||[]})},[e,m]),b=d.useCallback((k,R)=>{var P;(P=a.current)==null||P.removeClip(m(k,R))},[m]);d.useEffect(()=>{Object.entries(t).forEach(([k,R])=>{const P=Number(k);R==null||R.forEach(I=>x(P,I))})},[t,e,x]),d.useEffect(()=>{a.current&&Object.entries(n).forEach(([k,R])=>{const P=Number(k);a.current.setMidiCCEvents(P,R)})},[n]);const f=d.useCallback(()=>{a.current&&(s?a.current.pause():a.current.play())},[s]),j=d.useCallback(()=>{var k;(k=a.current)==null||k.stop()},[]),v=d.useCallback(k=>{var R;(R=a.current)==null||R.seek(k)},[]),C=d.useCallback(()=>{if(!a.current)return;const k=!h;p(k),a.current.setLoopRegion(0,c,k)},[h,c]),T=d.useCallback(k=>{var P;const R=Math.max(1,c+k);u(R),(P=a.current)==null||P.setLoopRegion(0,R,h)},[c,h]),M=d.useCallback(async(k,R=1024)=>{const P=await k.arrayBuffer(),I=new(window.AudioContext||window.webkitAudioContext),A=await I.decodeAudioData(P.slice(0)),L=A.getChannelData(0),E=L.length,D=Math.max(1,Math.floor(E/R)),Z=[];for(let G=0;G<R;G++){const F=G*D;if(F>=E)break;Z.push(L[F])}return I.close(),{waveform:Z.map(G=>Math.max(-1,Math.min(1,G))),duration:A.duration,buffer:A}},[]);return{engineRef:a,isPlaying:s,setIsPlaying:i,currentTime:o,setCurrentTime:l,duration:c,setDuration:u,isLooping:h,setIsLooping:p,bpm:g,setBpm:y,handlePlayPause:f,handleStop:j,handleSeek:v,handleToggleLoop:C,handleAdjustDuration:T,upsertEngineClip:x,removeEngineClip:b,makeEngineClipId:m,blobToWaveform:M}}class za{constructor(){this.stream=null,this.mediaRecorder=null,this.audioChunks=[],this.isRecording=!1,this.audioContext=null,this.analyser=null,this.gainNode=null,this.monitorGain=null,this.levelRaf=null}async startRecording(t={}){if(this.isRecording)return;this.levelCallback=t.onLevel,this.stream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t.deviceId||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}});const n=t.mimeType||"audio/webm";this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:n}),this.audioChunks=[],this.audioContext=new(window.AudioContext||window.webkitAudioContext);let s=this.audioContext.createMediaStreamSource(this.stream);t.gain!==void 0&&t.gain>0&&(this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=t.gain,s.connect(this.gainNode),s=this.gainNode),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,s.connect(this.analyser),t.monitorEnabled&&(this.monitorGain=this.audioContext.createGain(),this.monitorGain.gain.value=(t.monitorVolume??100)/100,s.connect(this.monitorGain),this.monitorGain.connect(this.audioContext.destination));const i=()=>{if(!this.analyser)return;const o=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(o);let l=0;for(let u=0;u<o.length;u++){const h=(o[u]-128)/128;l+=h*h}const c=Math.sqrt(l/o.length);this.levelCallback&&this.levelCallback(c),this.isRecording&&(this.levelRaf=requestAnimationFrame(i))};this.mediaRecorder.ondataavailable=o=>{o.data&&o.data.size>0&&this.audioChunks.push(o.data)},this.mediaRecorder.start(),this.isRecording=!0,this.levelRaf=requestAnimationFrame(i)}getStream(){return this.stream}async stopRecording(){return!this.isRecording||!this.mediaRecorder?null:new Promise(t=>{const n=this.mediaRecorder;n.onstop=()=>{const a=new Blob(this.audioChunks,{type:n.mimeType});this.cleanup(),t(a)},n.stop(),this.isRecording=!1})}cleanup(){this.levelRaf&&(cancelAnimationFrame(this.levelRaf),this.levelRaf=null),this.levelCallback=void 0,this.monitorGain&&(this.monitorGain.disconnect(),this.monitorGain=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.analyser&&(this.analyser.disconnect(),this.analyser=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.stream&&(this.stream.getTracks().forEach(t=>t.stop()),this.stream=null),this.mediaRecorder=null,this.audioChunks=[]}}function Su(e){const{t}=xe(),[n,a]=d.useState(!1),[s,i]=d.useState(!1),[o,l]=d.useState(0),[c,u]=d.useState(0),[h,p]=d.useState(null),g=d.useRef(null),y=d.useRef(null),m=d.useRef(0),x=d.useRef(null),b=d.useRef(null),f=d.useCallback(()=>{x.current&&(clearInterval(x.current),x.current=null),b.current&&(clearTimeout(b.current),b.current=null)},[]),j=d.useCallback(async()=>{if(!e.activeLayer){e.showToast("Select a layer to record.","error");return}n||(g.current||(g.current=new za),m.current=y.current??e.currentTime,a(!0),l(0),await g.current.startRecording({onLevel:l}))},[e,n]),v=d.useCallback(async()=>{var E;if(f(),i(!1),u(0),y.current=null,!g.current){a(!1),l(0);return}const M=await g.current.stopRecording();if(a(!1),l(0),!M||!e.activeLayer)return;const{waveform:k,duration:R,buffer:P}=await e.blobToWaveform(M),I=e.activeLayer.id;e.setWaveforms(D=>({...D,[I]:k}));const A=Math.max(0,m.current||0),L={id:Date.now(),label:t("useRecording.recording","Recording"),start:A,duration:R,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:(E=e.layerSettings[I])==null?void 0:E.color,blob:M,blobUrl:URL.createObjectURL(M),audioBuffer:P};e.setLayerClips(D=>({...D,[I]:[...D[I]||[],L]})),e.upsertEngineClip(I,L),e.setSelectedClip({layerId:I,clipId:L.id})},[e,f,t]),C=d.useCallback(M=>{if(M<=0){j();return}i(!0),u(M);const k=performance.now();x.current=window.setInterval(()=>{const R=(performance.now()-k)/1e3;u(Math.max(0,M-R))},100),b.current=window.setTimeout(()=>{f(),i(!1),u(0),y.current||j()},M*1e3)},[j,f]),T=d.useCallback(async()=>{if(n||s){await v();return}if(!e.activeLayer){e.showToast("Select a layer before recording","error");return}const M=Math.max(0,e.countInBars)*4*(60/e.bpm),k=e.punchIn!=null&&e.punchIn>e.currentTime?e.punchIn:null;k&&(y.current=k),e.overdubEnabled&&!e.isPlaying&&e.playEngine(),k?M>0&&C(M):C(M)},[n,s,e,v,C]);return{isRecording:n,isCountIn:s,monitorLevel:o,countInRemaining:c,punchOut:h,setPunchOut:p,armedPunchInRef:y,recorderRef:g,clearCountInTimers:f,startRecordingNow:j,stopRecordingFlow:v,handleRecord:T}}var ho=(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))(ho||{});const ku={};class er{constructor(t,n,a,s={}){this.type=t,this.name=n,this.component=ku[t]??(()=>null),this.audioType=a,this.parameters=s}}new er("Recorder","Recorder","vocal",{deviceId:"",gain:1,sensitivity:"high"}),new er("Audio Clip","Audio Clip","instrumental",{clipId:null,octave:"4"}),new er("Speech Synth","Speech Synth","vocal",{text:"",voice:"default"}),new er("Keyboard/Pads","Keyboard","instrumental",{instrument:"piano",preset:"default",velocity:100});function po(e,t,n,a,s){n(i=>t?[...i,t]:i),a([]),s(e)}function wu(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 Cu(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 ju{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 Mu=st.scoped("useProjectCRUD");function Ru(e){const{t}=xe(),{project:n,activeSection:a,setProject:s,setActiveSection:i,setLayers:o,setActiveLayer:l,setUndoStack:c,setRedoStack:u,addSection:h,addLayer:p}=e,g=d.useCallback(v=>po(v,n,c,u,s),[n,c,u,s]),y=d.useCallback(async()=>{var k;if(!n)return;const v=(((k=n.sections)==null?void 0:k.length)??0)+1,C=t("useProjectCRUD.section","Section"),M={id:await h(n.id,C,v),projectId:n.id,name:C,orderNumber:v,layers:[]};g({...n,sections:[...n.sections||[],M]}),i(M)},[n,g,i,h,t]),m=d.useCallback(async v=>{var M,k,R;if(!n||!await e.confirm(t("useProjectCRUD.deleteSectionConfirm","Delete this section?")))return;await e.deleteSection(v);const T=(n.sections??[]).filter(P=>P.id!==v);g({...n,sections:T}),i(T[0]??null),o(((M=T[0])==null?void 0:M.layers)??[]),l(((R=(k=T[0])==null?void 0:k.layers)==null?void 0:R[0])??null)},[n,g,i,o,l,e,t]),x=d.useCallback(async()=>{var C;if(!a)return;const v={id:-Date.now(),name:t("useProjectCRUD.newLayer","New Layer"),sectionId:a.id,audioSource:ho.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};o(T=>[...T,v]),l(v);try{const T=await p(a.id,v.name,v.audioSource,v.audioSourceParameters);o(M=>M.map(k=>k.id===v.id?{...v,id:T}:k)),n&&g({...n,sections:((C=n.sections)==null?void 0:C.map(M=>M.id===a.id?{...M,layers:[...(M.layers??[]).filter(k=>k.id!==T),{...v,id:T}]}:M))??[]})}catch(T){o(M=>M.filter(k=>k.id!==v.id)),Mu.error("Failed to add layer:",T)}},[a,n,g,o,l,p,t]),b=d.useCallback(async v=>{var T,M;if((T=e.layerSettings[v])!=null&&T.locked){e.showToast(t("useProjectCRUD.layerLocked","Layer is locked. Unlock to delete."),"error");return}await e.confirm(t("useProjectCRUD.deleteLayerConfirm","Delete this layer?"))&&((e.layerClips[v]||[]).forEach(k=>e.removeEngineClip(v,k.id)),e.setLayerMidiNotes(k=>{const R={...k};return delete R[v],R}),await e.deleteLayer(v),o(k=>k.filter(R=>R.id!==v)),l(k=>(k==null?void 0:k.id)===v?null:k),n&&g({...n,sections:((M=n.sections)==null?void 0:M.map(k=>k.id===(a==null?void 0:a.id)?{...k,layers:(k.layers??[]).filter(R=>R.id!==v)}:k))??[]}))},[n,a,g,o,l,e,t]),f=d.useCallback(async()=>{if(!n)return;const v=e.projectVolume===""?void 0:Number(e.projectVolume);if(Number.isNaN(v)){e.setStatusType("error"),e.setStatusMessage(t("useProjectCRUD.volumeNotNumber","Volume must be a number"));return}if(!e.projectName.trim()){e.setStatusType("error"),e.setStatusMessage(t("useProjectCRUD.projectNameEmpty","Project name cannot be empty"));return}await e.updateProject(n.id,{name:e.projectName||n.name,isTemplate:e.projectIsTemplate,volume:v}),g({...n,name:e.projectName||n.name,isTemplate:e.projectIsTemplate,volume:v}),e.setStatusType("success"),e.setStatusMessage(t("useProjectCRUD.projectSaved","Project saved"))},[n,e,g,t]),j=d.useCallback(async()=>{var T;if(!a)return;const v=e.sectionName||a.name,C=e.sectionOrder===""?a.orderNumber:Number(e.sectionOrder);if(!v.trim()){e.setStatusType("error"),e.setStatusMessage(t("useProjectCRUD.sectionNameEmpty","Section name cannot be empty"));return}if(Number.isNaN(C)){e.setStatusType("error"),e.setStatusMessage(t("useProjectCRUD.orderNotNumber","Order must be a number"));return}await e.updateSection(a.id,{name:v,orderNumber:C}),i({...a,name:v,orderNumber:C}),n&&g({...n,sections:((T=n.sections)==null?void 0:T.map(M=>M.id===a.id?{...M,name:v,orderNumber:C}:M))??[]}),e.setStatusType("success"),e.setStatusMessage(t("useProjectCRUD.sectionSaved","Section saved"))},[a,n,e,g,i,t]);return{handleAddSection:y,handleDeleteSection:m,handleAddLayer:x,handleDeleteLayer:b,handleSaveProject:f,handleSaveSection:j}}const fo=d.createContext(null);function Nu(){const e=d.useContext(fo);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const Fa=({value:e,children:t})=>r.jsx(fo.Provider,{value:e,children:t});process.env.NODE_ENV!=="production"&&(Fa.displayName="EditorTrackProvider");const hn=(e,t)=>t&&t>0?e*15/t:e/10,Oa=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},Tu=(e,t)=>{const n=t??Oa(e),a=[];let s="",i=0,o="",l=!0;function c(){o.trim()!==""&&(s.length>0&&(s+=" "),s+=o.trim()),o=""}return e.forEach(u=>{if(!(u.startsWith("#")||u.startsWith("E"))){if(u.startsWith("-"))c(),s.trim().length>0&&(a.push({text:s.trim(),timestamp:i}),s=""),l=!0;else if(u.startsWith(":")||u.startsWith("*")){const h=u.indexOf(" "),p=u.indexOf(" ",h+1),g=u.indexOf(" ",p+1),y=u.indexOf(" ",g+1);if(y===-1)return;const m=hn(parseFloat(u.substring(h+1,p)),n);s===""&&(i=m);const x=u.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},Pu=(e,t)=>{const n=t??Oa(e),a=[];let s=[],i="",o=0,l=!0,c=null,u="";function h(){c&&u.trim()!==""&&(c.text=u.trim(),s.push({...c}),i.length>0&&(i+=" "),i+=c.text),c=null,u=""}return e.forEach(p=>{if(!(p.startsWith("#")||p.startsWith("E"))){if(p.startsWith("-"))h(),i.trim().length>0&&(a.push({text:i.trim(),timestamp:o,words:s}),i="",s=[]),l=!0;else if(p.startsWith(":")||p.startsWith("*")){const g=p.startsWith("*"),y=p.indexOf(" "),m=p.indexOf(" ",y+1),x=p.indexOf(" ",m+1),b=p.indexOf(" ",x+1);if(b===-1)return;const f=hn(parseFloat(p.substring(y+1,m)),n),j=hn(parseFloat(p.substring(m+1,x)),n),v=f+j;i===""&&(o=f);const C=p.substring(b+1);if(C.trim()==="~"){c&&(c.endTime=v);return}let T=C;T.startsWith("~")&&(T=T.substring(1)),l?(h(),u=T.trimEnd(),c={text:"",startTime:f,endTime:v,isGolden:g}):c?(u+=T.trimEnd(),c.endTime=v,g&&(c.isGolden=!0)):(u=T.trimEnd(),c={text:"",startTime:f,endTime:v,isGolden:g}),l=C.endsWith(" ")}}}),h(),i.trim().length>0&&a.push({text:i.trim(),timestamp:o,words:s}),a},mo=(e,t)=>{const n=t??Oa(e),a=[];let s=[],i=0;function o(){s.length>0&&(a.push({timestamp:i,syllables:[...s]}),s=[])}return e.forEach(l=>{if(!(l.startsWith("#")||l.startsWith("E"))){if(l.startsWith("-")){o();const c=l.trim().split(/\s+/);if(c.length>=2){const u=parseFloat(c[1]);isFinite(u)&&(i=hn(u,n))}}else if(l.startsWith(":")||l.startsWith("*")){const c=l.startsWith("*"),u=l.indexOf(" "),h=l.indexOf(" ",u+1),p=l.indexOf(" ",h+1),g=l.indexOf(" ",p+1);if(g===-1)return;const y=parseFloat(l.substring(u+1,h)),m=parseFloat(l.substring(h+1,p)),x=hn(y,n),b=x+hn(m,n);s.length===0&&(i=x);const f=l.substring(g+1);if(f.trim()==="~"){s.length>0&&(s[s.length-1].endTime=b);return}let j=f;j.startsWith("~")&&(j=j.substring(1));const v=f.endsWith(" "),C=v?j.slice(0,-1):j;s.push({text:C,startTime:x,endTime:b,isGolden:c,hasTrailingSpace:v})}}}),o(),a},Eu=(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},$u=(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},Ns="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",Ts="var(--karaoke-gold-glow-first, 0 0 12px #FFD700)",Au="var(--karaoke-active-glow, 0 0 10px rgba(0,229,255,0.6), 0 0 4px rgba(255,230,0,0.4))",Iu="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",Lu=({song:e,currentTime:t=0})=>{const{t:n}=xe(),a=d.useMemo(()=>!e||!e.notes.length?[]:mo(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 u=a[c].timestamp,h=c+1<a.length?a[c+1].timestamp:u+30;if(s>=u&&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:Au,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,u)=>{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},u):h>=1?r.jsx("span",{style:{background:m?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Ns,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:m?`drop-shadow(${Ts})`:"none",transition:"filter 0.2s ease"},children:g},u):r.jsxs("span",{style:{position:"relative",display:"inline",filter:y?m?`drop-shadow(${Ts})`:`drop-shadow(${Iu})`:"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))":Ns,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",clipPath:`inset(0 ${100-p}% 0 0)`,pointerEvents:"none"},children:g})]},u)})}),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,u)=>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?" ":"")},u))})]}):a.length>0?r.jsx("p",{style:{color:"var(--karaoke-waiting-text, #999)"},children:r.jsx(B.NtdMusic,{size:20})}):r.jsxs("p",{style:{color:"var(--karaoke-waiting-text, #999)",display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(B.NtdMicrophone,{size:18})," ",n("karaokeLyrics.waitingForLyrics","Waiting for lyrics...")]})})},go=d.memo(Lu),_u=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function It(e){return 12*Math.log2(e/440)+69}function Lt(e){const t=Math.round(e);return`${_u[(t%12+12)%12]}${Math.floor(t/12)-1}`}function Vn(e,t){const n=e-t;return n-12*Math.round(n/12)}const Du="var(--nice-color-success, #22c55e)",zu="var(--nice-color-error, #ef4444)",Fu="var(--nice-color-primary, #3b82f6)",kn=e=>typeof e=="number"&&e>0,Ou=({pitch:e,target:t,history:n,showTarget:a=!0,showHistory:s=!0,historyLength:i=100,tolerance:o=1,range:l=6,hitColor:c=Du,missColor:u=zu,targetColor:h=Fu,height:p=120,idleText:g,className:y,style:m,"aria-label":x,"data-testid":b})=>{const{t:f}=xe(),j=d.useRef(null),v=d.useRef(null),[C,T]=d.useState(0),M=d.useRef([]),[,k]=d.useState(0);d.useEffect(()=>{n||(M.current=[...M.current,kn(e)?e:null].slice(-i),k(Z=>Z+1))},[e,n,i]);const R=(n??M.current).slice(-i),P=typeof t=="number",I=!kn(e)&&!P&&!R.some(kn),A=kn(e)?It(e):void 0;d.useEffect(()=>{const Z=v.current;if(!Z||I||(T(Z.clientWidth),typeof ResizeObserver>"u"))return;const G=new ResizeObserver(()=>T(Z.clientWidth));return G.observe(Z),()=>G.disconnect()},[I]),d.useEffect(()=>{const Z=j.current,G=Z==null?void 0:Z.getContext("2d");if(!Z||!G||C<=0)return;const F=typeof window<"u"&&window.devicePixelRatio||1;Z.width=Math.round(C*F),Z.height=Math.round(p*F),G.setTransform(F,0,0,F,0,0),G.clearRect(0,0,C,p);const q=_=>ve.resolveCssColor(_,Z),V=q(c),K=q(u),W=q(h),Q=q("var(--nice-border-color, rgba(127, 127, 127, 0.25))"),w=q("var(--nice-text-secondary, #888)"),N=P?t:A??69,S=l*2,O=_=>{const U=P?Vn(_,N):_-N;return p/2-Math.max(-l,Math.min(l,U))/S*p};G.strokeStyle=Q,G.lineWidth=1;for(let _=-l;_<=l;_++){const U=p/2-_/S*p;G.beginPath(),G.moveTo(0,U),G.lineTo(C,U),G.stroke()}if(P&&a){const _=o/S*p;G.globalAlpha=.25,G.fillStyle=W,G.fillRect(0,p/2-_,C,_*2),G.globalAlpha=1,G.strokeStyle=W,G.lineWidth=2,G.beginPath(),G.moveTo(0,p/2),G.lineTo(C,p/2),G.stroke()}const Y=_=>!P||Math.abs(Vn(_,t))<=o;if(s&&R.length>1){const _=C/Math.max(1,i-1),U=C-(R.length-1)*_;R.forEach(($,H)=>{if(!kn($))return;const X=It($);G.fillStyle=Y(X)?V:K,G.beginPath(),G.arc(U+H*_,O(X),2,0,Math.PI*2),G.fill()})}if(A!==void 0&&(G.fillStyle=Y(A)?V:K,G.beginPath(),G.arc(C-7,O(A),6,0,Math.PI*2),G.fill()),G.font="11px sans-serif",G.fillStyle=w,G.textBaseline="top",P&&G.fillText(Lt(t),4,4),A!==void 0){const _=Lt(A);G.fillText(_,C-18-G.measureText(_).width,4)}},[C,p,R,A,t,P,a,s,i,o,l,c,u,h]);const L=`nice-pitch-meter${I?" nice-pitch-meter--idle":""}${y?` ${y}`:""}`;if(I)return r.jsxs("div",{className:L,style:{height:p,...m},role:"status","data-testid":b,children:[r.jsx(B.NtdMicrophone,{size:18}),r.jsx("span",{children:g??f("pitchMeter.waiting","Waiting for a voice…")})]});const E=A!==void 0&&P?Vn(A,t):void 0,D=x??[P?f("pitchMeter.target","Target {note}").replace("{note}",Lt(t)):"",A!==void 0?f("pitchMeter.sung","sung {note}").replace("{note}",Lt(A)):f("pitchMeter.silent","silent"),E!==void 0?f("pitchMeter.offset","{n} semitones").replace("{n}",(E>0?"+":"")+E.toFixed(1)):""].filter(Boolean).join(", ");return r.jsx("div",{ref:v,className:L,style:{height:p,...m},"data-testid":b,children:r.jsx("canvas",{ref:j,role:"img","aria-label":D,style:{width:"100%",height:p}})})},Jr={},Bu=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:yt&&yt.tagName.toUpperCase()==="SCRIPT"&&yt.src||new URL("index.cjs",document.baseURI).href}<"u"&&(Jr==null?void 0:Jr.VITE_DEBUG_KARAOKE)==="true";function ma(e,t,...n){(Bu||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 yo=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},Ps=(e,t)=>t&&t>0?e*15/t:e/10,Zn=(e,t)=>{const n=t??yo(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]),n),duration:Ps(parseFloat(o[2]),n),pitch:parseInt(o[3],10),isGold:c})}}),s.length>0&&a.push(s),a},vo=(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},bo=st.scoped("karaokeScoringConfig"),Ba={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}},Gu="karaoke.scoringPresets";function Wu(){try{const e=localStorage.getItem(Gu);return e?JSON.parse(e):null}catch(e){return bo.warn("Failed to parse scoring presets overrides",e),null}}function xo(e){const t={...Ba},n=Wu();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=xo();const Uu=async e=>{try{let t=null;if(e?t=await e.getKaraokeScoringConfig():(bo.debug("No fetcher provided, using defaults"),t=null),t&&t.presets)return exports.ScoringPresets=xo(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},Or=(e="normal")=>exports.ScoringPresets[e]||Ba.normal,Vu=3,te=Vu;function Kt(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 pn(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 Ga(e){const t=Math.min(14,e*.22)|0,n=t+2,a=Math.max(t-te,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${te+a} ${te}H${n}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 Tr(e){const t=e*.3|0,n=t+2,a=Math.max(t-te,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e-t}V${t}Z`,inn:`M${te+a} ${te}H${n}V${e-te}H${te+a}L${te} ${e-te-a}V${te+a}Z`}}function Gt(e){const t=e*.42|0,n=t+2,a=Math.max(t-(te*1.4|0),2);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e/2}Z`,inn:`M${te+a} ${te}H${n}V${e-te}H${te+a}L${te} ${e/2}Z`}}function Pr(e){const t=e*.3|0,n=t+4,a=Math.max(t-te,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${te+a} ${te}H${n}V${e-te}H${te+(a*.6|0)}L${te} ${e-te-a}V${te+a}Q${te} ${te} ${te+a} ${te}Z`}}function Wa(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${te+(t*1.2|0)} ${te}H${n}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 Ua(e){const t=e*.32|0,n=t+3,a=Math.max(t-te,1);return{w:n,out:`M0 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}Z`,inn:`M${te} ${te}H${n}V${e-te}H${te+a}Q${te} ${e-te} ${te} ${e-te-a}Z`}}function Er(e){const t=e*.14|0,n=t*3+2;return{w:n,out:`M${t*2} 0H${n}V${e}H${t*2}C${t*.5|0} ${e*.8|0} ${t*3} ${e*.55|0} ${t*.5|0} ${e*.35|0}S${t} 0 ${t*2} 0Z`,inn:`M${te+(t*1.8|0)} ${te}H${n}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 Va(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${te+(t*2.5|0)} ${te}H${n}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 mr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M${t} 0H${n}V${e}H0Z`,inn:`M${te+t-(te*1.3|0)} ${te}H${n}V${e-te}H${te+1}Z`}}function ga(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}V${e}H${t}Z`,inn:`M${te} ${te}H${n}V${e-te}H${te+t-(te*1.3|0)+1}Z`}}function Ot(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 fn(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,n=t+2,a=Math.max(t-te,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 ${te}H${n-te-a}Q${n-te} ${te} ${n-te} ${te+a}V${e-te-a}Q${n-te} ${e-te} ${n-te-a} ${e-te}H0Z`}}function mn(e){const t=e*.3|0,n=t+2,a=Math.max(t-te,1);return{w:n,out:`M0 0H${n-t}L${n} ${t}V${e-t}L${n-t} ${e}H0Z`,inn:`M0 ${te}H${n-te-a}L${n-te} ${te+a}V${e-te-a}L${n-te-a} ${e-te}H0Z`}}function Rt(e){const t=e*.42|0,n=t+2,a=Math.max(t-(te*1.4|0),2);return{w:n,out:`M0 0H${n-t}L${n} ${e/2}L${n-t} ${e}H0Z`,inn:`M0 ${te}H${n-te-a}L${n-te} ${e/2}L${n-te-a} ${e-te}H0Z`}}function ko(e){const t=e*.3|0,n=t+4,a=Math.max(t-te,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 ${te}H${n-te-a}Q${n-te} ${te} ${n-te} ${te+a}V${e-te-a}L${n-te-(a*.6|0)} ${e-te}H0Z`}}function wo(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 ${te}H${n-te-(t*1.2|0)}C${n-te-(t*2.2|0)} ${e*.37|0} ${n-te-(t*2.2|0)} ${e*.63|0} ${n-te-(t*1.2|0)} ${e-te}H0Z`}}function Co(e){const t=e*.32|0,n=t+3,a=Math.max(t-te,1);return{w:n,out:`M0 0H${n}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${te}H${n-te}V${e-te-a}Q${n-te} ${e-te} ${n-te-a} ${e-te}H0Z`}}function qa(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 ${te}H${n-te-(t*1.8|0)}C${n-te-(t*.9|0)} ${te} ${n-te+(t*.1|0)} ${e*.22|0} ${n-te-(t*.4|0)} ${e*.37|0}S${n-te-(t*.4|0)} ${e*.78|0} ${n-te-(t*1.8|0)} ${e-te}H0Z`}}function $r(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 ${te}H${n-te-(t*2.5|0)}L${n-te-(t*.7|0)} ${te+(t*1.6|0)}L${n-te-(t*1.7|0)} ${e*.36|0}L${n-te} ${e/2|0}L${n-te-(t*1.7|0)} ${e*.64|0}L${n-te-(t*.7|0)} ${e-te-(t*1.6|0)}L${n-te-(t*2.5|0)} ${e-te}H0Z`}}function ya(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}L${n-t} ${e}H0Z`,inn:`M0 ${te}H${n-te}L${n-te-t+(te*1.3|0)} ${e-te}H0Z`}}function gr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n-t}L${n} ${e}H0Z`,inn:`M0 ${te}H${n-te-t+(te*1.3|0)}L${n-te} ${e-te}H0Z`}}const Ha=[{name:"Pill",L:Kt,R:Ot},{name:"Sharp",L:pn,R:fn},{name:"Soft",L:Ga,R:So},{name:"Chamfer",L:Tr,R:mn},{name:"Arrow",L:Gt,R:Rt},{name:"Shield",L:Pr,R:ko},{name:"Bracket",L:Wa,R:wo},{name:"Tab",L:Ua,R:Co},{name:"Wave",L:Er,R:qa},{name:"Ornate",L:Va,R:$r}],jo=[{name:"Pill→Arrow",L:Kt,R:Rt},{name:"Arrow→Pill",L:Gt,R:Ot},{name:"Pill→Sharp",L:Kt,R:fn},{name:"Sharp→Pill",L:pn,R:Ot},{name:"Pill→Chamfer",L:Kt,R:mn},{name:"Chamfer→Pill",L:Tr,R:Ot},{name:"Arrow→Sharp",L:Gt,R:fn},{name:"Sharp→Arrow",L:pn,R:Rt},{name:"Arrow→Chamfer",L:Gt,R:mn},{name:"Chamfer→Arrow",L:Tr,R:Rt},{name:"Soft→Arrow",L:Ga,R:Rt},{name:"Shield→Chamfer",L:Pr,R:mn},{name:"Pill→Wave",L:Kt,R:qa},{name:"Wave→Arrow",L:Er,R:Rt},{name:"Tab→Pill",L:Ua,R:Ot},{name:"Ornate→Sharp",L:Va,R:fn},{name:"Sharp→Ornate",L:pn,R:$r},{name:"Bracket→Arrow",L:Wa,R:Rt},{name:"Shield→Pill",L:Pr,R:Ot},{name:"Wave→Ornate",L:Er,R:$r}],Mo=[{name:"Skew ╲",L:mr,R:ya},{name:"Skew ╱",L:ga,R:gr},{name:"◇ Romb",L:Gt,R:Rt},{name:"╲→Pill",L:mr,R:Ot},{name:"Pill→╲",L:Kt,R:ya},{name:"╱→Sharp",L:ga,R:fn},{name:"Sharp→╱",L:pn,R:gr},{name:"╲→Arrow",L:mr,R:Rt},{name:"Arrow→╱",L:Gt,R:gr},{name:"◇→Chamfer",L:Gt,R:mn}],qn=(function(){return[...Ha,...jo,...Mo]})(),Ro=Ha[0];function Tn(e){return qn.find(t=>t.name===e)||Ro}const Ar=[{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 Pn(e){return Ar.find(t=>t.name===e)||null}const Ut={color:null,capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,glass:0,textureUrl:null,textureScale:1},Br=(function(){return{...Ut,glass:85}})(),Gr=(function(){return{...Ut,patternName:"Stars"}})(),Wr=(function(){return{...Ut,patternName:"Stars"}})(),Ur={fontFamily:null,fontSize:18,fontColor:null,outlineColor:null,outlineWidth:0,shadow:null},No=(function(){return{filledBar:{...Ut},emptyBar:{...Br},goldFilledBar:{...Wr},goldEmptyBar:{...Gr},font:{...Ur},disableGoldNotes:!1}})(),Es={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},$s="nice2dev-player-bar-style",As="nice2dev-player-karaoke-settings";function gn(e){return e!=null?`${As}-${e}`:As}function Is(e){return e!=null?`${$s}-${e}`:$s}function Ls(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 _s(e){const t=No,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 Ka(e){try{const t=localStorage.getItem(gn(e));if(t){const a=JSON.parse(t);return _s(a)}const n=localStorage.getItem(Is(e));if(n){const a=JSON.parse(n),s=Ls({...Es,...a});return localStorage.setItem(gn(e),JSON.stringify(s)),s}if(e!=null){const a=localStorage.getItem(gn());if(a)return _s(JSON.parse(a));const s=localStorage.getItem(Is());if(s)return Ls({...Es,...JSON.parse(s)})}}catch{}return{filledBar:{...Ut},emptyBar:{...Br},goldFilledBar:{...Wr},goldEmptyBar:{...Gr},font:{...Ur}}}function qu(e,t){const n=JSON.stringify(e);localStorage.setItem(gn(t),n)}let Ds=!1;async function Hu(e){if(Ds||(Ds=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(gn())||localStorage.setItem(gn(),t)}catch{}}function Ku(e){const t=new Map;for(const n of e)t.set(n,Ka(n));return t}const Yu={"&":"&","<":"<",">":">",'"':""","'":"'"},Zu=/[&<>"']/g;function Xu(e){return e.replace(Zu,t=>Yu[t])}function Qu(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 Ju=3,Ze=Ju;function Ir(e){const t=parseInt(e.slice(1,3),16)/255,n=parseInt(e.slice(3,5),16)/255,a=parseInt(e.slice(5,7),16)/255,s=Math.max(t,n,a),i=Math.min(t,n,a);let o=0,l=0;const c=(s+i)/2;if(s!==i){const u=s-i;switch(l=c>.5?u/(2-s-i):u/(s+i),s){case t:o=((n-a)/u+(n<a?6:0))/6;break;case n:o=((a-t)/u+2)/6;break;case a:o=((t-n)/u+4)/6;break}}return[Math.round(o*360),Math.round(l*100),Math.round(c*100)]}function Lr(e){let t=e.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),"#"+t.toLowerCase()}function dt(e,t){return e.replace(/([MLHVCSQTAZ])/gi,`
|
|
2
2
|
$1`).split(`
|
|
3
|
-
`).filter(Boolean).map(n=>{const 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
|
|
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 To(e){const{width:t,height:n,capStyle:a,color:s,highlight:i=70,glow:o=55,glass:l=0,pattern:c=null,patternColor:u=null,patternOnly:h=!1,textureUrl:p=null,textureScale:g=1}=e,y=p&&Qu(p)?Xu(p):null,[m,x,b]=Ir(Lr(s)),f="c"+Math.random().toString(36).slice(2,7),j=a.L(n),v=a.R(n),C=t-j.w-v.w;if(C<4)return"";if(h&&c){const X=`hsl(${m},${x}%,${b}%)`,re=`hsl(${m},${Math.max(x-20,0)}%,${Math.min(b+30,95)}%)`,oe=u||re,se=j.w,z=j.w+C,ee=j.inn,ae=`M${se} ${Ze}H${z}V${n-Ze}H${se}Z`,ce=dt(v.inn,z),le=j.out,ne=`M${se} 0H${z}V${n}H${se}Z`,pe=dt(v.out,z),fe=c.mk(f+"pat",oe,u||void 0),ge=Math.round(256*g),he=Math.round(256*g),we=y?`<pattern id="${f}tex" patternUnits="userSpaceOnUse" width="${ge}" height="${he}"><image href="${y}" width="${ge}" height="${he}" 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
4
|
${fe}
|
|
5
5
|
${we}
|
|
6
6
|
<clipPath id="${f}c"><path d="${ee}"/><path d="${ae}"/><path d="${ce}"/></clipPath>
|
|
@@ -24,7 +24,7 @@ ${H}
|
|
|
24
24
|
${Y}
|
|
25
25
|
<rect x="0" y="${F}" width="${t}" height="${Z-F}" fill="url(#${f}g)" clip-path="url(#${f}c)"/>
|
|
26
26
|
<rect x="0" y="${D}" width="${t}" height="${G-D}" fill="url(#${f}h)" clip-path="url(#${f}c)"/>
|
|
27
|
-
</svg>`}function et(e,t){const n=t.match(/[MLHVCSQTAZmlhvcsqtaz][^MLHVCSQTAZmlhvcsqtaz]*/g);if(!n)return;let a=0,s=0;for(const i of n){const o=i[0],l=i.slice(1).trim().split(/[\s,]+/).filter(Boolean).map(Number);switch(o){case"M":a=l[0],s=l[1],e.moveTo(a,s);break;case"L":a=l[0],s=l[1],e.lineTo(a,s);break;case"H":a=l[0],e.lineTo(a,s);break;case"V":s=l[0],e.lineTo(a,s);break;case"C":e.bezierCurveTo(l[0],l[1],l[2],l[3],l[4],l[5]),a=l[4],s=l[5];break;case"Q":e.quadraticCurveTo(l[0],l[1],l[2],l[3]),a=l[2],s=l[3];break;case"S":{e.bezierCurveTo(a,s,l[0],l[1],l[2],l[3]),a=l[2],s=l[3];break}case"A":{const c=Math.abs(l[0]),u=Math.abs(l[1]),h=l[3]!==0,p=l[4]!==0,g=l[5],y=l[6],m=a,x=s;if(Math.abs(m-g)<.001&&Math.abs(x-y)<.001||c<.001||u<.001){e.lineTo(g,y),a=g,s=y;break}const b=(c+u)/2,f=(m-g)/2,j=(x-y)/2,v=f*f+j*j,C=v>b*b?Math.sqrt(v):b,T=C*C,M=Math.sqrt(Math.max(0,(T-v)/v)),k=h!==p?1:-1,R=(m+g)/2+k*M*j,P=(x+y)/2-k*M*f,I=Math.atan2(x-P,m-R),A=Math.atan2(y-P,g-R);e.arc(R,P,C,I,A,!p),a=g,s=y;break}case"Z":e.closePath();break}}}function En(e,t,n,a,s,i,o,l=70,c=55,u=0,h,p,g=!1,y,m){const[x,b,f]=
|
|
27
|
+
</svg>`}function et(e,t){const n=t.match(/[MLHVCSQTAZmlhvcsqtaz][^MLHVCSQTAZmlhvcsqtaz]*/g);if(!n)return;let a=0,s=0;for(const i of n){const o=i[0],l=i.slice(1).trim().split(/[\s,]+/).filter(Boolean).map(Number);switch(o){case"M":a=l[0],s=l[1],e.moveTo(a,s);break;case"L":a=l[0],s=l[1],e.lineTo(a,s);break;case"H":a=l[0],e.lineTo(a,s);break;case"V":s=l[0],e.lineTo(a,s);break;case"C":e.bezierCurveTo(l[0],l[1],l[2],l[3],l[4],l[5]),a=l[4],s=l[5];break;case"Q":e.quadraticCurveTo(l[0],l[1],l[2],l[3]),a=l[2],s=l[3];break;case"S":{e.bezierCurveTo(a,s,l[0],l[1],l[2],l[3]),a=l[2],s=l[3];break}case"A":{const c=Math.abs(l[0]),u=Math.abs(l[1]),h=l[3]!==0,p=l[4]!==0,g=l[5],y=l[6],m=a,x=s;if(Math.abs(m-g)<.001&&Math.abs(x-y)<.001||c<.001||u<.001){e.lineTo(g,y),a=g,s=y;break}const b=(c+u)/2,f=(m-g)/2,j=(x-y)/2,v=f*f+j*j,C=v>b*b?Math.sqrt(v):b,T=C*C,M=Math.sqrt(Math.max(0,(T-v)/v)),k=h!==p?1:-1,R=(m+g)/2+k*M*j,P=(x+y)/2-k*M*f,I=Math.atan2(x-P,m-R),A=Math.atan2(y-P,g-R);e.arc(R,P,C,I,A,!p),a=g,s=y;break}case"Z":e.closePath();break}}}function En(e,t,n,a,s,i,o,l=70,c=55,u=0,h,p,g=!1,y,m){const[x,b,f]=Ir(Lr(o)),j=i.L(s),v=i.R(s),C=a-j.w-v.w;if(C<0){const[w,,N]=Ir(Lr(o));e.save(),e.translate(t,n),e.globalAlpha=1-u/100*.87,e.fillStyle=`hsl(${w},50%,${Math.min(N+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 T=j.w,M=j.w+C;if(g){const w=`hsla(${x},${b}%,${f}%,0.22)`;e.save(),e.translate(t,n),e.fillStyle="rgba(255,255,255,0.18)",e.beginPath(),et(e,j.out),e.fill(),e.fillRect(T,0,C,s),e.beginPath(),et(e,dt(v.out,M)),e.fill(),e.fillStyle=w,e.beginPath(),et(e,j.inn),e.fill(),e.fillRect(T,Ze,C,s-2*Ze),e.beginPath(),et(e,dt(v.inn,M)),e.fill(),y&&(e.save(),e.beginPath(),et(e,j.inn),e.rect(T,Ze,C,s-2*Ze),et(e,dt(v.inn,M)),e.clip(),e.globalAlpha=.85,e.fillStyle=y,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),m&&(e.save(),e.beginPath(),et(e,j.inn),e.rect(T,Ze,C,s-2*Ze),et(e,dt(v.inn,M)),e.clip(),e.globalAlpha=.85,e.fillStyle=m,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),e.restore();return}const k=`hsl(${x},${Math.min(b+10,100)}%,${Math.max(f-22,4)}%)`,R=`hsl(${x},${b}%,${f}%)`,P=`hsl(${x},${Math.max(b-12,0)}%,${Math.min(f+18,88)}%)`,I=`hsl(${x},${Math.min(b+20,100)}%,${Math.min(f+30,93)}%)`,A=l/100*.78,L=c/100*.65,E=1-u/100*.87,D=Ze,Z=s-Ze,G=Z-D,F=D+G*.44,q=D+G*.58;e.save(),e.translate(t,n);const V=e.createLinearGradient(0,0,0,s);V.addColorStop(0,"rgba(255,255,255,0.55)"),V.addColorStop(.3,"rgba(255,255,255,0.35)"),V.addColorStop(1,"rgba(255, 255, 255, 0.08)"),e.fillStyle=V,e.beginPath(),et(e,j.out),e.fill(),e.fillRect(T,0,C,s),e.beginPath(),et(e,dt(v.out,M)),e.fill();const K=e.createLinearGradient(0,D,0,Z);K.addColorStop(0,P),K.addColorStop(.5,R),K.addColorStop(1,k),e.globalAlpha=E,e.fillStyle=K,e.beginPath(),et(e,j.inn),e.fill(),e.fillRect(T,Ze,C,s-2*Ze),e.beginPath(),et(e,dt(v.inn,M)),e.fill(),e.globalAlpha=1,y&&(e.save(),e.beginPath(),et(e,j.inn),e.rect(T,Ze,C,s-2*Ze),et(e,dt(v.inn,M)),e.clip(),e.globalAlpha=E*.9,e.fillStyle=y,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),m&&(e.save(),e.beginPath(),et(e,j.inn),e.rect(T,Ze,C,s-2*Ze),et(e,dt(v.inn,M)),e.clip(),e.globalAlpha=E*.85,e.fillStyle=m,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),e.save(),e.beginPath(),et(e,j.inn),e.rect(T,Ze,C,s-2*Ze),et(e,dt(v.inn,M)),e.clip();const W=e.createLinearGradient(0,q,0,Z);W.addColorStop(0,"transparent"),W.addColorStop(.6,I.replace(")",`, ${L*.6})`).replace("hsl","hsla")),W.addColorStop(1,I.replace(")",`, ${L})`).replace("hsl","hsla")),e.fillStyle=W,e.fillRect(0,q,a,Z-q);const Q=e.createLinearGradient(0,D,0,F);Q.addColorStop(0,`rgba(255,255,255,${A})`),Q.addColorStop(.5,`rgba(255,255,255,${A*.25})`),Q.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=Q,e.fillRect(0,D,a,F-D),e.restore(),e.restore()}const Yt="var(--nice-warning, #FFD700)",Po="var(--nice-warning-bg, #fff0a8)";function eh(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?ve.resolveCssColor(Yt,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?ve.resolveCssColor(Yt,t.canvas):s,t.fillRect(c.x,c.y,c.w,c.h));t.restore()}function th(e){const{ctx:t,ballX:n,ballY:a,ballRadius:s,playerColor:i,ballIsGold:o,currentTime:l}=e,c=3,u=s*1.5,h=l*4;t.save();for(let g=0;g<c;g++){const y=(h+g*2.1)%(Math.PI*2),m=Math.sin(y)*.5+.5,x=u+m*s*3,b=(1-m)*.5;t.globalAlpha=b,t.strokeStyle=o?ve.resolveCssColor(Yt,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?ve.resolveCssColor(Yt,t.canvas):i,t.shadowBlur=16+Math.sin(l*8)*4,t.fillStyle=o?ve.resolveCssColor(Po,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?ve.resolveCssColor(Yt,t.canvas):i,t.fillRect(g.x,g.y,g.w,g.h)}t.restore()}function nh(e){const{ctx:t,ballX:n,ballY:a,ballRadius:s,playerColor:i,ballIsGold:o,currentTime:l}=e,c=20+Math.abs(Math.sin(l*3))*15,u=l*5%(Math.PI*2),h=-Math.abs(Math.sin(u))*c,p=a+h;t.save(),t.globalAlpha=.3,t.fillStyle=ve.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 b=0;b<y;b++){const f=(b+1)*.04,j=(l-f)*5%(Math.PI*2),v=a+-Math.abs(Math.sin(j))*c,C=.15*(1-b/y),T=s*(.6-b*.08);t.globalAlpha=C,t.fillStyle=i,t.beginPath(),t.arc(n-b*3,v,Math.max(2,T),0,Math.PI*2),t.fill()}t.restore(),t.save();const m=1+Math.abs(Math.sin(u))*.15,x=1/m;if(t.translate(n,p),t.scale(x,m),t.shadowColor=o?ve.resolveCssColor(Yt,t.canvas):i,t.shadowBlur=12,t.fillStyle=o?ve.resolveCssColor(Po,t.canvas):i,t.beginPath(),t.arc(0,0,s,0,Math.PI*2),t.fill(),t.lineWidth=1.5,t.strokeStyle=ve.resolveCssColor("var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",t.canvas),t.stroke(),t.restore(),Math.abs(Math.sin(u))<.1){t.save(),t.globalAlpha=.6,t.fillStyle=o?ve.resolveCssColor(Yt,t.canvas):i;for(let b=0;b<4;b++){const f=b/4*Math.PI*2+l,j=n+Math.cos(f)*(s+4),v=a+Math.sin(f)*2;t.beginPath(),t.arc(j,v,2,0,Math.PI*2),t.fill()}t.restore()}}function rh(e,t){switch(e){case"wipe":return eh(t),!0;case"pulse":return th(t),!0;case"bounce":return nh(t),!0;case"ball":default:return!1}}const ah=1e3,sh=20,ih=70,oh=5,zs=26,Fs="rgba(255,215,70,0.98)",Os=new Map,lh=(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%'>
|
|
@@ -36,15 +36,15 @@ ${Y}
|
|
|
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)}`},lh=(e,t,n,a,s)=>{const i=`${e}-${t}-${n}-${Math.round(a)}-${s}`;let o=Fs.get(i);return o||(o=new Image,o.src=oh(e,t,n,a,s),Fs.set(i,o),o)},ch=e=>{const t=e.replace("#",""),n=parseInt(t.length===3?t[0]+t[0]:t.substring(0,2),16)/255,a=parseInt(t.length===3?t[1]+t[1]:t.substring(2,4),16)/255,s=parseInt(t.length===3?t[2]+t[2]:t.substring(4,6),16)/255,i=Math.max(n,a,s),o=Math.min(n,a,s);let l=0,c=0;const u=(i+o)/2;if(i!==o){const h=i-o;switch(c=u>.5?h/(2-i-o):h/(i+o),i){case n:l=(a-s)/h+(a<s?6:0);break;case a:l=(s-n)/h+2;break;case s:l=(n-a)/h+4;break}l/=6}return{h:Math.round(l*360),s:Math.round(c*100),l:Math.round(u*100)}},dh=(e,t,n,a=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(n)}%, ${a})`;function tr(e){try{const t=ve.resolveCssColor(e),[n,a,s]=Gc(t),i=o=>o.toString(16).padStart(2,"0");return`#${i(n)}${i(a)}${i(s)}`.toLowerCase()}catch{return"var(--nice-warning, #ffcc00)"}}function uh(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 dn=new Map,$n=new Set,gr=new Set;function Ka(e){const t=dn.get(e);return t?Promise.resolve(t):gr.has(e)?Promise.reject(new Error(`Texture failed: ${e}`)):$n.has(e)?new Promise((n,a)=>{const s=()=>{dn.has(e)?n(dn.get(e)):gr.has(e)?a(new Error(`Texture failed: ${e}`)):requestAnimationFrame(s)};s()}):($n.add(e),new Promise((n,a)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{dn.set(e,s),$n.delete(e),n(s)},s.onerror=()=>{$n.delete(e),gr.add(e),a(new Error(`Failed to load texture: ${e}`))},s.src=e}))}function hh(e){return dn.get(e)??null}function An(e,t,n=1){const a=dn.get(t);if(!a)return!$n.has(t)&&!gr.has(t)&&Ka(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 ph(e){for(const t of e)t&&Ka(t).catch(()=>{})}const In=new Map,ln=new Set;function Po(e,t,n){return`${e}|${t}|${n??""}`}function fh(e,t,n){const a=Po(e.name,t,n),s=In.get(a);if(s)return Promise.resolve(s);if(ln.has(a))return new Promise((m,x)=>{const b=()=>{In.has(a)?m(In.get(a)):ln.has(a)?requestAnimationFrame(b):x(new Error(`Pattern render failed: ${a}`))};b()});ln.add(a);const i="p",o=e.mk(i,t,n??void 0),l=o.match(/width="(\d+)"/),c=o.match(/height="(\d+)"/),u=l?parseInt(l[1],10):16,h=c?parseInt(c[1],10):16,p=`<svg xmlns="http://www.w3.org/2000/svg" width="${u}" height="${h}"><defs>${o}</defs><rect width="${u}" height="${h}" fill="url(#${i})"/></svg>`,g=new Blob([p],{type:"image/svg+xml;charset=utf-8"}),y=URL.createObjectURL(g);return new Promise((m,x)=>{const b=new Image;b.onload=()=>{In.set(a,b),ln.delete(a),URL.revokeObjectURL(y),m(b)},b.onerror=()=>{ln.delete(a),URL.revokeObjectURL(y),x(new Error(`Failed to render pattern tile: ${e.name}`))},b.src=y})}function Ln(e,t,n,a){const s=Po(t.name,n,a),i=In.get(s);return i?e.createPattern(i,"repeat"):(ln.has(s)||fh(t,n,a).catch(()=>{}),null)}let Mt=null,nt=null,pt=null,Et=null,bt=null,Ve=null,Os="",Bs=0,Gs="";const ya=(e,t,n,a,s,i,o,l,c,u,h,p,g,y,m,x,b,f,j,v,C,T,M,k)=>{e.clearRect(0,0,t,n);const R=k??null,P=(R==null?void 0:R.filledBar)??Ut,I=(R==null?void 0:R.emptyBar)??Or,A=(R==null?void 0:R.goldFilledBar)??Gr,L=(R==null?void 0:R.goldEmptyBar)??Br,E=(R==null?void 0:R.font)??Wr,D=Tn(P.capStyleName),Z=Tn(I.capStyleName),G=Tn(A.capStyleName),F=Tn(L.capStyleName),q=P.patternName?Pn(P.patternName):null,V=I.patternName?Pn(I.patternName):null,K=A.patternName?Pn(A.patternName):null,W=L.patternName?Pn(L.patternName):null,Q=q?Ln(e,q,P.patternColor??P.color??"var(--nice-bg, #fff)",P.patternColor):null,w=V?Ln(e,V,I.patternColor??I.color??"var(--nice-border, #d1d5db)",I.patternColor):null,N=K?Ln(e,K,A.patternColor??"var(--nice-warning, #FFD700)",A.patternColor):null,S=W?Ln(e,W,L.patternColor??"var(--nice-warning, #FFD700)",L.patternColor):null;Gs!==i&&(Gs=i,fa("RENDER",`Renderer using settings for "${i}" — filled: cap=${P.capStyleName}, glass=${P.glass} | empty: cap=${I.capStyleName}, glass=${I.glass} | goldFilled: cap=${A.capStyleName}, pattern=${A.patternName??"none"} | goldEmpty: cap=${L.capStyleName}, pattern=${L.patternName??"none"} | hasSettings=${!!R}`,{filledBar:P,emptyBar:I,goldFilledBar:A,goldEmptyBar:L,filledOverlay:!!Q,emptyOverlay:!!w,goldFilledOverlay:!!N,goldEmptyOverlay:!!S}));const O=P.textureUrl?An(e,P.textureUrl,P.textureScale):null,Y=I.textureUrl?An(e,I.textureUrl,I.textureScale):null,_=A.textureUrl?An(e,A.textureUrl,A.textureScale):null,U=L.textureUrl?An(e,L.textureUrl,L.textureScale):null,$=typeof document<"u"?ve.resolveCssColor(l||"var(--nice-color-accent, #ffcc00)"):l||"var(--nice-color-accent, #ffcc00)",H=tr($||"var(--nice-warning, #ffcc00)"),X=ke=>ve.resolveCssColor(ke),re=E.fontFamily||"Arial",oe=E.fontSize||18,se=X(E.fontColor||"var(--btn-text, #fff)"),z=E.outlineColor?X(E.outlineColor):null,ee=typeof E.outlineWidth=="number"?E.outlineWidth:0,ae=E.shadow||null;typeof document<"u"&&((!Mt||Mt.width!==t||Mt.height!==n)&&(Mt=document.createElement("canvas"),Mt.width=t,Mt.height=n,nt=Mt.getContext("2d")),nt&&nt.clearRect(0,0,t,n),(!pt||pt.width!==t||pt.height!==n)&&(pt=document.createElement("canvas"),pt.width=t,pt.height=n,Et=pt.getContext("2d")),Et&&Et.clearRect(0,0,t,n),(!bt||bt.width!==t||bt.height!==n)&&(bt=document.createElement("canvas"),bt.width=t,bt.height=n,Ve=bt.getContext("2d")),Ve&&Ve.clearRect(0,0,t,n));const ce=j?-j:0,le=v||t;e.fillStyle=$,e.font=`bold ${oe}px ${re}`;const pe=e.measureText(i).width+20;if(e.fillRect(ce+10,5,pe,25),e.save(),e.fillStyle=se,ae){const ke=ae.match(/(-?\d+)px\s+(-?\d+)px\s+(\d+)px\s+(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\)|[a-zA-Z]+)/);ke&&(e.shadowOffsetX=parseInt(ke[1],10),e.shadowOffsetY=parseInt(ke[2],10),e.shadowBlur=parseInt(ke[3],10),e.shadowColor=ke[4])}if(e.fillText(i,ce+20,22),z&&ee>0&&(e.lineWidth=ee,e.strokeStyle=z,e.strokeText(i,ce+20,22)),e.restore(),b){const ke=X(f||"var(--nice-text-secondary, #6b7280)");e.font=`bold 12px ${re}`;const Ce=e.measureText(b).width,We=8,De=ce+10+pe+6,Ae=20,Ee=7,de=Ce+We*2,me=4;e.beginPath(),e.moveTo(De+me,Ee),e.lineTo(De+de-me,Ee),e.quadraticCurveTo(De+de,Ee,De+de,Ee+me),e.lineTo(De+de,Ee+Ae-me),e.quadraticCurveTo(De+de,Ee+Ae,De+de-me,Ee+Ae),e.lineTo(De+me,Ee+Ae),e.quadraticCurveTo(De,Ee+Ae,De,Ee+Ae-me),e.lineTo(De,Ee+me),e.quadraticCurveTo(De,Ee,De+me,Ee),e.closePath(),e.fillStyle=ke,e.fill(),e.fillStyle=se,e.fillText(b,De+We,Ee+14),e.font=`bold ${oe}px ${re}`}const fe=120;if(e.fillStyle=$,e.fillRect(ce+le-fe-10,5,fe,25),e.fillStyle=se,e.fillText(`${o} pts`,ce+le-fe+15,22),C&&C.currentCombo>=5){const ke=C.currentCombo>=50?"3x":C.currentCombo>=30?"2.5x":C.currentCombo>=20?"2x":C.currentCombo>=10?"1.5x":"",Ce=`${C.currentCombo} combo${ke?" "+ke:""}`;e.font=`bold 12px ${re}`;const De=e.measureText(Ce).width+16,Ae=ce+le-fe-10-De-6;e.fillStyle=X(C.currentCombo>=20?"var(--nice-color-success, #FFD700)":"var(--nice-color-warning, #ff9800)"),e.globalAlpha=.9,uh(e,Ae,7,De,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=X(C.currentCombo>=20?"var(--nice-text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(Ce,Ae+8,22),e.font=`bold 14px ${re}`}if(T&&T.length>0){const ke=T[T.length-1];if(ke.label){const Ce=`${T.length}-${ke.label}`;Ce!==Os&&(Os=Ce,Bs=Date.now());const We=Date.now()-Bs;if(We<2500){const De=We<2e3?1:1-(We-2e3)/500,Ae={Perfect:X("var(--nice-color-success, #00e676)"),Great:X("var(--nice-color-success, #66bb6a)"),Good:X("var(--nice-color-accent, #ffeb3b)"),OK:X("var(--nice-color-warning, #ff9800)"),Bad:X("var(--nice-color-error, #ef5350)"),Awful:X("var(--nice-color-error, #b71c1c)")};e.save(),e.globalAlpha=De,e.font=`bold ${Math.round(oe*1.2)}px ${re}`;const Ee=ke.label,de=e.measureText(Ee).width,me=ce+le/2-de/2;e.fillStyle=Ae[Ee]||se,e.shadowColor=ve.resolveCssColor("var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",e.canvas),e.shadowBlur=6,e.fillText(Ee,me,58),z&&ee>0&&(e.lineWidth=ee,e.strokeStyle=z,e.strokeText(Ee,me,58)),e.restore()}}}const ge=s-2,he=s+5,we=40;let je=1/0,Pe=-1/0;if(a.forEach(ke=>{ke.forEach(Ce=>{Ce.pitch<je&&(je=Ce.pitch),Ce.pitch>Pe&&(Pe=Ce.pitch)})}),c&&Array.isArray(c)&&c.length>0){let ke=null;isFinite(je)&&isFinite(Pe)&&(ke=Math.round((je+Pe)/2));let Ce=1/0,We=-1/0;c.forEach(({t:De,hz:Ae})=>{if(!Ae||Ae<=0)return;let Ee=ke;for(const me of a)for(const Re of me)De>=Re.startTime&&De<=Re.startTime+Re.duration&&(Ee=Re.pitch);const de=yo(Ae,Ee);de<Ce&&(Ce=de),de>We&&(We=de)}),Ce!==1/0&&We!==-1/0&&(Ce<je&&(je=Math.floor(Ce-2)),We>Pe&&(Pe=Math.ceil(We+2)))}(!isFinite(je)||!isFinite(Pe))&&(je=40,Pe=80),je===Pe&&(je=Math.max(0,je-6),Pe=Pe+6);const $e=ke=>{const Ce=n-we-10;return we+Ce-(ke-je)/(Pe-je)*Ce},ue=Fr(g||"normal"),Oe=(n-we-10)/Math.max(1,Pe-je),Me=Math.max(10,Math.round(Oe*(1+2*ue.semitoneTolerance)*.3)),Ie=Math.max(5,Math.round(Me*.45));((ke,Ce,We,De,Ae,Ee)=>{ke.lineWidth=1;for(let de=Math.ceil(Ae);de<=Math.floor(Ee);de++){const me=$e(de);ke.strokeStyle=X(de%2===0?"var(--guide-line-strong, rgba(255, 255, 255, 0.12))":"var(--guide-line-weak, rgba(255, 255, 255, 0.06))"),ke.beginPath(),ke.moveTo(0,Math.round(me)+.5),ke.lineTo(Ce,Math.round(me)+.5),ke.stroke()}})(e,t,n-we,we,je,Pe),Et&&Et.clearRect(0,0,t,n);const Be=(s-ge)/(he-ge)*t;let He=n*.5,Dt=!1,ct=!1;const ht=(ke,Ce,We,De,Ae,Ee,de=0)=>{const me=(Ne,_e,be,Te,Le,Ge)=>{const ze=Math.min(Ge,Te/2,Le/2);Ne.beginPath(),Ne.moveTo(_e+ze,be),Ne.lineTo(_e+Te-ze,be),Ne.quadraticCurveTo(_e+Te,be,_e+Te,be+ze),Ne.lineTo(_e+Te,be+Le-ze),Ne.quadraticCurveTo(_e+Te,be+Le,_e+Te-ze,be+Le),Ne.lineTo(_e+ze,be+Le),Ne.quadraticCurveTo(_e,be+Le,_e,be+Le-ze),Ne.lineTo(_e,be+ze),Ne.quadraticCurveTo(_e,be,_e+ze,be),Ne.closePath()},Re=Math.max(2,Me/2);De.forEach(Ne=>{if(Ne.startTime+Ne.duration<Ae||Ne.startTime>Ee)return;const _e=(Ne.startTime-Ae)/(Ee-Ae)*Ce,be=Ne.duration/(Ee-Ae)*Ce,Te=$e(Ne.pitch)-Me/2,Le=[];if(Array.isArray(p)){const Ge=Ne.startTime+Ne.duration;p.forEach(ze=>{if(ze.pitch!==Ne.pitch||ze.noteStart!=null&&ze.noteEnd!=null&&(Math.abs(ze.noteStart-Ne.startTime)>.01||Math.abs(ze.noteEnd-Ge)>.01))return;const tt=Math.max(ze.start,Ne.startTime),Ke=Math.min(ze.end,Ge);if(tt>=Ke)return;const Vt=(tt-Ae)/(Ee-Ae)*Ce,en=(Ke-Ae)/(Ee-Ae)*Ce;Le.push({x1:Vt,x2:en,frac:ze.frac})})}if(Ne.isGold){ke.save();const Ge=m&&m.shadowColor?m.shadowColor:zs,ze=m&&typeof m.glowBlur=="number"?m.glowBlur:Ds;ke.shadowColor=Ge,ke.shadowBlur=Math.max(4,ze-12),ke.fillStyle=X("var(--gold-overlay, rgba(255, 215, 0, 0.15))"),me(ke,_e-1,Te-1,be+2,Me+2,Re),ke.fill(),ke.restore();const tt=tr("var(--gold-base, #b4af9f)");En(ke,_e,Te,be,Me,F,L.color??tt,L.highlight,L.glow,L.glass,W,L.patternColor,L.patternOnly,U,S),ke.save(),me(ke,_e,Te,be,Me,Re),ke.clip(),ke.globalAlpha=.18,ke.fillStyle=X("var(--nice-color-success, #FFD700)"),ke.fillRect(_e,Te,be,Math.max(1,Me*.25)),ke.globalAlpha=1,ke.restore(),Le.length>0&&(ke.save(),me(ke,_e,Te,be,Me,Re),ke.clip(),Le.forEach(Ke=>{const Vt=Math.max(1,Ke.x2-Ke.x1);En(ke,Ke.x1,Te,Vt,Me,G,A.color??"var(--nice-warning, #FFD700)",A.highlight,A.glow,A.glass,K,A.patternColor,A.patternOnly,_,N)}),ke.restore()),Le.length===0&&(ke.lineWidth=1,ke.strokeStyle=X("var(--gold-outline, rgba(255, 215, 0, 0.35))"),me(ke,_e+.5,Te+.5,be-1,Math.max(1,Me-1),Re),ke.stroke())}else{const Ge=tr("var(--note-base, #d1d5db)");En(ke,_e,Te,be,Me,Z,I.color??Ge,I.highlight,I.glow,I.glass,V,I.patternColor,I.patternOnly,Y,w),Le.length>0&&(ke.save(),me(ke,_e,Te,be,Me,Re),ke.clip(),Le.forEach(ze=>{const tt=Math.max(1,ze.x2-ze.x1);En(ke,ze.x1,Te,tt,Me,D,P.color??H,P.highlight,P.glow,P.glass,q,P.patternColor,P.patternOnly,O,Q)}),ke.restore())}Et&&(Et.fillStyle=ve.resolveCssColor("var(--nice-bg, #fff)",Et.canvas),Et.fillRect(_e,Te,be,Me))})};if(a.forEach(ke=>{ht(e,t,n-we,ke,ge,he,we);for(const Ce of ke)if(s>=Ce.startTime&&s<=Ce.startTime+Ce.duration){He=$e(Ce.pitch),Dt=!0,ct=!!Ce.isGold;break}}),!Dt){let ke=null,Ce=null;for(const We of a)for(const De of We)De.startTime>s&&(!ke||De.startTime<ke.startTime)&&(ke=De),De.startTime<=s&&(!Ce||De.startTime>Ce.startTime)&&(Ce=De);ke?(He=$e(ke.pitch),ct=!!ke.isGold):Ce?(He=$e(Ce.pitch),ct=!!Ce.isGold):He=n*.5}const it=$||X("var(--nice-color-accent, #ffcc00)"),wt=1+Math.sin((s||0)*8)*.06,Je=Ie*wt,Pt=[];for(const ke of a)for(const Ce of ke){if(Ce.startTime+Ce.duration<ge||Ce.startTime>he)continue;const We=(Ce.startTime-ge)/(he-ge)*t,De=Ce.duration/(he-ge)*t,Ae=$e(Ce.pitch)-Me/2,Ee=Ce.startTime+Ce.duration<=s;Pt.push({x:We,y:Ae,w:De,h:Me,isGold:Ce.isGold,isSung:Ee})}if(!nh(M||"ball",{ctx:e,ballX:Be,ballY:He,ballRadius:Je,playerColor:it,ballIsGold:ct,currentTime:s,height:n,visibleNotes:Pt})){Mt&&e.drawImage(Mt,0,0),bt&&e.drawImage(bt,0,0),e.save(),e.globalCompositeOperation="source-over",e.globalAlpha=.28;const ke=Math.max(18,Je*5),Ce=e.createRadialGradient(Be,He,0,Be,He,ke);if(Ce.addColorStop(0,it),Ce.addColorStop(1,"transparent"),e.fillStyle=Ce,e.beginPath(),e.arc(Be,He,ke,0,Math.PI*2),e.fill(),e.restore(),y&&nt&&pt&&(nt.save(),nt.globalCompositeOperation="source-over",nt.globalAlpha=.95,nt.fillStyle=it,nt.beginPath(),nt.arc(Be,He,Je+4,0,Math.PI*2),nt.fill(),nt.restore(),nt.save(),nt.globalCompositeOperation="destination-in",nt.drawImage(pt,0,0),nt.restore(),e.drawImage(Mt,0,0)),y&&Ve&&pt)try{const Ae=tr(it),{h:Ee,s:de,l:me}=ch(Ae),Ne=dh(Ee,Math.max(10,Math.round(de*(typeof h=="number"?h:.25))),me,.85);Ve.save(),Ve.globalCompositeOperation="multiply",Ve.globalAlpha=.65,Ve.fillStyle=Ne,Ve.beginPath(),Ve.arc(Be,He,Math.max(8,Je+6),0,Math.PI*2),Ve.fill(),Ve.restore(),Ve.save(),Ve.globalCompositeOperation="destination-out",Ve.drawImage(pt,0,0),Ve.restore(),e.drawImage(bt,0,0)}catch{Ve.save(),Ve.globalCompositeOperation="source-over",Ve.globalAlpha=.6,Ve.fillStyle=it,Ve.beginPath(),Ve.arc(Be,He,Math.max(8,Je+6),0,Math.PI*2),Ve.fill(),Ve.restore(),Ve.save(),Ve.globalCompositeOperation="destination-out",Ve.drawImage(pt,0,0),Ve.restore(),e.drawImage(bt,0,0)}const We=m&&m.shadowColor?m.shadowColor:zs,De=m&&typeof m.glowBlur=="number"?m.glowBlur:Ds;e.save(),ct?(e.shadowColor=We,e.shadowBlur=De,e.fillStyle=X("var(--gold-light, #FFF0A8)")):(e.shadowColor=it,e.shadowBlur=10,e.fillStyle=it),e.globalCompositeOperation="source-over",e.globalAlpha=1,e.beginPath(),e.arc(Be,He,Je,0,Math.PI*2),e.fill(),e.lineWidth=1.5,e.strokeStyle=X("var(--nice-shadow-md, rgba(0,0,0,0.35))"),e.stroke(),e.restore()}try{if(Array.isArray(x)&&x.length>0){const ke=Date.now(),Ce=m&&typeof m.lifeMs=="number"?m.lifeMs:rh,We=(Ae,Ee,de,me=5)=>{const Re=de,Ne=de*.45;e.beginPath();let _e=Math.PI/2*3,be=Ae,Te=Ee;const Le=Math.PI/me;e.moveTo(Ae,Ee-Re);for(let Ge=0;Ge<me;Ge++)be=Ae+Math.cos(_e)*Re,Te=Ee+Math.sin(_e)*Re,e.lineTo(be,Te),_e+=Le,be=Ae+Math.cos(_e)*Ne,Te=Ee+Math.sin(_e)*Ne,e.lineTo(be,Te),_e+=Le;e.lineTo(Ae,Ee-Re),e.closePath()},De=Ae=>{let Ee=Ae>>>0;return()=>(Ee=Ee*1664525+1013904223>>>0,(Ee&2147483647)/2147483647)};x.forEach(Ae=>{const Ee=ke-Ae.createdAt;if(Ee<0||Ee>Ce)return;const de=Ee/Ce,me=(Ae.noteStart-(s-2))/7*t,Re=$e(Ae.notePitch),Ne=De(Ae.seed||Math.floor(Ae.createdAt%1e5)),_e=m&&typeof m.count=="number"?m.count:ah,be=m&&typeof m.baseSpeed=="number"?m.baseSpeed:sh,Te=m&&typeof m.baseSize=="number"?m.baseSize:ih;for(let Le=0;Le<_e;Le++){const Ge=Ne(),ze=Ne(),tt=Le/_e*Math.PI*2+Ge*Math.PI*.6+de*1.5,Ke=6+be*(1-de)*(.5+ze*.8),Vt=me+Math.cos(tt)*Ke,en=Re+Math.sin(tt)*Ke*(.8+Ge*.6),Ct=Math.max(1,Te*(1-de)*(.5+ze)),gs=40+Math.round(20*Ne()),ys=70+Math.round(20*Ne()),Hr=Math.max(0,1-de)*(.9-Ne()*.3),$c=Math.max(6,Ct*2.6),Kr=lh(gs,ys,60,Math.round($c),(Ae.seed||0)+Le);Kr&&Kr.complete?(e.save(),e.translate(Vt,en+4),e.rotate(tt+de*4+(Ne()-.5)*1.2),e.globalAlpha=Hr,e.drawImage(Kr,-Ct/2,-Ct/2,Ct,Ct),e.restore()):(e.save(),e.translate(Vt,en+4),e.rotate(tt+de*4),e.fillStyle=`hsla(${gs}, ${ys}%, 60%, ${Hr})`,e.fillRect(-Ct/2,-Ct/2,Ct,Ct),e.restore()),Ne()>.85&&(e.save(),e.globalAlpha=Math.max(.35,1-de),e.fillStyle=`hsla(${30+Math.round(10*Ne())}, ${60+Math.round(30*Ne())}%, ${70+Math.round(10*Ne())}%, ${Hr})`,e.strokeStyle=`rgba(0,0,0,${.12*(1-de)})`,e.lineWidth=.8,We(Vt,en+4,Ct*(1.4+Ne())),e.fill(),e.stroke(),e.restore())}})}}catch{}return{ballX:Be,ballY:He,ballIsGold:ct}},Eo=({song:e,currentTime:t,playerRef:n,config:a={},userPitch:s,segmentScores:i,goldBursts:o,combo:l,verseRatings:c})=>{const{t:u}=xe(),{isPlaying:h=!1,playerName:p=u("karaokeTimeline.defaultPlayer","Player"),score:g=1e4,playerBgColor:y="var(--karaoke-player-bg, #2196f3)",playerCount:m=2,gapDesaturation:x,goldSettings:b,difficultyLevel:f,algorithmLabel:j,algorithmColor:v,latencyMs:C=null,top:T,animationMode:M,karaokeSettings:k=null}=a,R=d.useRef(null),P=d.useRef(null),[I,A]=d.useState({width:600,height:150,top:250,visibleWidth:600}),[L,E]=d.useState(0),D=d.useRef(0),Z=d.useRef(null),G=d.useRef(null),F=d.useRef(null),q=d.useRef(t),V=d.useRef(performance.now()),K=d.useRef(e),W=d.useRef(I),Q=d.useRef(s),w=d.useRef(h),N=d.useRef(0),S=d.useRef(!1),O=d.useRef(null),Y=d.useRef(null),_=d.useCallback(()=>{const U=(e==null?void 0:e.id)??null;if(U!==Y.current||!O.current){Y.current=U;const $=e.notes.map(z=>z.noteLine);O.current=Zn($,e.bpm??void 0);const H=O.current.reduce((z,ee)=>z+ee.length,0),X=O.current.reduce((z,ee)=>z+ee.filter(ae=>ae.isGold).length,0),re=O.current.flat().map(z=>z.pitch),oe=re.length?Math.min(...re):0,se=re.length?Math.max(...re):0;fa("BARS",`Parsed notes for "${e.title}" — ${O.current.length} verses, ${H} notes (including ${X} golden), pitch range: ${oe}–${se}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:$.length,verseCount:O.current.length,totalNotes:H,goldCount:X,minPitch:oe,maxPitch:se})}return O.current},[e]);return d.useEffect(()=>{const U=(H,X,re)=>H+(X-H)*re,$=H=>{G.current===null&&(G.current=H);const X=Math.min(.1,(H-(G.current||H))/1e3);G.current=H;const re=N.current,oe=D.current,se=1-Math.exp(-12*X),z=Math.abs(oe-re)<.25?oe:U(re,oe,se);Math.abs(z-re)>1e-4&&(E(z),N.current=z,R.current&&(R.current.style.transform=`translateX(${z}px)`)),Z.current=requestAnimationFrame($)};return Z.current=requestAnimationFrame($),()=>{Z.current&&cancelAnimationFrame(Z.current),Z.current=null,G.current=null}},[]),d.useEffect(()=>{const U=()=>{if(!n.current)return;const $=n.current.getBoundingClientRect(),H=2/Math.max(1,m),X=Math.round($.width*H),re=Math.round($.width),oe=X*(150/600);A({width:X,height:oe,top:30,visibleWidth:re})};return U(),window.addEventListener("resize",U),()=>window.removeEventListener("resize",U)},[n,m]),d.useEffect(()=>{var re;if(h||!R.current)return;const U=R.current.getContext("2d");if(!U)return;const $=_(),H=t-(e.gap??0)/1e3,X=ya(U,I.width,I.height,$,H,p,g,y,s,e.id,x??void 0,i,f??void 0,h,b??void 0,o,j,v,N.current,I.visibleWidth,l,c,M,k);if(X&&R.current){const oe=I.visibleWidth||(((re=P.current)==null?void 0:re.getBoundingClientRect().width)??I.width),se=I.width;let z=Math.round(oe/2-X.ballX);const ee=oe-se;z=Math.max(ee,Math.min(0,z)),D.current=z}},[t,e,_,I,s,h,p,g,y,x,i,f,b,o,j,v,l,c,M,k]),d.useEffect(()=>{q.current=t,V.current=performance.now()},[t]),d.useEffect(()=>{K.current=e},[e]),d.useEffect(()=>{W.current=I},[I]),d.useEffect(()=>{Q.current=s},[s]),d.useEffect(()=>{w.current=h},[h]),d.useEffect(()=>{const U=()=>{var ce;const $=R.current,H=K.current,X=W.current;if(!$||!H||!X)return;const re=$.getContext("2d");if(!re)return;const oe=_(),se=Math.min(.5,(performance.now()-V.current)/1e3),ee=(w.current?q.current+se:q.current)-(H.gap??0)/1e3,ae=ya(re,X.width,X.height,oe,ee,p,g,y,Q.current,H.id,x??void 0,i,f??void 0,w.current,b??void 0,o,j,v,N.current,X.visibleWidth,l,c,M,k);if(ae){const le=X.visibleWidth||(((ce=P.current)==null?void 0:ce.getBoundingClientRect().width)??X.width),ne=X.width;let pe=Math.round(le/2-ae.ballX);const fe=le-ne;pe=Math.max(fe,Math.min(0,pe)),D.current=pe}};if(h){S.current||(S.current=!0,fa("BARS",`Drawing bars in RAF loop — canvas: ${W.current.width}×${W.current.height}px, player: ${p}`,{canvasSize:W.current}));const $=()=>{U(),F.current=requestAnimationFrame($)};return F.current=requestAnimationFrame($),()=>{F.current&&cancelAnimationFrame(F.current),F.current=null}}S.current=!1},[h,p,g,y,x,i,f,b,o,j,v,l,c,M,k,_]),r.jsxs("div",{ref:P,style:{position:"absolute",left:"50%",top:`${T??I.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:I.visibleWidth,height:I.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 C<"u"&&C!==null?(()=>{const U=C,$=U<=120?"var(--latency-good, #10b981)":U<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",H=`${U}ms`;return r.jsxs("div",{className:U>250?"av-latency-pulse":"",style:{background:$,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(B.NtdStopwatch,{size:12}),r.jsx("span",{children:H})]})})():r.jsx("div",{style:{background:"var(--latency-none-bg, rgba(75,85,99,0.9))",padding:"6px 8px",borderRadius:12,boxShadow:"0 4px 10px var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",minWidth:44,textAlign:"center"},children:"—"})}),r.jsx("canvas",{ref:R,width:I.width,height:I.height,role:"img","aria-label":u("karaokeTimeline.pitchTimelineFor","Pitch timeline for {player}. Score: {score}").replace("{player}",p).replace("{score}",String(g??0)),style:{position:"absolute",left:0,top:0,transform:`translateX(${L}px)`,willChange:"transform"}})]})},$o="/textures/seamless/256x256";function $t(e,t,n){return{name:e,icon:n,entries:Array.from({length:t},(a,s)=>{const i=String(s+1).padStart(2,"0");return{label:`${e} ${i}`,url:`${$o}/${e}/Photoreal_${e}_${i}-512x512.png`}})}}function zt(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:`${$o}/${e}/${e}_${i}-256x256.png`}})}}const Ya=[$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"),zt("Wall",24,"wall"),zt("Rust",24,"rust"),zt("Woven",24,"woven"),zt("Ground",24,"ground"),zt("Pebbles",24,"pebbles"),zt("Plant",24,"plant"),zt("Roof",24,"roof"),zt("Misc",24,"misc")],Ao=Ya.flatMap(e=>e.entries);function mh(e){return Ao.find(t=>t.url===e)}const gh={fire:B.NtdFire,metal:B.NtdSettings,ice:B.NtdSnowflake,stone:B.NtdMountain,wood:B.NtdTree,tile:B.NtdGrid,concrete:B.NtdLayers,trees:B.NtdTree,grass:B.NtdLeaf,wall:B.NtdHome,rust:B.NtdCircle,woven:B.NtdGrid,ground:B.NtdMountain,pebbles:B.NtdDroplet,plant:B.NtdLeaf,roof:B.NtdHome,misc:B.NtdPalette},yh=({icon:e})=>{const t=gh[e];return t?r.jsx(t,{size:14}):r.jsx(r.Fragment,{children:e})},At=({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}),vh=({fill:e=Ut,onChange:t=()=>{},previewColor:n="var(--nice-primary, #2196f3)",accentColor:a="var(--nice-primary, #0d6efd)",width:s,height:i})=>{const{t:o}=xe(),[l,c]=d.useState(null),u=(f,j)=>{t({...e,[f]:j})},h=d.useMemo(()=>{const f=e.color||n||"var(--nice-primary, #2196f3)";return(j,v,C)=>{const T=qn.find(k=>k.name===j)||qn[0],M=v?$r.find(k=>k.name===v)??null:null;return No({width:80,height:22,capStyle:T,color:f,highlight:e.highlight,glow:e.glow,glass:e.glass,pattern:M,patternColor:e.patternColor,patternOnly:e.patternOnly,textureUrl:C??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=d.useRef(null),m=d.useRef(null),x=d.useCallback((f,j)=>{f.current&&f.current.scrollBy({left:j*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-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(At,{inline:!0,children:o("playerForm.barColor","Color")}),r.jsx(ie.NiceCheckbox,{label:o("playerForm.auto","Auto"),checked:!e.color,onChange:f=>u("color",f?null:n||"var(--nice-primary, #2196f3)")}),e.color&&r.jsx("input",{type:"color",value:e.color,onChange:f=>u("color",f.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),r.jsx(At,{children:o("playerForm.capShape","Cap shape")}),r.jsxs("div",{style:{position:"relative",marginBottom:10},children:[r.jsx("button",{type:"button",style:{...b,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>x(y,-1),"aria-label":o("playerForm.scrollLeft","Scroll left"),children:r.jsx(B.NtdChevronLeft,{size:16})}),r.jsx("button",{type:"button",style:{...b,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>x(y,1),"aria-label":o("playerForm.scrollRight","Scroll right"),children:r.jsx(B.NtdChevronRight,{size:16})}),r.jsx("div",{ref:y,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:qn.map(f=>{const j=e.capStyleName===f.name;return r.jsx("div",{role:"button",tabIndex:0,"aria-pressed":j,onKeyDown:ie.clickOnActivationKey,title:f.name,onClick:()=>u("capStyleName",f.name),style:{cursor:"pointer",flexShrink:0,border:j?p:"1px solid var(--nice-border-color, #555)",borderRadius:6,padding:3,background:j?g:"var(--nice-bg-secondary, #222)"},dangerouslySetInnerHTML:{__html:h(f.name,null)}},f.name)})})]}),r.jsx(At,{children:o("playerForm.pattern","Pattern")}),r.jsxs("div",{style:{position:"relative",marginBottom:10},children:[r.jsx("button",{type:"button",style:{...b,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>x(m,-1),"aria-label":o("playerForm.scrollLeft","Scroll left"),children:r.jsx(B.NtdChevronLeft,{size:16})}),r.jsx("button",{type:"button",style:{...b,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>x(m,1),"aria-label":o("playerForm.scrollRight","Scroll right"),children:r.jsx(B.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",{role:"button",tabIndex:0,"aria-pressed":!e.patternName,onKeyDown:ie.clickOnActivationKey,title:o("playerForm.none","None"),onClick:()=>u("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:"—"}),$r.map(f=>{const j=e.patternName===f.name;return r.jsx("div",{role:"button",tabIndex:0,"aria-pressed":j,onKeyDown:ie.clickOnActivationKey,title:f.name,onClick:()=>u("patternName",f.name),style:{cursor:"pointer",flexShrink:0,border:j?p:"1px solid var(--nice-border-color, #555)",borderRadius:6,padding:3,background:j?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=>u("patternOnly",f)})}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[r.jsx(At,{inline:!0,children:o("playerForm.patternColor","Pattern color")}),r.jsx(ie.NiceCheckbox,{label:o("playerForm.auto","Auto"),checked:!e.patternColor,onChange:f=>u("patternColor",f?null:n||"var(--nice-bg, #fff)")}),e.patternColor&&r.jsx("input",{type:"color",value:e.patternColor,onChange:f=>u("patternColor",f.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),!e.patternOnly&&r.jsxs(r.Fragment,{children:[r.jsxs(At,{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=>u("highlight",f)})}),r.jsxs(At,{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=>u("glow",f)})})]}),r.jsxs(At,{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=>u("glass",f)})}),r.jsx("div",{style:{marginTop:4},children:r.jsx(At,{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:()=>{u("textureUrl",null),c(null)},children:o("playerForm.texNone","None")}),Ya.map(f=>r.jsx(ie.NiceButton,{size:"sm",variant:(l==null?void 0:l.name)===f.name?"primary":"outline",onClick:()=>c(j=>(j==null?void 0:j.name)===f.name?null:f),title:f.name,ariaLabel:f.name,children:r.jsx(yh,{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 j=e.textureUrl===f.url;return r.jsx("div",{role:"button",tabIndex:0,"aria-pressed":j,onKeyDown:ie.clickOnActivationKey,title:f.label,onClick:()=>u("textureUrl",j?null:f.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:j?`3px solid ${a}`:"1px solid var(--nice-text-muted, #bbb)",backgroundImage:`url(${f.url})`,backgroundSize:"cover",boxShadow:j?`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(At,{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=>u("textureScale",f/100)})})]})]})},rt=st.scoped("AudioPitchAnalyzer");function bh({onSegments:e,defaultCompareAll:t=!1,externalFile:n=null,postPitch:a,postLibrosaPitchTrack:s}){const{t:i}=xe(),[o,l]=d.useState("pitchy"),[c,u]=d.useState(null),[h,p]=d.useState(t),[g,y]=d.useState({}),[m,x]=d.useState({}),[b,f]=d.useState([]),[j,v]=d.useState([]),[C,T]=d.useState(!1),[M,k]=d.useState(null),[R]=d.useState(null),[P]=d.useState(null),[I,A]=d.useState(null),L=d.useRef(null);function E(W){try{if(W instanceof Error){let w=`${W.message}
|
|
39
|
+
</svg>`;return`data:image/svg+xml;utf8,${encodeURIComponent(o)}`},ch=(e,t,n,a,s)=>{const i=`${e}-${t}-${n}-${Math.round(a)}-${s}`;let o=Os.get(i);return o||(o=new Image,o.src=lh(e,t,n,a,s),Os.set(i,o),o)},dh=e=>{const t=e.replace("#",""),n=parseInt(t.length===3?t[0]+t[0]:t.substring(0,2),16)/255,a=parseInt(t.length===3?t[1]+t[1]:t.substring(2,4),16)/255,s=parseInt(t.length===3?t[2]+t[2]:t.substring(4,6),16)/255,i=Math.max(n,a,s),o=Math.min(n,a,s);let l=0,c=0;const u=(i+o)/2;if(i!==o){const h=i-o;switch(c=u>.5?h/(2-i-o):h/(i+o),i){case n:l=(a-s)/h+(a<s?6:0);break;case a:l=(s-n)/h+2;break;case s:l=(n-a)/h+4;break}l/=6}return{h:Math.round(l*360),s:Math.round(c*100),l:Math.round(u*100)}},uh=(e,t,n,a=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(n)}%, ${a})`;function tr(e){try{const t=ve.resolveCssColor(e),[n,a,s]=Wc(t),i=o=>o.toString(16).padStart(2,"0");return`#${i(n)}${i(a)}${i(s)}`.toLowerCase()}catch{return"var(--nice-warning, #ffcc00)"}}function hh(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 dn=new Map,$n=new Set,yr=new Set;function Ya(e){const t=dn.get(e);return t?Promise.resolve(t):yr.has(e)?Promise.reject(new Error(`Texture failed: ${e}`)):$n.has(e)?new Promise((n,a)=>{const s=()=>{dn.has(e)?n(dn.get(e)):yr.has(e)?a(new Error(`Texture failed: ${e}`)):requestAnimationFrame(s)};s()}):($n.add(e),new Promise((n,a)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{dn.set(e,s),$n.delete(e),n(s)},s.onerror=()=>{$n.delete(e),yr.add(e),a(new Error(`Failed to load texture: ${e}`))},s.src=e}))}function ph(e){return dn.get(e)??null}function An(e,t,n=1){const a=dn.get(t);if(!a)return!$n.has(t)&&!yr.has(t)&&Ya(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 fh(e){for(const t of e)t&&Ya(t).catch(()=>{})}const In=new Map,ln=new Set;function Eo(e,t,n){return`${e}|${t}|${n??""}`}function mh(e,t,n){const a=Eo(e.name,t,n),s=In.get(a);if(s)return Promise.resolve(s);if(ln.has(a))return new Promise((m,x)=>{const b=()=>{In.has(a)?m(In.get(a)):ln.has(a)?requestAnimationFrame(b):x(new Error(`Pattern render failed: ${a}`))};b()});ln.add(a);const i="p",o=e.mk(i,t,n??void 0),l=o.match(/width="(\d+)"/),c=o.match(/height="(\d+)"/),u=l?parseInt(l[1],10):16,h=c?parseInt(c[1],10):16,p=`<svg xmlns="http://www.w3.org/2000/svg" width="${u}" height="${h}"><defs>${o}</defs><rect width="${u}" height="${h}" fill="url(#${i})"/></svg>`,g=new Blob([p],{type:"image/svg+xml;charset=utf-8"}),y=URL.createObjectURL(g);return new Promise((m,x)=>{const b=new Image;b.onload=()=>{In.set(a,b),ln.delete(a),URL.revokeObjectURL(y),m(b)},b.onerror=()=>{ln.delete(a),URL.revokeObjectURL(y),x(new Error(`Failed to render pattern tile: ${e.name}`))},b.src=y})}function Ln(e,t,n,a){const s=Eo(t.name,n,a),i=In.get(s);return i?e.createPattern(i,"repeat"):(ln.has(s)||mh(t,n,a).catch(()=>{}),null)}let jt=null,nt=null,pt=null,Pt=null,vt=null,Ve=null,Bs="",Gs=0,Ws="";const va=(e,t,n,a,s,i,o,l,c,u,h,p,g,y,m,x,b,f,j,v,C,T,M,k)=>{e.clearRect(0,0,t,n);const R=k??null,P=(R==null?void 0:R.filledBar)??Ut,I=(R==null?void 0:R.emptyBar)??Br,A=(R==null?void 0:R.goldFilledBar)??Wr,L=(R==null?void 0:R.goldEmptyBar)??Gr,E=(R==null?void 0:R.font)??Ur,D=Tn(P.capStyleName),Z=Tn(I.capStyleName),G=Tn(A.capStyleName),F=Tn(L.capStyleName),q=P.patternName?Pn(P.patternName):null,V=I.patternName?Pn(I.patternName):null,K=A.patternName?Pn(A.patternName):null,W=L.patternName?Pn(L.patternName):null,Q=q?Ln(e,q,P.patternColor??P.color??"var(--nice-bg, #fff)",P.patternColor):null,w=V?Ln(e,V,I.patternColor??I.color??"var(--nice-border, #d1d5db)",I.patternColor):null,N=K?Ln(e,K,A.patternColor??"var(--nice-warning, #FFD700)",A.patternColor):null,S=W?Ln(e,W,L.patternColor??"var(--nice-warning, #FFD700)",L.patternColor):null;Ws!==i&&(Ws=i,ma("RENDER",`Renderer using settings for "${i}" — filled: cap=${P.capStyleName}, glass=${P.glass} | empty: cap=${I.capStyleName}, glass=${I.glass} | goldFilled: cap=${A.capStyleName}, pattern=${A.patternName??"none"} | goldEmpty: cap=${L.capStyleName}, pattern=${L.patternName??"none"} | hasSettings=${!!R}`,{filledBar:P,emptyBar:I,goldFilledBar:A,goldEmptyBar:L,filledOverlay:!!Q,emptyOverlay:!!w,goldFilledOverlay:!!N,goldEmptyOverlay:!!S}));const O=P.textureUrl?An(e,P.textureUrl,P.textureScale):null,Y=I.textureUrl?An(e,I.textureUrl,I.textureScale):null,_=A.textureUrl?An(e,A.textureUrl,A.textureScale):null,U=L.textureUrl?An(e,L.textureUrl,L.textureScale):null,$=typeof document<"u"?ve.resolveCssColor(l||"var(--nice-color-accent, #ffcc00)"):l||"var(--nice-color-accent, #ffcc00)",H=tr($||"var(--nice-warning, #ffcc00)"),X=ke=>ve.resolveCssColor(ke),re=E.fontFamily||"Arial",oe=E.fontSize||18,se=X(E.fontColor||"var(--btn-text, #fff)"),z=E.outlineColor?X(E.outlineColor):null,ee=typeof E.outlineWidth=="number"?E.outlineWidth:0,ae=E.shadow||null;typeof document<"u"&&((!jt||jt.width!==t||jt.height!==n)&&(jt=document.createElement("canvas"),jt.width=t,jt.height=n,nt=jt.getContext("2d")),nt&&nt.clearRect(0,0,t,n),(!pt||pt.width!==t||pt.height!==n)&&(pt=document.createElement("canvas"),pt.width=t,pt.height=n,Pt=pt.getContext("2d")),Pt&&Pt.clearRect(0,0,t,n),(!vt||vt.width!==t||vt.height!==n)&&(vt=document.createElement("canvas"),vt.width=t,vt.height=n,Ve=vt.getContext("2d")),Ve&&Ve.clearRect(0,0,t,n));const ce=j?-j:0,le=v||t;e.fillStyle=$,e.font=`bold ${oe}px ${re}`;const pe=e.measureText(i).width+20;if(e.fillRect(ce+10,5,pe,25),e.save(),e.fillStyle=se,ae){const ke=ae.match(/(-?\d+)px\s+(-?\d+)px\s+(\d+)px\s+(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\)|[a-zA-Z]+)/);ke&&(e.shadowOffsetX=parseInt(ke[1],10),e.shadowOffsetY=parseInt(ke[2],10),e.shadowBlur=parseInt(ke[3],10),e.shadowColor=ke[4])}if(e.fillText(i,ce+20,22),z&&ee>0&&(e.lineWidth=ee,e.strokeStyle=z,e.strokeText(i,ce+20,22)),e.restore(),b){const ke=X(f||"var(--nice-text-secondary, #6b7280)");e.font=`bold 12px ${re}`;const Ce=e.measureText(b).width,We=8,De=ce+10+pe+6,Ae=20,Ee=7,de=Ce+We*2,me=4;e.beginPath(),e.moveTo(De+me,Ee),e.lineTo(De+de-me,Ee),e.quadraticCurveTo(De+de,Ee,De+de,Ee+me),e.lineTo(De+de,Ee+Ae-me),e.quadraticCurveTo(De+de,Ee+Ae,De+de-me,Ee+Ae),e.lineTo(De+me,Ee+Ae),e.quadraticCurveTo(De,Ee+Ae,De,Ee+Ae-me),e.lineTo(De,Ee+me),e.quadraticCurveTo(De,Ee,De+me,Ee),e.closePath(),e.fillStyle=ke,e.fill(),e.fillStyle=se,e.fillText(b,De+We,Ee+14),e.font=`bold ${oe}px ${re}`}const fe=120;if(e.fillStyle=$,e.fillRect(ce+le-fe-10,5,fe,25),e.fillStyle=se,e.fillText(`${o} pts`,ce+le-fe+15,22),C&&C.currentCombo>=5){const ke=C.currentCombo>=50?"3x":C.currentCombo>=30?"2.5x":C.currentCombo>=20?"2x":C.currentCombo>=10?"1.5x":"",Ce=`${C.currentCombo} combo${ke?" "+ke:""}`;e.font=`bold 12px ${re}`;const De=e.measureText(Ce).width+16,Ae=ce+le-fe-10-De-6;e.fillStyle=X(C.currentCombo>=20?"var(--nice-color-success, #FFD700)":"var(--nice-color-warning, #ff9800)"),e.globalAlpha=.9,hh(e,Ae,7,De,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=X(C.currentCombo>=20?"var(--nice-text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(Ce,Ae+8,22),e.font=`bold 14px ${re}`}if(T&&T.length>0){const ke=T[T.length-1];if(ke.label){const Ce=`${T.length}-${ke.label}`;Ce!==Bs&&(Bs=Ce,Gs=Date.now());const We=Date.now()-Gs;if(We<2500){const De=We<2e3?1:1-(We-2e3)/500,Ae={Perfect:X("var(--nice-color-success, #00e676)"),Great:X("var(--nice-color-success, #66bb6a)"),Good:X("var(--nice-color-accent, #ffeb3b)"),OK:X("var(--nice-color-warning, #ff9800)"),Bad:X("var(--nice-color-error, #ef5350)"),Awful:X("var(--nice-color-error, #b71c1c)")};e.save(),e.globalAlpha=De,e.font=`bold ${Math.round(oe*1.2)}px ${re}`;const Ee=ke.label,de=e.measureText(Ee).width,me=ce+le/2-de/2;e.fillStyle=Ae[Ee]||se,e.shadowColor=ve.resolveCssColor("var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",e.canvas),e.shadowBlur=6,e.fillText(Ee,me,58),z&&ee>0&&(e.lineWidth=ee,e.strokeStyle=z,e.strokeText(Ee,me,58)),e.restore()}}}const ge=s-2,he=s+5,we=40;let je=1/0,Pe=-1/0;if(a.forEach(ke=>{ke.forEach(Ce=>{Ce.pitch<je&&(je=Ce.pitch),Ce.pitch>Pe&&(Pe=Ce.pitch)})}),c&&Array.isArray(c)&&c.length>0){let ke=null;isFinite(je)&&isFinite(Pe)&&(ke=Math.round((je+Pe)/2));let Ce=1/0,We=-1/0;c.forEach(({t:De,hz:Ae})=>{if(!Ae||Ae<=0)return;let Ee=ke;for(const me of a)for(const Re of me)De>=Re.startTime&&De<=Re.startTime+Re.duration&&(Ee=Re.pitch);const de=vo(Ae,Ee);de<Ce&&(Ce=de),de>We&&(We=de)}),Ce!==1/0&&We!==-1/0&&(Ce<je&&(je=Math.floor(Ce-2)),We>Pe&&(Pe=Math.ceil(We+2)))}(!isFinite(je)||!isFinite(Pe))&&(je=40,Pe=80),je===Pe&&(je=Math.max(0,je-6),Pe=Pe+6);const $e=ke=>{const Ce=n-we-10;return we+Ce-(ke-je)/(Pe-je)*Ce},ue=Or(g||"normal"),Oe=(n-we-10)/Math.max(1,Pe-je),Me=Math.max(10,Math.round(Oe*(1+2*ue.semitoneTolerance)*.3)),Ie=Math.max(5,Math.round(Me*.45));((ke,Ce,We,De,Ae,Ee)=>{ke.lineWidth=1;for(let de=Math.ceil(Ae);de<=Math.floor(Ee);de++){const me=$e(de);ke.strokeStyle=X(de%2===0?"var(--guide-line-strong, rgba(255, 255, 255, 0.12))":"var(--guide-line-weak, rgba(255, 255, 255, 0.06))"),ke.beginPath(),ke.moveTo(0,Math.round(me)+.5),ke.lineTo(Ce,Math.round(me)+.5),ke.stroke()}})(e,t,n-we,we,je,Pe),Pt&&Pt.clearRect(0,0,t,n);const Be=(s-ge)/(he-ge)*t;let He=n*.5,Dt=!1,ct=!1;const ht=(ke,Ce,We,De,Ae,Ee,de=0)=>{const me=(Ne,_e,be,Te,Le,Ge)=>{const ze=Math.min(Ge,Te/2,Le/2);Ne.beginPath(),Ne.moveTo(_e+ze,be),Ne.lineTo(_e+Te-ze,be),Ne.quadraticCurveTo(_e+Te,be,_e+Te,be+ze),Ne.lineTo(_e+Te,be+Le-ze),Ne.quadraticCurveTo(_e+Te,be+Le,_e+Te-ze,be+Le),Ne.lineTo(_e+ze,be+Le),Ne.quadraticCurveTo(_e,be+Le,_e,be+Le-ze),Ne.lineTo(_e,be+ze),Ne.quadraticCurveTo(_e,be,_e+ze,be),Ne.closePath()},Re=Math.max(2,Me/2);De.forEach(Ne=>{if(Ne.startTime+Ne.duration<Ae||Ne.startTime>Ee)return;const _e=(Ne.startTime-Ae)/(Ee-Ae)*Ce,be=Ne.duration/(Ee-Ae)*Ce,Te=$e(Ne.pitch)-Me/2,Le=[];if(Array.isArray(p)){const Ge=Ne.startTime+Ne.duration;p.forEach(ze=>{if(ze.pitch!==Ne.pitch||ze.noteStart!=null&&ze.noteEnd!=null&&(Math.abs(ze.noteStart-Ne.startTime)>.01||Math.abs(ze.noteEnd-Ge)>.01))return;const tt=Math.max(ze.start,Ne.startTime),Ke=Math.min(ze.end,Ge);if(tt>=Ke)return;const Vt=(tt-Ae)/(Ee-Ae)*Ce,en=(Ke-Ae)/(Ee-Ae)*Ce;Le.push({x1:Vt,x2:en,frac:ze.frac})})}if(Ne.isGold){ke.save();const Ge=m&&m.shadowColor?m.shadowColor:Fs,ze=m&&typeof m.glowBlur=="number"?m.glowBlur:zs;ke.shadowColor=Ge,ke.shadowBlur=Math.max(4,ze-12),ke.fillStyle=X("var(--gold-overlay, rgba(255, 215, 0, 0.15))"),me(ke,_e-1,Te-1,be+2,Me+2,Re),ke.fill(),ke.restore();const tt=tr("var(--gold-base, #b4af9f)");En(ke,_e,Te,be,Me,F,L.color??tt,L.highlight,L.glow,L.glass,W,L.patternColor,L.patternOnly,U,S),ke.save(),me(ke,_e,Te,be,Me,Re),ke.clip(),ke.globalAlpha=.18,ke.fillStyle=X("var(--nice-color-success, #FFD700)"),ke.fillRect(_e,Te,be,Math.max(1,Me*.25)),ke.globalAlpha=1,ke.restore(),Le.length>0&&(ke.save(),me(ke,_e,Te,be,Me,Re),ke.clip(),Le.forEach(Ke=>{const Vt=Math.max(1,Ke.x2-Ke.x1);En(ke,Ke.x1,Te,Vt,Me,G,A.color??"var(--nice-warning, #FFD700)",A.highlight,A.glow,A.glass,K,A.patternColor,A.patternOnly,_,N)}),ke.restore()),Le.length===0&&(ke.lineWidth=1,ke.strokeStyle=X("var(--gold-outline, rgba(255, 215, 0, 0.35))"),me(ke,_e+.5,Te+.5,be-1,Math.max(1,Me-1),Re),ke.stroke())}else{const Ge=tr("var(--note-base, #d1d5db)");En(ke,_e,Te,be,Me,Z,I.color??Ge,I.highlight,I.glow,I.glass,V,I.patternColor,I.patternOnly,Y,w),Le.length>0&&(ke.save(),me(ke,_e,Te,be,Me,Re),ke.clip(),Le.forEach(ze=>{const tt=Math.max(1,ze.x2-ze.x1);En(ke,ze.x1,Te,tt,Me,D,P.color??H,P.highlight,P.glow,P.glass,q,P.patternColor,P.patternOnly,O,Q)}),ke.restore())}Pt&&(Pt.fillStyle=ve.resolveCssColor("var(--nice-bg, #fff)",Pt.canvas),Pt.fillRect(_e,Te,be,Me))})};if(a.forEach(ke=>{ht(e,t,n-we,ke,ge,he,we);for(const Ce of ke)if(s>=Ce.startTime&&s<=Ce.startTime+Ce.duration){He=$e(Ce.pitch),Dt=!0,ct=!!Ce.isGold;break}}),!Dt){let ke=null,Ce=null;for(const We of a)for(const De of We)De.startTime>s&&(!ke||De.startTime<ke.startTime)&&(ke=De),De.startTime<=s&&(!Ce||De.startTime>Ce.startTime)&&(Ce=De);ke?(He=$e(ke.pitch),ct=!!ke.isGold):Ce?(He=$e(Ce.pitch),ct=!!Ce.isGold):He=n*.5}const it=$||X("var(--nice-color-accent, #ffcc00)"),kt=1+Math.sin((s||0)*8)*.06,Je=Ie*kt,Tt=[];for(const ke of a)for(const Ce of ke){if(Ce.startTime+Ce.duration<ge||Ce.startTime>he)continue;const We=(Ce.startTime-ge)/(he-ge)*t,De=Ce.duration/(he-ge)*t,Ae=$e(Ce.pitch)-Me/2,Ee=Ce.startTime+Ce.duration<=s;Tt.push({x:We,y:Ae,w:De,h:Me,isGold:Ce.isGold,isSung:Ee})}if(!rh(M||"ball",{ctx:e,ballX:Be,ballY:He,ballRadius:Je,playerColor:it,ballIsGold:ct,currentTime:s,height:n,visibleNotes:Tt})){jt&&e.drawImage(jt,0,0),vt&&e.drawImage(vt,0,0),e.save(),e.globalCompositeOperation="source-over",e.globalAlpha=.28;const ke=Math.max(18,Je*5),Ce=e.createRadialGradient(Be,He,0,Be,He,ke);if(Ce.addColorStop(0,it),Ce.addColorStop(1,"transparent"),e.fillStyle=Ce,e.beginPath(),e.arc(Be,He,ke,0,Math.PI*2),e.fill(),e.restore(),y&&nt&&pt&&(nt.save(),nt.globalCompositeOperation="source-over",nt.globalAlpha=.95,nt.fillStyle=it,nt.beginPath(),nt.arc(Be,He,Je+4,0,Math.PI*2),nt.fill(),nt.restore(),nt.save(),nt.globalCompositeOperation="destination-in",nt.drawImage(pt,0,0),nt.restore(),e.drawImage(jt,0,0)),y&&Ve&&pt)try{const Ae=tr(it),{h:Ee,s:de,l:me}=dh(Ae),Ne=uh(Ee,Math.max(10,Math.round(de*(typeof h=="number"?h:.25))),me,.85);Ve.save(),Ve.globalCompositeOperation="multiply",Ve.globalAlpha=.65,Ve.fillStyle=Ne,Ve.beginPath(),Ve.arc(Be,He,Math.max(8,Je+6),0,Math.PI*2),Ve.fill(),Ve.restore(),Ve.save(),Ve.globalCompositeOperation="destination-out",Ve.drawImage(pt,0,0),Ve.restore(),e.drawImage(vt,0,0)}catch{Ve.save(),Ve.globalCompositeOperation="source-over",Ve.globalAlpha=.6,Ve.fillStyle=it,Ve.beginPath(),Ve.arc(Be,He,Math.max(8,Je+6),0,Math.PI*2),Ve.fill(),Ve.restore(),Ve.save(),Ve.globalCompositeOperation="destination-out",Ve.drawImage(pt,0,0),Ve.restore(),e.drawImage(vt,0,0)}const We=m&&m.shadowColor?m.shadowColor:Fs,De=m&&typeof m.glowBlur=="number"?m.glowBlur:zs;e.save(),ct?(e.shadowColor=We,e.shadowBlur=De,e.fillStyle=X("var(--gold-light, #FFF0A8)")):(e.shadowColor=it,e.shadowBlur=10,e.fillStyle=it),e.globalCompositeOperation="source-over",e.globalAlpha=1,e.beginPath(),e.arc(Be,He,Je,0,Math.PI*2),e.fill(),e.lineWidth=1.5,e.strokeStyle=X("var(--nice-shadow-md, rgba(0,0,0,0.35))"),e.stroke(),e.restore()}try{if(Array.isArray(x)&&x.length>0){const ke=Date.now(),Ce=m&&typeof m.lifeMs=="number"?m.lifeMs:ah,We=(Ae,Ee,de,me=5)=>{const Re=de,Ne=de*.45;e.beginPath();let _e=Math.PI/2*3,be=Ae,Te=Ee;const Le=Math.PI/me;e.moveTo(Ae,Ee-Re);for(let Ge=0;Ge<me;Ge++)be=Ae+Math.cos(_e)*Re,Te=Ee+Math.sin(_e)*Re,e.lineTo(be,Te),_e+=Le,be=Ae+Math.cos(_e)*Ne,Te=Ee+Math.sin(_e)*Ne,e.lineTo(be,Te),_e+=Le;e.lineTo(Ae,Ee-Re),e.closePath()},De=Ae=>{let Ee=Ae>>>0;return()=>(Ee=Ee*1664525+1013904223>>>0,(Ee&2147483647)/2147483647)};x.forEach(Ae=>{const Ee=ke-Ae.createdAt;if(Ee<0||Ee>Ce)return;const de=Ee/Ce,me=(Ae.noteStart-(s-2))/7*t,Re=$e(Ae.notePitch),Ne=De(Ae.seed||Math.floor(Ae.createdAt%1e5)),_e=m&&typeof m.count=="number"?m.count:sh,be=m&&typeof m.baseSpeed=="number"?m.baseSpeed:ih,Te=m&&typeof m.baseSize=="number"?m.baseSize:oh;for(let Le=0;Le<_e;Le++){const Ge=Ne(),ze=Ne(),tt=Le/_e*Math.PI*2+Ge*Math.PI*.6+de*1.5,Ke=6+be*(1-de)*(.5+ze*.8),Vt=me+Math.cos(tt)*Ke,en=Re+Math.sin(tt)*Ke*(.8+Ge*.6),wt=Math.max(1,Te*(1-de)*(.5+ze)),ys=40+Math.round(20*Ne()),vs=70+Math.round(20*Ne()),Kr=Math.max(0,1-de)*(.9-Ne()*.3),Ac=Math.max(6,wt*2.6),Yr=ch(ys,vs,60,Math.round(Ac),(Ae.seed||0)+Le);Yr&&Yr.complete?(e.save(),e.translate(Vt,en+4),e.rotate(tt+de*4+(Ne()-.5)*1.2),e.globalAlpha=Kr,e.drawImage(Yr,-wt/2,-wt/2,wt,wt),e.restore()):(e.save(),e.translate(Vt,en+4),e.rotate(tt+de*4),e.fillStyle=`hsla(${ys}, ${vs}%, 60%, ${Kr})`,e.fillRect(-wt/2,-wt/2,wt,wt),e.restore()),Ne()>.85&&(e.save(),e.globalAlpha=Math.max(.35,1-de),e.fillStyle=`hsla(${30+Math.round(10*Ne())}, ${60+Math.round(30*Ne())}%, ${70+Math.round(10*Ne())}%, ${Kr})`,e.strokeStyle=`rgba(0,0,0,${.12*(1-de)})`,e.lineWidth=.8,We(Vt,en+4,wt*(1.4+Ne())),e.fill(),e.stroke(),e.restore())}})}}catch{}return{ballX:Be,ballY:He,ballIsGold:ct}},$o=({song:e,currentTime:t,playerRef:n,config:a={},userPitch:s,segmentScores:i,goldBursts:o,combo:l,verseRatings:c})=>{const{t:u}=xe(),{isPlaying:h=!1,playerName:p=u("karaokeTimeline.defaultPlayer","Player"),score:g=1e4,playerBgColor:y="var(--karaoke-player-bg, #2196f3)",playerCount:m=2,gapDesaturation:x,goldSettings:b,difficultyLevel:f,algorithmLabel:j,algorithmColor:v,latencyMs:C=null,top:T,animationMode:M,karaokeSettings:k=null}=a,R=d.useRef(null),P=d.useRef(null),[I,A]=d.useState({width:600,height:150,top:250,visibleWidth:600}),[L,E]=d.useState(0),D=d.useRef(0),Z=d.useRef(null),G=d.useRef(null),F=d.useRef(null),q=d.useRef(t),V=d.useRef(performance.now()),K=d.useRef(e),W=d.useRef(I),Q=d.useRef(s),w=d.useRef(h),N=d.useRef(0),S=d.useRef(!1),O=d.useRef(null),Y=d.useRef(null),_=d.useCallback(()=>{const U=(e==null?void 0:e.id)??null;if(U!==Y.current||!O.current){Y.current=U;const $=e.notes.map(z=>z.noteLine);O.current=Zn($,e.bpm??void 0);const H=O.current.reduce((z,ee)=>z+ee.length,0),X=O.current.reduce((z,ee)=>z+ee.filter(ae=>ae.isGold).length,0),re=O.current.flat().map(z=>z.pitch),oe=re.length?Math.min(...re):0,se=re.length?Math.max(...re):0;ma("BARS",`Parsed notes for "${e.title}" — ${O.current.length} verses, ${H} notes (including ${X} golden), pitch range: ${oe}–${se}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:$.length,verseCount:O.current.length,totalNotes:H,goldCount:X,minPitch:oe,maxPitch:se})}return O.current},[e]);return d.useEffect(()=>{const U=(H,X,re)=>H+(X-H)*re,$=H=>{G.current===null&&(G.current=H);const X=Math.min(.1,(H-(G.current||H))/1e3);G.current=H;const re=N.current,oe=D.current,se=1-Math.exp(-12*X),z=Math.abs(oe-re)<.25?oe:U(re,oe,se);Math.abs(z-re)>1e-4&&(E(z),N.current=z,R.current&&(R.current.style.transform=`translateX(${z}px)`)),Z.current=requestAnimationFrame($)};return Z.current=requestAnimationFrame($),()=>{Z.current&&cancelAnimationFrame(Z.current),Z.current=null,G.current=null}},[]),d.useEffect(()=>{const U=()=>{if(!n.current)return;const $=n.current.getBoundingClientRect(),H=2/Math.max(1,m),X=Math.round($.width*H),re=Math.round($.width),oe=X*(150/600);A({width:X,height:oe,top:30,visibleWidth:re})};return U(),window.addEventListener("resize",U),()=>window.removeEventListener("resize",U)},[n,m]),d.useEffect(()=>{var re;if(h||!R.current)return;const U=R.current.getContext("2d");if(!U)return;const $=_(),H=t-(e.gap??0)/1e3,X=va(U,I.width,I.height,$,H,p,g,y,s,e.id,x??void 0,i,f??void 0,h,b??void 0,o,j,v,N.current,I.visibleWidth,l,c,M,k);if(X&&R.current){const oe=I.visibleWidth||(((re=P.current)==null?void 0:re.getBoundingClientRect().width)??I.width),se=I.width;let z=Math.round(oe/2-X.ballX);const ee=oe-se;z=Math.max(ee,Math.min(0,z)),D.current=z}},[t,e,_,I,s,h,p,g,y,x,i,f,b,o,j,v,l,c,M,k]),d.useEffect(()=>{q.current=t,V.current=performance.now()},[t]),d.useEffect(()=>{K.current=e},[e]),d.useEffect(()=>{W.current=I},[I]),d.useEffect(()=>{Q.current=s},[s]),d.useEffect(()=>{w.current=h},[h]),d.useEffect(()=>{const U=()=>{var ce;const $=R.current,H=K.current,X=W.current;if(!$||!H||!X)return;const re=$.getContext("2d");if(!re)return;const oe=_(),se=Math.min(.5,(performance.now()-V.current)/1e3),ee=(w.current?q.current+se:q.current)-(H.gap??0)/1e3,ae=va(re,X.width,X.height,oe,ee,p,g,y,Q.current,H.id,x??void 0,i,f??void 0,w.current,b??void 0,o,j,v,N.current,X.visibleWidth,l,c,M,k);if(ae){const le=X.visibleWidth||(((ce=P.current)==null?void 0:ce.getBoundingClientRect().width)??X.width),ne=X.width;let pe=Math.round(le/2-ae.ballX);const fe=le-ne;pe=Math.max(fe,Math.min(0,pe)),D.current=pe}};if(h){S.current||(S.current=!0,ma("BARS",`Drawing bars in RAF loop — canvas: ${W.current.width}×${W.current.height}px, player: ${p}`,{canvasSize:W.current}));const $=()=>{U(),F.current=requestAnimationFrame($)};return F.current=requestAnimationFrame($),()=>{F.current&&cancelAnimationFrame(F.current),F.current=null}}S.current=!1},[h,p,g,y,x,i,f,b,o,j,v,l,c,M,k,_]),r.jsxs("div",{ref:P,style:{position:"absolute",left:"50%",top:`${T??I.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:I.visibleWidth,height:I.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 C<"u"&&C!==null?(()=>{const U=C,$=U<=120?"var(--latency-good, #10b981)":U<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",H=`${U}ms`;return r.jsxs("div",{className:U>250?"av-latency-pulse":"",style:{background:$,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(B.NtdStopwatch,{size:12}),r.jsx("span",{children:H})]})})():r.jsx("div",{style:{background:"var(--latency-none-bg, rgba(75,85,99,0.9))",padding:"6px 8px",borderRadius:12,boxShadow:"0 4px 10px var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",minWidth:44,textAlign:"center"},children:"—"})}),r.jsx("canvas",{ref:R,width:I.width,height:I.height,role:"img","aria-label":u("karaokeTimeline.pitchTimelineFor","Pitch timeline for {player}. Score: {score}").replace("{player}",p).replace("{score}",String(g??0)),style:{position:"absolute",left:0,top:0,transform:`translateX(${L}px)`,willChange:"transform"}})]})},Ao="/textures/seamless/256x256";function Et(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:`${Ao}/${e}/Photoreal_${e}_${i}-512x512.png`}})}}function zt(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:`${Ao}/${e}/${e}_${i}-256x256.png`}})}}const Za=[Et("Fire",8,"fire"),Et("Metal",8,"metal"),Et("Ice",8,"ice"),Et("Stone",8,"stone"),Et("Wood",8,"wood"),Et("Tile",8,"tile"),Et("Concrete",8,"concrete"),Et("Trees",8,"trees"),Et("Grass",8,"grass"),zt("Wall",24,"wall"),zt("Rust",24,"rust"),zt("Woven",24,"woven"),zt("Ground",24,"ground"),zt("Pebbles",24,"pebbles"),zt("Plant",24,"plant"),zt("Roof",24,"roof"),zt("Misc",24,"misc")],Io=Za.flatMap(e=>e.entries);function gh(e){return Io.find(t=>t.url===e)}const yh={fire:B.NtdFire,metal:B.NtdSettings,ice:B.NtdSnowflake,stone:B.NtdMountain,wood:B.NtdTree,tile:B.NtdGrid,concrete:B.NtdLayers,trees:B.NtdTree,grass:B.NtdLeaf,wall:B.NtdHome,rust:B.NtdCircle,woven:B.NtdGrid,ground:B.NtdMountain,pebbles:B.NtdDroplet,plant:B.NtdLeaf,roof:B.NtdHome,misc:B.NtdPalette},vh=({icon:e})=>{const t=yh[e];return t?r.jsx(t,{size:14}):r.jsx(r.Fragment,{children:e})},$t=({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}),bh=({fill:e=Ut,onChange:t=()=>{},previewColor:n="var(--nice-primary, #2196f3)",accentColor:a="var(--nice-primary, #0d6efd)",width:s,height:i})=>{const{t:o}=xe(),[l,c]=d.useState(null),u=(f,j)=>{t({...e,[f]:j})},h=d.useMemo(()=>{const f=e.color||n||"var(--nice-primary, #2196f3)";return(j,v,C)=>{const T=qn.find(k=>k.name===j)||qn[0],M=v?Ar.find(k=>k.name===v)??null:null;return To({width:80,height:22,capStyle:T,color:f,highlight:e.highlight,glow:e.glow,glass:e.glass,pattern:M,patternColor:e.patternColor,patternOnly:e.patternOnly,textureUrl:C??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=d.useRef(null),m=d.useRef(null),x=d.useCallback((f,j)=>{f.current&&f.current.scrollBy({left:j*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-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($t,{inline:!0,children:o("playerForm.barColor","Color")}),r.jsx(ie.NiceCheckbox,{label:o("playerForm.auto","Auto"),checked:!e.color,onChange:f=>u("color",f?null:n||"var(--nice-primary, #2196f3)")}),e.color&&r.jsx("input",{type:"color",value:e.color,onChange:f=>u("color",f.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),r.jsx($t,{children:o("playerForm.capShape","Cap shape")}),r.jsxs("div",{style:{position:"relative",marginBottom:10},children:[r.jsx("button",{type:"button",style:{...b,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>x(y,-1),"aria-label":o("playerForm.scrollLeft","Scroll left"),children:r.jsx(B.NtdChevronLeft,{size:16})}),r.jsx("button",{type:"button",style:{...b,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>x(y,1),"aria-label":o("playerForm.scrollRight","Scroll right"),children:r.jsx(B.NtdChevronRight,{size:16})}),r.jsx("div",{ref:y,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:qn.map(f=>{const j=e.capStyleName===f.name;return r.jsx("div",{role:"button",tabIndex:0,"aria-pressed":j,onKeyDown:ie.clickOnActivationKey,title:f.name,onClick:()=>u("capStyleName",f.name),style:{cursor:"pointer",flexShrink:0,border:j?p:"1px solid var(--nice-border-color, #555)",borderRadius:6,padding:3,background:j?g:"var(--nice-bg-secondary, #222)"},dangerouslySetInnerHTML:{__html:h(f.name,null)}},f.name)})})]}),r.jsx($t,{children:o("playerForm.pattern","Pattern")}),r.jsxs("div",{style:{position:"relative",marginBottom:10},children:[r.jsx("button",{type:"button",style:{...b,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>x(m,-1),"aria-label":o("playerForm.scrollLeft","Scroll left"),children:r.jsx(B.NtdChevronLeft,{size:16})}),r.jsx("button",{type:"button",style:{...b,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>x(m,1),"aria-label":o("playerForm.scrollRight","Scroll right"),children:r.jsx(B.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",{role:"button",tabIndex:0,"aria-pressed":!e.patternName,onKeyDown:ie.clickOnActivationKey,title:o("playerForm.none","None"),onClick:()=>u("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:"—"}),Ar.map(f=>{const j=e.patternName===f.name;return r.jsx("div",{role:"button",tabIndex:0,"aria-pressed":j,onKeyDown:ie.clickOnActivationKey,title:f.name,onClick:()=>u("patternName",f.name),style:{cursor:"pointer",flexShrink:0,border:j?p:"1px solid var(--nice-border-color, #555)",borderRadius:6,padding:3,background:j?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=>u("patternOnly",f)})}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[r.jsx($t,{inline:!0,children:o("playerForm.patternColor","Pattern color")}),r.jsx(ie.NiceCheckbox,{label:o("playerForm.auto","Auto"),checked:!e.patternColor,onChange:f=>u("patternColor",f?null:n||"var(--nice-bg, #fff)")}),e.patternColor&&r.jsx("input",{type:"color",value:e.patternColor,onChange:f=>u("patternColor",f.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),!e.patternOnly&&r.jsxs(r.Fragment,{children:[r.jsxs($t,{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=>u("highlight",f)})}),r.jsxs($t,{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=>u("glow",f)})})]}),r.jsxs($t,{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=>u("glass",f)})}),r.jsx("div",{style:{marginTop:4},children:r.jsx($t,{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:()=>{u("textureUrl",null),c(null)},children:o("playerForm.texNone","None")}),Za.map(f=>r.jsx(ie.NiceButton,{size:"sm",variant:(l==null?void 0:l.name)===f.name?"primary":"outline",onClick:()=>c(j=>(j==null?void 0:j.name)===f.name?null:f),title:f.name,ariaLabel:f.name,children:r.jsx(vh,{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 j=e.textureUrl===f.url;return r.jsx("div",{role:"button",tabIndex:0,"aria-pressed":j,onKeyDown:ie.clickOnActivationKey,title:f.label,onClick:()=>u("textureUrl",j?null:f.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:j?`3px solid ${a}`:"1px solid var(--nice-text-muted, #bbb)",backgroundImage:`url(${f.url})`,backgroundSize:"cover",boxShadow:j?`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($t,{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=>u("textureScale",f/100)})})]})]})},rt=st.scoped("AudioPitchAnalyzer");function xh({onSegments:e,defaultCompareAll:t=!1,externalFile:n=null,postPitch:a,postLibrosaPitchTrack:s}){const{t:i}=xe(),[o,l]=d.useState("pitchy"),[c,u]=d.useState(null),[h,p]=d.useState(t),[g,y]=d.useState({}),[m,x]=d.useState({}),[b,f]=d.useState([]),[j,v]=d.useState([]),[C,T]=d.useState(!1),[M,k]=d.useState(null),[R]=d.useState(null),[P]=d.useState(null),[I,A]=d.useState(null),L=d.useRef(null);function E(W){try{if(W instanceof Error){let w=`${W.message}
|
|
40
40
|
${W.stack??""}`;const N=W;if(N!=null&&N.attemptedUrls)try{w+=`
|
|
41
41
|
Attempted URLs: ${Array.isArray(N.attemptedUrls)?N.attemptedUrls.join(", "):String(N.attemptedUrls)}`}catch{w+=`
|
|
42
42
|
Attempted URLs: ${String(N.attemptedUrls)}`}return w}const Q=W;return Q!=null&&Q.attemptedUrls?`Error: ${String(Q.message??Q)}
|
|
43
|
-
Attempted URLs: ${Array.isArray(Q.attemptedUrls)?Q.attemptedUrls.join(", "):String(Q.attemptedUrls)}`:String(W)}catch{return i("audioPitch.unknownError","Unknown error")}}function D(W){if(!W||W<=0)return null;const Q=12*Math.log2(W/440)+69;return Math.round(Q-12)}async function Z(W){var w;const Q=(w=W.target.files)==null?void 0:w[0];Q&&await G(Q,h)}async function G(W,Q){k(null),v([]),T(!0);try{const w=await W.arrayBuffer(),N=window.AudioContext??window.webkitAudioContext,O=await new N().decodeAudioData(w),Y=O.getChannelData(0);u(Y);const _=O.sampleRate,U=Math.floor(_*.1),$=U,H=()=>{const ee=[],ae=da.PitchDetector.forFloat32Array(U);for(let ce=0;ce<Y.length-U;ce+=$){const le=Y.slice(ce,ce+U),[ne,pe]=ae.findPitch(le,_),fe=D(ne);fe&&ne>50&&ne<2e3&&pe>.7&&ee.push({start:ce/_,duration:U/_,pitch:fe,freq:ne})}return ee},X=()=>{const ee=[];for(let ae=0;ae<Y.length-U;ae+=$){const ce=Y.slice(ae,ae+U),le=q(ce,_),ne=D(le);ne&&le>50&&le<2e3&&ee.push({start:ae/_,duration:U/_,pitch:ne,freq:le})}return ee};if(Q){T(!0),k(null);const ee={};try{const ae={};try{ee.pitchy=H(),ae.pitchy=null}catch(ce){ee.pitchy=[],ae.pitchy=E(ce),rt.warn("pitchy failed",ce)}try{ee["ultrastar-wp"]=X(),ae["ultrastar-wp"]=null}catch(ce){ee["ultrastar-wp"]=[],ae["ultrastar-wp"]=E(ce),rt.warn("ultrastar-wp failed",ce)}ee.aubio=[],ae.aubio="disabled";try{if(!a)throw new Error("CREPE backend not configured");const le=(await a(W)).track??[];ee.crepe=le.map((ne,pe)=>{var fe;return{start:ne.t,duration:(fe=le[pe+1])!=null&&fe.t?le[pe+1].t-ne.t:.1,pitch:D(ne.hz)??0,freq:ne.hz}}),ae.crepe=null}catch(ce){ee.crepe=[],ae.crepe=E(ce),rt.warn("crepe failed",ce)}try{if(!s)throw new Error("Librosa backend not configured");const le=(await s(new File([W],W.name,{type:W.type}))).track??[];ee.librosa=le.map((ne,pe)=>{var fe;return{start:ne.t,duration:(fe=le[pe+1])!=null&&fe.t?le[pe+1].t-ne.t:.1,pitch:D(ne.hz)??0,freq:ne.hz}}),ae.librosa=null}catch(ce){ee.librosa=[],ae.librosa=E(ce),rt.warn("librosa failed",ce)}x(ae),y(ee),v(ee[o]??[])}catch(ae){rt.error("compareAll overall failed",ae);const ce=ae instanceof Error?ae.message:String(ae);k(i("audioPitch.errorComparing","Error comparing algorithms: ")+ce)}finally{T(!1)}return}const re=[],oe=[];let se=0;if(o==="pitchy"){const ee=da.PitchDetector.forFloat32Array(U);for(let ae=0;ae<Y.length-U;ae+=$){const ce=Y.slice(ae,ae+U);let le=0;for(let ge=0;ge<ce.length;ge++)le+=ce[ge]*ce[ge];le=Math.sqrt(le/ce.length),oe.push(le);const[ne,pe]=ee.findPitch(ce,_),fe=D(ne);fe&&ne>50&&ne<2e3&&pe>.7&&(re.push({start:ae/_,duration:U/_,pitch:fe,freq:ne}),se++)}}else if(o==="crepe")try{if(!a)throw new Error("CREPE backend not configured");const ee=await a(W);if(!ee.track||ee.track.length===0)k(i("audioPitch.crepeNoNotes","CREPE detected no notes")),rt.warn("Crepe: No notes detected in audio file.");else{const ae=ee.track.map((ce,le)=>{const ne=D(ce.hz);return ne&&ce.hz>50&&ce.hz<2e3?{start:ce.t,duration:le<ee.track.length-1?ee.track[le+1].t-ce.t:.1,pitch:ne,freq:ce.hz}:null}).filter(ce=>ce!==null);if(v(ae),e)try{e(ae)}catch(ce){rt.error("Error in onSegments:",ce)}f([]),u(null);return}}catch(ee){k(i("audioPitch.crepeBackendError","CREPE backend error")),A(E(ee)),rt.error("Crepe: Error calling backend:",ee)}else if(o==="librosa")try{await F(W),f([]),u(null);return}catch(ee){k(i("audioPitch.librosaBackendError","Librosa backend error")),A(E(ee)),rt.error("Librosa: Error calling backend:",ee)}else if(o==="ultrastar-wp")for(let ee=0;ee<Y.length-U;ee+=$){const ae=Y.slice(ee,ee+U);let ce=0;for(let pe=0;pe<ae.length;pe++)ce+=ae[pe]*ae[pe];ce=Math.sqrt(ce/ae.length),oe.push(ce);const le=q(ae,_),ne=D(le);ne&&le>50&&le<2e3&&(re.push({start:ee/_,duration:U/_,pitch:ne,freq:le}),se++)}f(oe);const z=V(re);if(v(z),e)try{e(z)}catch(ee){rt.error("Error in onSegments:",ee)}z.length===0&&o!=="crepe"&&(k(i("audioPitch.noNotesDetected","No notes detected")),rt.warn("No notes detected in audio file."))}catch(w){k(i("audioPitch.errorAnalyzing","Error analyzing the file: ")+(w instanceof Error?w.message:String(w))),A(E(w)),rt.error("Error analyzing audio file:",w)}finally{T(!1)}}d.useEffect(()=>{n&&G(n,!0)},[n]);async function F(W){try{if(!s)throw new Error("Librosa backend not configured");const Q=new File([W],"capture.wav",{type:"audio/wav"}),N=((await s(Q)).track??[]).map(S=>({t:S.t,hz:S.hz}));if(e){const S=N.map((O,Y)=>{var $;const _=(($=N[Y+1])==null?void 0:$.t)??O.t+.1,U=D(O.hz)??0;return{start:O.t,duration:Math.max(.05,_-O.t),pitch:U,freq:O.hz}});e(S),v(S)}}catch(Q){rt.warn("Librosa analysis failed, falling back to local detectors",Q);const N=(typeof Q=="object"&&Q!==null?Q:{}).attemptedUrls;N&&rt.error("Librosa attempted URLs:",N);const S=N?Array.isArray(N)?N.join(", "):String(N):null,O=Q instanceof Error?Q.message:String(Q);k(i("audioPitch.librosaBackendError","Librosa backend error")+": "+O+(S?" (attempted: "+S+")":"")),A(E(Q))}}function q(W,Q){const S=Math.floor(Q/50),O=Math.max(2,Math.floor(Q/2e3));let Y=0;for(let H=0;H<W.length;H++)Y+=W[H]*W[H];if(Y<=1e-8)return 0;let _=-1,U=0;const $=1e-10;for(let H=O;H<=Math.min(S,W.length-2);H++){let X=0;const re=W.length-H;for(let se=0;se<re;se++)X+=W[se]*W[se+H];const oe=X/(re+$)/(Y/W.length+$);oe>U&&(U=oe,_=H)}return _>0&&U>.01?Q/_:0}function V(W){if(W.length===0)return[];const Q=[];let w=W[0];for(let N=1;N<W.length;N++){const S=W[N];S.pitch===w.pitch&&Math.abs(S.freq-w.freq)<1?w.duration+=S.duration:(Q.push(w),w=S)}return Q.push(w),Q}function K(){try{const W=Object.keys(g).length>0?Object.keys(g):["pitchy","ultrastar-wp","aubio","crepe","librosa"],Q=(()=>{let se=0;for(const z of W){const ee=g[z]??[];for(const ae of ee)se=Math.max(se,ae.start+(ae.duration||0))}return se||0})(),w=(se,z)=>!se||!z?1/0:1200*Math.log2(se/z),N=(se,z)=>{if(!se||!z)return!1;const ee=Math.round(Math.log2(z/se)),ae=se*Math.pow(2,ee),ce=Math.abs(w(ae,z));return Math.abs(ee)>=1&&ce<50},S=se=>{const z={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!se||se.length===0)return z;z.count=se.length,z.totalDur=se.reduce((le,ne)=>le+(ne.duration||0),0);const ee=se.map(le=>le.freq).filter(Boolean);if(ee.length===0)return z;const ae=ee.reduce((le,ne)=>le+ne,0)/ee.length,ce=ee.reduce((le,ne)=>le+(ne-ae)*(ne-ae),0)/ee.length;return z.meanFreq=ae,z.stdFreq=Math.sqrt(ce||0),z.meanDur=z.totalDur/z.count,z.voicedFraction=Q>0?z.totalDur/Q:null,z},O=(se,z)=>{let ee=0,ae=0;const ce=[];for(const ne of se){const pe=ne.start,fe=ne.start+(ne.duration||.05);let ge=null,he=0;for(const we of z){const je=we.start,Pe=we.start+(we.duration||.05),$e=Math.max(0,Math.min(fe,Pe)-Math.max(pe,je));$e>he&&(he=$e,ge=we)}if(ge&&he>0){const we=Math.abs(w(ne.freq,ge.freq));ce.push(we),we<50&&ee++,N(ne.freq,ge.freq)&&ae++}}const le=ce.length?ce.reduce((ne,pe)=>ne+pe,0)/ce.length:null;return{matches:ee,compared:se.length,meanCents:le,octaveErrors:ae}},Y=[];Y.push("# AudioPitchAnalyzer — Comparative Report"),Y.push(`Generated: ${new Date().toISOString()}`),Y.push(""),Y.push("## Summary"),Y.push(`- Selected algorithm in UI: **${o}**`),Y.push(`- Total analyzed duration (approx): **${Q.toFixed(3)} s**`),Y.push(""),Y.push("## Per-algorithm statistics"),Y.push("| Algorithm | Segments | Total voiced (s) | Voiced fraction | Mean freq (Hz) | Std freq (Hz) | Mean dur (s) |"),Y.push("|---|---:|---:|---:|---:|---:|---:|");const _={};for(const se of W){const z=g[se]??[],ee=S(z);_[se]=ee,Y.push(`| ${se} | ${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"} |`)}Y.push(""),Y.push("## Pairwise agreement (reference -> test)");const U=W.includes("crepe")?"crepe":W.includes("librosa")?"librosa":W.includes("pitchy")?"pitchy":W[0];Y.push(`Reference algorithm: **${U}**`),Y.push(""),Y.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),Y.push("|---|---:|---:|---:|---:|---:|");for(const se of W){if(se===U)continue;const z=O(g[U]??[],g[se]??[]),ee=z.compared?(z.matches/z.compared*100).toFixed(1)+"%":"N/A";Y.push(`| ${U} -> ${se} | ${z.matches} | ${z.compared} | ${ee} | ${z.meanCents!==null?z.meanCents.toFixed(1):"N/A"} | ${z.octaveErrors} |`)}Y.push(""),Y.push("## Observations and analysis"),Y.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."),Y.push("- Pairwise match rate shows how often algorithms agree on the same regions (within ~50 cents). Octave error counts highlight typical autocorrelation octave mistakes."),Y.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."),Y.push("");for(const se of W){Y.push(`### ${se}`);const z=_[se];Y.push(`- Segments: ${z.count||0}`),Y.push(`- Total voiced (s): ${(z.totalDur||0).toFixed(3)}`),Y.push(`- Voiced fraction: ${z.voicedFraction!==null?(z.voicedFraction*100).toFixed(1)+"%":"N/A"}`),Y.push(`- Mean frequency: ${z.meanFreq?z.meanFreq.toFixed(2)+" Hz":"N/A"}`),Y.push(`- Std frequency: ${z.stdFreq?z.stdFreq.toFixed(2)+" Hz":"N/A"}`),Y.push("")}Y.push("## Conclusions & recommendation");const $=[];for(const se of W){if(se===U){$.push({alg:se,score:100});continue}const z=O(g[U]??[],g[se]??[]),ee=z.compared?z.matches/z.compared:0,ae=z.compared?z.octaveErrors/z.compared:0,ce=ee-ae*.5;$.push({alg:se,score:ce})}$.sort((se,z)=>z.score-se.score),Y.push(`- Based on this recording, recommended authoritative detector: **${$[0].alg}** (best agreement with reference).`),Y.push("- For live, low-latency feedback use Pitchy (YIN) with smoothing/hysteresis; use Crepe/Librosa for authoritative scoring or post-processing."),Y.push("- If octave errors are frequent, consider octave-correction heuristics (prefer lower octave when ambiguity) or combine detectors via voting."),Y.push(""),Y.push("## Raw data (per-algorithm segments)");for(const se of W){const z=g[se]??[];Y.push(`### ${se} — ${z.length} segments`);for(const ae of z)Y.push(`- ${ae.start.toFixed(3)} .. ${(ae.start+(ae.duration||0)).toFixed(3)} : ${ae.freq.toFixed(2)} Hz (pitch ${ae.pitch})`);const ee=m[se];ee&&Y.push(`- Error: ${ee}`),Y.push("")}const H=Y.join(`
|
|
43
|
+
Attempted URLs: ${Array.isArray(Q.attemptedUrls)?Q.attemptedUrls.join(", "):String(Q.attemptedUrls)}`:String(W)}catch{return i("audioPitch.unknownError","Unknown error")}}function D(W){if(!W||W<=0)return null;const Q=12*Math.log2(W/440)+69;return Math.round(Q-12)}async function Z(W){var w;const Q=(w=W.target.files)==null?void 0:w[0];Q&&await G(Q,h)}async function G(W,Q){k(null),v([]),T(!0);try{const w=await W.arrayBuffer(),N=window.AudioContext??window.webkitAudioContext,O=await new N().decodeAudioData(w),Y=O.getChannelData(0);u(Y);const _=O.sampleRate,U=Math.floor(_*.1),$=U,H=()=>{const ee=[],ae=ua.PitchDetector.forFloat32Array(U);for(let ce=0;ce<Y.length-U;ce+=$){const le=Y.slice(ce,ce+U),[ne,pe]=ae.findPitch(le,_),fe=D(ne);fe&&ne>50&&ne<2e3&&pe>.7&&ee.push({start:ce/_,duration:U/_,pitch:fe,freq:ne})}return ee},X=()=>{const ee=[];for(let ae=0;ae<Y.length-U;ae+=$){const ce=Y.slice(ae,ae+U),le=q(ce,_),ne=D(le);ne&&le>50&&le<2e3&&ee.push({start:ae/_,duration:U/_,pitch:ne,freq:le})}return ee};if(Q){T(!0),k(null);const ee={};try{const ae={};try{ee.pitchy=H(),ae.pitchy=null}catch(ce){ee.pitchy=[],ae.pitchy=E(ce),rt.warn("pitchy failed",ce)}try{ee["ultrastar-wp"]=X(),ae["ultrastar-wp"]=null}catch(ce){ee["ultrastar-wp"]=[],ae["ultrastar-wp"]=E(ce),rt.warn("ultrastar-wp failed",ce)}ee.aubio=[],ae.aubio="disabled";try{if(!a)throw new Error("CREPE backend not configured");const le=(await a(W)).track??[];ee.crepe=le.map((ne,pe)=>{var fe;return{start:ne.t,duration:(fe=le[pe+1])!=null&&fe.t?le[pe+1].t-ne.t:.1,pitch:D(ne.hz)??0,freq:ne.hz}}),ae.crepe=null}catch(ce){ee.crepe=[],ae.crepe=E(ce),rt.warn("crepe failed",ce)}try{if(!s)throw new Error("Librosa backend not configured");const le=(await s(new File([W],W.name,{type:W.type}))).track??[];ee.librosa=le.map((ne,pe)=>{var fe;return{start:ne.t,duration:(fe=le[pe+1])!=null&&fe.t?le[pe+1].t-ne.t:.1,pitch:D(ne.hz)??0,freq:ne.hz}}),ae.librosa=null}catch(ce){ee.librosa=[],ae.librosa=E(ce),rt.warn("librosa failed",ce)}x(ae),y(ee),v(ee[o]??[])}catch(ae){rt.error("compareAll overall failed",ae);const ce=ae instanceof Error?ae.message:String(ae);k(i("audioPitch.errorComparing","Error comparing algorithms: ")+ce)}finally{T(!1)}return}const re=[],oe=[];let se=0;if(o==="pitchy"){const ee=ua.PitchDetector.forFloat32Array(U);for(let ae=0;ae<Y.length-U;ae+=$){const ce=Y.slice(ae,ae+U);let le=0;for(let ge=0;ge<ce.length;ge++)le+=ce[ge]*ce[ge];le=Math.sqrt(le/ce.length),oe.push(le);const[ne,pe]=ee.findPitch(ce,_),fe=D(ne);fe&&ne>50&&ne<2e3&&pe>.7&&(re.push({start:ae/_,duration:U/_,pitch:fe,freq:ne}),se++)}}else if(o==="crepe")try{if(!a)throw new Error("CREPE backend not configured");const ee=await a(W);if(!ee.track||ee.track.length===0)k(i("audioPitch.crepeNoNotes","CREPE detected no notes")),rt.warn("Crepe: No notes detected in audio file.");else{const ae=ee.track.map((ce,le)=>{const ne=D(ce.hz);return ne&&ce.hz>50&&ce.hz<2e3?{start:ce.t,duration:le<ee.track.length-1?ee.track[le+1].t-ce.t:.1,pitch:ne,freq:ce.hz}:null}).filter(ce=>ce!==null);if(v(ae),e)try{e(ae)}catch(ce){rt.error("Error in onSegments:",ce)}f([]),u(null);return}}catch(ee){k(i("audioPitch.crepeBackendError","CREPE backend error")),A(E(ee)),rt.error("Crepe: Error calling backend:",ee)}else if(o==="librosa")try{await F(W),f([]),u(null);return}catch(ee){k(i("audioPitch.librosaBackendError","Librosa backend error")),A(E(ee)),rt.error("Librosa: Error calling backend:",ee)}else if(o==="ultrastar-wp")for(let ee=0;ee<Y.length-U;ee+=$){const ae=Y.slice(ee,ee+U);let ce=0;for(let pe=0;pe<ae.length;pe++)ce+=ae[pe]*ae[pe];ce=Math.sqrt(ce/ae.length),oe.push(ce);const le=q(ae,_),ne=D(le);ne&&le>50&&le<2e3&&(re.push({start:ee/_,duration:U/_,pitch:ne,freq:le}),se++)}f(oe);const z=V(re);if(v(z),e)try{e(z)}catch(ee){rt.error("Error in onSegments:",ee)}z.length===0&&o!=="crepe"&&(k(i("audioPitch.noNotesDetected","No notes detected")),rt.warn("No notes detected in audio file."))}catch(w){k(i("audioPitch.errorAnalyzing","Error analyzing the file: ")+(w instanceof Error?w.message:String(w))),A(E(w)),rt.error("Error analyzing audio file:",w)}finally{T(!1)}}d.useEffect(()=>{n&&G(n,!0)},[n]);async function F(W){try{if(!s)throw new Error("Librosa backend not configured");const Q=new File([W],"capture.wav",{type:"audio/wav"}),N=((await s(Q)).track??[]).map(S=>({t:S.t,hz:S.hz}));if(e){const S=N.map((O,Y)=>{var $;const _=(($=N[Y+1])==null?void 0:$.t)??O.t+.1,U=D(O.hz)??0;return{start:O.t,duration:Math.max(.05,_-O.t),pitch:U,freq:O.hz}});e(S),v(S)}}catch(Q){rt.warn("Librosa analysis failed, falling back to local detectors",Q);const N=(typeof Q=="object"&&Q!==null?Q:{}).attemptedUrls;N&&rt.error("Librosa attempted URLs:",N);const S=N?Array.isArray(N)?N.join(", "):String(N):null,O=Q instanceof Error?Q.message:String(Q);k(i("audioPitch.librosaBackendError","Librosa backend error")+": "+O+(S?" (attempted: "+S+")":"")),A(E(Q))}}function q(W,Q){const S=Math.floor(Q/50),O=Math.max(2,Math.floor(Q/2e3));let Y=0;for(let H=0;H<W.length;H++)Y+=W[H]*W[H];if(Y<=1e-8)return 0;let _=-1,U=0;const $=1e-10;for(let H=O;H<=Math.min(S,W.length-2);H++){let X=0;const re=W.length-H;for(let se=0;se<re;se++)X+=W[se]*W[se+H];const oe=X/(re+$)/(Y/W.length+$);oe>U&&(U=oe,_=H)}return _>0&&U>.01?Q/_:0}function V(W){if(W.length===0)return[];const Q=[];let w=W[0];for(let N=1;N<W.length;N++){const S=W[N];S.pitch===w.pitch&&Math.abs(S.freq-w.freq)<1?w.duration+=S.duration:(Q.push(w),w=S)}return Q.push(w),Q}function K(){try{const W=Object.keys(g).length>0?Object.keys(g):["pitchy","ultrastar-wp","aubio","crepe","librosa"],Q=(()=>{let se=0;for(const z of W){const ee=g[z]??[];for(const ae of ee)se=Math.max(se,ae.start+(ae.duration||0))}return se||0})(),w=(se,z)=>!se||!z?1/0:1200*Math.log2(se/z),N=(se,z)=>{if(!se||!z)return!1;const ee=Math.round(Math.log2(z/se)),ae=se*Math.pow(2,ee),ce=Math.abs(w(ae,z));return Math.abs(ee)>=1&&ce<50},S=se=>{const z={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!se||se.length===0)return z;z.count=se.length,z.totalDur=se.reduce((le,ne)=>le+(ne.duration||0),0);const ee=se.map(le=>le.freq).filter(Boolean);if(ee.length===0)return z;const ae=ee.reduce((le,ne)=>le+ne,0)/ee.length,ce=ee.reduce((le,ne)=>le+(ne-ae)*(ne-ae),0)/ee.length;return z.meanFreq=ae,z.stdFreq=Math.sqrt(ce||0),z.meanDur=z.totalDur/z.count,z.voicedFraction=Q>0?z.totalDur/Q:null,z},O=(se,z)=>{let ee=0,ae=0;const ce=[];for(const ne of se){const pe=ne.start,fe=ne.start+(ne.duration||.05);let ge=null,he=0;for(const we of z){const je=we.start,Pe=we.start+(we.duration||.05),$e=Math.max(0,Math.min(fe,Pe)-Math.max(pe,je));$e>he&&(he=$e,ge=we)}if(ge&&he>0){const we=Math.abs(w(ne.freq,ge.freq));ce.push(we),we<50&&ee++,N(ne.freq,ge.freq)&&ae++}}const le=ce.length?ce.reduce((ne,pe)=>ne+pe,0)/ce.length:null;return{matches:ee,compared:se.length,meanCents:le,octaveErrors:ae}},Y=[];Y.push("# AudioPitchAnalyzer — Comparative Report"),Y.push(`Generated: ${new Date().toISOString()}`),Y.push(""),Y.push("## Summary"),Y.push(`- Selected algorithm in UI: **${o}**`),Y.push(`- Total analyzed duration (approx): **${Q.toFixed(3)} s**`),Y.push(""),Y.push("## Per-algorithm statistics"),Y.push("| Algorithm | Segments | Total voiced (s) | Voiced fraction | Mean freq (Hz) | Std freq (Hz) | Mean dur (s) |"),Y.push("|---|---:|---:|---:|---:|---:|---:|");const _={};for(const se of W){const z=g[se]??[],ee=S(z);_[se]=ee,Y.push(`| ${se} | ${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"} |`)}Y.push(""),Y.push("## Pairwise agreement (reference -> test)");const U=W.includes("crepe")?"crepe":W.includes("librosa")?"librosa":W.includes("pitchy")?"pitchy":W[0];Y.push(`Reference algorithm: **${U}**`),Y.push(""),Y.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),Y.push("|---|---:|---:|---:|---:|---:|");for(const se of W){if(se===U)continue;const z=O(g[U]??[],g[se]??[]),ee=z.compared?(z.matches/z.compared*100).toFixed(1)+"%":"N/A";Y.push(`| ${U} -> ${se} | ${z.matches} | ${z.compared} | ${ee} | ${z.meanCents!==null?z.meanCents.toFixed(1):"N/A"} | ${z.octaveErrors} |`)}Y.push(""),Y.push("## Observations and analysis"),Y.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."),Y.push("- Pairwise match rate shows how often algorithms agree on the same regions (within ~50 cents). Octave error counts highlight typical autocorrelation octave mistakes."),Y.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."),Y.push("");for(const se of W){Y.push(`### ${se}`);const z=_[se];Y.push(`- Segments: ${z.count||0}`),Y.push(`- Total voiced (s): ${(z.totalDur||0).toFixed(3)}`),Y.push(`- Voiced fraction: ${z.voicedFraction!==null?(z.voicedFraction*100).toFixed(1)+"%":"N/A"}`),Y.push(`- Mean frequency: ${z.meanFreq?z.meanFreq.toFixed(2)+" Hz":"N/A"}`),Y.push(`- Std frequency: ${z.stdFreq?z.stdFreq.toFixed(2)+" Hz":"N/A"}`),Y.push("")}Y.push("## Conclusions & recommendation");const $=[];for(const se of W){if(se===U){$.push({alg:se,score:100});continue}const z=O(g[U]??[],g[se]??[]),ee=z.compared?z.matches/z.compared:0,ae=z.compared?z.octaveErrors/z.compared:0,ce=ee-ae*.5;$.push({alg:se,score:ce})}$.sort((se,z)=>z.score-se.score),Y.push(`- Based on this recording, recommended authoritative detector: **${$[0].alg}** (best agreement with reference).`),Y.push("- For live, low-latency feedback use Pitchy (YIN) with smoothing/hysteresis; use Crepe/Librosa for authoritative scoring or post-processing."),Y.push("- If octave errors are frequent, consider octave-correction heuristics (prefer lower octave when ambiguity) or combine detectors via voting."),Y.push(""),Y.push("## Raw data (per-algorithm segments)");for(const se of W){const z=g[se]??[];Y.push(`### ${se} — ${z.length} segments`);for(const ae of z)Y.push(`- ${ae.start.toFixed(3)} .. ${(ae.start+(ae.duration||0)).toFixed(3)} : ${ae.freq.toFixed(2)} Hz (pitch ${ae.pitch})`);const ee=m[se];ee&&Y.push(`- Error: ${ee}`),Y.push("")}const H=Y.join(`
|
|
44
44
|
`),X=new Blob([H],{type:"text/markdown;charset=utf-8"}),re=URL.createObjectURL(X),oe=document.createElement("a");oe.href=re,oe.download="audiopitch_scientific_report_"+(n?n.name:"capture")+".md",document.body.appendChild(oe),oe.click(),oe.remove(),URL.revokeObjectURL(re)}catch(W){rt.error("generateScientificReport error",W),rt.warn(i("audioPitch.reportError","Could not generate the report: ")+String(W))}}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:W=>l(W.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:W=>p(W.target.checked)})," ",i("audioPitch.compareAll","Compare all algorithms")]}),r.jsx("input",{type:"file",accept:"audio/*",ref:L,onChange:Z,disabled:C})]}),C&&r.jsx("div",{children:i("audioPitch.analyzing","Analyzing...")}),r.jsxs("div",{style:{marginTop:8},children:[r.jsx("b",{children:i("audioPitch.method","Method:")})," ",o]}),M&&r.jsxs("div",{style:{color:"red",marginTop:8},children:[r.jsxs("b",{children:[o,": "]}),r.jsx("div",{children:M}),I&&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:I})]}),R&&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:R}),P&&r.jsxs("div",{style:{marginTop:8},children:[r.jsx("b",{children:i("audioPitch.probe","Probe:")})," ",P]})]}),(Object.keys(g).length>0||Object.keys(m).length>0)&&r.jsxs("div",{style:{marginTop:12},children:[r.jsx("button",{onClick:()=>K(),children:i("audioPitch.downloadReport","Download report")}),Object.entries(m).length>0&&r.jsxs("div",{style:{marginTop:8},children:[r.jsx("b",{children:i("audioPitch.perAlgorithmErrors","Per-algorithm errors:")}),Object.entries(m).filter(([W,Q])=>Q).map(([W,Q])=>r.jsxs("div",{style:{marginTop:6},children:[r.jsxs("b",{children:[W,":"]}),r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:Q})]},W))]})]}),j.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:[j.map(W=>`: ${Math.round(W.start*10)} ${Math.round(W.duration*10)} ${W.pitch} [${W.freq.toFixed(1)} Hz]`).join(`
|
|
45
45
|
`),`
|
|
46
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:W=>{if(!W)return;const Q=W.getContext("2d");if(Q){Q.clearRect(0,0,600,100),Q.strokeStyle=ve.resolveCssColor("var(--nice-info, #0ff)",Q.canvas),Q.beginPath();for(let w=0;w<c.length;w+=Math.ceil(c.length/600)){const N=w/c.length*600,S=50-c[w]*48;w===0?Q.moveTo(N,S):Q.lineTo(N,S)}if(Q.stroke(),b.length>0){Q.strokeStyle=ve.resolveCssColor("var(--nice-warning, #ff0)",Q.canvas),Q.beginPath();for(let w=0;w<b.length;w++){const N=w/b.length*600,S=100-b[w]*90;w===0?Q.moveTo(N,S):Q.lineTo(N,S)}Q.stroke()}}}}),r.jsxs("div",{style:{color:"var(--nice-text-muted, #aaa)",fontSize:12,marginTop:4},children:[r.jsx("span",{style:{color:"var(--nice-info, #0ff)"},children:i("audioPitch.waveform","Waveform")})," "," | ",r.jsx("span",{style:{color:"var(--nice-warning, #ff0)"},children:"RMS"})]})]}),!C&&j.length===0&&!M&&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(([W,Q])=>r.jsxs("div",{style:{marginBottom:12},children:[r.jsx("b",{children:W}),": ",i("audioPitch.detectedSegments","detected segments:")," ",Q.length,r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-text-inverse, #ddd)",padding:8,borderRadius:4,marginTop:8},children:Q.map(w=>`: ${Math.round(w.start*10)} ${Math.round(w.duration*10)} ${w.pitch} [${w.freq.toFixed(1)} Hz]`).join(`
|
|
47
|
-
`)})]},W))]})]})}const Ft=1e4,Ws=5e3;function Jr(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 xh=["var(--nice-warning, #facc15)","var(--nice-text-secondary, #cbd5e1)","var(--nice-warning, #d97706)"],Sh=({entry:e,rank:t,animDelay:n})=>{const[a,s]=d.useState(0),[i,o]=d.useState(0),[l,c]=d.useState(0),[u,h]=d.useState(0),p=Math.min(e.classicScore,Ft),g=Math.min(e.bonusScore,Ft),y=p/Ft*Ws,m=g>0?g/Ft*Ws:0;return d.useEffect(()=>{let x,b=null;const f=Math.max(y,400),j=Math.max(m,m>0?300:0),v=C=>{b===null&&(b=C);const T=C-b-n;if(T<0){x=requestAnimationFrame(v);return}if(T<=f){const M=Math.min(1,T/f),k=1-Math.pow(1-M,3);s(Math.min(k*(p/Ft)*100,100)),c(Math.round(k*e.classicScore)),x=requestAnimationFrame(v);return}if(s(Math.min(p/Ft*100,100)),c(e.classicScore),j>0){const M=T-f;if(M<=j){const k=Math.min(1,M/j),R=1-Math.pow(1-k,3);o(Math.min(R*(g/Ft)*100,100)),h(Math.round(R*e.bonusScore)),x=requestAnimationFrame(v);return}o(Math.min(g/Ft*100,100)),h(e.bonusScore)}};return x=requestAnimationFrame(v),()=>cancelAnimationFrame(x)},[e.classicScore,e.bonusScore,p,g,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(B.NtdMedal,{size:18,primaryColor:xh[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:Jr(e.color,.45)}}),r.jsx("div",{className:"nice-karaoke-summary__bar-fill-classic",style:{width:`${a}%`,background:`linear-gradient(90deg, ${e.color}, ${Jr(e.color,.15)})`,boxShadow:`0 0 8px ${e.color}55`}}),r.jsxs("div",{className:"nice-karaoke-summary__bar-text",children:[l.toLocaleString(),u>0&&r.jsxs("span",{className:"nice-karaoke-summary__bar-text-bonus",style:{color:Jr(e.color,.5)},children:["+",u.toLocaleString()]})]})]}),r.jsx("span",{className:"nice-karaoke-summary__bar-total",children:(l+u).toLocaleString()})]})},Us=({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(B.NtdCircle,{size:8})," "]}),s.name]}),r.jsx("td",{className:"nice-karaoke-summary__rank-score",children:s.score.toLocaleString()})]},`${s.name}-${i}`)})})})]}),Io=({uploadedSong:e,playerScores:t,topSingings:n,onRestart:a,onContinue:s,t:i,renderReport:o,className:l,style:c,id:u,accessMode:h,"data-testid":p})=>{const[g,y]=d.useState(!1),m=d.useMemo(()=>[...t].sort((C,T)=>T.totalScore-C.totalScore),[t]),x=d.useMemo(()=>{const C=new Map;for(const T of t)C.set(T.name,T.color);return C},[t]),b=d.useMemo(()=>new Set(t.map(C=>C.name)),[t]),f=d.useMemo(()=>m.map((C,T)=>({rank:T+1,name:C.name,score:C.totalScore,color:C.color})),[m]),j=d.useMemo(()=>{const C=n.map(M=>({name:M.playerName,score:M.score})),T=new Set;for(const M of m)T.has(M.id)||(T.add(M.id),C.push({name:M.name,score:M.totalScore}));return C.sort((M,k)=>k.score-M.score),C.slice(0,10).map((M,k)=>({rank:k+1,name:M.name,score:M.score}))},[n,m]),v=e?e.artist?`${e.artist} — ${e.title}`:e.title:i("karaokeSummary.unknownSong","Unknown song");return h==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-summary ${l??""}`,style:c,id:u,"data-testid":p,children:[r.jsxs("div",{className:"nice-karaoke-summary__card",children:[r.jsx("h1",{className:"nice-karaoke-summary__title",children:v}),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((C,T)=>r.jsx(Sh,{entry:C,rank:T+1,animDelay:T*300},C.id))}),(m.length>1||n.length>0)&&r.jsxs("div",{className:"nice-karaoke-summary__ranks",children:[m.length>1&&r.jsx(Us,{title:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(B.NtdHome,{size:14})," ",i("karaokeSummary.localRanking","Session ranking")]}),entries:f,highlightNames:b,playerColorMap:x}),n.length>0&&r.jsx(Us,{title:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(B.NtdTrophy,{size:14})," ",i("karaokeSummary.globalRanking","Top 10")]}),entries:j,highlightNames:b,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(B.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)))]})},kh=st.scoped("GenericPlayer"),wh=e=>/youtu(\.be|be\.com)/i.test(e),Lo=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),Ch=e=>!!e&&/\.(mp3|aac|m4a|flac|wav|ogg)(\?.*)?$/i.test(e),jh=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&&wh(o.url)))??null;if(n)return n;const a=t("hls")||e.sources.find(o=>o.url&&Lo(o.url))||null;if(a)return a;const s=t("audio")||e.sources.find(o=>o.url&&Ch(o.url))||null;return s||(e.sources[0]??null)},Lr=e=>{(!isFinite(e)||e<0)&&(e=0);const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`},Mh=[.25,.5,.75,1,1.25,1.5,1.75,2],_o=({tracks:e=[],initialIndex:t=0,autoPlay:n=!0,countdownSeconds:a=0,height:s=360,onIndexChange:i,onPlayingChange:o,onTimeUpdate:l,externalRef:c,uiMode:u="full",compactNextCount:h=3,progressBarPosition:p="inline",loop:g=!1,onEnded:y,enableKeyboardShortcuts:m=!0,shuffle:x=!1,repeatMode:b="none",playbackSpeed:f=1,abLoop:j=null,onRepeatModeChange:v,onShuffleChange:C,onSpeedChange:T,sleepTimer:M=0,onSleepTimerExpired:k})=>{const{t:R}=xe(),{t:P}=xe(),[I,A]=d.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),L=e[I],E=d.useMemo(()=>jh(L),[L]),D=(L==null?void 0:L.startOffset)??0,[Z,G]=d.useState(!1),[F,q]=d.useState(0),[V,K]=d.useState(0),[W,Q]=d.useState(.9),[w,N]=d.useState(null),[S,O]=d.useState(null),Y=d.useRef(null),[_,U]=d.useState(x),[$,H]=d.useState(b),[X,re]=d.useState(f),[oe,se]=d.useState(j),[z,ee]=d.useState([]),[ae,ce]=d.useState(M>0?M*60:null),le=d.useRef(null),[ne,pe]=d.useState(()=>Ai()),fe=d.useRef(null),ge=d.useRef(null),he=d.useRef(null),we=d.useRef(null);d.useEffect(()=>{if(_&&e.length>0){const de=Array.from({length:e.length},(me,Re)=>Re);for(let me=de.length-1;me>0;me--){const Re=Math.floor(Math.random()*(me+1));[de[me],de[Re]]=[de[Re],de[me]]}ee(de)}},[_,e.length]);const je=d.useRef(k);je.current=k,d.useEffect(()=>(le.current&&(window.clearInterval(le.current),le.current=null),M>0&&Z&&(ce(M*60),le.current=window.setInterval(()=>{ce(de=>{var me;return!de||de<=1?(le.current&&window.clearInterval(le.current),le.current=null,(me=je.current)==null||me.call(je),null):de-1})},1e3)),()=>{le.current&&window.clearInterval(le.current)}),[M,Z]);const Pe=d.useCallback(de=>{const me=Math.min(Math.max(0,de),Math.max(0,e.length-1));A(me),i==null||i(me)},[e.length,i]),$e=d.useCallback(()=>{if(_&&z.length>0){const me=z.indexOf(I)+1;return me<z.length?z[me]:$==="all"?z[0]:-1}return I<e.length-1?I+1:$==="all"?0:-1},[I,e.length,_,z,$]),Ye=d.useCallback(()=>{if(_&&z.length>0){const de=z.indexOf(I);return de>0?z[de-1]:$==="all"?z[z.length-1]:-1}return I>0?I-1:$==="all"?e.length-1:-1},[I,e.length,_,z,$]),ue=d.useCallback(()=>{const de=$e();de>=0&&Pe(de)},[$e,Pe]),Se=d.useCallback(async()=>{var de,me;await Xt(),pe(!0),(E==null?void 0:E.kind)==="youtube"?(de=fe.current)==null||de.playVideo():(me=ge.current)==null||me.play(),G(!0),o==null||o(!0)},[E,o]),Oe=d.useCallback(()=>{var de,me;(E==null?void 0:E.kind)==="youtube"?(de=fe.current)==null||de.pauseVideo():(me=ge.current)==null||me.pause(),G(!1),o==null||o(!1)},[E,o]),Me=d.useCallback(()=>Z?Oe():Se(),[Z,Se,Oe]),Ie=d.useCallback(de=>{var Ne;const me=de+D;(E==null?void 0:E.kind)==="youtube"?(Ne=fe.current)==null||Ne.seekTo(me,!0):ge.current&&(ge.current.currentTime=me);const Re=Math.max(0,de);K(Re),l==null||l(Re)},[E==null?void 0:E.kind,l,D]),Qe=d.useCallback(()=>{if(V>3){Ie(0);return}const de=Ye();de>=0&&Pe(de)},[Ye,Pe,V,Ie]),Be=d.useCallback(de=>{var me,Re;Q(de),N(null),(E==null?void 0:E.kind)==="youtube"?(Re=(me=fe.current)==null?void 0:me.setVolume)==null||Re.call(me,Math.round(de*100)):ge.current&&(ge.current.volume=de)},[E]),He=d.useCallback(()=>{w!==null?Be(w):(N(W),Be(0))},[W,w,Be]),Dt=d.useCallback(de=>{var me,Re;re(de),ge.current&&(ge.current.playbackRate=de),(E==null?void 0:E.kind)==="youtube"&&((Re=(me=fe.current)==null?void 0:me.setPlaybackRate)==null||Re.call(me,de)),T==null||T(de)},[E,T]),ct=d.useCallback(()=>{const de=["none","all","one"],me=de[(de.indexOf($)+1)%de.length];H(me),v==null||v(me)},[$,v]),ht=d.useCallback(()=>{const de=!_;U(de),C==null||C(de)},[_,C]),it=d.useCallback(de=>{se(de)},[]);d.useImperativeHandle(c,()=>({play:Se,pause:Oe,toggle:Me,seekTo:Ie,setVolume:Be,setSpeed:Dt,setRepeatMode:de=>{H(de),v==null||v(de)},toggleShuffle:ht,setABLoop:it,getUnderlyingPlayer:()=>(E==null?void 0:E.kind)==="youtube"?fe.current:(E==null?void 0:E.kind)==="hls"||(E==null?void 0:E.kind)==="audio"?ge.current:null}),[Se,Oe,Me,Ie,Be,Dt,v,ht,it,E==null?void 0:E.kind]),d.useEffect(()=>{const de=window.setInterval(()=>{let me=0,Re=0;(E==null?void 0:E.kind)==="youtube"&&fe.current?(me=fe.current.getCurrentTime()||0,Re=fe.current.getDuration()||0):ge.current&&(me=ge.current.currentTime||0,Re=ge.current.duration||0);const Ne=Math.max(0,me-D);K(Ne),q(Re),l==null||l(Ne),oe&&Ne>=oe.b&&Ie(oe.a)},250);return()=>window.clearInterval(de)},[E==null?void 0:E.kind,l,oe,D,Ie]),d.useEffect(()=>()=>{Y.current&&(window.clearInterval(Y.current),Y.current=null)},[]);const wt=E==null?void 0:E.url,Je=E==null?void 0:E.kind,Pt=E==null?void 0:E.withCredentials,Jt=JSON.stringify((E==null?void 0:E.headers)??null),ke=d.useRef(W);ke.current=W;const Ce=d.useRef(a);Ce.current=a;const We=d.useRef(o);We.current=o,d.useEffect(()=>{if(he.current){try{he.current.destroy()}catch{}he.current=null}if(ge.current&&(ge.current.volume=ke.current,ge.current.crossOrigin=Pt?"use-credentials":"anonymous"),Je==="hls"&&Lo(wt)){const de=ge.current;if(!de)return;const me=()=>{de.src=wt,de.load();try{D&&!isNaN(D)&&(de.currentTime=D)}catch{}n&&de.play().catch(()=>{})};de.canPlayType("application/vnd.apple.mpegurl")?me():(async()=>{var Re;try{const _e=(await import("hls.js")).default;if((Re=_e==null?void 0:_e.isSupported)!=null&&Re.call(_e)){const be=JSON.parse(Jt),Te=new _e({xhrSetup:Le=>{if(Pt&&(Le.withCredentials=!0),be)for(const[Ge,ze]of Object.entries(be))try{Le.setRequestHeader(Ge,ze)}catch{}}});he.current=Te,Te.loadSource(wt),Te.attachMedia(de),Te.on(_e.Events.MANIFEST_PARSED,()=>{n&&de.play().catch(()=>{})})}else me()}catch(Ne){kh.debug("HLS.js setup failed, falling back to native playback",Ne),me()}})()}else if(Je==="audio"&&wt&&ge.current){const de=ge.current;de.src=wt,de.load();try{D&&!isNaN(D)&&(de.currentTime=D)}catch{}n&&de.play().catch(()=>{})}Y.current&&(window.clearInterval(Y.current),Y.current=null),O(null),K(0),q(0),n&&Je==="youtube"&&Ce.current>0?(O(Ce.current),Y.current=window.setInterval(()=>{O(de=>{var me,Re;if(!de)return null;if(de<=1){Y.current&&(window.clearInterval(Y.current),Y.current=null);try{(me=fe.current)==null||me.playVideo()}catch{}return G(!0),(Re=We.current)==null||Re.call(We,!0),null}return de-1})},1e3)):G(!!n)},[wt,Je,Pt,Jt,D,n]);const De=d.useCallback(()=>{if($==="one"){Ie(0),Se();return}const de=$e();de>=0?Pe(de):(G(!1),o==null||o(!1),Ie(0),y==null||y())},[$,$e,Pe,o,Ie,y,Se]);d.useEffect(()=>{if(!m)return;const de=me=>{var _e;const Re=me.target instanceof HTMLElement?me.target:document.body;if(Re.tagName==="INPUT"||Re.tagName==="TEXTAREA"||Re.isContentEditable||Re!==document.body&&!((_e=we.current)!=null&&_e.contains(Re))||me.key===" "&&Re.closest('button, a[href], [role="button"], [role="slider"], [role="menuitem"]')||me.key.startsWith("Arrow")&&Re.closest('[role="slider"], [role="listbox"], [role="menu"]'))return;const Ne=me.niceSource;if(!(me.key.startsWith("Arrow")&&Ne&&Ne!=="keyboard"&&Re!==document.body&&Re!==we.current))switch(me.key){case" ":me.preventDefault(),Me();break;case"ArrowRight":me.preventDefault(),Ie(Math.min(V+5,F));break;case"ArrowLeft":me.preventDefault(),Ie(Math.max(0,V-5));break;case"ArrowUp":me.preventDefault(),Be(Math.min(1,W+.05));break;case"ArrowDown":me.preventDefault(),Be(Math.max(0,W-.05));break;case"m":case"M":He();break;case"n":case"N":ue();break;case"p":case"P":Qe();break;case"r":case"R":ct();break;case"s":case"S":ht();break}};return document.addEventListener("keydown",de),()=>document.removeEventListener("keydown",de)},[m,Me,Ie,V,F,Be,W,He,ue,Qe,ct,ht]);const Ae=(E==null?void 0:E.kind)==="youtube"||u==="full"||u==="nobuttons",Ee=h>0?e.slice(I+1,I+1+h):[];return r.jsxs("div",{ref:we,className:"gp-player",style:{display:"grid",gap:12},tabIndex:-1,children:[n&&!ne&&r.jsx("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,className:"gp-audio-activation",onClick:()=>{pe(!0),Se()},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:R("player.clickToActivateAudio","Click to activate audio")})}),Ae&&r.jsxs("div",{className:"gp-stage",style:{width:"100%",height:s,background:(E==null?void 0:E.kind)==="youtube"?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(E==null?void 0:E.kind)==="youtube"&&r.jsx($a,{videoId:E.videoId??$h(E.url),onReady:de=>{fe.current=de.target,Be(W);const me=(L==null?void 0:L.startOffset)??0;try{me&&de.target.seekTo(me,!0)}catch{}if(u==="nobuttons"){try{de.target.playVideo()}catch{}G(!0)}},onEnd:De,opts:{width:"100%",height:"100%",playerVars:{autoplay:n||u==="nobuttons"?1:0,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,loop:g?1:0}},style:{width:"100%",height:"100%"}}),S!==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:S})}),u==="nobuttons"&&r.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"auto",zIndex:100,cursor:"default"}}),((E==null?void 0:E.kind)==="audio"||(E==null?void 0:E.kind)==="hls")&&r.jsxs(r.Fragment,{children:[u==="full"&&r.jsx("div",{style:{textAlign:"center",color:"var(--nice-overlay-light-90, rgba(255, 255, 255, 0.9))"},children:L!=null&&L.coverUrl?r.jsx("img",{alt:"cover",src:L.coverUrl,style:{height:s-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[L==null?void 0:L.artist," — ",L==null?void 0:L.title]}),r.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--nice-text-secondary, #64748b)"},children:(E==null?void 0:E.label)??`${(E==null?void 0:E.codec)??""} ${(E==null?void 0:E.quality)??""}`.trim()})]})}),r.jsx("audio",{ref:ge,onEnded:De,onLoadedMetadata:()=>{const de=ge.current;de&&q(de.duration||0)},crossOrigin:E!=null&&E.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]})]}),(u==="minimal"||u==="compact")&&r.jsx("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:r.jsxs("div",{children:[r.jsx("div",{style:{fontWeight:600},children:(L==null?void 0:L.title)??""}),r.jsx("div",{style:{color:"var(--nice-text-secondary, #64748b)",fontSize:13},children:(L==null?void 0:L.artist)??""})]})}),u==="full"&&r.jsxs(r.Fragment,{children:[r.jsx(Do,{currentTime:V,duration:F}),r.jsx(Rh,{isPlaying:Z,index:I,count:e.length,currentTime:V,duration:F,volume:W,onPrev:Qe,onNext:ue,onToggle:Me,onSeek:Ie,onVolume:Be}),r.jsx(Eh,{shuffleOn:_,repeatMode:$,speed:X,abLoop:oe,currentTime:V,sleepRemaining:ae,onToggleShuffle:ht,onCycleRepeat:ct,onSpeedChange:Dt,onSetABLoop:it,onMuteToggle:He,isMuted:w!==null})]}),u==="progressOnly"&&r.jsx("div",{style:p==="fixedBottom"?{position:"fixed",left:0,right:0,bottom:0,padding:"8px 12px",background:"var(--nice-overlay-90, rgba(15, 23, 42, 0.9))",backdropFilter:"blur(2px)",zIndex:1e3}:{},children:r.jsx(Nh,{currentTime:V,duration:F,onSeek:Ie})}),(u==="minimal"||u==="compact")&&r.jsx(Th,{isPlaying:Z,canPrev:I>0,canNext:I<e.length-1,onPrev:Qe,onNext:ue,onToggle:Me}),u==="compact"&&Ee.length>0&&r.jsx(Ph,{items:Ee,onSelect:de=>Pe(I+1+de)}),u==="nobuttons"&&r.jsx(r.Fragment,{}),u==="full"&&e.length>0&&r.jsx("div",{className:"gp-list",style:{display:"grid",gap:4},children:e.map((de,me)=>r.jsxs("button",{onClick:()=>Pe(me),style:{textAlign:"left",border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"8px 10px",background:me===I?"color-mix(in srgb, var(--nice-color-primary) 14%, transparent)":"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},title:de.sources.map(Re=>Re.kind).join(", "),children:[r.jsx("div",{style:{fontWeight:600},children:de.title}),r.jsx("div",{style:{color:"var(--nice-text-secondary)",fontSize:12},children:de.artist})]},de.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"},Do=({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:[Lr(e)," / ",Lr(t)]})]}),Rh=({isPlaying:e,index:t,count:n,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek:u,onVolume:h})=>{const{t:p}=xe();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:yt,children:r.jsx(B.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:yt,children:e?r.jsx(B.NtdPause,{size:16}):r.jsx(B.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:yt,children:r.jsx(B.NtdSkipForward,{size:16})})]}),r.jsx("input",{type:"range",min:0,max:Math.max(1,s),step:.1,value:a,onChange:g=>u(parseFloat(g.target.value)),"aria-label":p("player.seekPosition","Seek position")}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx(B.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")})]})]})},Nh=({currentTime:e,duration:t,onSeek:n})=>{const{t:a}=xe();return r.jsxs(r.Fragment,{children:[r.jsx(Do,{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")})]})},Th=({isPlaying:e,canPrev:t,canNext:n,onPrev:a,onNext:s,onToggle:i})=>{const{t:o}=xe();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:yt,children:r.jsx(B.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:yt,children:e?r.jsx(B.NtdPause,{size:16}):r.jsx(B.NtdPlay,{size:16})}),r.jsx("button",{onClick:s,disabled:!n,title:o("player.nextTrack","Next track"),"aria-label":o("player.nextTrack","Next track"),style:yt,children:r.jsx(B.NtdSkipForward,{size:16})})]})},Ph=({items:e,onSelect:t})=>{const{t:n}=xe();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))})]})},Eh=({shuffleOn:e,repeatMode:t,speed:n,abLoop:a,currentTime:s,sleepRemaining:i,onToggleShuffle:o,onCycleRepeat:l,onSpeedChange:c,onSetABLoop:u,onMuteToggle:h,isMuted:p})=>{const{t:g}=xe(),y={none:g("player.off","Off"),all:g("player.all","All"),one:g("player.one","One")},m=t==="one"?r.jsxs("span",{style:{position:"relative",display:"inline-flex"},children:[r.jsx(B.NtdRepeat,{size:16}),r.jsx("span",{style:{position:"absolute",right:-3,bottom:-3,fontSize:8,fontWeight:700},children:"1"})]}):t==="all"?r.jsx(B.NtdRepeat,{size:16}):r.jsx(B.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:{...yt,opacity:e?1:.4,fontWeight:e?700:400},children:r.jsx(B.NtdShuffle,{size:16})}),r.jsx("button",{onClick:l,title:`${g("player.repeat","Repeat")}: ${y[t]}`,"aria-label":`${g("player.repeat","Repeat")}: ${y[t]}`,style:{...yt,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:{...yt,minWidth:56,fontSize:12},children:Mh.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:{...yt,opacity:p?1:.6},children:p?r.jsx(B.NtdVolumeMute,{size:16}):r.jsx(B.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: ",Lr(a.a)," — B: ",Lr(a.b)]}),r.jsx("button",{onClick:()=>u(null),title:g("player.clearLoop","Clear loop"),style:{...yt,fontSize:11,padding:"2px 6px"},children:r.jsx(B.NtdClose,{size:12})})]}):r.jsx("button",{onClick:()=>u({a:s,b:s+10}),title:g("player.abLoop","A-B Loop"),"aria-label":g("player.setAbLoop","Set A-B Loop"),style:{...yt,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(B.NtdMoon,{size:12})," ",Math.floor(i/60),":",(i%60).toString().padStart(2,"0")]})]})};function $h(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 zo(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 Ah(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 Ih(e,t="/backgrounds"){return e.backgroundImage?`${t}/${e.backgroundImage}`:""}function Fo(e,t,n=.01){let a=0;for(let o=0;o<e.length;o++)a+=e[o]*e[o];if(a=Math.sqrt(a/e.length),a<n)return 0;let s=-1,i=0;for(let o=20;o<e.length/2;o++){let l=0;for(let c=0;c<e.length/2;c++)l+=e[c]*e[c+o];l/=e.length/2,l>i&&(i=l,s=o)}return s>0?t/s:0}function Za(e,t){const n=[];return e.forEach((a,s)=>{a.forEach((i,o)=>{n.push({startTime:i.startTime+t,duration:i.duration,pitch:i.pitch,isGold:i.isGold,line:s,idx:o})})}),n}function Oo(e,t,n){const a=[];return e.forEach(s=>{var c;const[i,o]=s.noteKey.split("-").map(Number),l=(c=t[i])==null?void 0:c[o];l&&s.segments.forEach(u=>{a.push({start:u.visualStart-n,end:u.visualEnd-n,pitch:l.pitch,frac:u.frac,isGold:l.isGold,noteStart:l.startTime,noteEnd:l.startTime+l.duration})})}),a}function Bo(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 Go(e,t,n){const s=Date.parse(e)-n;return Math.max(0,Math.round(t-s))}const Wo={crepe:"var(--nice-accent, #a78bfa)",librosa:"var(--nice-success-light, #34d399)",pitchy:"var(--nice-primary-light, #60a5fa)",autocorr:"var(--nice-text-secondary, #555555)"};function Lh(e){return e==="autocorr"?"Ultrastar":e.charAt(0).toUpperCase()+e.slice(1)}function _h(e){return Wo[e]??"var(--nice-text-secondary, #555555)"}function Dh(e){const t=Wo[e]??"var(--nice-text-secondary, #555555)";return`var(--algo-${e}, ${t})`}function Uo(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=zo(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 zh(e){const t=e.videoPath??e.video??void 0;return{id:e.id,title:e.title??"",artist:e.artist??"",year:e.year,genre:e.genre,language:e.language,filePath:e.filePath,coverPath:e.coverPath,audioPath:e.audioPath??e.audio??void 0,videoPath:t,format:0,notes:e.notes??[],gap:e.gap,bpm:e.bpm,videoGap:e.videoGap,start:e.start,end:e.end,youtubeId:e.youtubeId,instrumentalPath:e.instrumentalPath,isVerified:e.isVerified,coverImage:e.coverImage,backgroundImage:e.backgroundImage}}var Xa=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(Xa||{});function Vo(e,t="song.txt"){const n=e.split(/\r?\n/),a={},s=[];for(const o of n){const l=o.replace(/\uFEFF/g,"");if(l.trim()){if(l.startsWith("#")){const c=l.indexOf(":");c>0&&(a[l.slice(1,c).trim().toUpperCase()]=l.slice(c+1).trim())}else if(/^[:*\-FG]/.test(l))s.push({noteLine:l});else if(l.trim()==="E")break}}const i=o=>{if(!o)return;const l=parseFloat(o.replace(",","."));return Number.isFinite(l)?l:void 0};return{title:a.TITLE||t.replace(/\.txt$/i,""),artist:a.ARTIST||"",format:Xa.Ultrastar,bpm:i(a.BPM),gap:i(a.GAP),genre:a.GENRE||void 0,language:a.LANGUAGE||void 0,year:a.YEAR||void 0,audioPath:a.MP3||void 0,videoPath:a.VIDEO||a.MP3||void 0,notes:s}}const Fh=e=>window.btoa(unescape(encodeURIComponent(e))),qo=({onSongUpload:e,parseSong:t,onError:n,accept:a=".txt",maxFileSize:s=5*1024*1024,t:i})=>{const{t:o}=xe(),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:Fh(y)}):Vo(y,h.name);e(x)}catch(x){n==null||n(x)}},p.readAsText(h,"UTF-8")},u=h=>/\.txt$/i.test(h.name)?h.size===0?l("karaokeUploader.empty","The file is empty."):null:l("karaokeUploader.notTxt","Please choose an UltraStar .txt file.");return r.jsx("div",{className:"nice-karaoke-uploader",children:r.jsx(ie.NiceUpload,{accept:a,maxFileSize:s,validateFile:u,multiple:!1,text:l("karaokeUploader.dropPrompt","Click or drag & drop an UltraStar file (.txt)"),onFilesSelected:h=>{const p=h[0];p&&c(p)}})})},Oh=[],Bh=[],Gh=[],Wh=[];function Uh(e,t,n,a,s){const o=a*.45;e.beginPath();for(let l=0;l<10;l++){const c=l%2===0?a:o,u=Math.PI/5*l-Math.PI/2,h=t+Math.cos(u)*c,p=n+Math.sin(u)*c;l===0?e.moveTo(h,p):e.lineTo(h,p)}e.closePath(),e.fillStyle=s,e.fill()}const qt=60,Vs=4,ea="#888",qs=["A","B","X","Y","LB","RB","LT","RT"],Ho=({lanes:e=Oh,events:t=Bh,currentTime:n,activeLanes:a=Gh,difficulty:s,feedbackQueue:i=Wh,isPlaying:o,height:l=300})=>{const{t:c}=xe(),u=e.length,h=d.useRef(null),p=d.useRef([]);return d.useEffect(()=>{p.current=i},[i]),d.useEffect(()=>{var T,M;const g=h.current;if(!g)return;const y=g.getContext("2d");if(!y)return;const m=window.devicePixelRatio||1,x=g.clientWidth,b=g.clientHeight;if(g.width=x*m,g.height=b*m,y.scale(m,m),y.clearRect(0,0,x,b),u===0)return;const f=x/u;for(let k=0;k<u;k++){const R=k*f;y.fillStyle=k%2===0?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",y.fillRect(R,0,f,b),k>0&&(y.strokeStyle="rgba(255,255,255,0.1)",y.lineWidth=1,y.beginPath(),y.moveTo(R,0),y.lineTo(R,b),y.stroke())}const j=b-qt-10;y.strokeStyle="rgba(255,255,255,0.4)",y.lineWidth=2,y.setLineDash([8,4]),y.beginPath(),y.moveTo(0,j),y.lineTo(x,j),y.stroke(),y.setLineDash([]);const v=e.map(k=>ve.resolveCssColor((k==null?void 0:k.color)??ea,g)),C=(b-qt-20)/Vs;for(const k of t){const R=k.note.startTime,P=R+k.note.duration,I=R-n;if(I>Vs||P<n-.5)continue;const A=k.lane,L=A*f+4,E=f-8,D=j-I*C,Z=k.note.duration*C,G=n>=R-.15&&n<=P+.15,F=n>P+.15,q=v[A]??ea;F?y.fillStyle="rgba(100,100,100,0.3)":G?(y.fillStyle=q,y.shadowColor=q,y.shadowBlur=12):(y.fillStyle=q,y.globalAlpha=.6);const V=Math.max(Z,8),K=6;y.beginPath(),y.moveTo(L+K,D),y.lineTo(L+E-K,D),y.quadraticCurveTo(L+E,D,L+E,D+K),y.lineTo(L+E,D+V-K),y.quadraticCurveTo(L+E,D+V,L+E-K,D+V),y.lineTo(L+K,D+V),y.quadraticCurveTo(L,D+V,L,D+V-K),y.lineTo(L,D+K),y.quadraticCurveTo(L,D,L+K,D),y.fill(),y.globalAlpha=1,y.shadowBlur=0,k.note.isGold&&Uh(y,L+E/2,D+V/2,Math.min(7,E/4),"#fbbf24")}for(let k=0;k<u;k++){const R=k*f,P=b-qt,I=a[k],A=v[k]??ea;y.fillStyle=I?A:"rgba(30,30,30,0.9)",y.fillRect(R+2,P+2,f-4,qt-4),y.strokeStyle=I?"#fff":A,y.lineWidth=I?3:1,y.strokeRect(R+2,P+2,f-4,qt-4),y.fillStyle=I?"#000":"#fff",y.font=`bold ${Math.min(24,f*.3)}px monospace`,y.textAlign="center",y.textBaseline="middle",y.fillText(((T=e[k])==null?void 0:T.label)??"",R+f/2,P+qt/2);const L=((M=e[k])==null?void 0:M.gamepadButton)??-1;L>=0&&L<qs.length&&(y.fillStyle=I?"rgba(0,0,0,0.6)":"rgba(255,255,255,0.4)",y.font="10px sans-serif",y.fillText(qs[L],R+f/2,P+qt-8))}for(const k of p.current){const R=n-k.time;if(R<0||R>.8)continue;const P=Math.max(0,1-R/.8),I=k.lane*f;y.save(),y.globalAlpha=P,y.font="bold 20px sans-serif",y.textAlign="center",y.textBaseline="bottom",y.fillStyle=k.type==="perfect"?"#10b981":k.type==="good"?"#f59e0b":"#ef4444";const A=k.type==="perfect"?c("padKaraokeOverlay.perfect","PERFECT"):k.type==="good"?c("padKaraokeOverlay.good","GOOD"):c("padKaraokeOverlay.miss","MISS");y.fillText(A,I+f/2,j-10-R*40),y.restore()}},[n,e,t,a,u,o,c]),!o||u===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(B.NtdGamepad,{size:14})," ",c("padKaraokeOverlay.pad","PAD — {difficulty}").replace("{difficulty}",String(s))]})]})},_n=["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)"],Ko={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 va(e){return 440*Math.pow(2,(e-69)/12)}function Yo(e,t){const n=Ko[t],a=n.keys.length,s=[];for(const u of e)for(const h of u)s.includes(h.pitch)||s.push(h.pitch);if(s.sort((u,h)=>u-h),s.length===0)return n.keys.map((u,h)=>({index:h,key:u,gamepadButton:n.buttons[h],label:n.labels[h],minPitch:-999,maxPitch:999,color:_n[h%_n.length]}));const i=s[0],l=s[s.length-1]-i+1,c=[];for(let u=0;u<a;u++){const h=i+Math.floor(l*u/a),p=i+Math.floor(l*(u+1)/a)-1;c.push({index:u,key:n.keys[u],gamepadButton:n.buttons[u],label:n.labels[u],minPitch:u===0?-999:h,maxPitch:u===a-1?999:p,color:_n[u%_n.length]})}return c}function Zo(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 Xo(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:Zo(o.pitch,t),lineIndex:s,noteIndex:i})}return a.sort((s,i)=>s.note.startTime-i.note.startTime),a}class Qo{constructor(t){this.lanes=[],this.events=[],this.raf=null,this.keysDown=new Set,this.gamepadButtonsDown=new Set,this.running=!1,this.getCurrentTime=()=>0,this.lastFeedbackTime=0,this.lastActiveNote=null,this.preWindow=.15,this.postWindow=.15,this.loop=()=>{var c,u,h,p,g,y,m,x;if(!this.running)return;const s=this.getCurrentTime();this.pollGamepad();const i=this.getActiveLanes();(u=(c=this.config).onLaneActive)==null||u.call(c,i);const o=this.findActiveNote(s);if(o!==this.lastActiveNote&&(this.lastActiveNote=o,(p=(h=this.config).onCurrentNote)==null||p.call(h,o)),i.some(Boolean)&&o){const b=o.lane,f=i.indexOf(!0);if(i[b]){const j=va(o.note.pitch);this.config.onPitch(j),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(y=(g=this.config).onHitFeedback)==null||y.call(g,{type:"perfect",lane:b,time:s}))}else if(f>=0){const v=Math.abs(f-b)*3,C=va(o.note.pitch+v);this.config.onPitch(C),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=Zn(t.noteLines,t.bpm),a=(t.gap??0)/1e3;switch(this.lanes=Yo(n,t.difficulty),this.events=Xo(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 n;const t=ve.getInputEngine().gamepadSnapshot[0];if(t){this.gamepadButtonsDown.clear();for(let a=0;a<t.buttons.length;a++)(n=t.buttons[a])!=null&&n.pressed&&this.gamepadButtonsDown.add(a)}}getActiveLanes(){const t=new Array(this.lanes.length).fill(!1);for(const n of this.lanes)(this.keysDown.has(n.key)||this.gamepadButtonsDown.has(n.gamepadButton))&&(t[n.index]=!0);return t}findActiveNote(t){for(const n of this.events){const 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 ft=st.scoped("BaseStreamClient");function Hs(e,t,n){if(t===n)return e.slice();const a=Math.round(e.length*n/t),s=new Float32Array(a),i=e.length/a;for(let o=0;o<a;o++){const l=o*i,c=Math.floor(l),u=Math.min(e.length-1,c+1),h=l-c;s[o]=e[c]*(1-h)+e[u]*h}return s}function Vh(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 wn=16e3,qh="/scripts/pitch-worklet.js";class Jo{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 qh}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,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,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(u){(o=(i=this.opts).onError)==null||o.call(i,u);break}}finally{this.sendQueue=[]}ft.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(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 n,a;ft.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,b,f,j,v;const n=new Float32Array(this.buffer.length+t.length);n.set(this.buffer,0),n.set(t,this.buffer.length),this.buffer=n;const a=this.audioCtx.sampleRate,s=Math.round((this.opts.chunkMs??200)*wn/1e3),i=Math.floor(this.buffer.length*wn/a),o=Math.floor(i/s);if(o<=0)return;const l=o*s,c=Math.floor(l*a/wn),u=this.buffer.slice(0,c);this.buffer=this.buffer.slice(c);const h=Hs(u,a,wn);let p=0;for(;p+s<=h.length;){const C=h.subarray(p,p+s),M=Vh(C).buffer,k=this.ws;if(k&&k.readyState===WebSocket.OPEN)try{k.send(M),this.chunksSent++,(y=(g=this.opts).onSend)==null||y.call(g,M.byteLength)}catch(P){(x=(m=this.opts).onError)==null||x.call(m,P)}else k&&k.readyState===WebSocket.CONNECTING?this.sendQueue.length<this.maxQueue&&(this.sendQueue.push(M),(f=(b=this.opts).onSend)==null||f.call(b,0)):(this.chunksDropped++,(v=(j=this.opts).onSend)==null||v.call(j,0));const R=Date.now();R-this.lastStatusLog>5e3&&(this.lastStatusLog=R,ft.info(`[${this.ts()}] STATUS: sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived} ws=${(k==null?void 0:k.readyState)??"none"} worklet=${this.usingWorklet}`)),p+=s}if(p<h.length){const C=h.subarray(p),T=Hs(C,wn,a),M=new Float32Array(T.length+this.buffer.length);M.set(T,0),M.set(this.buffer,T.length),this.buffer=M}}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 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,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 n=this.audioCtx.createMediaStreamSource(this.mediaStream);await this.setupAudioNodes(n)}stop(){var t,n;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{(n=this.ws)==null||n.close()}catch{}this.ws=void 0,this.sendQueue=[]}}const Hh=st.scoped("CrepeStreaming");class Kh extends Jo{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;Hh.warn(`[${this.tag}] [${this.ts()}] triggering fallback`),this.stopAudioNodes();try{(n=(t=this.crepeOpts).onFallback)==null||n.call(t)}catch{}}}class Yh extends Jo{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 It={debug:(...e)=>{},warn:(...e)=>{typeof console<"u"&&console.warn("[KaraokePitch]",...e)}};function Zh(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 Xh(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 el({isPlaying:e,gameMode:t,players:n,playersMicKey:a,micAlgorithms:s={},defaultPitchAlgorithm:i="pitchy",micRmsThresholds:o={},micOffsets:l={},micGains:c={},micPitchThresholds:u={},micSmoothingWindows:h={},micHysteresisFrames:p={},micUseHanning:g={},micMonitorEnabled:y={},micMonitorVolumes:m={},currentTimeRef:x,isPadMode:b,clockOffsetMsRef:f,currentPartyIdRef:j,rtc:v}){const[C,T]=d.useState({}),M=d.useRef({}),k=d.useRef({}),[R,P]=d.useState({}),I=d.useRef({}),A=d.useRef([]),L=d.useRef(null),E=d.useRef(null),[,D]=d.useState({}),[,Z]=d.useState({}),[,G]=d.useState({}),[F,q]=d.useState({}),[V,K]=d.useState(!0),[W,Q]=d.useState(!1),w=d.useRef(n);w.current=n;const N=d.useRef(0),S=d.useRef(performance.now());return d.useEffect(()=>{A.current.forEach($=>$()),A.current=[];const O={current:!1};function Y($,H,X=0){x.current!==N.current&&(N.current=x.current,S.current=performance.now());const re=Math.min(.25,(performance.now()-S.current)/1e3),oe=x.current+re-X/1e3;T(z=>{const ee=z[$]||[];return{...z,[$]:[...ee,{t:oe,hz:H}]}}),M.current[$]=(M.current[$]||[]).concat({t:oe,hz:H});const se=M.current[$];se.length>500&&(M.current[$]=se.slice(-500))}function _($,H,X,re=.02,oe=0,se=.6,z=0,ee=0,ae=0,ce=!1){let le=null,ne=null,pe=null;return(async()=>{try{le=new AudioContext;let he=le.createMediaStreamSource(H);if(z>0){const Se=le.createGain();Se.gain.value=z,he.connect(Se),he=Se}const we=le.createAnalyser();we.fftSize=2048,he.connect(we);const je=new Float32Array(we.fftSize),Pe=ce?Zh(we.fftSize):null,$e=[];let Ye=0;if(X==="pitchy")try{const{PitchDetector:Se}=await import("pitchy");pe=Se.forFloat32Array(we.fftSize)}catch(Se){It.warn("pitchy import failed, falling back to autocorrelation",Se)}const ue=()=>{try{we.getFloatTimeDomainData(je)}catch{}const Se=Pe?Xh(je,Pe):je;let Oe=0;for(let Ie=0;Ie<Se.length;Ie++)Oe+=Se[Ie]*Se[Ie];Oe=Math.sqrt(Oe/Se.length);let Me=0;if(Oe>=re)if(pe)try{const[Ie,Qe]=pe.findPitch(Se,le.sampleRate);Ie>50&&Ie<3e3&&Qe>se&&(Me=Ie)}catch{}else Me=Fo(Se,le.sampleRate,re),(Me<50||Me>3e3)&&(Me=0);if(Me>0&&ee>1&&($e.push(Me),$e.length>ee&&$e.shift(),Me=$e.reduce((Ie,Qe)=>Ie+Qe,0)/$e.length),Me>0)Ye=0,Y($,Me,oe);else if(Ye++,ae>0&&Ye<=ae&&$e.length>0){const Ie=$e[$e.length-1];Ie>0&&Y($,Ie,oe)}ne=requestAnimationFrame(ue),I.current[$]=ne};ue()}catch(ge){It.warn("startLocalPitch error",ge)}})(),()=>{ne&&cancelAnimationFrame(ne),le&&le.close().catch(()=>{})}}function U($,H,X,re=0){X==="crepe"&&E.current?(E.current.stop(),E.current=null):X==="librosa"&&L.current&&(L.current.stop(),L.current=null);const oe=window.location,se=oe.protocol==="https:"?"wss:":"ws:",z=X==="librosa"?`${se}//${oe.host}/api/librosa/ws/pyin`:`${se}//${oe.host}/api/ai/audio/pitch/ws/pitch_server`,ee=X==="librosa"?D:Z;ee(pe=>({...pe,[$]:"connecting"}));const ae=[],ce=pe=>{if(pe>0){for(ae.push(x.current);ae.length>200;)ae.shift();X==="crepe"&&G(fe=>({...fe,[$]:(fe[$]||0)+1}))}},le=()=>{ee(pe=>({...pe,[$]:"closed"})),ae.length=0},ne=pe=>{if(typeof pe.hz=="number"&&pe.hz>0){const fe=pe.hz,he=(ae.length>0?ae.shift():x.current)-re/1e3;T(we=>{const je=we[$]||[];return{...we,[$]:[...je,{t:he,hz:fe}]}})}else ae.length>0&&ae.shift()};if(X==="librosa"){const pe=new Yh({wsUrl:z,onOpen:()=>ee(fe=>({...fe,[$]:"connected"})),onClose:le,onError:fe=>{ee(ge=>({...ge,[$]:"error"})),It.warn("Librosa WS error",fe)},onMessage:ne,onSend:ce});return L.current=pe,pe.startWithMediaStream(H).catch(fe=>{It.warn("Librosa client start failed",fe),ee(ge=>({...ge,[$]:"failed"}))}),()=>{pe.stop(),L.current=null,ee(fe=>({...fe,[$]:""}))}}else{const pe=new Kh({wsUrl:z,onOpen:()=>ee(fe=>({...fe,[$]:"connected"})),onClose:le,onError:fe=>{ee(ge=>({...ge,[$]:"error"})),It.warn("Crepe WS error",fe)},onMessage:ne,onSend:ce,onFallback:()=>{ee(ge=>({...ge,[$]:"fallback-pitchy"})),E.current=null;const fe=_($,H,"pitchy",.02,re);A.current.push(fe)}});return E.current=pe,pe.startWithMediaStream(H).catch(fe=>{It.warn("Crepe client start failed",fe),ee(ge=>({...ge,[$]:"failed"}))}),()=>{pe.stop(),E.current=null,ee(fe=>({...fe,[$]:""}))}}}if(e){if(T({}),t!=="pad"){const $={};w.current.forEach(H=>{if(!H.micId)return;const X=s[H.id]||i,re=H.micId&&o[H.micId]||.02,oe=H.micId&&l[H.micId]||0,se=H.micId&&c[H.micId]||0,z=H.micId&&u[H.micId]||.6,ee=H.micId&&h[H.micId]||0,ae=H.micId&&p[H.micId]||0,ce=H.micId&&g[H.micId]||!1,le=H.micId&&y[H.micId]||!1,ne=(H.micId?m[H.micId]:void 0)??100,pe=new Da;pe.startRecording({deviceId:H.micId,onLevel:()=>{},gain:se,monitorEnabled:le,monitorVolume:ne}).then(()=>{if(O.current){pe.stopRecording().catch(()=>{});return}$[H.id]=pe;const fe=pe.getStream();if(!fe){It.warn(`No stream from recorder for player ${H.id}`);return}if(X==="librosa"||X==="crepe"){const ge=U(H.id,fe,X,oe);A.current.push(ge)}else{const ge=_(H.id,fe,X,re,oe,z,se,ee,ae,ce);A.current.push(ge)}}).catch(fe=>It.warn(`recorder start failed for player ${H.id}`,fe))}),k.current=$}}else{const $=k.current,H=Object.keys($).map(Number);Promise.allSettled(H.map(async X=>{const re=await $[X].stopRecording();return{pid:X,blob:re}})).then(X=>{const re={};for(const oe of X)oe.status==="fulfilled"&&oe.value.blob&&(re[oe.value.pid]=oe.value.blob);Object.keys(re).length>0&&P(oe=>({...oe,...re}))}),k.current={},Object.values(I.current).forEach(X=>X&&cancelAnimationFrame(X)),I.current={}}return()=>{O.current=!0,A.current.forEach($=>$()),A.current=[],Object.values(k.current).forEach($=>$.stopRecording().catch(()=>{})),k.current={},Object.values(I.current).forEach($=>$&&cancelAnimationFrame($)),I.current={}}},[e,t,a,s,i,o,l,c,u,h,p,g,y,m]),d.useEffect(()=>{if(!v)return;const O=300,Y=async()=>{try{const U={...M.current};for(const $ of Object.keys(U)){const H=Number($),X=U[H]||[];if(!X||X.length===0)continue;M.current[H]=[];const re=Bo(X,120),oe={playerId:H,points:re,clientNowUtc:new Date().toISOString(),quantized:!0};j!=null&&j.current&&(oe.EventId=j.current);try{v.isConnected()&&await v.publishTimelineUpdate(oe)}catch(se){It.warn("failed to publish timeline update, will retry",se),M.current[H]=(M.current[H]||[]).concat(X).slice(-1e3)}}}catch{}},_=window.setInterval(Y,O);return()=>{_&&window.clearInterval(_)}},[v,j]),d.useEffect(()=>{if(!v)return;const O=Y=>{try{const _=Y;if(!_||typeof _.playerId>"u"||!Array.isArray(_.points))return;const U=Number(_.playerId),$=_.points.map(H=>({t:H.t,hz:H.hz}));if(!$.length)return;if(_.serverTimeUtc){const H=Go(_.serverTimeUtc,Date.now(),(f==null?void 0:f.current)||0);q(X=>({...X,[U]:H}))}T(H=>{const X=H[U]||[];return{...H,[U]:[...X,...$]}})}catch{}};return v.onTimelineUpdate(O),()=>v.offTimelineUpdate(O)},[v,f]),{livePitch:C,setLivePitch:T,recordings:R,recordersRef:k,unsentPitchRef:M,pitchCleanupsRef:A,remoteLatencyMs:F,showRemoteTimelines:V,setShowRemoteTimelines:K,compactTimelines:W,setCompactTimelines:Q}}function tl(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function nl(e){return e>=50?3:e>=30?2.5:e>=20?2:e>=10?1.5:1}function rl(e,t,n){const{semitoneTolerance:a,preWindow:s,postExtra:i}=n,o=n.segMs??.25,l=typeof n.completionBonusFactor=="number"?n.completionBonusFactor:.15,c=typeof n.goldFullBonusFactor=="number"?n.goldFullBonusFactor:.3,u=typeof n.difficultyMult=="number"?n.difficultyMult:1,h=!!n.disableGoldNotes;let p=0,g=0,y=0;const m=[];let x=0,b=0,f=0;const j=new Map;e.forEach((P,I)=>{const A=P.startTime,L=P.startTime+P.duration,E=A-s,D=L+i,Z=t.filter(w=>w.t>=E&&w.t<=D&&w.hz>0);if(!Z||Z.length===0)return;const G=Math.max(1,Math.ceil((P.duration||.25)/o)),F=Math.max(10,Math.round(100*(P.duration||1))),q=Math.max(1,Math.round(F/G));let V=0;const K=[];for(let w=0;w<G;w++){const N=A+w*(P.duration/G),S=A+(w+1)*(P.duration/G),O=Math.min(.06,P.duration/G*.2),Y=N-O,_=S+O,U=t.filter(se=>se.t>=Y&&se.t<=_&&se.hz>0);if(!U||U.length===0)continue;let $=0;U.forEach(se=>{let ee=((12*Math.log2(se.hz/440)+69)%12+12)%12;for(;ee-P.pitch>6;)ee-=12;for(;ee-P.pitch<-6;)ee+=12;const ae=Math.abs(ee-P.pitch);$+=ae});const H=$/U.length;let X=0;if(a<=0)X=H===0?1:0;else{const se=a*2;X=Math.max(0,1-Math.min(H/se,1))}if(X<=0)continue;const re=!h&&P.isGold?2:1,oe=Math.round(q*re*X);oe>0&&(p+=oe,V+=oe,K.push({segIndex:w,frac:X,add:oe,segStart:Y,segEnd:_,visualStart:N,visualEnd:S}))}const W=P.line??0;j.has(W)||j.set(W,{total:0,hit:0,comboBonus:0});const Q=j.get(W);if(Q.total++,V>0){x++,x>b&&(b=x),Q.hit++;const w=nl(x),N=w>1?Math.round(V*(w-1)):0;f+=N,Q.comboBonus+=N;const S=Math.max(1,Math.ceil((P.duration||.25)/o)),Y=K.length>=S,_=Y?Math.round(Math.max(10,Math.round(100*(P.duration||1)))*l*(!h&&P.isGold?1.5:1)*u):0,U=Y&&!h&&P.isGold?Math.round(Math.max(10,Math.round(100*(P.duration||1)))*c*u):0;g+=_,y+=U,m.push({noteKey:`${P.line??0}-${P.idx??0}`,segments:K,totalAdded:V,completed:Y,completionBonus:_,goldFullBonus:U})}else x=0});const v=[];for(const[P,I]of j.entries()){const A=I.total>0?I.hit/I.total:0;v.push({verseIndex:P,hitFraction:A,label:tl(A),comboBonus:I.comboBonus})}const C={maxCombo:b,currentCombo:0,totalComboBonus:f},T=f+g+y,M=m.length,k=m.filter(P=>P.completed).length,R={hits:M,misses:e.length-M,good:M-k,perfect:k,maxCombo:b};return{classicScore:p,bonusScore:T,totalScore:p+T,perNote:m,combo:C,verseRatings:v,noteStats:R}}function al(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 sl(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function il(e,t,n){const a=al(t,n);if(a<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0};const s=sl(e.classicScore,a),i=Math.round(e.bonusScore/a*1e4);return{...e,classicScore:s,bonusScore:i,totalScore:s+i}}const Cn={maxCombo:0,currentCombo:0,totalComboBonus:0},Ks={hits:0,misses:0,good:0,perfect:0,maxCombo:0};function ol({livePitch:e,uploadedSong:t,isPlaying:n,difficulty:a,players:s,isPadMode:i}){const[o,l]=d.useState(0),[c,u]=d.useState(0),[h,p]=d.useState(0),[g,y]=d.useState([]),[m,x]=d.useState(Cn),[b,f]=d.useState([]),[j,v]=d.useState([]),[C,T]=d.useState({}),[M,k]=d.useState({}),[R,P]=d.useState({}),[I,A]=d.useState({}),[L,E]=d.useState({});return d.useEffect(()=>{if(!t||!n)return;const D=Zn(t.notes.map(U=>U.noteLine),t.bpm??void 0),Z=(t.gap??0)/1e3,G=Za(D,Z),F=Fr(a),q=[];let V=null,K=null,W=null,Q=[];const w={},N={},S={},O={},Y={},_=i?s[0]:s.find(U=>!!U.micId)||s[0];for(let U=0;U<s.length;U++){const $=s[U],H=($==null?void 0:$.id)!=null?e[$.id]||[]:[];if(H.length===0){q.push({id:$.id,name:$.name||`Player ${$.id}`,color:$.color||Xe[U%Xe.length],classicScore:0,bonusScore:0,totalScore:0}),w[$.id]=[],N[$.id]={...Cn},S[$.id]=[],O[$.id]=0,Y[$.id]={...Ks};continue}const X=Ha($.id),re=!!(X!=null&&X.disableGoldNotes),oe=rl(G,H,{semitoneTolerance:F.semitoneTolerance,preWindow:F.preWindow,postExtra:F.postExtra,difficultyMult:F.difficultyMult,disableGoldNotes:re}),se=il(oe,G,re);q.push({id:$.id,name:$.name||`Player ${$.id}`,color:$.color||Xe[U%Xe.length],classicScore:se.classicScore,bonusScore:se.bonusScore,totalScore:se.totalScore}),w[$.id]=Oo(oe.perNote,D,Z),N[$.id]=oe.combo??{...Cn},S[$.id]=oe.verseRatings??[],O[$.id]=se.totalScore,Y[$.id]=oe.noteStats??{...Ks},$.id===(_==null?void 0:_.id)&&(V=se,K=oe.combo??null,W=oe.verseRatings??null,Q=w[$.id])}v(q),T(w),k(N),P(S),A(O),E(Y),V?(l(V.classicScore),u(V.bonusScore),p(V.totalScore),y(Q),x(K??Cn),f(W??[])):(l(0),u(0),p(0),y([]),x(Cn),f([]))},[e,t,n,a,s,i]),{liveScore:o,liveBonusScore:c,liveTotalScore:h,liveSegmentScores:g,liveCombo:m,liveVerseRatings:b,perPlayerScores:j,perPlayerSegmentScores:C,perPlayerCombo:M,perPlayerVerseRatings:R,perPlayerTotalScores:I,perPlayerNoteStats:L}}const Qh=[],Jh=e=>!!e&&/youtu(\.be|be\.com)/i.test(e),ep=({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:u=!0,initiallyActivated:h=!1,showUploader:p=!1,parseSong:g,micAlgorithms:y,defaultPitchAlgorithm:m="pitchy",micRmsThresholds:x,micOffsets:b,micGains:f,micPitchThresholds:j,micSmoothingWindows:v,micHysteresisFrames:C,micUseHanning:T,micMonitorEnabled:M,micMonitorVolumes:k,searchYouTubeByArtistTitle:R,fetchTopSingings:P,onSaveResults:I,rtc:A,onSongChange:L,onPlayingChange:E,onTimeUpdate:D,onEnded:Z,onContinue:G,renderReport:F,t:q,className:V,style:K,id:W,accessMode:Q,"data-testid":w})=>{var _e;const{t:N}=xe(),S=q??N,[O,Y]=d.useState(t??n??null),[_,U]=d.useState(!1),[$,H]=d.useState(0),[X,re]=d.useState(h),[oe,se]=d.useState(!1),[z,ee]=d.useState([]),[ae,ce]=d.useState(""),[le,ne]=d.useState(null),[pe,fe]=d.useState(0),ge=s==="pad",[he,we]=d.useState([]),[je,Pe]=d.useState([]),[$e,Ye]=d.useState([]),[ue,Se]=d.useState([]),Oe=d.useRef(null),Me=d.useRef(null),Ie=d.useRef(null),Qe=d.useRef(!1),Be=d.useRef(0);d.useEffect(()=>{Be.current=$},[$]);const He=d.useRef(t);d.useEffect(()=>{t!==void 0&&t!==He.current&&(He.current=t,Y(t),se(!1),H(0),fe(be=>be+1))},[t]);const Dt=d.useMemo(()=>JSON.stringify(e.map(be=>({id:be.id,micId:be.micId}))),[e]),{livePitch:ct,setLivePitch:ht,recordings:it,remoteLatencyMs:wt}=el({isPlaying:_,gameMode:s,players:e,playersMicKey:Dt,micAlgorithms:y,defaultPitchAlgorithm:m,micRmsThresholds:x,micOffsets:b,micGains:f,micPitchThresholds:j,micSmoothingWindows:v,micHysteresisFrames:C,micUseHanning:T,micMonitorEnabled:M,micMonitorVolumes:k,currentTimeRef:Be,isPadMode:ge,rtc:A}),Je=ol({livePitch:ct,uploadedSong:O,isPlaying:_,difficulty:a,players:e,isPadMode:ge}),Pt=d.useRef(Je);Pt.current=Je;const Jt=d.useMemo(()=>O?Uo(O,s):null,[O,s]),ke=((_e=e[0])==null?void 0:_e.id)??1;d.useEffect(()=>{var Te;if(!ge||!_||!O){(Te=Oe.current)==null||Te.stop(),Oe.current=null,we([]),Pe([]),Ye([]),Se([]);return}const be=new Qo({difficulty:a,noteLines:O.notes.map(Le=>Le.noteLine),bpm:O.bpm??void 0,gap:O.gap??0,onPitch:Le=>{const Ge=Be.current;ht(ze=>{const tt=ze[ke]||[];return{...ze,[ke]:[...tt,{t:Ge,hz:Le}]}})},onHitFeedback:Le=>Se(Ge=>[...Ge.slice(-20),Le]),onLaneActive:Le=>Ye(Le)});return we(be.getLanes()),Pe(be.getEvents()),Ye(new Array(be.getLanes().length).fill(!1)),be.start(()=>Be.current),Oe.current=be,()=>{be.stop(),Oe.current=null}},[ge,_,O,a,ke,ht]);const Ce=d.useCallback(be=>{U(be),E==null||E(be)},[E]),We=d.useCallback(be=>{H(be),D==null||D(be)},[D]),De=d.useCallback(()=>{var Te;try{Xt()}catch{}const be=()=>{re(!0),Qe.current=!0};!ge&&u&&((Te=navigator.mediaDevices)!=null&&Te.getUserMedia)?navigator.mediaDevices.getUserMedia({audio:!0}).then(Le=>Le.getTracks().forEach(Ge=>Ge.stop())).catch(()=>{}).finally(be):be()},[ge,u]);d.useEffect(()=>{if(!X||!Qe.current)return;Qe.current=!1;const be=window.setInterval(()=>{Me.current&&(window.clearInterval(be),Me.current.play())},100),Te=window.setTimeout(()=>window.clearInterval(be),3e3);return()=>{window.clearInterval(be),window.clearTimeout(Te)}},[X]);const Ae=d.useCallback(()=>{se(!0),Z==null||Z();const be=(O==null?void 0:O.id)??0,Te=Pt.current,Le=[];for(const ze of e){const tt=Te.perPlayerTotalScores[ze.id]??0;if(tt<=0)continue;const Ke=Te.perPlayerNoteStats[ze.id];Le.push({playerId:ze.id,songId:be,score:tt,hits:(Ke==null?void 0:Ke.hits)??0,misses:(Ke==null?void 0:Ke.misses)??0,good:(Ke==null?void 0:Ke.good)??0,perfect:(Ke==null?void 0:Ke.perfect)??0,combo:(Ke==null?void 0:Ke.maxCombo)??0})}const Ge=()=>{P&&be>0&&Promise.resolve(P(be)).then(ee).catch(()=>{})};I&&Le.length>0?Promise.resolve(I(Le)).then(Ge).catch(Ge):Ge()},[e,O,I,P,Z]);d.useEffect(()=>{var be;s==="demo"&&_&&$>=12&&((be=Me.current)==null||be.pause(),Ae())},[s,_,$,Ae]),d.useEffect(()=>{if(!O||pe===0||!R||Jh(O.videoPath))return;if(O.youtubeId){const Te=`https://www.youtube.com/watch?v=${O.youtubeId}`;Y(Le=>Le&&{...Le,videoPath:Te});return}if(!O.artist||!O.title)return;let be=!1;return ce(S("karaokeManager.ytSearching","Searching YouTube…")),ne("searching"),Promise.resolve(R(O.artist,O.title)).then(Te=>{if(!be)if(Te){const Le=`https://www.youtube.com/watch?v=${Te}`;Y(Ge=>Ge&&{...Ge,videoPath:Le}),ce(""),ne(null)}else ce(S("karaokeManager.ytNotFound","Not found on YouTube")),ne("error"),window.setTimeout(()=>{be||(ce(""),ne(null))},4e3)}).catch(()=>{be||(ce(S("karaokeManager.ytSearchError","Search error")),ne("error"))}),()=>{be=!0}},[pe,O,R,S]);const Ee=d.useCallback(()=>{var be,Te;se(!1),ht({}),(be=Me.current)==null||be.seekTo(0),(Te=Me.current)==null||Te.play()},[ht]),de=d.useCallback(()=>{se(!1),G==null||G()},[G]),me=d.useCallback(be=>{Y(be),se(!1),H(0),fe(Te=>Te+1),L==null||L(be)},[L]),Re=d.useMemo(()=>{if(!c)return e;const be=e.find(Te=>!!Te.micId)||e[0];return be?[be]:[]},[e,c]),Ne=((O==null?void 0:O.gap)??0)/1e3;return Q==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-manager${V?` ${V}`:""}`,style:{position:"relative",textAlign:"center",minHeight:i,...K},id:W,"data-testid":w,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:[le==="error"?r.jsx(B.NtdClose,{size:16}):r.jsx(B.NtdSearch,{size:16}),ae]}),!O&&p&&r.jsx(qo,{onSongUpload:me,parseSong:g,t:S}),O&&!X&&r.jsxs("button",{type:"button",className:"nice-karaoke-manager__activate",onClick:De,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:ge?r.jsx(B.NtdGamepad,{size:56}):r.jsx(B.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:ge?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.")})]}),O&&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(_o,{tracks:Jt?[Jt]:[],autoPlay:!1,uiMode:"nobuttons",height:i,externalRef:Me,onPlayingChange:Ce,onTimeUpdate:We,onEnded:Ae})}),o&&X&&r.jsx("div",{style:{position:"absolute",inset:0,zIndex:20,pointerEvents:"none"},children:Re.map((be,Te)=>{const Le=ct[be.id]||[],Ge=Ne?Le.map(ze=>({t:ze.t-Ne,hz:ze.hz})):Le;return r.jsx(Eo,{song:O,currentTime:$,playerRef:Ie,userPitch:Ge,segmentScores:Je.perPlayerSegmentScores[be.id],combo:Je.perPlayerCombo[be.id],verseRatings:Je.perPlayerVerseRatings[be.id],config:{playerName:be.name,score:Je.perPlayerTotalScores[be.id]??0,playerBgColor:be.color||Xe[Te%Xe.length],difficultyLevel:a,isPlaying:_,playerCount:Re.length,latencyMs:wt[be.id]??null,top:30+Te*160}},be.id)})}),ge&&he.length>0&&r.jsx(Ho,{lanes:he,events:je,currentTime:$,activeLanes:$e,difficulty:a,feedbackQueue:ue,isPlaying:_}),l&&X&&r.jsx("div",{style:{position:"absolute",bottom:20,left:0,right:0,zIndex:25,pointerEvents:"none"},children:r.jsx(mo,{song:O,currentTime:$})})]}),oe&&Object.keys(it).length>0&&r.jsx(tp,{recordings:it,players:e,t:S}),oe&&r.jsx(Io,{uploadedSong:O,playerScores:Je.perPlayerScores,topSingings:z,onRestart:Ee,onContinue:de,t:S,renderReport:F})]})},tp=({recordings:e,players:t,t:n})=>{const a=d.useMemo(()=>{const s={};for(const[i,o]of Object.entries(e))o&&(s[Number(i)]=URL.createObjectURL(o));return s},[e]);return d.useEffect(()=>()=>{for(const s of Object.values(a))URL.revokeObjectURL(s)},[a]),r.jsxs("div",{style:{margin:"24px auto",maxWidth:640,background:"var(--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(B.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||n("karaokeManager.player","Player {id}").replace("{id}",String(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(B.NtdDownload,{size:13})," ",n("karaokeManager.download","Download")]})]}):r.jsx("span",{style:{opacity:.6},children:n("karaokeManager.noRecording","No recording")})]},s.id))})]})},np=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],ta=Vn;function nr(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 ll(e){const{playerName:t,playerColor:n,songTitle:a,songArtist:s,songBpm:i,difficulty:o,pitchPoints:l,notes:c,verseRatings:u,combo:h,classicScore:p,bonusScore:g,totalScore:y,micSettings:m}=e,x=l.filter(ue=>ue.hz>0),b=x.map(ue=>Lt(ue.hz)),f=[],j=[],v=[...c].sort((ue,Se)=>ue.startTime-Se.startTime);function C(ue){let Se=0,Oe=v.length-1;for(;Se<=Oe;){const Me=Se+Oe>>>1,Ie=v[Me];if(ue<Ie.startTime)Oe=Me-1;else if(ue>Ie.startTime+Ie.duration)Se=Me+1;else return Ie.pitch}return null}const T=[];for(const ue of l){const Se=ue.hz>0?Lt(ue.hz):0,Oe=C(ue.t);T.push({t:ue.t,sung:Se,expected:Oe}),Se>0&&Oe!==null&&f.push(ta(Se,Oe)*100)}const M=T.flatMap(ue=>ue.sung>0&&ue.expected!==null?[ue.sung-ue.expected]:[]).sort((ue,Se)=>ue-Se),k=M.length>0?12*Math.round(nr(M,50)/12):0,R=T.map(ue=>({t:ue.t,sung:ue.sung,expected:ue.expected===null?0:ue.expected+k}));let P=0;for(const ue of v){const Se=ue.startTime-.3,Oe=ue.startTime+ue.duration;for(;P<x.length&&x[P].t<Se;)P++;P<x.length&&x[P].t<=Oe&&j.push((x[P].t-ue.startTime)*1e3)}const I=f.map(Math.abs),A=[...I].sort((ue,Se)=>ue-Se),L=I.length>0?I.reduce((ue,Se)=>ue+Se,0)/I.length:0,E=nr(A,50),D=I.length>1?Math.sqrt(I.reduce((ue,Se)=>ue+(Se-L)**2,0)/(I.length-1)):0,Z=I.filter(ue=>ue<=50).length,G=I.filter(ue=>ue<=15).length,F=I.length>0?Z/I.length*100:0,q=I.length>0?G/I.length*100:0,V=["< −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"],K=new Array(10).fill(0);for(const ue of f){const Se=ue<-100?0:ue<-50?1:ue<-25?2:ue<-15?3:ue<0?4:ue<15?5:ue<25?6:ue<50?7:ue<100?8:9;K[Se]++}const W=V.map((ue,Se)=>({centRange:ue,count:K[Se],pct:f.length>0?K[Se]/f.length*100:0})),Q=x.map(ue=>ue.hz).sort((ue,Se)=>ue-Se),w=Q.length>0?Q[0]:0,N=Q.length>0?Q[Q.length-1]:0,S=w>0?Lt(w):0,O=N>0?Lt(N):0,Y=O-S,_=[...b].sort((ue,Se)=>ue-Se),U=nr(_,10),$=nr(_,90),H=new Array(12).fill(0);for(const ue of b){const Se=Math.round(ue)%12;Se>=0&&Se<12&&H[Se]++}const X=H.reduce((ue,Se)=>ue+Se,0),re=np.map((ue,Se)=>({note:ue,count:H[Se],pct:X>0?H[Se]/X*100:0})),oe=rp(x),se=j.length>0?j.reduce((ue,Se)=>ue+Se,0)/j.length:0,z=j.length>1?Math.sqrt(j.reduce((ue,Se)=>ue+(Se-se)**2,0)/(j.length-1)):0,ee=z>0?Math.max(0,Math.min(100,100-z/2)):100;let ae=0,ce=0;for(let ue=1;ue<b.length;ue++){const Se=Math.abs(b[ue]-b[ue-1]);ae+=Se,ce++}const le=ce>0?ae/ce*100/12:0,ne=l.filter(ue=>ue.hz<=0).length,pe=l.length>0?(1-ne/l.length)*100:0,fe=new Map;for(const ue of c){const Se=ue.line??0;fe.has(Se)||fe.set(Se,[]),fe.get(Se).push(ue)}const ge=new Map;for(const ue of x){const Se=C(ue.t);if(Se===null)continue;let Oe=0,Me=v.length-1,Ie=-1;for(;Oe<=Me;){const Be=Oe+Me>>>1,He=v[Be];if(ue.t<He.startTime)Me=Be-1;else if(ue.t>He.startTime+He.duration)Oe=Be+1;else{Ie=He.line??0;break}}if(Ie<0)continue;const Qe=Math.abs(ta(Lt(ue.hz),Se)*100);ge.has(Ie)||ge.set(Ie,[]),ge.get(Ie).push(Qe)}const he=u.map(ue=>{const Se=fe.get(ue.verseIndex)??[],Oe=ge.get(ue.verseIndex)??[],Me=Oe.length>0?Oe.reduce((Ie,Qe)=>Ie+Qe,0)/Oe.length:0;return{verseIndex:ue.verseIndex,label:ue.label,hitFraction:ue.hitFraction,avgCentDeviation:Math.round(Me*10)/10,noteCount:Se.length,notesHit:Math.round(ue.hitFraction*Se.length),comboBonus:ue.comboBonus}}),we=2,je=.5,Pe=l.length>0?l[l.length-1].t:0,$e=[],Ye=T.flatMap(ue=>ue.sung>0&&ue.expected!==null?[{t:ue.t,hit:Math.abs(ta(ue.sung,ue.expected))<=.5}]:[]);if(Ye.length>0){let ue=0,Se=0,Oe=0;for(let Me=0;Me<=Pe;Me+=je){const Ie=Me-we/2,Qe=Me+we/2;for(;Se<Ye.length&&Ye[Se].t<Qe;)Ye[Se].hit&&Oe++,Se++;for(;ue<Se&&Ye[ue].t<Ie;)Ye[ue].hit&&Oe--,ue++;const Be=Se-ue;$e.push({t:Me,accuracy:Be>0?Oe/Be*100:0})}}else for(let ue=0;ue<=Pe;ue+=je)$e.push({t:ue,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(L*10)/10,medianCentDeviation:Math.round(E*10)/10,stdDevCents:Math.round(D*10)/10,intonationAccuracyPct:Math.round(F*10)/10,perfectHitPct:Math.round(q*10)/10,pitchDeviationHistogram:W,lowestHz:Math.round(w*10)/10,highestHz:Math.round(N*10)/10,lowestNote:S>0?_t(S):"—",highestNote:O>0?_t(O):"—",rangeInSemitones:Math.round(Y*10)/10,tessituraLow:U>0?_t(U):"—",tessituraHigh:$>0?_t($):"—",pitchClassDistribution:re,vibrato:oe,avgOnsetDeviationMs:Math.round(se*10)/10,rhythmStabilityPct:Math.round(ee*10)/10,jitterPct:Math.round(le*100)/100,shimmerProxy:Math.round(pe*10)/10,verseMetrics:he,micSettings:m,pitchOverTime:R,accuracyOverTime:$e}}function rp(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(y=>Lt(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,b=t[o]-m,f=Math.abs(b);for(let C=o+1;C<=y;C++){const T=t[C]-m;T*b<0&&x++,b=T;const M=Math.abs(T);M>f&&(f=M)}const j=n[y]-n[o];if(j<=0)continue;const v=x/2/j;v>=3&&v<=12&&(s.push(v),i.push(f*100))}if(s.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const u=s.reduce((y,m)=>y+m,0)/s.length,h=i.reduce((y,m)=>y+m,0)/i.length,p=Math.sqrt(s.reduce((y,m)=>y+(m-u)**2,0)/s.length),g=Math.max(0,Math.min(100,100-p*20));return{detected:!0,avgRateHz:Math.round(u*10)/10,avgExtentCents:Math.round(h*10)/10,regularityPct:Math.round(g)}}const J={overlay:{position:"fixed",inset:0,background:"var(--nice-overlay-90, rgba(0,0,0,0.92))",display:"flex",alignItems:"flex-start",justifyContent:"center",zIndex:250,color:"var(--nice-text, #e2e8f0)",overflowY:"auto",padding:"24px 12px"},container:{background:"var(--nice-bg, #0f172a)",borderRadius:16,padding:32,width:"min(960px, 95vw)",boxShadow:"0 16px 48px var(--nice-overlay-60, rgba(0,0,0,0.6))",fontFamily:"'Segoe UI', system-ui, -apple-system, sans-serif"},header:{textAlign:"center",marginBottom:24,borderBottom:"2px solid var(--nice-border, #334155)",paddingBottom:20},title:{fontSize:28,fontWeight:800,color:"var(--nice-text, #f1f5f9)",margin:"0 0 4px"},subtitle:{fontSize:14,color:"var(--nice-text-muted, #64748b)",margin:0},sectionTitle:{fontSize:18,fontWeight:700,color:"var(--nice-accent, #38bdf8)",margin:"28px 0 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",paddingBottom:6,display:"flex",alignItems:"center",gap:8},table:{width:"100%",borderCollapse:"collapse",fontSize:13,margin:"8px 0"},th:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"left",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},thRight:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"right",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},td:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-secondary, #cbd5e1)"},tdRight:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",textAlign:"right",color:"var(--nice-text, #e2e8f0)",fontWeight:500},tdBold:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text, #f1f5f9)",fontWeight:700},kpiGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:12,margin:"12px 0"},kpiCard:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:"14px 16px",textAlign:"center",border:"1px solid var(--nice-border, #334155)"},kpiValue:{fontSize:26,fontWeight:800,color:"var(--nice-warning, #fbbf24)"},kpiLabel:{fontSize:11,color:"var(--nice-text-muted, #64748b)",marginTop:2,textTransform:"uppercase",letterSpacing:.8},kpiUnit:{fontSize:13,fontWeight:400,color:"var(--nice-text-muted, #94a3b8)",marginLeft:2},chartWrap:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:16,margin:"12px 0",border:"1px solid var(--nice-border, #334155)"},chartTitle:{fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:8,textAlign:"center"},badge:e=>({display:"inline-block",padding:"2px 10px",borderRadius:20,background:e,color:"#fff",fontSize:12,fontWeight:700}),btnPrimary:{background:"var(--nice-info, #3b82f6)",color:"#fff",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:700,cursor:"pointer"},btnSecondary:{background:"var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:600,cursor:"pointer"},row:{display:"flex",gap:16,flexWrap:"wrap"},half:{flex:"1 1 45%",minWidth:280},footer:{textAlign:"center",marginTop:24,paddingTop:16,borderTop:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #475569)",fontSize:11}};function 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 ap(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 Ht=e=>Math.round(e*10)/10;function Zs(e,t,n){return e.map((a,s)=>({name:a,color:n[s],data:t.map((i,o)=>o===s?Ht(i):0)}))}function Xs(e,t){if(e.length<=t)return e;const n=Math.ceil(e.length/t);return e.filter((a,s)=>s%n===0)}function Qs(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 Js=240,sp=({reports:e,noteCount:t,uploadedSong:n=null,playerScores:a,livePitch:s,liveVerseRatings:i,liveCombo:o,difficulty:l="normal",micSettings:c,onClose:u,t:h,className:p,style:g,id:y,accessMode:m,"data-testid":x})=>{const{t:b}=xe(),f=h??b,j=d.useRef(null),v=d.useMemo(()=>{if(e||!n)return[];const S=Zn(n.notes.map(Y=>Y.noteLine),n.bpm??void 0),O=(n.gap??0)/1e3;return Za(S,O)},[e,n]),C=d.useMemo(()=>e||(!n||!a||!o?[]:a.map(S=>{const O=(s==null?void 0:s[S.id])||[];return ll({playerName:S.name,playerColor:S.color,songTitle:n.title,songArtist:n.artist,songBpm:n.bpm??0,difficulty:l,pitchPoints:O,notes:v,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,v,c]),T=d.useCallback(()=>{var U,$;if(!j.current)return;const S=`<!DOCTYPE html>
|
|
47
|
+
`)})]},W))]})]})}const Ft=1e4,Us=5e3;function ea(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 Sh=["var(--nice-warning, #facc15)","var(--nice-text-secondary, #cbd5e1)","var(--nice-warning, #d97706)"],kh=({entry:e,rank:t,animDelay:n})=>{const[a,s]=d.useState(0),[i,o]=d.useState(0),[l,c]=d.useState(0),[u,h]=d.useState(0),p=Math.min(e.classicScore,Ft),g=Math.min(e.bonusScore,Ft),y=p/Ft*Us,m=g>0?g/Ft*Us:0;return d.useEffect(()=>{let x,b=null;const f=Math.max(y,400),j=Math.max(m,m>0?300:0),v=C=>{b===null&&(b=C);const T=C-b-n;if(T<0){x=requestAnimationFrame(v);return}if(T<=f){const M=Math.min(1,T/f),k=1-Math.pow(1-M,3);s(Math.min(k*(p/Ft)*100,100)),c(Math.round(k*e.classicScore)),x=requestAnimationFrame(v);return}if(s(Math.min(p/Ft*100,100)),c(e.classicScore),j>0){const M=T-f;if(M<=j){const k=Math.min(1,M/j),R=1-Math.pow(1-k,3);o(Math.min(R*(g/Ft)*100,100)),h(Math.round(R*e.bonusScore)),x=requestAnimationFrame(v);return}o(Math.min(g/Ft*100,100)),h(e.bonusScore)}};return x=requestAnimationFrame(v),()=>cancelAnimationFrame(x)},[e.classicScore,e.bonusScore,p,g,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(B.NtdMedal,{size:18,primaryColor:Sh[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:ea(e.color,.45)}}),r.jsx("div",{className:"nice-karaoke-summary__bar-fill-classic",style:{width:`${a}%`,background:`linear-gradient(90deg, ${e.color}, ${ea(e.color,.15)})`,boxShadow:`0 0 8px ${e.color}55`}}),r.jsxs("div",{className:"nice-karaoke-summary__bar-text",children:[l.toLocaleString(),u>0&&r.jsxs("span",{className:"nice-karaoke-summary__bar-text-bonus",style:{color:ea(e.color,.5)},children:["+",u.toLocaleString()]})]})]}),r.jsx("span",{className:"nice-karaoke-summary__bar-total",children:(l+u).toLocaleString()})]})},Vs=({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(B.NtdCircle,{size:8})," "]}),s.name]}),r.jsx("td",{className:"nice-karaoke-summary__rank-score",children:s.score.toLocaleString()})]},`${s.name}-${i}`)})})})]}),Lo=({uploadedSong:e,playerScores:t,topSingings:n,onRestart:a,onContinue:s,t:i,renderReport:o,className:l,style:c,id:u,accessMode:h,"data-testid":p})=>{const[g,y]=d.useState(!1),m=d.useMemo(()=>[...t].sort((C,T)=>T.totalScore-C.totalScore),[t]),x=d.useMemo(()=>{const C=new Map;for(const T of t)C.set(T.name,T.color);return C},[t]),b=d.useMemo(()=>new Set(t.map(C=>C.name)),[t]),f=d.useMemo(()=>m.map((C,T)=>({rank:T+1,name:C.name,score:C.totalScore,color:C.color})),[m]),j=d.useMemo(()=>{const C=n.map(M=>({name:M.playerName,score:M.score})),T=new Set;for(const M of m)T.has(M.id)||(T.add(M.id),C.push({name:M.name,score:M.totalScore}));return C.sort((M,k)=>k.score-M.score),C.slice(0,10).map((M,k)=>({rank:k+1,name:M.name,score:M.score}))},[n,m]),v=e?e.artist?`${e.artist} — ${e.title}`:e.title:i("karaokeSummary.unknownSong","Unknown song");return h==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-summary ${l??""}`,style:c,id:u,"data-testid":p,children:[r.jsxs("div",{className:"nice-karaoke-summary__card",children:[r.jsx("h1",{className:"nice-karaoke-summary__title",children:v}),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((C,T)=>r.jsx(kh,{entry:C,rank:T+1,animDelay:T*300},C.id))}),(m.length>1||n.length>0)&&r.jsxs("div",{className:"nice-karaoke-summary__ranks",children:[m.length>1&&r.jsx(Vs,{title:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(B.NtdHome,{size:14})," ",i("karaokeSummary.localRanking","Session ranking")]}),entries:f,highlightNames:b,playerColorMap:x}),n.length>0&&r.jsx(Vs,{title:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(B.NtdTrophy,{size:14})," ",i("karaokeSummary.globalRanking","Top 10")]}),entries:j,highlightNames:b,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(B.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)))]})},wh=st.scoped("GenericPlayer"),Ch=e=>/youtu(\.be|be\.com)/i.test(e),_o=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),jh=e=>!!e&&/\.(mp3|aac|m4a|flac|wav|ogg)(\?.*)?$/i.test(e),Mh=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&&Ch(o.url)))??null;if(n)return n;const a=t("hls")||e.sources.find(o=>o.url&&_o(o.url))||null;if(a)return a;const s=t("audio")||e.sources.find(o=>o.url&&jh(o.url))||null;return s||(e.sources[0]??null)},_r=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")}`},Rh=[.25,.5,.75,1,1.25,1.5,1.75,2],Do=({tracks:e=[],initialIndex:t=0,autoPlay:n=!0,countdownSeconds:a=0,height:s=360,onIndexChange:i,onPlayingChange:o,onTimeUpdate:l,externalRef:c,uiMode:u="full",compactNextCount:h=3,progressBarPosition:p="inline",loop:g=!1,onEnded:y,enableKeyboardShortcuts:m=!0,shuffle:x=!1,repeatMode:b="none",playbackSpeed:f=1,abLoop:j=null,onRepeatModeChange:v,onShuffleChange:C,onSpeedChange:T,sleepTimer:M=0,onSleepTimerExpired:k})=>{const{t:R}=xe(),{t:P}=xe(),[I,A]=d.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),L=e[I],E=d.useMemo(()=>Mh(L),[L]),D=(L==null?void 0:L.startOffset)??0,[Z,G]=d.useState(!1),[F,q]=d.useState(0),[V,K]=d.useState(0),[W,Q]=d.useState(.9),[w,N]=d.useState(null),[S,O]=d.useState(null),Y=d.useRef(null),[_,U]=d.useState(x),[$,H]=d.useState(b),[X,re]=d.useState(f),[oe,se]=d.useState(j),[z,ee]=d.useState([]),[ae,ce]=d.useState(M>0?M*60:null),le=d.useRef(null),[ne,pe]=d.useState(()=>Ii()),fe=d.useRef(null),ge=d.useRef(null),he=d.useRef(null),we=d.useRef(null);d.useEffect(()=>{if(_&&e.length>0){const de=Array.from({length:e.length},(me,Re)=>Re);for(let me=de.length-1;me>0;me--){const Re=Math.floor(Math.random()*(me+1));[de[me],de[Re]]=[de[Re],de[me]]}ee(de)}},[_,e.length]);const je=d.useRef(k);je.current=k,d.useEffect(()=>(le.current&&(window.clearInterval(le.current),le.current=null),M>0&&Z&&(ce(M*60),le.current=window.setInterval(()=>{ce(de=>{var me;return!de||de<=1?(le.current&&window.clearInterval(le.current),le.current=null,(me=je.current)==null||me.call(je),null):de-1})},1e3)),()=>{le.current&&window.clearInterval(le.current)}),[M,Z]);const Pe=d.useCallback(de=>{const me=Math.min(Math.max(0,de),Math.max(0,e.length-1));A(me),i==null||i(me)},[e.length,i]),$e=d.useCallback(()=>{if(_&&z.length>0){const me=z.indexOf(I)+1;return me<z.length?z[me]:$==="all"?z[0]:-1}return I<e.length-1?I+1:$==="all"?0:-1},[I,e.length,_,z,$]),Ye=d.useCallback(()=>{if(_&&z.length>0){const de=z.indexOf(I);return de>0?z[de-1]:$==="all"?z[z.length-1]:-1}return I>0?I-1:$==="all"?e.length-1:-1},[I,e.length,_,z,$]),ue=d.useCallback(()=>{const de=$e();de>=0&&Pe(de)},[$e,Pe]),Se=d.useCallback(async()=>{var de,me;await Xt(),pe(!0),(E==null?void 0:E.kind)==="youtube"?(de=fe.current)==null||de.playVideo():(me=ge.current)==null||me.play(),G(!0),o==null||o(!0)},[E,o]),Oe=d.useCallback(()=>{var de,me;(E==null?void 0:E.kind)==="youtube"?(de=fe.current)==null||de.pauseVideo():(me=ge.current)==null||me.pause(),G(!1),o==null||o(!1)},[E,o]),Me=d.useCallback(()=>Z?Oe():Se(),[Z,Se,Oe]),Ie=d.useCallback(de=>{var Ne;const me=de+D;(E==null?void 0:E.kind)==="youtube"?(Ne=fe.current)==null||Ne.seekTo(me,!0):ge.current&&(ge.current.currentTime=me);const Re=Math.max(0,de);K(Re),l==null||l(Re)},[E==null?void 0:E.kind,l,D]),Qe=d.useCallback(()=>{if(V>3){Ie(0);return}const de=Ye();de>=0&&Pe(de)},[Ye,Pe,V,Ie]),Be=d.useCallback(de=>{var me,Re;Q(de),N(null),(E==null?void 0:E.kind)==="youtube"?(Re=(me=fe.current)==null?void 0:me.setVolume)==null||Re.call(me,Math.round(de*100)):ge.current&&(ge.current.volume=de)},[E]),He=d.useCallback(()=>{w!==null?Be(w):(N(W),Be(0))},[W,w,Be]),Dt=d.useCallback(de=>{var me,Re;re(de),ge.current&&(ge.current.playbackRate=de),(E==null?void 0:E.kind)==="youtube"&&((Re=(me=fe.current)==null?void 0:me.setPlaybackRate)==null||Re.call(me,de)),T==null||T(de)},[E,T]),ct=d.useCallback(()=>{const de=["none","all","one"],me=de[(de.indexOf($)+1)%de.length];H(me),v==null||v(me)},[$,v]),ht=d.useCallback(()=>{const de=!_;U(de),C==null||C(de)},[_,C]),it=d.useCallback(de=>{se(de)},[]);d.useImperativeHandle(c,()=>({play:Se,pause:Oe,toggle:Me,seekTo:Ie,setVolume:Be,setSpeed:Dt,setRepeatMode:de=>{H(de),v==null||v(de)},toggleShuffle:ht,setABLoop:it,getUnderlyingPlayer:()=>(E==null?void 0:E.kind)==="youtube"?fe.current:(E==null?void 0:E.kind)==="hls"||(E==null?void 0:E.kind)==="audio"?ge.current:null}),[Se,Oe,Me,Ie,Be,Dt,v,ht,it,E==null?void 0:E.kind]),d.useEffect(()=>{const de=window.setInterval(()=>{let me=0,Re=0;(E==null?void 0:E.kind)==="youtube"&&fe.current?(me=fe.current.getCurrentTime()||0,Re=fe.current.getDuration()||0):ge.current&&(me=ge.current.currentTime||0,Re=ge.current.duration||0);const Ne=Math.max(0,me-D);K(Ne),q(Re),l==null||l(Ne),oe&&Ne>=oe.b&&Ie(oe.a)},100);return()=>window.clearInterval(de)},[E==null?void 0:E.kind,l,oe,D,Ie]),d.useEffect(()=>()=>{Y.current&&(window.clearInterval(Y.current),Y.current=null)},[]);const kt=E==null?void 0:E.url,Je=E==null?void 0:E.kind,Tt=E==null?void 0:E.withCredentials,Jt=JSON.stringify((E==null?void 0:E.headers)??null),ke=d.useRef(W);ke.current=W;const Ce=d.useRef(a);Ce.current=a;const We=d.useRef(o);We.current=o,d.useEffect(()=>{if(he.current){try{he.current.destroy()}catch{}he.current=null}if(ge.current&&(ge.current.volume=ke.current,ge.current.crossOrigin=Tt?"use-credentials":"anonymous"),Je==="hls"&&_o(kt)){const de=ge.current;if(!de)return;const me=()=>{de.src=kt,de.load();try{D&&!isNaN(D)&&(de.currentTime=D)}catch{}n&&de.play().catch(()=>{})};de.canPlayType("application/vnd.apple.mpegurl")?me():(async()=>{var Re;try{const _e=(await import("hls.js")).default;if((Re=_e==null?void 0:_e.isSupported)!=null&&Re.call(_e)){const be=JSON.parse(Jt),Te=new _e({xhrSetup:Le=>{if(Tt&&(Le.withCredentials=!0),be)for(const[Ge,ze]of Object.entries(be))try{Le.setRequestHeader(Ge,ze)}catch{}}});he.current=Te,Te.loadSource(kt),Te.attachMedia(de),Te.on(_e.Events.MANIFEST_PARSED,()=>{n&&de.play().catch(()=>{})})}else me()}catch(Ne){wh.debug("HLS.js setup failed, falling back to native playback",Ne),me()}})()}else if(Je==="audio"&&kt&&ge.current){const de=ge.current;de.src=kt,de.load();try{D&&!isNaN(D)&&(de.currentTime=D)}catch{}n&&de.play().catch(()=>{})}Y.current&&(window.clearInterval(Y.current),Y.current=null),O(null),K(0),q(0),n&&Je==="youtube"&&Ce.current>0?(O(Ce.current),Y.current=window.setInterval(()=>{O(de=>{var me,Re;if(!de)return null;if(de<=1){Y.current&&(window.clearInterval(Y.current),Y.current=null);try{(me=fe.current)==null||me.playVideo()}catch{}return G(!0),(Re=We.current)==null||Re.call(We,!0),null}return de-1})},1e3)):G(!!n)},[kt,Je,Tt,Jt,D,n]);const De=d.useCallback(()=>{if($==="one"){Ie(0),Se();return}const de=$e();de>=0?Pe(de):(G(!1),o==null||o(!1),Ie(0),y==null||y())},[$,$e,Pe,o,Ie,y,Se]);d.useEffect(()=>{if(!m)return;const de=me=>{var _e;const Re=me.target instanceof HTMLElement?me.target:document.body;if(Re.tagName==="INPUT"||Re.tagName==="TEXTAREA"||Re.isContentEditable||Re!==document.body&&!((_e=we.current)!=null&&_e.contains(Re))||me.key===" "&&Re.closest('button, a[href], [role="button"], [role="slider"], [role="menuitem"]')||me.key.startsWith("Arrow")&&Re.closest('[role="slider"], [role="listbox"], [role="menu"]'))return;const Ne=me.niceSource;if(!(me.key.startsWith("Arrow")&&Ne&&Ne!=="keyboard"&&Re!==document.body&&Re!==we.current))switch(me.key){case" ":me.preventDefault(),Me();break;case"ArrowRight":me.preventDefault(),Ie(Math.min(V+5,F));break;case"ArrowLeft":me.preventDefault(),Ie(Math.max(0,V-5));break;case"ArrowUp":me.preventDefault(),Be(Math.min(1,W+.05));break;case"ArrowDown":me.preventDefault(),Be(Math.max(0,W-.05));break;case"m":case"M":He();break;case"n":case"N":ue();break;case"p":case"P":Qe();break;case"r":case"R":ct();break;case"s":case"S":ht();break}};return document.addEventListener("keydown",de),()=>document.removeEventListener("keydown",de)},[m,Me,Ie,V,F,Be,W,He,ue,Qe,ct,ht]);const Ae=(E==null?void 0:E.kind)==="youtube"||u==="full"||u==="nobuttons",Ee=h>0?e.slice(I+1,I+1+h):[];return r.jsxs("div",{ref:we,className:"gp-player",style:{display:"grid",gap:12,color:"var(--nice-text-primary)",accentColor:"var(--nice-color-primary)"},tabIndex:-1,children:[n&&!ne&&r.jsx("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,className:"gp-audio-activation",onClick:()=>{pe(!0),Se()},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:"var(--nice-color-white, #fff)",fontSize:24},children:R("player.clickToActivateAudio","Click to activate audio")})}),Ae&&r.jsxs("div",{className:"gp-stage",style:{width:"100%",height:s,background:(E==null?void 0:E.kind)==="youtube"?"transparent":"var(--player-bg, color-mix(in srgb, var(--nice-color-primary, #3b82f6) 14%, var(--nice-color-black, #000)))",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(E==null?void 0:E.kind)==="youtube"&&r.jsx(Aa,{videoId:E.videoId??Ah(E.url),onReady:de=>{fe.current=de.target,Be(W);const me=(L==null?void 0:L.startOffset)??0;try{me&&de.target.seekTo(me,!0)}catch{}if(u==="nobuttons"){try{de.target.playVideo()}catch{}G(!0)}},onEnd:De,opts:{width:"100%",height:"100%",playerVars:{autoplay:n||u==="nobuttons"?1:0,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,loop:g?1:0}},style:{width:"100%",height:"100%"}}),S!==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:"var(--nice-color-white, #fff)",fontSize:72,fontWeight:"bold"},children:S})}),u==="nobuttons"&&r.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"auto",zIndex:100,cursor:"default"}}),((E==null?void 0:E.kind)==="audio"||(E==null?void 0:E.kind)==="hls")&&r.jsxs(r.Fragment,{children:[u==="full"&&r.jsx("div",{style:{textAlign:"center",color:"var(--nice-overlay-light-90, rgba(255, 255, 255, 0.9))"},children:L!=null&&L.coverUrl?r.jsx("img",{alt:"cover",src:L.coverUrl,style:{height:s-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[L==null?void 0:L.artist," — ",L==null?void 0:L.title]}),r.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--nice-text-secondary, #64748b)"},children:(E==null?void 0:E.label)??`${(E==null?void 0:E.codec)??""} ${(E==null?void 0:E.quality)??""}`.trim()})]})}),r.jsx("audio",{ref:ge,onEnded:De,onLoadedMetadata:()=>{const de=ge.current;de&&q(de.duration||0)},crossOrigin:E!=null&&E.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]})]}),(u==="minimal"||u==="compact")&&r.jsx("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:r.jsxs("div",{children:[r.jsx("div",{style:{fontWeight:600},children:(L==null?void 0:L.title)??""}),r.jsx("div",{style:{color:"var(--nice-text-secondary, #64748b)",fontSize:13},children:(L==null?void 0:L.artist)??""})]})}),u==="full"&&r.jsxs(r.Fragment,{children:[r.jsx(zo,{currentTime:V,duration:F}),r.jsx(Nh,{isPlaying:Z,index:I,count:e.length,currentTime:V,duration:F,volume:W,onPrev:Qe,onNext:ue,onToggle:Me,onSeek:Ie,onVolume:Be}),r.jsx($h,{shuffleOn:_,repeatMode:$,speed:X,abLoop:oe,currentTime:V,sleepRemaining:ae,onToggleShuffle:ht,onCycleRepeat:ct,onSpeedChange:Dt,onSetABLoop:it,onMuteToggle:He,isMuted:w!==null})]}),u==="progressOnly"&&r.jsx("div",{style:p==="fixedBottom"?{position:"fixed",left:0,right:0,bottom:0,padding:"8px 12px",background:"var(--nice-overlay-90, rgba(15, 23, 42, 0.9))",backdropFilter:"blur(2px)",zIndex:1e3}:{},children:r.jsx(Th,{currentTime:V,duration:F,onSeek:Ie})}),(u==="minimal"||u==="compact")&&r.jsx(Ph,{isPlaying:Z,canPrev:I>0,canNext:I<e.length-1,onPrev:Qe,onNext:ue,onToggle:Me}),u==="compact"&&Ee.length>0&&r.jsx(Eh,{items:Ee,onSelect:de=>Pe(I+1+de)}),u==="nobuttons"&&r.jsx(r.Fragment,{}),u==="full"&&e.length>0&&r.jsx("div",{className:"gp-list",style:{display:"grid",gap:4},children:e.map((de,me)=>r.jsxs("button",{onClick:()=>Pe(me),style:{textAlign:"left",border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"8px 10px",background:me===I?"color-mix(in srgb, var(--nice-color-primary) 14%, transparent)":"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},title:de.sources.map(Re=>Re.kind).join(", "),children:[r.jsx("div",{style:{fontWeight:600},children:de.title}),r.jsx("div",{style:{color:"var(--nice-text-secondary)",fontSize:12},children:de.artist})]},de.id))})]})},_t={border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center"},nr=e=>({..._t,color:e?"var(--nice-color-primary)":"var(--nice-text-secondary)",borderColor:e?"var(--nice-color-primary)":"var(--nice-border-color)",fontWeight:e?700:400}),zo=({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:[_r(e)," / ",_r(t)]})]}),Nh=({isPlaying:e,index:t,count:n,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek:u,onVolume:h})=>{const{t:p}=xe();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:_t,children:r.jsx(B.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:_t,children:e?r.jsx(B.NtdPause,{size:16}):r.jsx(B.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:_t,children:r.jsx(B.NtdSkipForward,{size:16})})]}),r.jsx("input",{type:"range",min:0,max:Math.max(1,s),step:.1,value:a,onChange:g=>u(parseFloat(g.target.value)),"aria-label":p("player.seekPosition","Seek position")}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx(B.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")})]})]})},Th=({currentTime:e,duration:t,onSeek:n})=>{const{t:a}=xe();return r.jsxs(r.Fragment,{children:[r.jsx(zo,{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")})]})},Ph=({isPlaying:e,canPrev:t,canNext:n,onPrev:a,onNext:s,onToggle:i})=>{const{t:o}=xe();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:_t,children:r.jsx(B.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:_t,children:e?r.jsx(B.NtdPause,{size:16}):r.jsx(B.NtdPlay,{size:16})}),r.jsx("button",{onClick:s,disabled:!n,title:o("player.nextTrack","Next track"),"aria-label":o("player.nextTrack","Next track"),style:_t,children:r.jsx(B.NtdSkipForward,{size:16})})]})},Eh=({items:e,onSelect:t})=>{const{t:n}=xe();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))})]})},$h=({shuffleOn:e,repeatMode:t,speed:n,abLoop:a,currentTime:s,sleepRemaining:i,onToggleShuffle:o,onCycleRepeat:l,onSpeedChange:c,onSetABLoop:u,onMuteToggle:h,isMuted:p})=>{const{t:g}=xe(),y={none:g("player.off","Off"),all:g("player.all","All"),one:g("player.one","One")},m=t==="one"?r.jsxs("span",{style:{position:"relative",display:"inline-flex"},children:[r.jsx(B.NtdRepeat,{size:16}),r.jsx("span",{style:{position:"absolute",right:-3,bottom:-3,fontSize:8,fontWeight:700},children:"1"})]}):t==="all"?r.jsx(B.NtdRepeat,{size:16}):r.jsx(B.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"),"aria-pressed":e,style:nr(e),children:r.jsx(B.NtdShuffle,{size:16})}),r.jsx("button",{onClick:l,title:`${g("player.repeat","Repeat")}: ${y[t]}`,"aria-label":`${g("player.repeat","Repeat")}: ${y[t]}`,style:nr(t!=="none"),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:{..._t,minWidth:56,fontSize:12},children:Rh.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"),"aria-pressed":p,style:nr(p),children:p?r.jsx(B.NtdVolumeMute,{size:16}):r.jsx(B.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: ",_r(a.a)," — B: ",_r(a.b)]}),r.jsx("button",{onClick:()=>u(null),title:g("player.clearLoop","Clear loop"),style:{..._t,fontSize:11,padding:"2px 6px"},children:r.jsx(B.NtdClose,{size:12})})]}):r.jsx("button",{onClick:()=>u({a:s,b:s+10}),title:g("player.abLoop","A-B Loop"),"aria-label":g("player.setAbLoop","Set A-B Loop"),style:nr(!1),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(B.NtdMoon,{size:12})," ",Math.floor(i/60),":",(i%60).toString().padStart(2,"0")]})]})};function Ah(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 Fo(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 Ih(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 Lh(e,t="/backgrounds"){return e.backgroundImage?`${t}/${e.backgroundImage}`:""}function Oo(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 Xa(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 Bo(e,t,n){const a=[];return e.forEach(s=>{var c;const[i,o]=s.noteKey.split("-").map(Number),l=(c=t[i])==null?void 0:c[o];l&&s.segments.forEach(u=>{a.push({start:u.visualStart-n,end:u.visualEnd-n,pitch:l.pitch,frac:u.frac,isGold:l.isGold,noteStart:l.startTime,noteEnd:l.startTime+l.duration})})}),a}function Go(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 Wo(e,t,n){const s=Date.parse(e)-n;return Math.max(0,Math.round(t-s))}const Uo={crepe:"var(--nice-accent, #a78bfa)",librosa:"var(--nice-success-light, #34d399)",pitchy:"var(--nice-primary-light, #60a5fa)",autocorr:"var(--nice-text-secondary, #555555)"};function _h(e){return e==="autocorr"?"Ultrastar":e.charAt(0).toUpperCase()+e.slice(1)}function Dh(e){return Uo[e]??"var(--nice-text-secondary, #555555)"}function zh(e){const t=Uo[e]??"var(--nice-text-secondary, #555555)";return`var(--algo-${e}, ${t})`}function Vo(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=Fo(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 Fh(e){const t=e.videoPath??e.video??void 0;return{id:e.id,title:e.title??"",artist:e.artist??"",year:e.year,genre:e.genre,language:e.language,filePath:e.filePath,coverPath:e.coverPath,audioPath:e.audioPath??e.audio??void 0,videoPath:t,format:0,notes:e.notes??[],gap:e.gap,bpm:e.bpm,videoGap:e.videoGap,start:e.start,end:e.end,youtubeId:e.youtubeId,instrumentalPath:e.instrumentalPath,isVerified:e.isVerified,coverImage:e.coverImage,backgroundImage:e.backgroundImage}}var Qa=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(Qa||{});function qo(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:Qa.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 Oh=e=>window.btoa(unescape(encodeURIComponent(e))),Ho=({onSongUpload:e,parseSong:t,onError:n,accept:a=".txt",maxFileSize:s=5*1024*1024,t:i})=>{const{t:o}=xe(),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:Oh(y)}):qo(y,h.name);e(x)}catch(x){n==null||n(x)}},p.readAsText(h,"UTF-8")},u=h=>/\.txt$/i.test(h.name)?h.size===0?l("karaokeUploader.empty","The file is empty."):null:l("karaokeUploader.notTxt","Please choose an UltraStar .txt file.");return r.jsx("div",{className:"nice-karaoke-uploader",children:r.jsx(ie.NiceUpload,{accept:a,maxFileSize:s,validateFile:u,multiple:!1,text:l("karaokeUploader.dropPrompt","Click or drag & drop an UltraStar file (.txt)"),onFilesSelected:h=>{const p=h[0];p&&c(p)}})})},Bh=[],Gh=[],Wh=[],Uh=[];function Vh(e,t,n,a,s){const o=a*.45;e.beginPath();for(let l=0;l<10;l++){const c=l%2===0?a:o,u=Math.PI/5*l-Math.PI/2,h=t+Math.cos(u)*c,p=n+Math.sin(u)*c;l===0?e.moveTo(h,p):e.lineTo(h,p)}e.closePath(),e.fillStyle=s,e.fill()}const qt=60,qs=4,ta="#888",Hs=["A","B","X","Y","LB","RB","LT","RT"],Ko=({lanes:e=Bh,events:t=Gh,currentTime:n,activeLanes:a=Wh,difficulty:s,feedbackQueue:i=Uh,isPlaying:o,height:l=300})=>{const{t:c}=xe(),u=e.length,h=d.useRef(null),p=d.useRef([]);return d.useEffect(()=>{p.current=i},[i]),d.useEffect(()=>{var T,M;const g=h.current;if(!g)return;const y=g.getContext("2d");if(!y)return;const m=window.devicePixelRatio||1,x=g.clientWidth,b=g.clientHeight;if(g.width=x*m,g.height=b*m,y.scale(m,m),y.clearRect(0,0,x,b),u===0)return;const f=x/u;for(let k=0;k<u;k++){const R=k*f;y.fillStyle=k%2===0?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",y.fillRect(R,0,f,b),k>0&&(y.strokeStyle="rgba(255,255,255,0.1)",y.lineWidth=1,y.beginPath(),y.moveTo(R,0),y.lineTo(R,b),y.stroke())}const j=b-qt-10;y.strokeStyle="rgba(255,255,255,0.4)",y.lineWidth=2,y.setLineDash([8,4]),y.beginPath(),y.moveTo(0,j),y.lineTo(x,j),y.stroke(),y.setLineDash([]);const v=e.map(k=>ve.resolveCssColor((k==null?void 0:k.color)??ta,g)),C=(b-qt-20)/qs;for(const k of t){const R=k.note.startTime,P=R+k.note.duration,I=R-n;if(I>qs||P<n-.5)continue;const A=k.lane,L=A*f+4,E=f-8,D=j-I*C,Z=k.note.duration*C,G=n>=R-.15&&n<=P+.15,F=n>P+.15,q=v[A]??ta;F?y.fillStyle="rgba(100,100,100,0.3)":G?(y.fillStyle=q,y.shadowColor=q,y.shadowBlur=12):(y.fillStyle=q,y.globalAlpha=.6);const V=Math.max(Z,8),K=6;y.beginPath(),y.moveTo(L+K,D),y.lineTo(L+E-K,D),y.quadraticCurveTo(L+E,D,L+E,D+K),y.lineTo(L+E,D+V-K),y.quadraticCurveTo(L+E,D+V,L+E-K,D+V),y.lineTo(L+K,D+V),y.quadraticCurveTo(L,D+V,L,D+V-K),y.lineTo(L,D+K),y.quadraticCurveTo(L,D,L+K,D),y.fill(),y.globalAlpha=1,y.shadowBlur=0,k.note.isGold&&Vh(y,L+E/2,D+V/2,Math.min(7,E/4),"#fbbf24")}for(let k=0;k<u;k++){const R=k*f,P=b-qt,I=a[k],A=v[k]??ta;y.fillStyle=I?A:"rgba(30,30,30,0.9)",y.fillRect(R+2,P+2,f-4,qt-4),y.strokeStyle=I?"#fff":A,y.lineWidth=I?3:1,y.strokeRect(R+2,P+2,f-4,qt-4),y.fillStyle=I?"#000":"#fff",y.font=`bold ${Math.min(24,f*.3)}px monospace`,y.textAlign="center",y.textBaseline="middle",y.fillText(((T=e[k])==null?void 0:T.label)??"",R+f/2,P+qt/2);const L=((M=e[k])==null?void 0:M.gamepadButton)??-1;L>=0&&L<Hs.length&&(y.fillStyle=I?"rgba(0,0,0,0.6)":"rgba(255,255,255,0.4)",y.font="10px sans-serif",y.fillText(Hs[L],R+f/2,P+qt-8))}for(const k of p.current){const R=n-k.time;if(R<0||R>.8)continue;const P=Math.max(0,1-R/.8),I=k.lane*f;y.save(),y.globalAlpha=P,y.font="bold 20px sans-serif",y.textAlign="center",y.textBaseline="bottom",y.fillStyle=k.type==="perfect"?"#10b981":k.type==="good"?"#f59e0b":"#ef4444";const A=k.type==="perfect"?c("padKaraokeOverlay.perfect","PERFECT"):k.type==="good"?c("padKaraokeOverlay.good","GOOD"):c("padKaraokeOverlay.miss","MISS");y.fillText(A,I+f/2,j-10-R*40),y.restore()}},[n,e,t,a,u,o,c]),!o||u===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(B.NtdGamepad,{size:14})," ",c("padKaraokeOverlay.pad","PAD — {difficulty}").replace("{difficulty}",String(s))]})]})},_n=["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)"],Yo={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 ba(e){return 440*Math.pow(2,(e-69)/12)}function Zo(e,t){const n=Yo[t],a=n.keys.length,s=[];for(const u of e)for(const h of u)s.includes(h.pitch)||s.push(h.pitch);if(s.sort((u,h)=>u-h),s.length===0)return n.keys.map((u,h)=>({index:h,key:u,gamepadButton:n.buttons[h],label:n.labels[h],minPitch:-999,maxPitch:999,color:_n[h%_n.length]}));const i=s[0],l=s[s.length-1]-i+1,c=[];for(let u=0;u<a;u++){const h=i+Math.floor(l*u/a),p=i+Math.floor(l*(u+1)/a)-1;c.push({index:u,key:n.keys[u],gamepadButton:n.buttons[u],label:n.labels[u],minPitch:u===0?-999:h,maxPitch:u===a-1?999:p,color:_n[u%_n.length]})}return c}function Xo(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 Qo(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:Xo(o.pitch,t),lineIndex:s,noteIndex:i})}return a.sort((s,i)=>s.note.startTime-i.note.startTime),a}class Jo{constructor(t){this.lanes=[],this.events=[],this.raf=null,this.keysDown=new Set,this.gamepadButtonsDown=new Set,this.running=!1,this.getCurrentTime=()=>0,this.lastFeedbackTime=0,this.lastActiveNote=null,this.preWindow=.15,this.postWindow=.15,this.loop=()=>{var c,u,h,p,g,y,m,x;if(!this.running)return;const s=this.getCurrentTime();this.pollGamepad();const i=this.getActiveLanes();(u=(c=this.config).onLaneActive)==null||u.call(c,i);const o=this.findActiveNote(s);if(o!==this.lastActiveNote&&(this.lastActiveNote=o,(p=(h=this.config).onCurrentNote)==null||p.call(h,o)),i.some(Boolean)&&o){const b=o.lane,f=i.indexOf(!0);if(i[b]){const j=ba(o.note.pitch);this.config.onPitch(j),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(y=(g=this.config).onHitFeedback)==null||y.call(g,{type:"perfect",lane:b,time:s}))}else if(f>=0){const v=Math.abs(f-b)*3,C=ba(o.note.pitch+v);this.config.onPitch(C),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=Zn(t.noteLines,t.bpm),a=(t.gap??0)/1e3;switch(this.lanes=Zo(n,t.difficulty),this.events=Qo(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 n;const t=ve.getInputEngine().gamepadSnapshot[0];if(t){this.gamepadButtonsDown.clear();for(let a=0;a<t.buttons.length;a++)(n=t.buttons[a])!=null&&n.pressed&&this.gamepadButtonsDown.add(a)}}getActiveLanes(){const t=new Array(this.lanes.length).fill(!1);for(const n of this.lanes)(this.keysDown.has(n.key)||this.gamepadButtonsDown.has(n.gamepadButton))&&(t[n.index]=!0);return t}findActiveNote(t){for(const n of this.events){const 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 ft=st.scoped("BaseStreamClient");function Ks(e,t,n){if(t===n)return e.slice();const a=Math.round(e.length*n/t),s=new Float32Array(a),i=e.length/a;for(let o=0;o<a;o++){const l=o*i,c=Math.floor(l),u=Math.min(e.length-1,c+1),h=l-c;s[o]=e[c]*(1-h)+e[u]*h}return s}function qh(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 wn=16e3,Hh="/scripts/pitch-worklet.js";class el{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 Hh}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,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,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(u){(o=(i=this.opts).onError)==null||o.call(i,u);break}}finally{this.sendQueue=[]}ft.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(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 n,a;ft.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,b,f,j,v;const n=new Float32Array(this.buffer.length+t.length);n.set(this.buffer,0),n.set(t,this.buffer.length),this.buffer=n;const a=this.audioCtx.sampleRate,s=Math.round((this.opts.chunkMs??200)*wn/1e3),i=Math.floor(this.buffer.length*wn/a),o=Math.floor(i/s);if(o<=0)return;const l=o*s,c=Math.floor(l*a/wn),u=this.buffer.slice(0,c);this.buffer=this.buffer.slice(c);const h=Ks(u,a,wn);let p=0;for(;p+s<=h.length;){const C=h.subarray(p,p+s),M=qh(C).buffer,k=this.ws;if(k&&k.readyState===WebSocket.OPEN)try{k.send(M),this.chunksSent++,(y=(g=this.opts).onSend)==null||y.call(g,M.byteLength)}catch(P){(x=(m=this.opts).onError)==null||x.call(m,P)}else k&&k.readyState===WebSocket.CONNECTING?this.sendQueue.length<this.maxQueue&&(this.sendQueue.push(M),(f=(b=this.opts).onSend)==null||f.call(b,0)):(this.chunksDropped++,(v=(j=this.opts).onSend)==null||v.call(j,0));const R=Date.now();R-this.lastStatusLog>5e3&&(this.lastStatusLog=R,ft.info(`[${this.ts()}] STATUS: sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived} ws=${(k==null?void 0:k.readyState)??"none"} worklet=${this.usingWorklet}`)),p+=s}if(p<h.length){const C=h.subarray(p),T=Ks(C,wn,a),M=new Float32Array(T.length+this.buffer.length);M.set(T,0),M.set(this.buffer,T.length),this.buffer=M}}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 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,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 n=this.audioCtx.createMediaStreamSource(this.mediaStream);await this.setupAudioNodes(n)}stop(){var t,n;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{(n=this.ws)==null||n.close()}catch{}this.ws=void 0,this.sendQueue=[]}}const Kh=st.scoped("CrepeStreaming");class Yh extends el{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;Kh.warn(`[${this.tag}] [${this.ts()}] triggering fallback`),this.stopAudioNodes();try{(n=(t=this.crepeOpts).onFallback)==null||n.call(t)}catch{}}}class Zh extends el{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 At={debug:(...e)=>{},warn:(...e)=>{typeof console<"u"&&console.warn("[KaraokePitch]",...e)}};function Xh(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 Qh(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 tl({isPlaying:e,gameMode:t,players:n,playersMicKey:a,micAlgorithms:s={},defaultPitchAlgorithm:i="pitchy",micRmsThresholds:o={},micOffsets:l={},micGains:c={},micPitchThresholds:u={},micSmoothingWindows:h={},micHysteresisFrames:p={},micUseHanning:g={},micMonitorEnabled:y={},micMonitorVolumes:m={},currentTimeRef:x,isPadMode:b,clockOffsetMsRef:f,currentPartyIdRef:j,rtc:v}){const[C,T]=d.useState({}),M=d.useRef({}),k=d.useRef({}),[R,P]=d.useState({}),I=d.useRef({}),A=d.useRef([]),L=d.useRef(null),E=d.useRef(null),[,D]=d.useState({}),[,Z]=d.useState({}),[,G]=d.useState({}),[F,q]=d.useState({}),[V,K]=d.useState(!0),[W,Q]=d.useState(!1),w=d.useRef(n);w.current=n;const N=d.useRef(0),S=d.useRef(performance.now());return d.useEffect(()=>{A.current.forEach($=>$()),A.current=[];const O={current:!1};function Y($,H,X=0){x.current!==N.current&&(N.current=x.current,S.current=performance.now());const re=Math.min(.25,(performance.now()-S.current)/1e3),oe=x.current+re-X/1e3;T(z=>{const ee=z[$]||[];return{...z,[$]:[...ee,{t:oe,hz:H}]}}),M.current[$]=(M.current[$]||[]).concat({t:oe,hz:H});const se=M.current[$];se.length>500&&(M.current[$]=se.slice(-500))}function _($,H,X,re=.02,oe=0,se=.6,z=0,ee=0,ae=0,ce=!1){let le=null,ne=null,pe=null;return(async()=>{try{le=new AudioContext;let he=le.createMediaStreamSource(H);if(z>0){const Se=le.createGain();Se.gain.value=z,he.connect(Se),he=Se}const we=le.createAnalyser();we.fftSize=2048,he.connect(we);const je=new Float32Array(we.fftSize),Pe=ce?Xh(we.fftSize):null,$e=[];let Ye=0;if(X==="pitchy")try{const{PitchDetector:Se}=await import("pitchy");pe=Se.forFloat32Array(we.fftSize)}catch(Se){At.warn("pitchy import failed, falling back to autocorrelation",Se)}const ue=()=>{try{we.getFloatTimeDomainData(je)}catch{}const Se=Pe?Qh(je,Pe):je;let Oe=0;for(let Ie=0;Ie<Se.length;Ie++)Oe+=Se[Ie]*Se[Ie];Oe=Math.sqrt(Oe/Se.length);let Me=0;if(Oe>=re)if(pe)try{const[Ie,Qe]=pe.findPitch(Se,le.sampleRate);Ie>50&&Ie<3e3&&Qe>se&&(Me=Ie)}catch{}else Me=Oo(Se,le.sampleRate,re),(Me<50||Me>3e3)&&(Me=0);if(Me>0&&ee>1&&($e.push(Me),$e.length>ee&&$e.shift(),Me=$e.reduce((Ie,Qe)=>Ie+Qe,0)/$e.length),Me>0)Ye=0,Y($,Me,oe);else if(Ye++,ae>0&&Ye<=ae&&$e.length>0){const Ie=$e[$e.length-1];Ie>0&&Y($,Ie,oe)}ne=requestAnimationFrame(ue),I.current[$]=ne};ue()}catch(ge){At.warn("startLocalPitch error",ge)}})(),()=>{ne&&cancelAnimationFrame(ne),le&&le.close().catch(()=>{})}}function U($,H,X,re=0){X==="crepe"&&E.current?(E.current.stop(),E.current=null):X==="librosa"&&L.current&&(L.current.stop(),L.current=null);const oe=window.location,se=oe.protocol==="https:"?"wss:":"ws:",z=X==="librosa"?`${se}//${oe.host}/api/librosa/ws/pyin`:`${se}//${oe.host}/api/ai/audio/pitch/ws/pitch_server`,ee=X==="librosa"?D:Z;ee(pe=>({...pe,[$]:"connecting"}));const ae=[],ce=pe=>{if(pe>0){for(ae.push(x.current);ae.length>200;)ae.shift();X==="crepe"&&G(fe=>({...fe,[$]:(fe[$]||0)+1}))}},le=()=>{ee(pe=>({...pe,[$]:"closed"})),ae.length=0},ne=pe=>{if(typeof pe.hz=="number"&&pe.hz>0){const fe=pe.hz,he=(ae.length>0?ae.shift():x.current)-re/1e3;T(we=>{const je=we[$]||[];return{...we,[$]:[...je,{t:he,hz:fe}]}})}else ae.length>0&&ae.shift()};if(X==="librosa"){const pe=new Zh({wsUrl:z,onOpen:()=>ee(fe=>({...fe,[$]:"connected"})),onClose:le,onError:fe=>{ee(ge=>({...ge,[$]:"error"})),At.warn("Librosa WS error",fe)},onMessage:ne,onSend:ce});return L.current=pe,pe.startWithMediaStream(H).catch(fe=>{At.warn("Librosa client start failed",fe),ee(ge=>({...ge,[$]:"failed"}))}),()=>{pe.stop(),L.current=null,ee(fe=>({...fe,[$]:""}))}}else{const pe=new Yh({wsUrl:z,onOpen:()=>ee(fe=>({...fe,[$]:"connected"})),onClose:le,onError:fe=>{ee(ge=>({...ge,[$]:"error"})),At.warn("Crepe WS error",fe)},onMessage:ne,onSend:ce,onFallback:()=>{ee(ge=>({...ge,[$]:"fallback-pitchy"})),E.current=null;const fe=_($,H,"pitchy",.02,re);A.current.push(fe)}});return E.current=pe,pe.startWithMediaStream(H).catch(fe=>{At.warn("Crepe client start failed",fe),ee(ge=>({...ge,[$]:"failed"}))}),()=>{pe.stop(),E.current=null,ee(fe=>({...fe,[$]:""}))}}}if(e){if(T({}),t!=="pad"){const $={};w.current.forEach(H=>{if(!H.micId)return;const X=s[H.id]||i,re=H.micId&&o[H.micId]||.02,oe=H.micId&&l[H.micId]||0,se=H.micId&&c[H.micId]||0,z=H.micId&&u[H.micId]||.6,ee=H.micId&&h[H.micId]||0,ae=H.micId&&p[H.micId]||0,ce=H.micId&&g[H.micId]||!1,le=H.micId&&y[H.micId]||!1,ne=(H.micId?m[H.micId]:void 0)??100,pe=new za;pe.startRecording({deviceId:H.micId,onLevel:()=>{},gain:se,monitorEnabled:le,monitorVolume:ne}).then(()=>{if(O.current){pe.stopRecording().catch(()=>{});return}$[H.id]=pe;const fe=pe.getStream();if(!fe){At.warn(`No stream from recorder for player ${H.id}`);return}if(X==="librosa"||X==="crepe"){const ge=U(H.id,fe,X,oe);A.current.push(ge)}else{const ge=_(H.id,fe,X,re,oe,z,se,ee,ae,ce);A.current.push(ge)}}).catch(fe=>At.warn(`recorder start failed for player ${H.id}`,fe))}),k.current=$}}else{const $=k.current,H=Object.keys($).map(Number);Promise.allSettled(H.map(async X=>{const re=await $[X].stopRecording();return{pid:X,blob:re}})).then(X=>{const re={};for(const oe of X)oe.status==="fulfilled"&&oe.value.blob&&(re[oe.value.pid]=oe.value.blob);Object.keys(re).length>0&&P(oe=>({...oe,...re}))}),k.current={},Object.values(I.current).forEach(X=>X&&cancelAnimationFrame(X)),I.current={}}return()=>{O.current=!0,A.current.forEach($=>$()),A.current=[],Object.values(k.current).forEach($=>$.stopRecording().catch(()=>{})),k.current={},Object.values(I.current).forEach($=>$&&cancelAnimationFrame($)),I.current={}}},[e,t,a,s,i,o,l,c,u,h,p,g,y,m]),d.useEffect(()=>{if(!v)return;const O=300,Y=async()=>{try{const U={...M.current};for(const $ of Object.keys(U)){const H=Number($),X=U[H]||[];if(!X||X.length===0)continue;M.current[H]=[];const re=Go(X,120),oe={playerId:H,points:re,clientNowUtc:new Date().toISOString(),quantized:!0};j!=null&&j.current&&(oe.EventId=j.current);try{v.isConnected()&&await v.publishTimelineUpdate(oe)}catch(se){At.warn("failed to publish timeline update, will retry",se),M.current[H]=(M.current[H]||[]).concat(X).slice(-1e3)}}}catch{}},_=window.setInterval(Y,O);return()=>{_&&window.clearInterval(_)}},[v,j]),d.useEffect(()=>{if(!v)return;const O=Y=>{try{const _=Y;if(!_||typeof _.playerId>"u"||!Array.isArray(_.points))return;const U=Number(_.playerId),$=_.points.map(H=>({t:H.t,hz:H.hz}));if(!$.length)return;if(_.serverTimeUtc){const H=Wo(_.serverTimeUtc,Date.now(),(f==null?void 0:f.current)||0);q(X=>({...X,[U]:H}))}T(H=>{const X=H[U]||[];return{...H,[U]:[...X,...$]}})}catch{}};return v.onTimelineUpdate(O),()=>v.offTimelineUpdate(O)},[v,f]),{livePitch:C,setLivePitch:T,recordings:R,recordersRef:k,unsentPitchRef:M,pitchCleanupsRef:A,remoteLatencyMs:F,showRemoteTimelines:V,setShowRemoteTimelines:K,compactTimelines:W,setCompactTimelines:Q}}function nl(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function rl(e){return e>=50?3:e>=30?2.5:e>=20?2:e>=10?1.5:1}function al(e,t,n){const{semitoneTolerance:a,preWindow:s,postExtra:i}=n,o=n.segMs??.25,l=typeof n.completionBonusFactor=="number"?n.completionBonusFactor:.15,c=typeof n.goldFullBonusFactor=="number"?n.goldFullBonusFactor:.3,u=typeof n.difficultyMult=="number"?n.difficultyMult:1,h=!!n.disableGoldNotes;let p=0,g=0,y=0;const m=[];let x=0,b=0,f=0;const j=new Map;e.forEach((P,I)=>{const A=P.startTime,L=P.startTime+P.duration,E=A-s,D=L+i,Z=t.filter(w=>w.t>=E&&w.t<=D&&w.hz>0);if(!Z||Z.length===0)return;const G=Math.max(1,Math.ceil((P.duration||.25)/o)),F=Math.max(10,Math.round(100*(P.duration||1))),q=Math.max(1,Math.round(F/G));let V=0;const K=[];for(let w=0;w<G;w++){const N=A+w*(P.duration/G),S=A+(w+1)*(P.duration/G),O=Math.min(.06,P.duration/G*.2),Y=N-O,_=S+O,U=t.filter(se=>se.t>=Y&&se.t<=_&&se.hz>0);if(!U||U.length===0)continue;let $=0;U.forEach(se=>{let ee=((12*Math.log2(se.hz/440)+69)%12+12)%12;for(;ee-P.pitch>6;)ee-=12;for(;ee-P.pitch<-6;)ee+=12;const ae=Math.abs(ee-P.pitch);$+=ae});const H=$/U.length;let X=0;if(a<=0)X=H===0?1:0;else{const se=a*2;X=Math.max(0,1-Math.min(H/se,1))}if(X<=0)continue;const re=!h&&P.isGold?2:1,oe=Math.round(q*re*X);oe>0&&(p+=oe,V+=oe,K.push({segIndex:w,frac:X,add:oe,segStart:Y,segEnd:_,visualStart:N,visualEnd:S}))}const W=P.line??0;j.has(W)||j.set(W,{total:0,hit:0,comboBonus:0});const Q=j.get(W);if(Q.total++,V>0){x++,x>b&&(b=x),Q.hit++;const w=rl(x),N=w>1?Math.round(V*(w-1)):0;f+=N,Q.comboBonus+=N;const S=Math.max(1,Math.ceil((P.duration||.25)/o)),Y=K.length>=S,_=Y?Math.round(Math.max(10,Math.round(100*(P.duration||1)))*l*(!h&&P.isGold?1.5:1)*u):0,U=Y&&!h&&P.isGold?Math.round(Math.max(10,Math.round(100*(P.duration||1)))*c*u):0;g+=_,y+=U,m.push({noteKey:`${P.line??0}-${P.idx??0}`,segments:K,totalAdded:V,completed:Y,completionBonus:_,goldFullBonus:U})}else x=0});const v=[];for(const[P,I]of j.entries()){const A=I.total>0?I.hit/I.total:0;v.push({verseIndex:P,hitFraction:A,label:nl(A),comboBonus:I.comboBonus})}const C={maxCombo:b,currentCombo:0,totalComboBonus:f},T=f+g+y,M=m.length,k=m.filter(P=>P.completed).length,R={hits:M,misses:e.length-M,good:M-k,perfect:k,maxCombo:b};return{classicScore:p,bonusScore:T,totalScore:p+T,perNote:m,combo:C,verseRatings:v,noteStats:R}}function sl(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 il(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function ol(e,t,n){const a=sl(t,n);if(a<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0};const s=il(e.classicScore,a),i=Math.round(e.bonusScore/a*1e4);return{...e,classicScore:s,bonusScore:i,totalScore:s+i}}const Cn={maxCombo:0,currentCombo:0,totalComboBonus:0},Ys={hits:0,misses:0,good:0,perfect:0,maxCombo:0};function ll({livePitch:e,uploadedSong:t,isPlaying:n,difficulty:a,players:s,isPadMode:i}){const[o,l]=d.useState(0),[c,u]=d.useState(0),[h,p]=d.useState(0),[g,y]=d.useState([]),[m,x]=d.useState(Cn),[b,f]=d.useState([]),[j,v]=d.useState([]),[C,T]=d.useState({}),[M,k]=d.useState({}),[R,P]=d.useState({}),[I,A]=d.useState({}),[L,E]=d.useState({});return d.useEffect(()=>{if(!t||!n)return;const D=Zn(t.notes.map(U=>U.noteLine),t.bpm??void 0),Z=(t.gap??0)/1e3,G=Xa(D,Z),F=Or(a),q=[];let V=null,K=null,W=null,Q=[];const w={},N={},S={},O={},Y={},_=i?s[0]:s.find(U=>!!U.micId)||s[0];for(let U=0;U<s.length;U++){const $=s[U],H=($==null?void 0:$.id)!=null?e[$.id]||[]:[];if(H.length===0){q.push({id:$.id,name:$.name||`Player ${$.id}`,color:$.color||Xe[U%Xe.length],classicScore:0,bonusScore:0,totalScore:0}),w[$.id]=[],N[$.id]={...Cn},S[$.id]=[],O[$.id]=0,Y[$.id]={...Ys};continue}const X=Ka($.id),re=!!(X!=null&&X.disableGoldNotes),oe=al(G,H,{semitoneTolerance:F.semitoneTolerance,preWindow:F.preWindow,postExtra:F.postExtra,difficultyMult:F.difficultyMult,disableGoldNotes:re}),se=ol(oe,G,re);q.push({id:$.id,name:$.name||`Player ${$.id}`,color:$.color||Xe[U%Xe.length],classicScore:se.classicScore,bonusScore:se.bonusScore,totalScore:se.totalScore}),w[$.id]=Bo(oe.perNote,D,Z),N[$.id]=oe.combo??{...Cn},S[$.id]=oe.verseRatings??[],O[$.id]=se.totalScore,Y[$.id]=oe.noteStats??{...Ys},$.id===(_==null?void 0:_.id)&&(V=se,K=oe.combo??null,W=oe.verseRatings??null,Q=w[$.id])}v(q),T(w),k(N),P(S),A(O),E(Y),V?(l(V.classicScore),u(V.bonusScore),p(V.totalScore),y(Q),x(K??Cn),f(W??[])):(l(0),u(0),p(0),y([]),x(Cn),f([]))},[e,t,n,a,s,i]),{liveScore:o,liveBonusScore:c,liveTotalScore:h,liveSegmentScores:g,liveCombo:m,liveVerseRatings:b,perPlayerScores:j,perPlayerSegmentScores:C,perPlayerCombo:M,perPlayerVerseRatings:R,perPlayerTotalScores:I,perPlayerNoteStats:L}}const Jh=[],ep=e=>!!e&&/youtu(\.be|be\.com)/i.test(e),tp=({players:e=Jh,song:t,initialSong:n=null,difficulty:a="normal",gameMode:s="normal",height:i=480,showTimelines:o=!0,showLyrics:l=!0,singleTimeline:c=!1,requestMicPermission:u=!0,initiallyActivated:h=!1,showUploader:p=!1,parseSong:g,micAlgorithms:y,defaultPitchAlgorithm:m="pitchy",micRmsThresholds:x,micOffsets:b,micGains:f,micPitchThresholds:j,micSmoothingWindows:v,micHysteresisFrames:C,micUseHanning:T,micMonitorEnabled:M,micMonitorVolumes:k,searchYouTubeByArtistTitle:R,fetchTopSingings:P,onSaveResults:I,rtc:A,onSongChange:L,onPlayingChange:E,onTimeUpdate:D,onEnded:Z,onContinue:G,renderReport:F,t:q,className:V,style:K,id:W,accessMode:Q,"data-testid":w})=>{var _e;const{t:N}=xe(),S=q??N,[O,Y]=d.useState(t??n??null),[_,U]=d.useState(!1),[$,H]=d.useState(0),[X,re]=d.useState(h),[oe,se]=d.useState(!1),[z,ee]=d.useState([]),[ae,ce]=d.useState(""),[le,ne]=d.useState(null),[pe,fe]=d.useState(0),ge=s==="pad",[he,we]=d.useState([]),[je,Pe]=d.useState([]),[$e,Ye]=d.useState([]),[ue,Se]=d.useState([]),Oe=d.useRef(null),Me=d.useRef(null),Ie=d.useRef(null),Qe=d.useRef(!1),Be=d.useRef(0);d.useEffect(()=>{Be.current=$},[$]);const He=d.useRef(t);d.useEffect(()=>{t!==void 0&&t!==He.current&&(He.current=t,Y(t),se(!1),H(0),fe(be=>be+1))},[t]);const Dt=d.useMemo(()=>JSON.stringify(e.map(be=>({id:be.id,micId:be.micId}))),[e]),{livePitch:ct,setLivePitch:ht,recordings:it,remoteLatencyMs:kt}=tl({isPlaying:_,gameMode:s,players:e,playersMicKey:Dt,micAlgorithms:y,defaultPitchAlgorithm:m,micRmsThresholds:x,micOffsets:b,micGains:f,micPitchThresholds:j,micSmoothingWindows:v,micHysteresisFrames:C,micUseHanning:T,micMonitorEnabled:M,micMonitorVolumes:k,currentTimeRef:Be,isPadMode:ge,rtc:A}),Je=ll({livePitch:ct,uploadedSong:O,isPlaying:_,difficulty:a,players:e,isPadMode:ge}),Tt=d.useRef(Je);Tt.current=Je;const Jt=d.useMemo(()=>O?Vo(O,s):null,[O,s]),ke=((_e=e[0])==null?void 0:_e.id)??1;d.useEffect(()=>{var Te;if(!ge||!_||!O){(Te=Oe.current)==null||Te.stop(),Oe.current=null,we([]),Pe([]),Ye([]),Se([]);return}const be=new Jo({difficulty:a,noteLines:O.notes.map(Le=>Le.noteLine),bpm:O.bpm??void 0,gap:O.gap??0,onPitch:Le=>{const Ge=Be.current;ht(ze=>{const tt=ze[ke]||[];return{...ze,[ke]:[...tt,{t:Ge,hz:Le}]}})},onHitFeedback:Le=>Se(Ge=>[...Ge.slice(-20),Le]),onLaneActive:Le=>Ye(Le)});return we(be.getLanes()),Pe(be.getEvents()),Ye(new Array(be.getLanes().length).fill(!1)),be.start(()=>Be.current),Oe.current=be,()=>{be.stop(),Oe.current=null}},[ge,_,O,a,ke,ht]);const Ce=d.useCallback(be=>{U(be),E==null||E(be)},[E]),We=d.useCallback(be=>{H(be),D==null||D(be)},[D]),De=d.useCallback(()=>{var Te;try{Xt()}catch{}const be=()=>{re(!0),Qe.current=!0};!ge&&u&&((Te=navigator.mediaDevices)!=null&&Te.getUserMedia)?navigator.mediaDevices.getUserMedia({audio:!0}).then(Le=>Le.getTracks().forEach(Ge=>Ge.stop())).catch(()=>{}).finally(be):be()},[ge,u]);d.useEffect(()=>{if(!X||!Qe.current)return;Qe.current=!1;const be=window.setInterval(()=>{Me.current&&(window.clearInterval(be),Me.current.play())},100),Te=window.setTimeout(()=>window.clearInterval(be),3e3);return()=>{window.clearInterval(be),window.clearTimeout(Te)}},[X]);const Ae=d.useCallback(()=>{se(!0),Z==null||Z();const be=(O==null?void 0:O.id)??0,Te=Tt.current,Le=[];for(const ze of e){const tt=Te.perPlayerTotalScores[ze.id]??0;if(tt<=0)continue;const Ke=Te.perPlayerNoteStats[ze.id];Le.push({playerId:ze.id,songId:be,score:tt,hits:(Ke==null?void 0:Ke.hits)??0,misses:(Ke==null?void 0:Ke.misses)??0,good:(Ke==null?void 0:Ke.good)??0,perfect:(Ke==null?void 0:Ke.perfect)??0,combo:(Ke==null?void 0:Ke.maxCombo)??0})}const Ge=()=>{P&&be>0&&Promise.resolve(P(be)).then(ee).catch(()=>{})};I&&Le.length>0?Promise.resolve(I(Le)).then(Ge).catch(Ge):Ge()},[e,O,I,P,Z]);d.useEffect(()=>{var be;s==="demo"&&_&&$>=12&&((be=Me.current)==null||be.pause(),Ae())},[s,_,$,Ae]),d.useEffect(()=>{if(!O||pe===0||!R||ep(O.videoPath))return;if(O.youtubeId){const Te=`https://www.youtube.com/watch?v=${O.youtubeId}`;Y(Le=>Le&&{...Le,videoPath:Te});return}if(!O.artist||!O.title)return;let be=!1;return ce(S("karaokeManager.ytSearching","Searching YouTube…")),ne("searching"),Promise.resolve(R(O.artist,O.title)).then(Te=>{if(!be)if(Te){const Le=`https://www.youtube.com/watch?v=${Te}`;Y(Ge=>Ge&&{...Ge,videoPath:Le}),ce(""),ne(null)}else ce(S("karaokeManager.ytNotFound","Not found on YouTube")),ne("error"),window.setTimeout(()=>{be||(ce(""),ne(null))},4e3)}).catch(()=>{be||(ce(S("karaokeManager.ytSearchError","Search error")),ne("error"))}),()=>{be=!0}},[pe,O,R,S]);const Ee=d.useCallback(()=>{var be,Te;se(!1),ht({}),(be=Me.current)==null||be.seekTo(0),(Te=Me.current)==null||Te.play()},[ht]),de=d.useCallback(()=>{se(!1),G==null||G()},[G]),me=d.useCallback(be=>{Y(be),se(!1),H(0),fe(Te=>Te+1),L==null||L(be)},[L]),Re=d.useMemo(()=>{if(!c)return e;const be=e.find(Te=>!!Te.micId)||e[0];return be?[be]:[]},[e,c]),Ne=((O==null?void 0:O.gap)??0)/1e3;return Q==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-manager${V?` ${V}`:""}`,style:{position:"relative",textAlign:"center",minHeight:i,...K},id:W,"data-testid":w,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:[le==="error"?r.jsx(B.NtdClose,{size:16}):r.jsx(B.NtdSearch,{size:16}),ae]}),!O&&p&&r.jsx(Ho,{onSongUpload:me,parseSong:g,t:S}),O&&!X&&r.jsxs("button",{type:"button",className:"nice-karaoke-manager__activate",onClick:De,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:ge?r.jsx(B.NtdGamepad,{size:56}):r.jsx(B.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:ge?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.")})]}),O&&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(Do,{tracks:Jt?[Jt]:[],autoPlay:!1,uiMode:"nobuttons",height:i,externalRef:Me,onPlayingChange:Ce,onTimeUpdate:We,onEnded:Ae})}),o&&X&&r.jsx("div",{style:{position:"absolute",inset:0,zIndex:20,pointerEvents:"none"},children:Re.map((be,Te)=>{const Le=ct[be.id]||[],Ge=Ne?Le.map(ze=>({t:ze.t-Ne,hz:ze.hz})):Le;return r.jsx($o,{song:O,currentTime:$,playerRef:Ie,userPitch:Ge,segmentScores:Je.perPlayerSegmentScores[be.id],combo:Je.perPlayerCombo[be.id],verseRatings:Je.perPlayerVerseRatings[be.id],config:{playerName:be.name,score:Je.perPlayerTotalScores[be.id]??0,playerBgColor:be.color||Xe[Te%Xe.length],difficultyLevel:a,isPlaying:_,playerCount:Re.length,latencyMs:kt[be.id]??null,top:30+Te*160}},be.id)})}),ge&&he.length>0&&r.jsx(Ko,{lanes:he,events:je,currentTime:$,activeLanes:$e,difficulty:a,feedbackQueue:ue,isPlaying:_}),l&&X&&r.jsx("div",{style:{position:"absolute",bottom:20,left:0,right:0,zIndex:25,pointerEvents:"none"},children:r.jsx(go,{song:O,currentTime:$})})]}),oe&&Object.keys(it).length>0&&r.jsx(np,{recordings:it,players:e,t:S}),oe&&r.jsx(Lo,{uploadedSong:O,playerScores:Je.perPlayerScores,topSingings:z,onRestart:Ee,onContinue:de,t:S,renderReport:F})]})},np=({recordings:e,players:t,t:n})=>{const a=d.useMemo(()=>{const s={};for(const[i,o]of Object.entries(e))o&&(s[Number(i)]=URL.createObjectURL(o));return s},[e]);return d.useEffect(()=>()=>{for(const s of Object.values(a))URL.revokeObjectURL(s)},[a]),r.jsxs("div",{style:{margin:"24px auto",maxWidth:640,background:"var(--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(B.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||n("karaokeManager.player","Player {id}").replace("{id}",String(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(B.NtdDownload,{size:13})," ",n("karaokeManager.download","Download")]})]}):r.jsx("span",{style:{opacity:.6},children:n("karaokeManager.noRecording","No recording")})]},s.id))})]})},rp=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],na=Vn;function rr(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 cl(e){const{playerName:t,playerColor:n,songTitle:a,songArtist:s,songBpm:i,difficulty:o,pitchPoints:l,notes:c,verseRatings:u,combo:h,classicScore:p,bonusScore:g,totalScore:y,micSettings:m}=e,x=l.filter(ue=>ue.hz>0),b=x.map(ue=>It(ue.hz)),f=[],j=[],v=[...c].sort((ue,Se)=>ue.startTime-Se.startTime);function C(ue){let Se=0,Oe=v.length-1;for(;Se<=Oe;){const Me=Se+Oe>>>1,Ie=v[Me];if(ue<Ie.startTime)Oe=Me-1;else if(ue>Ie.startTime+Ie.duration)Se=Me+1;else return Ie.pitch}return null}const T=[];for(const ue of l){const Se=ue.hz>0?It(ue.hz):0,Oe=C(ue.t);T.push({t:ue.t,sung:Se,expected:Oe}),Se>0&&Oe!==null&&f.push(na(Se,Oe)*100)}const M=T.flatMap(ue=>ue.sung>0&&ue.expected!==null?[ue.sung-ue.expected]:[]).sort((ue,Se)=>ue-Se),k=M.length>0?12*Math.round(rr(M,50)/12):0,R=T.map(ue=>({t:ue.t,sung:ue.sung,expected:ue.expected===null?0:ue.expected+k}));let P=0;for(const ue of v){const Se=ue.startTime-.3,Oe=ue.startTime+ue.duration;for(;P<x.length&&x[P].t<Se;)P++;P<x.length&&x[P].t<=Oe&&j.push((x[P].t-ue.startTime)*1e3)}const I=f.map(Math.abs),A=[...I].sort((ue,Se)=>ue-Se),L=I.length>0?I.reduce((ue,Se)=>ue+Se,0)/I.length:0,E=rr(A,50),D=I.length>1?Math.sqrt(I.reduce((ue,Se)=>ue+(Se-L)**2,0)/(I.length-1)):0,Z=I.filter(ue=>ue<=50).length,G=I.filter(ue=>ue<=15).length,F=I.length>0?Z/I.length*100:0,q=I.length>0?G/I.length*100:0,V=["< −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"],K=new Array(10).fill(0);for(const ue of f){const Se=ue<-100?0:ue<-50?1:ue<-25?2:ue<-15?3:ue<0?4:ue<15?5:ue<25?6:ue<50?7:ue<100?8:9;K[Se]++}const W=V.map((ue,Se)=>({centRange:ue,count:K[Se],pct:f.length>0?K[Se]/f.length*100:0})),Q=x.map(ue=>ue.hz).sort((ue,Se)=>ue-Se),w=Q.length>0?Q[0]:0,N=Q.length>0?Q[Q.length-1]:0,S=w>0?It(w):0,O=N>0?It(N):0,Y=O-S,_=[...b].sort((ue,Se)=>ue-Se),U=rr(_,10),$=rr(_,90),H=new Array(12).fill(0);for(const ue of b){const Se=Math.round(ue)%12;Se>=0&&Se<12&&H[Se]++}const X=H.reduce((ue,Se)=>ue+Se,0),re=rp.map((ue,Se)=>({note:ue,count:H[Se],pct:X>0?H[Se]/X*100:0})),oe=ap(x),se=j.length>0?j.reduce((ue,Se)=>ue+Se,0)/j.length:0,z=j.length>1?Math.sqrt(j.reduce((ue,Se)=>ue+(Se-se)**2,0)/(j.length-1)):0,ee=z>0?Math.max(0,Math.min(100,100-z/2)):100;let ae=0,ce=0;for(let ue=1;ue<b.length;ue++){const Se=Math.abs(b[ue]-b[ue-1]);ae+=Se,ce++}const le=ce>0?ae/ce*100/12:0,ne=l.filter(ue=>ue.hz<=0).length,pe=l.length>0?(1-ne/l.length)*100:0,fe=new Map;for(const ue of c){const Se=ue.line??0;fe.has(Se)||fe.set(Se,[]),fe.get(Se).push(ue)}const ge=new Map;for(const ue of x){const Se=C(ue.t);if(Se===null)continue;let Oe=0,Me=v.length-1,Ie=-1;for(;Oe<=Me;){const Be=Oe+Me>>>1,He=v[Be];if(ue.t<He.startTime)Me=Be-1;else if(ue.t>He.startTime+He.duration)Oe=Be+1;else{Ie=He.line??0;break}}if(Ie<0)continue;const Qe=Math.abs(na(It(ue.hz),Se)*100);ge.has(Ie)||ge.set(Ie,[]),ge.get(Ie).push(Qe)}const he=u.map(ue=>{const Se=fe.get(ue.verseIndex)??[],Oe=ge.get(ue.verseIndex)??[],Me=Oe.length>0?Oe.reduce((Ie,Qe)=>Ie+Qe,0)/Oe.length:0;return{verseIndex:ue.verseIndex,label:ue.label,hitFraction:ue.hitFraction,avgCentDeviation:Math.round(Me*10)/10,noteCount:Se.length,notesHit:Math.round(ue.hitFraction*Se.length),comboBonus:ue.comboBonus}}),we=2,je=.5,Pe=l.length>0?l[l.length-1].t:0,$e=[],Ye=T.flatMap(ue=>ue.sung>0&&ue.expected!==null?[{t:ue.t,hit:Math.abs(na(ue.sung,ue.expected))<=.5}]:[]);if(Ye.length>0){let ue=0,Se=0,Oe=0;for(let Me=0;Me<=Pe;Me+=je){const Ie=Me-we/2,Qe=Me+we/2;for(;Se<Ye.length&&Ye[Se].t<Qe;)Ye[Se].hit&&Oe++,Se++;for(;ue<Se&&Ye[ue].t<Ie;)Ye[ue].hit&&Oe--,ue++;const Be=Se-ue;$e.push({t:Me,accuracy:Be>0?Oe/Be*100:0})}}else for(let ue=0;ue<=Pe;ue+=je)$e.push({t:ue,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(L*10)/10,medianCentDeviation:Math.round(E*10)/10,stdDevCents:Math.round(D*10)/10,intonationAccuracyPct:Math.round(F*10)/10,perfectHitPct:Math.round(q*10)/10,pitchDeviationHistogram:W,lowestHz:Math.round(w*10)/10,highestHz:Math.round(N*10)/10,lowestNote:S>0?Lt(S):"—",highestNote:O>0?Lt(O):"—",rangeInSemitones:Math.round(Y*10)/10,tessituraLow:U>0?Lt(U):"—",tessituraHigh:$>0?Lt($):"—",pitchClassDistribution:re,vibrato:oe,avgOnsetDeviationMs:Math.round(se*10)/10,rhythmStabilityPct:Math.round(ee*10)/10,jitterPct:Math.round(le*100)/100,shimmerProxy:Math.round(pe*10)/10,verseMetrics:he,micSettings:m,pitchOverTime:R,accuracyOverTime:$e}}function ap(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(y=>It(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,b=t[o]-m,f=Math.abs(b);for(let C=o+1;C<=y;C++){const T=t[C]-m;T*b<0&&x++,b=T;const M=Math.abs(T);M>f&&(f=M)}const j=n[y]-n[o];if(j<=0)continue;const v=x/2/j;v>=3&&v<=12&&(s.push(v),i.push(f*100))}if(s.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const u=s.reduce((y,m)=>y+m,0)/s.length,h=i.reduce((y,m)=>y+m,0)/i.length,p=Math.sqrt(s.reduce((y,m)=>y+(m-u)**2,0)/s.length),g=Math.max(0,Math.min(100,100-p*20));return{detected:!0,avgRateHz:Math.round(u*10)/10,avgExtentCents:Math.round(h*10)/10,regularityPct:Math.round(g)}}const J={overlay:{position:"fixed",inset:0,background:"var(--nice-overlay-90, rgba(0,0,0,0.92))",display:"flex",alignItems:"flex-start",justifyContent:"center",zIndex:250,color:"var(--nice-text, #e2e8f0)",overflowY:"auto",padding:"24px 12px"},container:{background:"var(--nice-bg, #0f172a)",borderRadius:16,padding:32,width:"min(960px, 95vw)",boxShadow:"0 16px 48px var(--nice-overlay-60, rgba(0,0,0,0.6))",fontFamily:"'Segoe UI', system-ui, -apple-system, sans-serif"},header:{textAlign:"center",marginBottom:24,borderBottom:"2px solid var(--nice-border, #334155)",paddingBottom:20},title:{fontSize:28,fontWeight:800,color:"var(--nice-text, #f1f5f9)",margin:"0 0 4px"},subtitle:{fontSize:14,color:"var(--nice-text-muted, #64748b)",margin:0},sectionTitle:{fontSize:18,fontWeight:700,color:"var(--nice-accent, #38bdf8)",margin:"28px 0 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",paddingBottom:6,display:"flex",alignItems:"center",gap:8},table:{width:"100%",borderCollapse:"collapse",fontSize:13,margin:"8px 0"},th:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"left",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},thRight:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"right",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},td:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-secondary, #cbd5e1)"},tdRight:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",textAlign:"right",color:"var(--nice-text, #e2e8f0)",fontWeight:500},tdBold:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text, #f1f5f9)",fontWeight:700},kpiGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:12,margin:"12px 0"},kpiCard:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:"14px 16px",textAlign:"center",border:"1px solid var(--nice-border, #334155)"},kpiValue:{fontSize:26,fontWeight:800,color:"var(--nice-warning, #fbbf24)"},kpiLabel:{fontSize:11,color:"var(--nice-text-muted, #64748b)",marginTop:2,textTransform:"uppercase",letterSpacing:.8},kpiUnit:{fontSize:13,fontWeight:400,color:"var(--nice-text-muted, #94a3b8)",marginLeft:2},chartWrap:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:16,margin:"12px 0",border:"1px solid var(--nice-border, #334155)"},chartTitle:{fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:8,textAlign:"center"},badge:e=>({display:"inline-block",padding:"2px 10px",borderRadius:20,background:e,color:"#fff",fontSize:12,fontWeight:700}),btnPrimary:{background:"var(--nice-info, #3b82f6)",color:"#fff",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:700,cursor:"pointer"},btnSecondary:{background:"var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:600,cursor:"pointer"},row:{display:"flex",gap:16,flexWrap:"wrap"},half:{flex:"1 1 45%",minWidth:280},footer:{textAlign:"center",marginTop:24,paddingTop:16,borderTop:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #475569)",fontSize:11}};function mt(e){return e>=90?"#22c55e":e>=70?"#84cc16":e>=50?"#eab308":e>=30?"#f97316":"#ef4444"}function Zs(e){switch(e){case"Perfect":return"#22c55e";case"Great":return"#84cc16";case"Good":return"#eab308";case"OK":return"#f97316";default:return"#ef4444"}}function sp(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 Ht=e=>Math.round(e*10)/10;function Xs(e,t,n){return e.map((a,s)=>({name:a,color:n[s],data:t.map((i,o)=>o===s?Ht(i):0)}))}function Qs(e,t){if(e.length<=t)return e;const n=Math.ceil(e.length/t);return e.filter((a,s)=>s%n===0)}function Js(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 ei=240,ip=({reports:e,noteCount:t,uploadedSong:n=null,playerScores:a,livePitch:s,liveVerseRatings:i,liveCombo:o,difficulty:l="normal",micSettings:c,onClose:u,t:h,className:p,style:g,id:y,accessMode:m,"data-testid":x})=>{const{t:b}=xe(),f=h??b,j=d.useRef(null),v=d.useMemo(()=>{if(e||!n)return[];const S=Zn(n.notes.map(Y=>Y.noteLine),n.bpm??void 0),O=(n.gap??0)/1e3;return Xa(S,O)},[e,n]),C=d.useMemo(()=>e||(!n||!a||!o?[]:a.map(S=>{const O=(s==null?void 0:s[S.id])||[];return cl({playerName:S.name,playerColor:S.color,songTitle:n.title,songArtist:n.artist,songBpm:n.bpm??0,difficulty:l,pitchPoints:O,notes:v,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,v,c]),T=d.useCallback(()=>{var U,$;if(!j.current)return;const S=`<!DOCTYPE html>
|
|
48
48
|
<html lang="en"><head><meta charset="utf-8">
|
|
49
49
|
<title>Vocal Performance Report — ${((U=C[0])==null?void 0:U.songTitle)??"Karaoke"}</title>
|
|
50
50
|
<style>
|
|
@@ -57,18 +57,18 @@ th{background:var(--nice-bg-secondary, #1e293b);color:var(--nice-text-muted, #94
|
|
|
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
59
|
${j.current.innerHTML}
|
|
60
|
-
</body></html>`,O=new Blob([S],{type:"text/html"}),Y=URL.createObjectURL(O),_=document.createElement("a");_.href=Y,_.download=`vocal-report-${((($=C[0])==null?void 0:$.songTitle)??"karaoke").replace(/[^a-z0-9]/gi,"_")}.html`,_.click(),URL.revokeObjectURL(Y)},[C]),M=d.useCallback(()=>window.print(),[]),k=d.useCallback(()=>{var U;const S=JSON.stringify(C,null,2),O=new Blob([S],{type:"application/json"}),Y=URL.createObjectURL(O),_=document.createElement("a");_.href=Y,_.download=`vocal-data-${(((U=C[0])==null?void 0:U.songTitle)??"karaoke").replace(/[^a-z0-9]/gi,"_")}.json`,_.click(),URL.revokeObjectURL(Y)},[C]);if(m==="hidden")return null;if(C.length===0)return r.jsx("div",{className:p,style:{...J.overlay,...g},id:y,"data-testid":x,onClick:S=>S.target===S.currentTarget&&(u==null?void 0:u()),onKeyDown:S=>S.key==="Escape"&&(u==null?void 0:u()),children:r.jsxs("div",{style:{...J.container,textAlign:"center"},children:[r.jsxs("div",{style:J.header,children:[r.jsxs("h2",{style:J.title,children:[r.jsx(B.NtdBarChart,{size:24})," ",f("karaoke.report.title","Vocal Performance Report")]}),r.jsx("p",{style:J.subtitle,children:f("karaoke.report.empty","No performance data yet — sing a song to see the report.")})]}),u&&r.jsxs("button",{style:J.btnSecondary,onClick:u,children:[r.jsx(B.NtdClose,{size:16})," ",f("common.close","Close")]})]})});const R=C[0],P=t??v.length,I=
|
|
60
|
+
</body></html>`,O=new Blob([S],{type:"text/html"}),Y=URL.createObjectURL(O),_=document.createElement("a");_.href=Y,_.download=`vocal-report-${((($=C[0])==null?void 0:$.songTitle)??"karaoke").replace(/[^a-z0-9]/gi,"_")}.html`,_.click(),URL.revokeObjectURL(Y)},[C]),M=d.useCallback(()=>window.print(),[]),k=d.useCallback(()=>{var U;const S=JSON.stringify(C,null,2),O=new Blob([S],{type:"application/json"}),Y=URL.createObjectURL(O),_=document.createElement("a");_.href=Y,_.download=`vocal-data-${(((U=C[0])==null?void 0:U.songTitle)??"karaoke").replace(/[^a-z0-9]/gi,"_")}.json`,_.click(),URL.revokeObjectURL(Y)},[C]);if(m==="hidden")return null;if(C.length===0)return r.jsx("div",{className:p,style:{...J.overlay,...g},id:y,"data-testid":x,onClick:S=>S.target===S.currentTarget&&(u==null?void 0:u()),onKeyDown:S=>S.key==="Escape"&&(u==null?void 0:u()),children:r.jsxs("div",{style:{...J.container,textAlign:"center"},children:[r.jsxs("div",{style:J.header,children:[r.jsxs("h2",{style:J.title,children:[r.jsx(B.NtdBarChart,{size:24})," ",f("karaoke.report.title","Vocal Performance Report")]}),r.jsx("p",{style:J.subtitle,children:f("karaoke.report.empty","No performance data yet — sing a song to see the report.")})]}),u&&r.jsxs("button",{style:J.btnSecondary,onClick:u,children:[r.jsx(B.NtdClose,{size:16})," ",f("common.close","Close")]})]})});const R=C[0],P=t??v.length,I=Or(l),A=R.intonationAccuracyPct*.3+R.perfectHitPct*.2+R.rhythmStabilityPct*.15+R.shimmerProxy*.1+Math.min(100,R.maxCombo/Math.max(P,1)*100)*.1+Math.min(100,R.totalScore/1e4*100)*.15,L=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",E={"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 D=0;const Z=[{metric:f("vocalReport.radarIntonation","Intonation"),value:R.intonationAccuracyPct,max:100},{metric:f("vocalReport.radarPerfectHits","Perfect hits"),value:R.perfectHitPct,max:100},{metric:f("vocalReport.radarRhythm","Rhythm"),value:R.rhythmStabilityPct,max:100},{metric:f("vocalReport.radarVocalRange","Range"),value:Math.min(100,R.rangeInSemitones/24*100),max:100},{metric:f("vocalReport.radarStability","Stability"),value:R.shimmerProxy,max:100},{metric:f("vocalReport.radarCombo","Combo"),value:Math.min(100,R.maxCombo/Math.max(P,1)*100),max:100}],G=[{name:f("vocalReport.perfLabel","Perfect"),value:R.perfectHitPct,fill:"var(--nice-success, #22c55e)"},{name:f("vocalReport.goodLabel","Good"),value:R.intonationAccuracyPct-R.perfectHitPct,fill:"var(--nice-success, #84cc16)"},{name:f("vocalReport.offPitch","Off-pitch"),value:100-R.intonationAccuracyPct,fill:"var(--nice-danger, #ef4444)"}].filter(S=>S.value>0),F=R.pitchClassDistribution.filter(S=>S.count>0).sort((S,O)=>O.pct-S.pct),q=R.verseMetrics.map(S=>({verse:`V${S.verseIndex+1}`,accuracy:Math.round(S.hitFraction*100),label:S.label})),V=Qs(R.pitchOverTime,ei),K=Qs(R.accuracyOverTime,ei),W=R.pitchDeviationHistogram,Q=f("vocalReport.samples","Samples"),w=f("vocalReport.hitPct","Hit %"),N=f("vocalReport.cents","cents");return r.jsxs("div",{className:p,style:{...J.overlay,...g},id:y,"data-testid":x,onClick:S=>S.target===S.currentTarget&&(u==null?void 0:u()),onKeyDown:S=>S.key==="Escape"&&(u==null?void 0:u()),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
|
-
`}),r.jsxs("div",{ref:j,style:J.container,children:[r.jsxs("div",{style:J.header,children:[r.jsxs("h1",{style:{...J.title,display:"inline-flex",alignItems:"center",gap:8},children:[r.jsx(B.NtdBarChart,{size:26})," ",f("vocalReport.title","Vocal Performance Report")]}),r.jsxs("p",{style:J.subtitle,children:[R.songArtist," — ",R.songTitle," | ",f("vocalReport.difficulty","Difficulty"),": ",r.jsx("strong",{children:R.difficulty})," "," | ",new Date(R.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, ${mt(A)}44, ${mt(A)})`,border:`3px solid ${mt(A)}`,boxShadow:`0 0 20px ${mt(A)}44`},children:r.jsx("span",{style:{fontSize:28,fontWeight:900,color:"#fff"},children:L})}),r.jsxs("div",{style:{textAlign:"left"},children:[r.jsxs("div",{style:{fontSize:14,fontWeight:700,color:mt(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:E[L]??""})]})]})]}),r.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end",marginBottom:16,flexWrap:"wrap"},children:[r.jsxs("button",{style:J.btnPrimary,onClick:T,children:[r.jsx(B.NtdDownload,{size:14})," ",f("vocalReport.downloadHtml","Download HTML")]}),r.jsxs("button",{style:J.btnSecondary,onClick:M,children:[r.jsx(B.NtdPrint,{size:14})," ",f("vocalReport.printPdf","Print / PDF")]}),r.jsxs("button",{style:J.btnSecondary,onClick:k,children:[r.jsx(B.NtdCode,{size:14})," ",f("vocalReport.exportJson","Export JSON")]}),r.jsxs("button",{style:J.btnSecondary,onClick:u,children:[r.jsx(B.NtdClose,{size:14})," ",f("vocalReport.close","Close")]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.scoreOverview","Score overview")]}),r.jsxs("div",{style:J.kpiGrid,children:[r.jsxs("div",{style:J.kpiCard,children:[r.jsx("div",{style:J.kpiValue,children:R.totalScore.toLocaleString()}),r.jsx("div",{style:J.kpiLabel,children:f("vocalReport.totalScore","Total score")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsx("div",{style:J.kpiValue,children:R.classicScore.toLocaleString()}),r.jsx("div",{style:J.kpiLabel,children:f("vocalReport.classicScore","Classic score")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsx("div",{style:J.kpiValue,children:R.bonusScore.toLocaleString()}),r.jsx("div",{style:J.kpiLabel,children:f("vocalReport.bonusScore","Bonus score")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsxs("div",{style:J.kpiValue,children:[R.maxCombo,"×"]}),r.jsx("div",{style:J.kpiLabel,children:f("vocalReport.maxCombo","Max combo")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsxs("div",{style:{...J.kpiValue,color:mt(R.intonationAccuracyPct)},children:[R.intonationAccuracyPct,"%"]}),r.jsx("div",{style:J.kpiLabel,children:f("vocalReport.intonationAccuracy","Intonation accuracy")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsxs("div",{style:{...J.kpiValue,color:mt(R.perfectHitPct)},children:[R.perfectHitPct,"%"]}),r.jsx("div",{style:J.kpiLabel,children:f("vocalReport.perfectHits","Perfect hits")})]})]}),C.length>1&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.playerComparison","Player comparison")]}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:"#"}),r.jsx("th",{style:J.th,children:f("vocalReport.player","Player")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.classic","Classic")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.bonus","Bonus")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.total","Total")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.intonation","Intonation")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.perfect","Perfect")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.range","Range")})]})}),r.jsx("tbody",{children:C.map((S,O)=>r.jsxs("tr",{children:[r.jsx("td",{style:J.td,children:O+1}),r.jsx("td",{style:{...J.tdBold,color:S.playerColor},children:S.playerName}),r.jsx("td",{style:J.tdRight,children:S.classicScore.toLocaleString()}),r.jsx("td",{style:J.tdRight,children:S.bonusScore.toLocaleString()}),r.jsx("td",{style:{...J.tdRight,fontWeight:700,color:"var(--nice-warning, #fbbf24)"},children:S.totalScore.toLocaleString()}),r.jsx("td",{style:J.tdRight,children:r.jsxs("span",{style:J.badge(mt(S.intonationAccuracyPct)),children:[S.intonationAccuracyPct,"%"]})}),r.jsx("td",{style:J.tdRight,children:r.jsxs("span",{style:J.badge(mt(S.perfectHitPct)),children:[S.perfectHitPct,"%"]})}),r.jsxs("td",{style:J.tdRight,children:[S.lowestNote,"–",S.highestNote]})]},O))})]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.pitchAccuracy","Pitch accuracy")]}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:f("vocalReport.metric","Metric")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.value","Value")}),r.jsx("th",{style:J.th,children:f("vocalReport.description","Description")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.meanAbsDev","Mean abs. deviation")}),r.jsxs("td",{style:J.tdRight,children:[R.avgCentDeviation,r.jsxs("span",{style:J.kpiUnit,children:[" ",N]})]}),r.jsx("td",{style:J.td,children:f("vocalReport.meanAbsDevDesc","Average distance from the target pitch.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.medianDev","Median deviation")}),r.jsxs("td",{style:J.tdRight,children:[R.medianCentDeviation,r.jsxs("span",{style:J.kpiUnit,children:[" ",N]})]}),r.jsx("td",{style:J.td,children:f("vocalReport.medianDevDesc","Typical deviation, robust to outliers.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.stdDev","Std. deviation")}),r.jsxs("td",{style:J.tdRight,children:[R.stdDevCents,r.jsxs("span",{style:J.kpiUnit,children:[" ",N]})]}),r.jsx("td",{style:J.td,children:f("vocalReport.stdDevDesc","Consistency of pitch (lower = steadier).")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.intonationAccuracyLabel","Intonation accuracy")}),r.jsxs("td",{style:{...J.tdRight,color:mt(R.intonationAccuracyPct)},children:[R.intonationAccuracyPct,"%"]}),r.jsx("td",{style:J.td,children:f("vocalReport.intonationAccuracyDesc","Share of frames within tolerance.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.perfectHitRate","Perfect-hit rate")}),r.jsxs("td",{style:{...J.tdRight,color:mt(R.perfectHitPct)},children:[R.perfectHitPct,"%"]}),r.jsx("td",{style:J.td,children:f("vocalReport.perfectHitRateDesc","Notes hit dead-on.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.totalPitchSamples","Total pitch samples")}),r.jsx("td",{style:J.tdRight,children:R.totalPitchPoints.toLocaleString()}),r.jsx("td",{style:J.td,children:f("vocalReport.totalPitchSamplesDesc","Number of analysed pitch frames.")})]})]})]}),r.jsxs("div",{style:J.chartWrap,children:[r.jsx("div",{style:J.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:W.map(S=>S.centRange),series:Zs(W.map(S=>`${Q} (${S.centRange})`),W.map(S=>S.count),W.map(S=>ap(S.centRange)))})})]}),r.jsxs("div",{style:J.row,children:[r.jsxs("div",{style:{...J.chartWrap,...J.half},children:[r.jsx("div",{style:J.chartTitle,children:f("vocalReport.hitClassification","Hit classification")}),r.jsx("div",{style:{height:220},children:r.jsx(ie.NicePieChart,{width:400,height:260,data:G.map(S=>({label:S.name,value:Ht(S.value),color:S.fill}))})})]}),r.jsxs("div",{style:{...J.chartWrap,...J.half},children:[r.jsx("div",{style:J.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:Z.map(S=>S.metric),series:[{name:f("vocalReport.performanceProfile","Performance profile"),type:"radar",color:"var(--nice-info, #3b82f6)",data:Z.map(S=>Ht(S.value))},{name:"100%",type:"radar",color:"transparent",data:Z.map(S=>S.max)}]})})]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.pitchTracking","Pitch tracking")]}),r.jsxs("div",{style:J.chartWrap,children:[r.jsx("div",{style:J.chartTitle,children:f("vocalReport.sungVsExpected","Sung vs expected")}),r.jsx("div",{style:{height:260},children:r.jsx(ie.NiceChart,{width:860,height:230,categories:Qs(V.map(S=>S.t)),series:[{name:f("vocalReport.expected","Expected"),type:"line",color:"var(--nice-success, #22c55e)",data:V.map(S=>Ht(S.expected))},{name:f("vocalReport.sung","Sung"),type:"line",color:"var(--nice-info, #3b82f6)",data:V.map(S=>Ht(S.sung))}]})})]}),r.jsxs("div",{style:J.chartWrap,children:[r.jsx("div",{style:J.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:Qs(K.map(S=>S.t)),series:[{name:f("vocalReport.rollingAccuracy","Rolling accuracy"),type:"area",color:"var(--nice-accent, #8b5cf6)",data:K.map(S=>Ht(S.accuracy))}]})})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.vocalRange","Vocal range")]}),r.jsxs("div",{style:J.row,children:[r.jsx("div",{style:J.half,children:r.jsx("table",{style:J.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.lowestNote","Lowest note")}),r.jsx("td",{style:J.tdRight,children:f("vocalReport.hz","{lowestNote} ({lowestHz} Hz)").replace("{lowestNote}",String(R.lowestNote)).replace("{lowestHz}",String(R.lowestHz))})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.highestNote","Highest note")}),r.jsx("td",{style:J.tdRight,children:f("vocalReport.hz2","{highestNote} ({highestHz} Hz)").replace("{highestNote}",String(R.highestNote)).replace("{highestHz}",String(R.highestHz))})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.rangeLabel","Range")}),r.jsxs("td",{style:J.tdRight,children:[R.rangeInSemitones," ",f("vocalReport.semitones","semitones")]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.tessitura","Tessitura")}),r.jsxs("td",{style:J.tdRight,children:[R.tessituraLow," — ",R.tessituraHigh]})]})]})})}),r.jsxs("div",{style:{...J.chartWrap,...J.half},children:[r.jsx("div",{style:J.chartTitle,children:f("vocalReport.chromagram","Chromagram")}),r.jsx("div",{style:{height:180},children:r.jsx(ie.NiceChart,{width:400,height:180,showLegend:!1,categories:F.map(S=>S.note),series:[{name:f("vocalReport.usagePct","Usage %"),type:"bar",color:"var(--nice-primary, #6366f1)",data:F.map(S=>Ht(S.pct))}]})})]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.vibratoStability","Vibrato & stability")]}),r.jsxs("div",{style:J.row,children:[r.jsx("div",{style:J.half,children:r.jsx("table",{style:J.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.vibratoDetected","Vibrato detected")}),r.jsx("td",{style:J.tdRight,children:r.jsx("span",{style:J.badge(R.vibrato.detected?"var(--nice-success, #22c55e)":"var(--nice-text-muted, #64748b)"),children:R.vibrato.detected?f("vocalReport.yes","Yes"):f("vocalReport.no","No")})})]}),R.vibrato.detected&&r.jsxs(r.Fragment,{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.avgRate","Avg. rate")}),r.jsxs("td",{style:J.tdRight,children:[R.vibrato.avgRateHz," Hz"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.avgExtent","Avg. extent")}),r.jsxs("td",{style:J.tdRight,children:["±",R.vibrato.avgExtentCents," ",N]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.regularity","Regularity")}),r.jsxs("td",{style:J.tdRight,children:[R.vibrato.regularityPct,"%"]})]})]})]})})}),r.jsx("div",{style:J.half,children:r.jsx("table",{style:J.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.jitter","Jitter")}),r.jsxs("td",{style:J.tdRight,children:[R.jitterPct,"%"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.vocalPresence","Vocal presence")}),r.jsxs("td",{style:J.tdRight,children:[R.shimmerProxy,"%"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.avgOnsetDev","Avg. onset deviation")}),r.jsxs("td",{style:J.tdRight,children:[R.avgOnsetDeviationMs," ms"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.rhythmStability","Rhythm stability")}),r.jsx("td",{style:J.tdRight,children:r.jsxs("span",{style:J.badge(mt(R.rhythmStabilityPct)),children:[R.rhythmStabilityPct,"%"]})})]})]})})})]}),R.verseMetrics.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.verseBreakdown","Per-verse breakdown")]}),r.jsxs("div",{style:J.chartWrap,children:[r.jsx("div",{style:J.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:q.map(S=>S.verse),series:Zs(q.map(S=>`${w} (${S.verse})`),q.map(S=>S.accuracy),q.map(S=>Ys(S.label)))})})]}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:f("vocalReport.verse","Verse")}),r.jsx("th",{style:J.th,children:f("vocalReport.rating","Rating")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.hitPct","Hit %")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.avgDeviation","Avg. dev.")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.notes","Notes")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.notesHit","Hit")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.comboBonus","Combo bonus")})]})}),r.jsx("tbody",{children:R.verseMetrics.map((S,O)=>r.jsxs("tr",{children:[r.jsxs("td",{style:J.td,children:[f("vocalReport.verse","Verse")," ",S.verseIndex+1]}),r.jsx("td",{style:J.td,children:r.jsx("span",{style:J.badge(Ys(S.label)),children:S.label})}),r.jsxs("td",{style:J.tdRight,children:[(S.hitFraction*100).toFixed(1),"%"]}),r.jsxs("td",{style:J.tdRight,children:[S.avgCentDeviation," ¢"]}),r.jsx("td",{style:J.tdRight,children:S.noteCount}),r.jsx("td",{style:J.tdRight,children:S.notesHit}),r.jsxs("td",{style:J.tdRight,children:["+",S.comboBonus]})]},O))})]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.scoringConfig","Scoring configuration")]}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:f("vocalReport.parameter","Parameter")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.value","Value")}),r.jsx("th",{style:J.th,children:f("vocalReport.description","Description")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.difficultyLevel","Difficulty level")}),r.jsx("td",{style:J.tdRight,children:R.difficulty}),r.jsx("td",{style:J.td,children:f("vocalReport.difficultyLevelDesc","Affects tolerance and multiplier.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.semitoneTolerance","Semitone tolerance")}),r.jsx("td",{style:J.tdRight,children:I.semitoneTolerance}),r.jsx("td",{style:J.td,children:f("vocalReport.semitoneToleranceDesc","Pitch window counted as a hit.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.preWindow","Pre window")}),r.jsxs("td",{style:J.tdRight,children:[I.preWindow," s"]}),r.jsx("td",{style:J.td,children:f("vocalReport.preWindowDesc","Lead-in time before a note.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.postExtra","Post extra")}),r.jsxs("td",{style:J.tdRight,children:[I.postExtra," s"]}),r.jsx("td",{style:J.td,children:f("vocalReport.postExtraDesc","Grace time after a note.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.difficultyMultiplier","Difficulty multiplier")}),r.jsxs("td",{style:J.tdRight,children:[I.difficultyMult,"×"]}),r.jsx("td",{style:J.td,children:f("vocalReport.difficultyMultiplierDesc","Score scaling for difficulty.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.songBpm","Song BPM")}),r.jsx("td",{style:J.tdRight,children:R.songBpm}),r.jsx("td",{style:J.td,children:f("vocalReport.songBpmDesc","Tempo used for note timing.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.totalNotes","Total notes")}),r.jsx("td",{style:J.tdRight,children:P}),r.jsx("td",{style:J.td,children:f("vocalReport.totalNotesDesc","Number of scored notes in the song.")})]})]})]}),C.some(S=>S.micSettings)&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.micConfig","Microphone configuration")]}),C.map((S,O)=>S.micSettings&&r.jsxs("div",{style:{marginBottom:16},children:[C.length>1&&r.jsx("h4",{style:{color:S.playerColor,margin:"0 0 8px",fontSize:14},children:S.playerName}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:f("vocalReport.setting","Setting")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.value","Value")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.device","Device")}),r.jsx("td",{style:J.tdRight,children:S.micSettings.deviceLabel||S.micSettings.deviceId})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.pitchAlgorithm","Pitch algorithm")}),r.jsx("td",{style:J.tdRight,children:S.micSettings.algorithm})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.inputGain","Input gain")}),r.jsxs("td",{style:J.tdRight,children:[S.micSettings.gain,"×"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.rmsThreshold","RMS threshold")}),r.jsx("td",{style:J.tdRight,children:S.micSettings.rmsThreshold})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.pitchThreshold","Pitch threshold")}),r.jsx("td",{style:J.tdRight,children:S.micSettings.pitchThreshold})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.smoothingWindow","Smoothing window")}),r.jsxs("td",{style:J.tdRight,children:[S.micSettings.smoothingWindow," ",f("vocalReport.frames","frames")]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.hysteresisFrames","Hysteresis frames")}),r.jsx("td",{style:J.tdRight,children:S.micSettings.hysteresisFrames})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.hanningWindow","Hanning window")}),r.jsx("td",{style:J.tdRight,children:S.micSettings.useHanning?f("vocalReport.enabled","Enabled"):f("vocalReport.disabled","Disabled")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.latencyOffset","Latency offset")}),r.jsxs("td",{style:J.tdRight,children:[S.micSettings.latencyOffsetMs," ms"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.monitor","Monitor")}),r.jsx("td",{style:J.tdRight,children:S.micSettings.monitorEnabled?`${f("vocalReport.on","On")} (${Math.round(S.micSettings.monitorVolume*100)}%)`:f("vocalReport.off","Off")})]})]})]})]},O))]}),r.jsx("div",{style:J.footer,children:r.jsxs("p",{children:[f("vocalReport.footerGenerated","Report generated")," ·"," ",R.timestamp.replace(/[-:T.Z]/g,"").slice(0,14)]})})]})]})},ip="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 op(e){if(!e)return"";const t=Math.floor(e/60),n=Math.round(e%60);return`${t}:${n.toString().padStart(2,"0")}`}function ei(e){return Array.from(new Set(e.filter(t=>!!t))).sort((t,n)=>t.localeCompare(n))}const lp=Object.assign(d.memo(({song:e,index:t,active:n,coverUrl:a,topScore:s,selected:i,multiSelect:o,disabled:l,t:c,onPlay:u,onToggleSelect:h,onFocusRow:p})=>{const g=()=>{o?h(e.id):l||u==null||u(e)};return r.jsxs("div",{className:`nice-ksb-row${i?" nice-ksb-row--selected":""}${n?" nice-ksb-row--active":""}`,role:"option","aria-selected":i,"data-ksb-index":t,tabIndex:n?0:-1,onClick: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:op(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(B.NtdTrophy,{size:11})," ",s.score.toLocaleString()]})]}),!o&&r.jsxs("button",{type:"button",className:"nice-ksb-row__play",disabled:l,onClick:y=>{y.stopPropagation(),u==null||u(e)},children:[r.jsx(B.NtdPlay,{size:13})," ",c("karaokeBrowser.play","Play")]})]})}),{displayName:"NiceKaraokeSongRow"}),cp={artist:"Artist",title:"Title",year:"Year",genre:"Genre"},dp=({songs:e,fetchSongs:t,loading:n=!1,getCover:a,getTopScore:s,onPlay:i,onSelect:o,multiSelect:l=!1,maxSelections:c=0,showSidebar:u=!0,enableGamepad:h=!0,disabled:p=!1,disabledReason:g,t:y,className:m,style:x,id:b,accessMode:f,"data-testid":j})=>{const{t:v}=xe(),C=y??v,[T,M]=d.useState(""),[k,R]=d.useState(""),[P,I]=d.useState(""),[A,L]=d.useState(""),[E,D]=d.useState("artist"),[Z,G]=d.useState("asc"),[F,q]=d.useState({type:"all"}),[V,K]=d.useState(new Set),[W,Q]=d.useState([]),[w,N]=d.useState(!1);d.useEffect(()=>{const he=setTimeout(()=>R(T),300);return()=>clearTimeout(he)},[T]),d.useEffect(()=>{if(e||!t)return;let he=!1;return N(!0),Promise.resolve(t({searchQuery:k.trim()||void 0,genres:P?[P]:void 0,languages:A?[A]:void 0})).then(we=>!he&&Q(we)).catch(()=>!he&&Q([])).finally(()=>!he&&N(!1)),()=>{he=!0}},[e,t,k,P,A]);const S=e??W,O=d.useMemo(()=>ei(S.map(he=>he.genre)),[S]),Y=d.useMemo(()=>ei(S.map(he=>he.language)),[S]),_=d.useMemo(()=>{let he=S;const we=k.trim().toLowerCase();we&&(he=he.filter(Pe=>`${Pe.title} ${Pe.artist}`.toLowerCase().includes(we))),P&&(he=he.filter(Pe=>Pe.genre===P)),A&&(he=he.filter(Pe=>Pe.language===A)),F.type==="genre"&&(he=he.filter(Pe=>Pe.genre===F.value)),F.type==="language"&&(he=he.filter(Pe=>Pe.language===F.value));const je=Z==="asc"?1:-1;return[...he].sort((Pe,$e)=>{const Ye=Pe[E]??"",ue=$e[E]??"";return typeof Ye=="number"&&typeof ue=="number"?(Ye-ue)*je:String(Ye).localeCompare(String(ue))*je})},[S,k,P,A,F,E,Z]),U=he=>{K(we=>{const je=new Set(we);return je.has(he)?je.delete(he):(c===0||je.size<c)&&je.add(he),je})},$=()=>{const he=S.filter(we=>V.has(we.id));o==null||o({songs:he})},H=n||w,X=he=>{he===E?G(we=>we==="asc"?"desc":"asc"):(D(he),G("asc"))},re=d.useRef(null),[oe,se]=d.useState(0),z=d.useRef(0),ee=d.useRef(_);ee.current=_,d.useEffect(()=>{se(he=>{const we=Math.min(Math.max(0,he),Math.max(0,_.length-1));return z.current=we,we})},[_.length]);const ae=d.useCallback(he=>{var je;const we=(je=re.current)==null?void 0:je.querySelector(`[data-ksb-index="${he}"]`);we==null||we.focus(),we==null||we.scrollIntoView({block:"nearest"})},[]),ce=d.useCallback(he=>{z.current=he,se(he)},[]),le=d.useCallback((he,we=!0)=>{const je=ee.current.length;if(je===0)return;const Pe=Math.min(je-1,Math.max(0,he));z.current=Pe,se(Pe),we&&requestAnimationFrame(()=>ae(Pe))},[ae]),ne=d.useCallback(he=>le(z.current+he),[le]),pe=he=>{const we=ee.current[he];we&&(l?U(we.id):p||i==null||i(we))},fe=he=>{switch(he.key){case"ArrowDown":he.preventDefault(),ne(1);break;case"ArrowUp":he.preventDefault(),ne(-1);break;case"Home":he.preventDefault(),le(0);break;case"End":he.preventDefault(),le(ee.current.length-1);break;case"PageDown":he.preventDefault(),ne(5);break;case"PageUp":he.preventDefault(),ne(-5);break}},ge=ve.useGamepad({enabled:h,actions:{navUp:{button:"DpadUp",onPress:()=>ne(-1),repeatDelay:350,repeatRate:110},navDown:{button:"DpadDown",onPress:()=>ne(1),repeatDelay:350,repeatRate:110},stickUp:{axis:"LeftY",axisDirection:"negative",onPress:()=>ne(-1),repeatDelay:350,repeatRate:130},stickDown:{axis:"LeftY",axisDirection:"positive",onPress:()=>ne(1),repeatDelay:350,repeatRate:130},select:{button:"A",onPress:()=>pe(z.current)},confirm:{button:"Start",onPress:()=>{l&&$()}}}});return f==="hidden"?null:r.jsxs("div",{className:`nice-ksb${m?` ${m}`:""}`,style:x,id:b,"data-testid":j,children:[u&&r.jsxs("aside",{className:"nice-ksb__sidebar",children:[r.jsxs("button",{type:"button",className:`nice-ksb__node${F.type==="all"?" nice-ksb__node--active":""}`,onClick:()=>q({type:"all"}),children:[r.jsx(B.NtdMusic,{size:14})," ",C("karaokeBrowser.allSongs","All songs")," (",S.length,")"]}),O.length>0&&r.jsxs("div",{className:"nice-ksb__facet",children:[r.jsx("div",{className:"nice-ksb__facet-title",children:C("karaokeBrowser.genres","Genres")}),O.map(he=>r.jsx("button",{type:"button",className:`nice-ksb__node${F.type==="genre"&&F.value===he?" nice-ksb__node--active":""}`,onClick:()=>q({type:"genre",value:he}),children:he},he))]}),Y.length>0&&r.jsxs("div",{className:"nice-ksb__facet",children:[r.jsx("div",{className:"nice-ksb__facet-title",children:C("karaokeBrowser.languages","Languages")}),Y.map(he=>r.jsx("button",{type:"button",className:`nice-ksb__node${F.type==="language"&&F.value===he?" nice-ksb__node--active":""}`,onClick:()=>q({type:"language",value:he}),children:he},he))]})]}),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:T,placeholder:C("karaokeBrowser.search","Search title or artist…"),onChange:he=>M(he.target.value)}),r.jsx("div",{className:"nice-ksb__sort",children:["artist","title","year","genre"].map(he=>r.jsxs("button",{type:"button",className:`nice-ksb__sort-btn${E===he?" nice-ksb__sort-btn--active":""}`,onClick:()=>X(he),children:[C(`karaokeBrowser.sort.${he}`,cp[he]??he),E===he&&(Z==="asc"?r.jsx(B.NtdChevronUp,{size:12}):r.jsx(B.NtdChevronDown,{size:12}))]},he))}),r.jsxs("span",{className:`nice-ksb__navhint${ge.connected?" nice-ksb__navhint--pad":""}`,title:C("karaokeBrowser.navHint","Navigate with ↑ ↓ or the D-pad · Enter / A to play"),children:[ge.connected?r.jsx(B.NtdGamepad,{size:14}):r.jsx(B.NtdMove,{size:14}),r.jsx("span",{className:"nice-ksb__navhint-keys",children:ge.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":C("karaokeBrowser.songs","Songs"),ref:re,onKeyDown:fe,children:H?r.jsx("div",{className:"nice-ksb__empty",children:C("karaokeBrowser.loading","Loading…")}):_.length===0?r.jsx("div",{className:"nice-ksb__empty",children:C("karaokeBrowser.noResults","No songs found")}):_.map((he,we)=>r.jsx(lp,{song:he,index:we,active:we===oe,coverUrl:(a==null?void 0:a(he))||he.coverImage||he.externalCoverUrl||he.coverPath||ip,topScore:s==null?void 0:s(he),selected:V.has(he.id),multiSelect:l,disabled:p,t:C,onPlay:i,onToggleSelect:U,onFocusRow:ce},he.id))}),l&&r.jsxs("div",{className:"nice-ksb__footer",children:[r.jsxs("span",{children:[V.size,c>0?` / ${c}`:""," ",C("karaokeBrowser.selected","selected")]}),r.jsx("button",{type:"button",className:"nice-ksb__confirm",disabled:V.size===0,onClick:$,children:C("karaokeBrowser.confirm","Add selected")})]})]})]})};function cl(e,t,n=50,a=30){const s=Math.round(e/1e3*t),i=Math.round(n/1e3*t),o=Math.max(1,Math.round(a/1e3*t)),l=new Float32Array(s);for(let c=0;c<o;c++){const u=.5*(1-Math.cos(2*Math.PI*c/(o-1))),h=i+c-Math.floor(o/2);h>=0&&h<s&&(l[h]=u)}return l}function ti(e,t,n=1e3){const a=Math.max(1,Math.round(t/n)),s=Math.ceil(e.length/a),i=new Float32Array(s);for(let l=0;l<s;l++){const c=l*a,u=Math.min(e.length,c+a);let h=0;for(let p=c;p<u;p++)h+=Math.abs(e[p]);i[l]=h/(u-c||1)}let o=0;for(let l=0;l<i.length;l++)i[l]>o&&(o=i[l]);if(o>0)for(let l=0;l<i.length;l++)i[l]=i[l]/o;return{env:i,factor:a}}function up(e,t){const n=e.length,a=t.length;if(n===0||a===0)return 0;let s={lag:0,score:-1/0};const i=Math.min(2e3,a);for(let o=-i;o<=i;o++){let l=0,c=0,u=0;for(let 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,u+=x*x}const h=Math.sqrt(Math.max(1e-9,c*u)),p=l/h;p>s.score&&(s={lag:o,score:p})}return s.lag}function dl(e,t,n=50,a=30){try{const s=Math.max(300,Math.round(e.length/t*1e3)),i=cl(s,t,n,a),o=ti(e,t,1e3),l=ti(i,t,1e3),u=up(l.env,o.env)*1e3/1e3;return Math.round(u)}catch{return null}}const hp=({deviceId:e,initialOffsetMs:t=null,onSave:n,onClose:a,rounds:s=3,t:i,className:o,style:l,id:c,accessMode:u,"data-testid":h})=>{const{t:p}=xe(),g=i??p,[y,m]=d.useState(null),[x,b]=d.useState(t),[f,j]=d.useState(!1),[v,C]=d.useState([]),[T,M]=d.useState(0),[k,R]=d.useState(!1),P=d.useRef(!1);d.useEffect(()=>{b(t??null)},[t,e]);const I=async()=>{const D=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),Z=new AudioContext,G=Z.sampleRate,F=Z.createMediaStreamSource(D),q=Z.createScriptProcessor(2048,1,1);F.connect(q),q.connect(Z.destination);const V=1200,K=Math.round(V/1e3*G),W=new Float32Array(K);let Q=0,w=!1;q.onaudioprocess=U=>{if(w)return;const $=U.inputBuffer.getChannelData(0),H=Math.min($.length,K-Q);H>0&&(W.set($.subarray(0,H),Q),Q+=H),Q>=K&&(w=!0)},await new Promise(U=>setTimeout(U,80));const N=new AudioContext,S=N.createOscillator(),O=N.createGain();S.type="sine",S.frequency.value=1e3,O.gain.value=1e-4,S.connect(O),O.connect(N.destination);const Y=N.currentTime+.05;O.gain.setValueAtTime(1e-4,Y-.01),O.gain.linearRampToValueAtTime(1,Y),O.gain.linearRampToValueAtTime(1e-4,Y+.06),S.start(Y-.02),S.stop(Y+.1),await new Promise(U=>{const $=()=>{if(w||Q>=K){U();return}setTimeout($,50)};setTimeout(()=>{w=!0,U()},V+500),$()}),q.onaudioprocess=null;try{q.disconnect()}catch{}try{F.disconnect()}catch{}try{await N.close()}catch{}try{await Z.close()}catch{}D.getTracks().forEach(U=>U.stop());const _=W.subarray(0,Q);return dl(_,G,130,30)},A=async()=>{if(!P.current){P.current=!0,R(!0),m(g("latencyCalibrator.requestingMic","Requesting microphone — click allow if prompted")),b(null),C([]),M(0);try{const D=[];for(let G=0;G<s;G++){m(`${g("latencyCalibrator.playingTone","Playing test tone and recording…")} (${G+1}/${s})`),M(Math.round(G/s*100));const F=await I();F!==null&&(D.push(Math.max(-500,Math.min(2e3,Math.round(F)))),C([...D])),G<s-1&&await new Promise(q=>setTimeout(q,400))}if(M(100),D.length===0){m(g("latencyCalibrator.noSignal","No signal detected — try louder or check the microphone"));return}let Z;if(D.length>=3){const F=[...D].sort((q,V)=>q-V).slice(1,-1);Z=Math.round(F.reduce((q,V)=>q+V,0)/F.length)}else Z=Math.round(D.reduce((G,F)=>G+F,0)/D.length);b(Z),m(`${g("latencyCalibrator.measured","Measured")} ~${Z} ms (${D.length}: ${D.join(", ")} ms)`)}catch(D){m(`${g("latencyCalibrator.calibrationError","Calibration error: ")}${D instanceof Error?D.message:String(D)}`)}finally{P.current=!1,R(!1)}}},L=async()=>{if(!(x===null||!n)){j(!0);try{await n(Math.round(x)),m(g("latencyCalibrator.saved","Saved"))}catch(D){m(`${g("latencyCalibrator.saveError","Save error: ")}${String(D)}`)}finally{j(!1)}}},E={padding:"7px 16px",border:"none",borderRadius:8,cursor:"pointer",fontWeight:600};return u==="hidden"?null:r.jsxs("div",{className:`nice-latency-calibrator${o?` ${o}`:""}`,style:{padding:12,color:"var(--nice-text, inherit)",...l},id:c,"data-testid":h,children:[r.jsxs("h5",{style:{margin:"0 0 8px",display:"flex",alignItems:"center",gap:6},children:[r.jsx(B.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:k,style:{...E,background:"var(--nice-accent, #3b82f6)",color:"var(--nice-text-on-primary, #fff)"},children:g("latencyCalibrator.calibrate","Calibrate")}),r.jsx("button",{type:"button",onClick:()=>{b(null),m(null),C([]),M(0)},style:{...E,background:"var(--nice-bg-tertiary)",color:"var(--nice-text, #e2e8f0)"},children:g("latencyCalibrator.clear","Clear")})]}),k&&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:`${T}%`,background:"var(--nice-accent, #3b82f6)",transition:"width 0.2s"}})}),v.length>0&&r.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:[g("latencyCalibrator.rounds","Rounds"),": ",v.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:L,disabled:x===null||f,style:{...E,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:{...E,background:"transparent",border:"1px solid var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)"},children:g("latencyCalibrator.close","Close")})]})]})},pp=e=>[{value:"normal",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.NtdMicrophone,{size:14})," ",e("karaokeSetup.modeMic","Mic")]})},{value:"pad",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.NtdGamepad,{size:14})," ",e("karaokeSetup.modePad","Pad")]})},{value:"demo",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.NtdStopwatch,{size:14})," ",e("karaokeSetup.modeDemo","Demo")]})}],ul=({players:e,defaultPlayers:t,onPlayersChange:n,gameMode:a="normal",onGameModeChange:s,gameModes:i,difficulty:o="normal",onDifficultyChange:l,audioInputs:c,maxPlayers:u=4,onCalibrate:h,t:p,className:g,style:y,id:m,accessMode:x,"data-testid":b})=>{const{t:f}=xe(),j=p??f,v=d.useMemo(()=>i??pp(j),[i,j]),[C,T]=ve.useControllableState({value:e,defaultValue:t,fallbackValue:[],onChange:n,componentName:"NiceKaraokeSetupPanel"}),[M,k]=d.useState([]);d.useEffect(()=>{var Z,G,F;if(c||!((Z=navigator.mediaDevices)!=null&&Z.enumerateDevices))return;let E=!1;const D=()=>navigator.mediaDevices.enumerateDevices().then(q=>!E&&k(q.filter(V=>V.kind==="audioinput"))).catch(()=>{});return D(),(F=(G=navigator.mediaDevices).addEventListener)==null||F.call(G,"devicechange",D),()=>{var q,V;E=!0,(V=(q=navigator.mediaDevices).removeEventListener)==null||V.call(q,"devicechange",D)}},[c]);const R=c??M,P=d.useMemo(()=>[{value:"",label:j("karaokeSetup.noMic","No microphone")},...R.map((E,D)=>({value:E.deviceId,label:E.label||`${j("karaokeSetup.microphone","Microphone")} ${D+1}`}))],[R,j]),I=(E,D)=>T(C.map(Z=>Z.id===E?{...Z,...D}:Z)),A=()=>{if(C.length>=u)return;const E=C.reduce((D,Z)=>Math.max(D,Z.id),0)+1;T([...C,{id:E,name:`${j("karaokeSetup.player","Player")} ${C.length+1}`,color:Xe[C.length%Xe.length],micId:null}])},L=E=>T(C.filter(D=>D.id!==E));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":b,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:j("karaokeSetup.mode","Game mode")}),r.jsx(ie.NiceSegmentedControl,{options:v,value:a,onChange:E=>s==null?void 0:s(E)})]}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:12,fontWeight:600,marginBottom:6,color:"var(--nice-text-muted, #94a3b8)"},children:j("karaokeSetup.difficulty","Difficulty")}),r.jsx(ie.NiceSegmentedControl,{options:[{value:"easy",label:j("karaokeSetup.easy","Easy")},{value:"normal",label:j("karaokeSetup.normal","Normal")},{value:"hard",label:j("karaokeSetup.hard","Hard")}],value:o,onChange:E=>l==null?void 0:l(E)})]})]}),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:[j("karaokeSetup.players","Players")," (",C.length,"/",u,")"]}),C.map(E=>r.jsx(ie.NiceCard,{children:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[r.jsx(ie.NiceColorPicker,{value:E.color||Xe[0],onChange:D=>I(E.id,{color:D})}),r.jsx("div",{style:{flex:"1 1 160px",minWidth:140},children:r.jsx(ie.NiceTextInput,{value:E.name,onChange:D=>I(E.id,{name:D}),placeholder:j("karaokeSetup.playerName","Player name"),size:"sm"})}),r.jsx("div",{style:{flex:"1 1 180px",minWidth:150},children:r.jsx(ie.NiceSelect,{options:P,value:E.micId??"",onChange:D=>I(E.id,{micId:(typeof D=="string"?D:D[0])||null}),placeholder:j("karaokeSetup.selectMic","Microphone"),size:"sm"})}),h&&E.micId&&r.jsxs(ie.NiceButton,{variant:"ghost",size:"sm",onClick:()=>h(E.micId),children:[r.jsx(B.NtdSettings,{size:14})," ",j("karaokeSetup.calibrate","Calibrate")]}),r.jsx(ie.NiceButton,{variant:"danger",size:"sm",onClick:()=>L(E.id),"aria-label":j("karaokeSetup.remove","Remove"),children:r.jsx(B.NtdClose,{size:14})})]})},E.id)),r.jsx("div",{children:r.jsxs(ie.NiceButton,{variant:"primary",onClick:A,disabled:C.length>=u,children:[r.jsx(B.NtdPlus,{size:14})," ",j("karaokeSetup.addPlayer","Add player")]})})]})]})},fp=[],mp=["freeForAll","roundRobin","hostOnly","firstCome"],gp={freeForAll:B.NtdDice,roundRobin:B.NtdRepeat,hostOnly:B.NtdCrown,firstCome:B.NtdLightning},yp={freeForAll:"success",roundRobin:"warning",hostOnly:"info",firstCome:"danger"},hl=({players:e=fp,mode:t,defaultMode:n,onModeChange:a,turnTimeSec:s=30,hostIndex:i=0,onActivePlayerChange:o,myPlayerIndex:l,t:c,className:u,style:h,id:p,accessMode:g,"data-testid":y})=>{const{t:m}=xe(),x=c??m,[b,f]=ve.useControllableState({value:t,defaultValue:n,fallbackValue:"freeForAll",onChange:a,componentName:"NiceKaraokeSelectionMode"}),j={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,C]=d.useState(0),[T,M]=d.useState(s),k=d.useRef(null),[R,P]=d.useState(null),[I,A]=d.useState(!1),[L,E]=d.useState(null),D=d.useRef(null),Z=d.useMemo(()=>b==="hostOnly"?i:b==="roundRobin"?v%Math.max(1,e.length):b==="firstCome"?I?-1:L??-1:-1,[b,v,e.length,i,I,L]);d.useEffect(()=>{o==null||o(Z)},[Z,o]),d.useEffect(()=>{if(b!=="roundRobin"||s<=0){k.current&&clearInterval(k.current);return}return M(s),k.current=setInterval(()=>{M(K=>K<=1?(C(W=>W+1),s):K-1)},1e3),()=>{k.current&&clearInterval(k.current)}},[b,s,v]);const G=d.useCallback(()=>{E(null),A(!1),P(3),D.current&&clearInterval(D.current),D.current=setInterval(()=>{P(K=>K===null||K<=1?(D.current&&clearInterval(D.current),A(!0),null):K-1)},1e3)},[]);d.useEffect(()=>()=>{D.current&&clearInterval(D.current)},[]),d.useEffect(()=>{b!=="firstCome"&&(P(null),A(!1),E(null))},[b]);const F=d.useCallback(()=>{C(K=>K+1),M(s)},[s]),q=K=>{var W;return((W=e[K])==null?void 0:W.name)||`${x("songSelection.player","Player")} ${K+1}`},V=Z>=0&&Z<e.length?e[Z]:null;return g==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-selection-mode${u?` ${u}`:""}`,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:mp.map(K=>r.jsxs(ie.NiceButton,{size:"sm",variant:b===K?yp[K]:"outline",onClick:()=>f(K),children:[d.createElement(gp[K],{size:14})," ",j[K]]},K))}),b!=="freeForAll"&&b!=="firstCome"&&V&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsxs(ie.NiceBadge,{variant:Z===l?"success":"secondary",children:[r.jsx(B.NtdMicrophone,{size:12})," ",q(Z)]}),Z===l&&r.jsx("span",{style:{color:"var(--nice-success, #4caf50)",fontSize:12,fontWeight:600},children:x("songSelection.yourTurn","Your turn!")})]}),b==="roundRobin"&&s>0&&r.jsx("div",{style:{flex:1,minWidth:120,maxWidth:200},children:r.jsx(ie.NiceProgress,{value:T,max:s,variant:T<=5?"error":T<=10?"warning":"info",showValue:!0,formatValue:K=>`${K}s`})}),b==="roundRobin"&&r.jsxs(ie.NiceButton,{size:"sm",variant:"ghost",onClick:F,children:[x("songSelection.next","Next")," ",r.jsx(B.NtdPlay,{size:12})]}),b==="firstCome"&&r.jsxs(r.Fragment,{children:[R!==null&&r.jsx("div",{style:{fontSize:32,fontWeight:900,color:"var(--nice-error, #f44336)",minWidth:60,textAlign:"center"},children:R}),I&&L===null&&r.jsxs(ie.NiceBadge,{variant:"danger",children:[r.jsx(B.NtdLightning,{size:12})," ",x("songSelection.raceGo","GO! Pick a song!")]}),L!==null&&L<e.length&&r.jsxs(ie.NiceBadge,{variant:"success",children:[r.jsx(B.NtdTrophy,{size:12})," ",q(L)," ",x("songSelection.raceWon","picks!")]}),r.jsx(ie.NiceButton,{size:"sm",variant:R!==null?"secondary":"danger",onClick:G,disabled:R!==null,children:L!==null?r.jsxs(r.Fragment,{children:[r.jsx(B.NtdRepeat,{size:12})," ",x("songSelection.raceAgain","New race")]}):r.jsxs(r.Fragment,{children:[r.jsx(B.NtdLightning,{size:12})," ",x("songSelection.raceStart","Start race")]})})]})]})};function vp(e,t,n,a){return d.useMemo(()=>e==="freeForAll"?!0:e==="firstCome"?t===-1:e==="hostOnly"?a===n:e==="roundRobin"?a===t:!1,[e,t,n,a])}const bp=({players:e,defaultPlayers:t,onPlayersChange:n,gameMode:a,onGameModeChange:s,gameModes:i,difficulty:o,onDifficultyChange:l,audioInputs:c,maxPlayers:u=4,onCalibrate:h,initialSelectionMode:p="freeForAll",turnTimeSec:g=30,hostIndex:y=0,myPlayerIndex:m,onChange:x,variant:b="bar",t:f,className:j,style:v,id:C,accessMode:T,"data-testid":M})=>{const{t:k}=xe(),R=f??k,[P,I]=ve.useControllableState({value:e,defaultValue:t,fallbackValue:[],onChange:n,componentName:"NiceKaraokeSessionJoin"}),[A,L]=d.useState([]);d.useEffect(()=>{var Y,_,U;if(c||!((Y=navigator.mediaDevices)!=null&&Y.enumerateDevices))return;let S=!1;const O=()=>navigator.mediaDevices.enumerateDevices().then($=>!S&&L($.filter(H=>H.kind==="audioinput"))).catch(()=>{});return O(),(U=(_=navigator.mediaDevices).addEventListener)==null||U.call(_,"devicechange",O),()=>{var $,H;S=!0,(H=($=navigator.mediaDevices).removeEventListener)==null||H.call($,"devicechange",O)}},[c]);const E=c??A,D=E.length===0,Z=P.some(S=>!S.micId),G=!Z,[F,q]=d.useState(p),[V,K]=d.useState(-1),W=d.useCallback((S,O)=>{x==null||x({selectionMode:S,activePickerIndex:O,allMicsAssigned:G,noInputDevices:D})},[x,G,D]),Q=d.useCallback(S=>{q(S),W(S,V)},[W,V]),w=d.useCallback(S=>{K(S),W(F,S)},[W,F]),N=d.useMemo(()=>({padding:10,borderRadius:8,fontWeight:700,marginTop:8,textAlign:"center"}),[]);return T==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-session-join${j?` ${j}`:""}`,style:b==="card"?{background:"var(--nice-bg-secondary)",borderRadius:12,padding:16,...v}:v,id:C,"data-testid":M,children:[r.jsx(ul,{players:P,onPlayersChange:I,gameMode:a,onGameModeChange:s,gameModes:i,difficulty:o,onDifficultyChange:l,audioInputs:E,maxPlayers:u,onCalibrate:h,t:R}),D&&r.jsxs("div",{style:{...N,background:"var(--nice-error, #ef4444)",color:"#fff"},children:[R("karaokeSessionJoin.noInputDevices","No microphone detected"),r.jsx("br",{}),r.jsx("span",{style:{fontWeight:400,fontSize:13},children:R("karaokeSessionJoin.noInputDevicesHint","Connect a microphone to sing.")})]}),!D&&Z&&r.jsx("div",{style:{...N,background:"var(--nice-warning, #f59e0b)",color:"var(--nice-text-on-primary, #222)",fontSize:14},children:R("karaokeSessionJoin.assignMicWarning","Assign a microphone to each player.")}),P.length>1&&r.jsx("div",{style:{marginTop:12},children:r.jsx(hl,{players:P,mode:F,onModeChange:Q,onActivePlayerChange:w,turnTimeSec:g,hostIndex:y,myPlayerIndex:m,t:R})})]})};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 xp=[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")],Qa="nice2dev-karaoke-display",Sp=(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"},...xp.map(e=>({value:e.family,label:e.family}))]})(),pl=[{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)"}],yn={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 fl(){try{const e=localStorage.getItem(Qa);if(e){const t=JSON.parse(e);return{...yn,...t}}}catch{}return{...yn}}async function kp(e){if(ni||(ni=!0,!e))return;const t=await e();if(t)try{const n=JSON.parse(t),a={...yn,...n};localStorage.setItem(Qa,JSON.stringify(a))}catch{}}function wp(e){const t=JSON.stringify(e);localStorage.setItem(Qa,t),Ja(e)}function ml(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=pl.find(n=>n.id===e.presetId);return t?{sungGradient:t.sungGradient,goldGradient:t.goldGradient,glowColor:t.glowColor}:{sungGradient:yn.customSungGradient,goldGradient:yn.customGoldGradient,glowColor:yn.customGlowColor}}function Ja(e){const{sungGradient:t,goldGradient:n,glowColor:a}=ml(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 Cp(){const e=fl();Ja(e)}function jp(e){const t=(e||"").split(/\r?\n/),n=[];for(let a=0;a<t.length;a++){const s=t[a].trim();if(s&&/^[:*F]\s/.test(s)){const i=s.slice(1).trim().split(/\s+/),o=parseInt(i[0]||"0",10),l=parseInt(i[1]||"0",10),c=isNaN(o)?0:o/10,u=isNaN(l)?0:l/10;n.push({lineIndex:a,start:c,duration:u,raw:t[a]})}}return n}const Mp=({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,u=(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))",b={transition:u?`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:{...b,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})})})},Rp=({ultrastarText:e,audioUrl:t,audioRef:n,animationConfig:a})=>{const{t:s}=xe(),i=d.useRef(null),o=n??i,[l,c]=d.useState(!1),u=d.useMemo(()=>jp(e),[e]),h=d.useRef(null),p=d.useRef(null),g=d.useRef(0),y=d.useRef(0),[m,x]=d.useState(-1),b=d.useMemo(()=>(e||"").split(/\r?\n/),[e]),f=28,j=b.length*f,v=d.useMemo(()=>({lines:b,notes:u,currentIndex:m,animationConfig:a}),[b,u,m,a]),C=d.useCallback((T,M)=>r.jsx(Mp,{index:M,data:v}),[v]);return d.useEffect(()=>{const T=o.current;T&&(l?T.play().catch(()=>c(!1)):T.pause())},[l,o]),d.useEffect(()=>{const T=o.current;if(!T)return;let M=-1;const k=a??null,R=k&&typeof k.scrollSmooth=="number"?k.scrollSmooth:.18;let P=performance.now();const I=()=>{var W,Q;const A=performance.now(),L=Math.max(0,Math.min(.2,(A-P)/1e3));P=A;const E=T.currentTime||0;g.current=E;let D=-1;for(let w=0;w<u.length;w++){const N=u[w];if(E>=N.start&&E<N.start+Math.max(.001,N.duration)){D=w;break}}D!==M&&(M=D,x(D));let Z=0;if(M>=0){const w=((W=u[M])==null?void 0:W.lineIndex)??0,N=((Q=h.current)==null?void 0:Q.clientHeight)??220;Z=w*f-N/2+f/2;const S=Math.max(0,j-N);(isNaN(Z)||!isFinite(Z))&&(Z=0),Z=Math.max(0,Math.min(Z,S))}const G=1-Math.pow(Math.max(0,1-R),Math.min(4,L*60)),K=(((a==null?void 0:a.scrollEasing)||"easeOutCubic")==="linear"?w=>w:w=>1-Math.pow(1-w,3))(G);y.current=y.current+(Z-y.current)*K;try{const w=h.current;w&&typeof w.scrollTop=="number"&&(w.scrollTop=Math.round(y.current))}catch{}p.current=requestAnimationFrame(I)};return p.current=requestAnimationFrame(I),()=>{p.current&&cancelAnimationFrame(p.current)}},[o,u,j,a]),r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[r.jsx("button",{onClick:()=>c(T=>!T),disabled:!t,children:l?s("karaokeEditor.pause","Pause"):s("karaokeEditor.play","Play")}),r.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-secondary, #666)"},children:[(g.current||0).toFixed(2),"s"]}),r.jsx("div",{style:{marginLeft:"auto",fontSize:13,color:"var(--nice-text-secondary, #666)"},children:s("karaokeEditor.notes","Notes: {notes}").replace("{notes}",String(u.length))})]}),r.jsx("div",{style:{border:"1px solid var(--nice-border, #ddd)",height:220,overflow:"hidden",padding:8,position:"relative"},children:e?r.jsx(ie.NiceVirtualScroller,{ref:h,items:b,itemHeight:f,height:220,renderItem:C,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 Np(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 Tp=new Set;function Pp({ultrastarText:e,audioUrl:t,audioRef:n,ytRef:a}){const{lines:s,notes:i}=d.useMemo(()=>Np(e),[e]),[o,l]=d.useState(Tp),c=d.useRef(i);c.current=i;const u=d.useRef(t);return u.current=t,d.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:u.current&&(p=document.createElement("audio"),p.src=u.current,p.preload="metadata",p.style.display="none",document.body.appendChild(p),h=p)}let g=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 f=new Set;for(const v of c.current)x>=v.start&&x<v.start+Math.max(.001,v.duration)&&f.add(v.lineIndex);const j=[...f].join(",");j!==y&&(y=j,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 Ep=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),ri=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")}`},na={border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},$p=({isPlaying:e,index:t,count:n,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek:u,onVolume:h})=>{const{t:p}=xe();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:[ri(a)," / ",ri(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:na,children:r.jsx(B.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:na,children:e?r.jsx(B.NtdPause,{size:16}):r.jsx(B.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:na,children:r.jsx(B.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=>u(parseFloat(g.target.value))}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx(B.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))})]})]})]})},Ap=d.memo($p);function Ip(e,t,n,a,s){const o=Math.max(1,Math.floor(a.length/48)),l=t/48;for(let c=0;c<48;c++){const u=a[c*o]/255,h=u*(n-6),p=c*l,g=n-h,y=c/48*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+u*30)}%)`,e.fillRect(p+1,g,l-2,h)}}function Lp(e,t,n,a,s,i){if(!i.current){const p=[];for(let y=0;y<24;y++)p.push({ang:y/24*Math.PI*2,phase:Math.random()*Math.PI*2,baseR:Math.min(t,n)*.22+Math.random()*30});i.current={nodes:p}}const o=i.current,l=t/2,c=n/2,u=26+a*80,h=[];for(const p of o.nodes){p.phase+=.02+a*.06;const g=p.baseR+Math.sin(p.phase)*u,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],b=(g+m)/2,f=(y+x)/2;p===0?e.moveTo(b,f):e.quadraticCurveTo(g,y,b,f)}e.closePath(),e.fill(),e.stroke()}function _p(e,t,n,a,s,i){i.current||(i.current={items:[]});const o=i.current;Math.random()<.06+a*.25&&o.items.push({x:Math.random()*t,y:Math.random()*n,r:8+Math.random()*24,life:1,hue:(s+Math.random()*120)%360});const l=[];for(const c of o.items){c.r+=2+a*14,c.life*=.975-a*.02,c.life>.04&&l.push(c);const u=e.createRadialGradient(c.x,c.y,1,c.x,c.y,c.r);u.addColorStop(0,`hsla(${c.hue}, 90%, 60%, ${.35*c.life})`),u.addColorStop(.6,`hsla(${(c.hue+40)%360}, 80%, 55%, ${.18*c.life})`),u.addColorStop(1,`hsla(${(c.hue+80)%360}, 70%, 50%, 0)`),e.fillStyle=u,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}o.items=l}const Dp="var(--nice-text-muted, #94a3b8)",zp=({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:Dp},children:s??a??"—"})]})});function rn(e,t){return e+Math.random()*(t-e)}function Fp(e,t,n,a,s,i,o){o.current||(o.current={embers:[],t:0});const l=o.current,c=e.createLinearGradient(0,n,0,n*.4);c.addColorStop(0,`hsla(${(i+30)%360}, 90%, 50%, .35)`),c.addColorStop(1,`hsla(${(i+10)%360}, 90%, 50%, 0)`),e.fillStyle=c,e.fillRect(0,0,t,n);const u=6;for(let p=0;p<u;p++){const g=(p+.5)/u*t,y=(a[Math.floor((p+1)/(u+1)*a.length)]||0)/255,m=n*.18+(.25+s*.6+y*.7)*n*.55,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 b=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+b,n-m*.75,g+b,n-m),e.bezierCurveTo(g+25+b*.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:rn(t*.25,t*.75),y:n-rn(4,14),r:rn(1,3),vx:rn(-.15,.15),vy:-rn(.6,1.8)-s*1.2,life:rn(.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 Op(e,t,n,a,s){const i=t/2,o=n/2,l=Math.min(t,n)*.28,c=96,u=Math.max(1,Math.floor(a.length/c));for(let h=0;h<c;h++){const p=(a[h*u]??0)/255,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,b=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(b,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 Bp(e,t,n,a,s){const l=t/14,c=n/8;for(let u=0;u<8;u++)for(let h=0;h<14;h++){const p=Math.min(a.length-1,u*14+h),g=a[p]/255,y=(s+h/14*210+u/8*90)%360,m=65+g*30,x=20+g*40,b=(1-g)*4;e.fillStyle=`hsl(${y}, ${m}%, ${x}%)`,e.fillRect(h*l+b,u*c+b,Math.max(1,l-2*b),Math.max(1,c-2*b))}}function Gp(e){const n=Array.from(new Set(e.filter(Boolean))).map(a=>new Promise(s=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>s(i),i.onerror=()=>s(i),i.src=a}));return Promise.all(n)}async function Wp(e,t,n,a,s){e.current||(e.current={sprites:[],loadedUrls:[],ready:!1});const i=e.current,o=t.join("|")!==i.loadedUrls.join("|");if(!i.ready||o){const l=await Gp(t.length?t:[]);i.loadedUrls=t,i.sprites=[],i.ready=!0;const c=u=>l[u%Math.max(1,l.length)]??new Image;for(let u=0;u<n;u++){const h=Math.random()*Math.min(a,s)*.38+40;i.sprites.push({img:c(u),x:(Math.random()-.5)*h*.4,y:(Math.random()-.5)*h*.4,z:Math.random()*600+100,ang:Math.random()*Math.PI*2,spin:(Math.random()*.03+.01)*(Math.random()<.5?-1:1),vz:Math.random()*1.2+.2,size:Math.random()*.35+.65})}}}function Up(e,t,n,a,s,i,o,l){const c=i.current;if(!(c!=null&&c.ready))return;const u=t/2,h=n/2,p=900,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,b=u+m.x*x,f=h+m.y*x,j=64*x,v=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(b,f,j*.7,v*.7,0,0,Math.PI*2),e.fill(),e.restore(),m.img&&m.img.width?e.drawImage(m.img,b-j/2,f-v/2,j,v):(e.save(),e.fillStyle=`hsl(${(s+180)%360}, 40%, 55%)`,e.fillRect(b-j/2,f-v/2,j,v),e.restore())}}function jn(e,t){return e+Math.random()*(t-e)}function Vp(e,t,n,a,s,i){i.current||(i.current={blobs:Array.from({length:7},(u,h)=>({x:jn(t*.2,t*.8),y:jn(n*.2,n*.8),r:jn(Math.min(t,n)*.05,Math.min(t,n)*.12),vx:jn(-.6,.6),vy:jn(-.6,.6),hue:(s+h*10)%360}))});const o=i.current,l=.6+a*2.2;e.save(),e.globalCompositeOperation="lighter";for(const c of o.blobs){c.x+=c.vx*l,c.y+=c.vy*l,c.vy-=.01-a*.015,c.x<c.r&&(c.x=c.r,c.vx=Math.abs(c.vx)),c.x>t-c.r&&(c.x=t-c.r,c.vx=-Math.abs(c.vx)),c.y<c.r&&(c.y=c.r,c.vy=Math.abs(c.vy)),c.y>n-c.r&&(c.y=n-c.r,c.vy=-Math.abs(c.vy));const u=(c.hue+a*120)%360,h=e.createRadialGradient(c.x,c.y,c.r*.2,c.x,c.y,c.r);h.addColorStop(0,`hsla(${u}, 95%, 70%, .8)`),h.addColorStop(1,`hsla(${(u+40)%360}, 90%, 30%, 0)`),e.fillStyle=h,e.shadowBlur=18,e.shadowColor=`hsl(${u}, 100%, 60%)`,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}e.restore(),e.strokeStyle=ve.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 qp(e,t,n,a,s,i){i.current||(i.current={tris:[]});const o=i.current,l=6;for(;o.tris.length<l;)o.tris.push({a:Math.random()*Math.PI*2,r:30+Math.random()*Math.min(t,n)*.35,dr:(Math.random()*.6+.2)*(Math.random()<.5?-1:1)});const c=t/2,u=n/2;for(const h of o.tris){h.a+=.002+a*.02*(h.dr>0?1:-1),h.r+=Math.sin(h.a*2)*(.3+a*1.4);const p=Math.max(40,Math.min(h.r,Math.min(t,n)*.48));e.save(),e.translate(c,u),e.rotate(h.a),e.strokeStyle=`hsla(${(s+p*.2)%360}, 90%, 60%, .9)`,e.lineWidth=2.5,e.beginPath(),e.moveTo(p,0);for(let 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 Hp(e,t,n,a,s,i){const o=t/2,l=n/2,c=5,u=Math.min(t,n)*.42;i.current+=.01;for(let h=0;h<c;h++){const p=(h+1)/(c+1),g=p*u;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 b=0;b<x;b++){const f=i.current*(1+h*.15)+b/x*Math.PI*2,j=g+Math.sin(f*2)*6*m,v=o+Math.cos(f)*j,C=l+Math.sin(f)*j;e.fillStyle=`hsla(${(s+h*30+b*6)%360}, 90%, ${55+m*30}%, ${.6+m*.3})`,e.beginPath(),e.arc(v,C,2+m*4,0,Math.PI*2),e.fill()}}}function Kp(e,t,n,a,s){const l=t/12,c=n/6;for(let u=0;u<6;u++)for(let h=0;h<12;h++){const p=(u*12+h)%a.length,g=a[p]/255,y=(s+h/12*180+u/6*90)%360,m=70+g*25,x=25+g*35;e.fillStyle=`hsl(${y}, ${m}%, ${x}%)`,e.fillRect(h*l,u*c,Math.ceil(l),Math.ceil(c))}}function Yp(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 u=i.current;for(let h=u.length-1;h>=0;h--){const p=u[h];p.x+=p.vx,p.y+=p.vy,p.life+=1;const 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)&&u.splice(h,1)}u.length>1200&&u.splice(0,u.length-1200)}function Zp(e,t,n,a,s,i){e.fillStyle="rgba(10,16,28,0.25)",e.fillRect(0,0,t,n);const o=t/2,l=n/2,c=Math.min(t,n)*(.38+s*.12),u=e.createRadialGradient(o,l,c*.1,o,l,c);u.addColorStop(0,`hsla(${(i+200)%360},90%,70%,0.95)`),u.addColorStop(.5,`hsla(${(i+260)%360},80%,55%,0.6)`),u.addColorStop(1,"transparent"),e.fillStyle=u,e.beginPath(),e.arc(o,l,c,0,Math.PI*2),e.fill();const h=18+Math.floor(s*50);for(let p=0;p<h;p++){const 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 j=m/x*f,v=(Math.sin(a*3+p*.8+f)*.6+Math.cos(a*2+p+f*.7))*(8+24*s),C=j,T=v;e.lineTo(T,C)}e.globalCompositeOperation="lighter";const b=(i+p*(240/h))%360;e.strokeStyle=`hsla(${b}, 90%, ${60+s*20}%, ${.35+s*.4})`,e.lineWidth=2+s*2,e.stroke(),e.restore()}e.beginPath(),e.arc(o,l,c*(.98+.02*Math.sin(a*2)),0,Math.PI*2),e.strokeStyle=`hsla(${(i+40)%360},90%,70%,${.25+s*.25})`,e.lineWidth=1.5,e.stroke(),e.globalCompositeOperation="source-over"}function Xp(e,t,n,a,s){const o=Math.max(1,Math.floor(a.length/96)),l=t/2,c=n/2,u=Math.min(t,n)*.22,h=Math.min(t,n)*.48;for(let p=0;p<96;p++){const g=a[p*o]/255,y=p/96*Math.PI*2,m=u,x=u+g*(h-u),b=l+Math.cos(y)*m,f=c+Math.sin(y)*m,j=l+Math.cos(y)*x,v=c+Math.sin(y)*x;e.strokeStyle=`hsl(${p/96*360+s},85%,60%)`,e.lineWidth=3,e.beginPath(),e.moveTo(b,f),e.lineTo(j,v),e.stroke()}e.fillStyle=ve.resolveCssColor("var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.canvas),e.beginPath(),e.arc(l,c,u*.85,0,Math.PI*2),e.fill()}function Qp(e,t,n,a,s,i){const o=t/2,l=n/2,c=Math.min(t,n)*.5,u=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 p=24;for(let g=0;g<p;g++){const y=i.current+g/p*Math.PI*2,m=(.35+u*.55)*c,x=o+Math.cos(y)*m,b=l+Math.sin(y)*m,f=e.createRadialGradient(o,l,0,o,l,m),j=g/p*360+s;f.addColorStop(0,`hsla(${j},85%,65%,0.0)`),f.addColorStop(1,`hsla(${j},85%,65%,0.9)`),e.strokeStyle=f,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,n)}function ai(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 Jp(e,t,n,a,s,i){e.fillStyle="rgba(10,16,28,0.35)",e.fillRect(0,0,t,n);const o=n/2,l=Math.max(8,18-s*10),c=n*.35*(.6+s*.7),u=a.length,h=t/(u-1);e.beginPath();for(let y=0;y<u;y++){const m=(a[y]-128)/128,x=Math.sin(i*1.5+y*.03)*.12,b=y*h,f=o-l-(m+x)*c;y===0?e.moveTo(b,f):e.lineTo(b,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<u;y++){const m=(a[y]-128)/128,x=Math.cos(i*1.3+y*.035)*.12,b=y*h,f=o+l+(m+x)*c;y===0?e.moveTo(b,f):e.lineTo(b,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=ve.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 ef(e,t,n,a,s,i){const o=t/2,l=n/2,c=5,u=Math.min(t,n)*.12;for(let h=0;h<c;h++){const p=Math.floor(h/c*a.length),g=a[p]/255,y=u+h*u*.55+g*u*.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 tf(e,t,n,a,s){const i=Math.min(a.length,256),o=Math.max(1,Math.floor(a.length/i)),l=t/i;for(let c=0;c<i;c++){const u=a[c*o]/255,h=u*(n-6),p=c*l,g=n-h,y=c/i*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+u*30)}%)`,e.fillRect(p+1,g,l-2,h)}}function nf(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 rf(e,t,n,a,s,i){const o=i.current,l=t/2,c=n/2,u=4+a*18;e.save(),e.translate(l,c);for(const h of o.stars){h.z-=u,h.z<20&&(h.x=(Math.random()-.5)*t,h.y=(Math.random()-.5)*n,h.z=900,h.pz=h.z);const p=h.x/h.z*600,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 af(e,t,n,a){e.lineWidth=2,e.strokeStyle=ve.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 sf=({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}),gl=({modes:e=[],active:t,setActive:n,rows:a=2})=>{const{t:s}=xe(),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(sf,{active:t===o,onClick:()=>n(o),title:`${s("visualizer.mode","Mode")}: ${o}`,children:o},o))})})};function of(e,t){const[n,a]=d.useState(()=>{try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}});return d.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(n))}catch{}},[e,n]),[n,a]}const lf=({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)})})},cf="var(--player-bg, #0f172a)";function df(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 uf(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 yl=({kind:e,audioRef:t,width:n="100%",height:a=360,coverUrl:s,title:i,subtitle:o,label:l,defaultMode:c="cover",storageKey:u="gp-stage:mode",allowedModes:h,imageUrls:p,imageCount:g=14,autoAnimate:y=!1})=>{const{t:m}=xe(),x=d.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette","radial","rays","particles","rings","grid","imageTornado","colorRipples","starfield","orbitals","eqcircle","triangles","blob","plasma","lavaLamp","cozyFire","rift"],[e,h]),b=d.useMemo(()=>{const Q=x.includes(c)?c:x[0];try{const w=localStorage.getItem(u);if(!w)return Q;const N=JSON.parse(w);return x.includes(N)?N:Q}catch{return Q}},[x,c,u]),[f,j]=of(u,b),v=d.useRef(null),C=d.useRef(null),T=d.useRef(null),M=d.useRef(null),k=d.useRef(null),R=d.useRef(null),P=d.useRef(0),I=d.useRef(0),A=d.useRef([]),[L,E]=d.useState(0),D=d.useRef(null),Z=d.useRef(null),G=d.useRef(null),F=d.useRef(null),q=d.useRef(null),V=d.useRef(null),K=d.useRef(null),W=f!=="cover"&&f!=="video";return d.useEffect(()=>{var _;if(e==="youtube"||(C.current&&(cancelAnimationFrame(C.current),C.current=null),!W))return;Xt();const Q=Yn(),w=t.current;if(!w&&!y)return;if(w&&!T.current)try{T.current=Q.createMediaElementSource(w)}catch{}if(w&&!M.current){const U=Q.createAnalyser();U.fftSize=2048,U.smoothingTimeConstant=.85,M.current=U;try{(_=T.current)==null||_.connect(U)}catch{}try{U.connect(Q.destination)}catch{}}const N=M.current;k.current=new Uint8Array(N?N.frequencyBinCount:1024),R.current=new Uint8Array(N?N.fftSize:2048);const S=()=>{const U=v.current,$=Math.max(1,Math.floor(window.devicePixelRatio||1));U.width=Math.floor(U.clientWidth*$),U.height=Math.floor(U.clientHeight*$);const H=U.getContext("2d");H==null||H.setTransform(1,0,0,1,0,0),H==null||H.scale($,$)};S();const O=()=>S();window.addEventListener("resize",O),nf(G,220,v.current.width,v.current.height);const Y=async()=>{const U=v.current;if(!U)return;const $=U.getContext("2d");if(!$)return;const H=Math.max(1,Math.floor(window.devicePixelRatio||1)),X=U.width/H,re=U.height/H,oe=performance.now()*.001,se=f==="waveform"||f==="rift";N&&(se?N.getByteTimeDomainData(R.current):N.getByteFrequencyData(k.current)),y&&(df(k.current,oe),uf(R.current,oe));let z=0;const ee=se?R.current:k.current;for(let ae=0;ae<ee.length;ae++){const ce=se?(ee[ae]-128)/128:ee[ae]/255;z+=ce*ce}if(z=Math.sqrt(z/ee.length),E(Math.min(1,z)),$.clearRect(0,0,X,re),f==="spectrum")tf($,X,re,k.current,P.current);else if(f==="bars")Ip($,X,re,k.current,P.current);else if(f==="waveform")af($,X,re,R.current);else if(f==="palette"){const ae=(P.current+z*120)%360;Kp($,X,re,k.current,ae)}else if(f==="radial")Xp($,X,re,k.current,P.current);else if(f==="rays")Qp($,X,re,k.current,P.current,I);else if(f==="particles")Yp($,X,re,z,P.current,A);else if(f==="rings")ef($,X,re,k.current,z,P.current);else if(f==="grid"){const ae=(P.current+z*160)%360;Bp($,X,re,k.current,ae)}else if(f==="imageTornado"){const ae=p!=null&&p.length?p:s?[s]:[];await Wp(D,ae,g,X,re);const ce=(P.current+z*100)%360;Up($,X,re,z,ce,D)}else if(f==="colorRipples"){const ae=(P.current+z*120)%360;_p($,X,re,z,ae,Z)}else if(f==="starfield"){const ae=(P.current+60)%360;rf($,X,re,z,ae,G)}else if(f==="orbitals"){const ae=(P.current+z*180)%360;Hp($,X,re,k.current,ae,I)}else if(f==="eqcircle"){const ae=(P.current+120)%360;Op($,X,re,k.current,ae)}else if(f==="triangles"){const ae=(P.current+40)%360;qp($,X,re,z,ae,F)}else if(f==="blob"){const ae=(P.current+90)%360;Lp($,X,re,z,ae,q)}else if(f==="plasma"){const ae=(P.current+z*200)%360;Zp($,X,re,oe,z,ae)}else if(f==="rift")Jp($,X,re,R.current,z,oe);else if(f==="lavaLamp"){const ae=(P.current+z*80)%360;Vp($,X,re,z,ae,V)}else if(f==="cozyFire"){const ae=(P.current+z*140)%360;Fp($,X,re,k.current,z,ae,K)}P.current=(P.current+.4)%360,C.current=requestAnimationFrame(Y)};return C.current=requestAnimationFrame(Y),()=>{window.removeEventListener("resize",O),C.current&&cancelAnimationFrame(C.current)}},[W,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":cf},children:f==="cover"?r.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:r.jsx(zp,{height:a,coverUrl:s,title:i,subtitle:o,label:l})}):r.jsx("canvas",{ref:v,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(gl,{modes:x,active:f,setActive:j,rows:2}),r.jsx(lf,{vu:L,hide:e==="youtube"})]})]})},hf=({height:e,autoPlay:t,track:n,source:a,ytRef:s,audioRef:i,hlsRef:o,setVol:l,onEnd:c,volume:u,extractVideoId:h})=>{const p=a==null?void 0:a.url,g=a==null?void 0:a.kind,y=a==null?void 0:a.withCredentials,m=JSON.stringify((a==null?void 0:a.headers)??null),x=d.useRef(u);x.current=u,d.useEffect(()=>{i.current&&(i.current.volume=u)},[i,u]),d.useEffect(()=>{const v=i.current;if(v){if(v.volume=x.current,v.crossOrigin=y?"use-credentials":"anonymous",g==="hls"&&Ep(p)){const C=()=>{v.src=p,v.load(),t&&v.play().catch(()=>{})};if(v.canPlayType("application/vnd.apple.mpegurl")){C();return}(async()=>{const M=(await import("hls.js")).default;if(M.isSupported()){const k=JSON.parse(m),R=new M({xhrSetup:P=>{if(y&&(P.withCredentials=!0),k)for(const[I,A]of Object.entries(k))P.setRequestHeader(I,String(A))}});o.current=R,R.loadSource(p),R.attachMedia(v),R.on(M.Events.MANIFEST_PARSED,()=>t&&v.play().catch(()=>{}))}else C()})()}g==="audio"&&p&&(v.src=p,v.load(),t&&v.play().catch(()=>{}))}},[i,o,p,g,y,m,t]);const b=(a==null?void 0:a.kind)==="youtube",f=b?"video":"cover",j=`gp-stage:mode:${(a==null?void 0:a.kind)??"none"}`;return r.jsxs("div",{className:"gp-stage",style:{width:"100%",height:e,background:b?"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($a,{videoId:a.videoId??h(a.url),onReady:v=>{s.current=v.target,l(u),t&&v.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(yl,{kind:(a==null?void 0:a.kind)==="hls"?"hls":(a==null?void 0:a.kind)??"audio",audioRef:i,hlsRef:o,height:e,coverUrl:n==null?void 0:n.coverUrl,title:n==null?void 0:n.title,subtitle:n==null?void 0:n.artist,label:(a==null?void 0:a.label)??`${(a==null?void 0:a.codec)??""} ${(a==null?void 0:a.quality)??""}`.trim(),defaultMode:f,storageKey:j},`vis-${j}`)]})},pf=({artist:e,title:t,hideControls:n=!0,isPlaying:a,onTimeUpdate:s,searchYouTubeByArtistTitle:i})=>{const{t:o}=xe(),[l,c]=d.useState(e||""),[u,h]=d.useState(t||""),[p,g]=d.useState(null),[y,m]=d.useState(null),x=d.useRef(null),[b,f]=d.useState({width:Math.min(560,window.innerWidth-32),height:Math.min(315,(window.innerWidth-32)*9/16)});d.useEffect(()=>{e&&t&&i&&i(e,t).then(g)},[e,t,i]),d.useEffect(()=>{y&&(a?y.playVideo():y.pauseVideo())},[a,y]),d.useEffect(()=>{if(y&&s){const v=setInterval(()=>{const C=y.getCurrentTime();s(C)},100);return()=>clearInterval(v)}},[y,s]),d.useEffect(()=>{const v=()=>{if(x.current){const C=x.current.clientWidth,T=Math.round(C*(9/16));f({width:C,height:T})}};return v(),window.addEventListener("resize",v),()=>window.removeEventListener("resize",v)},[]);const j=async()=>{if(!i)return;const v=await i(l,u);g(v)};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:v=>c(v.target.value),placeholder:o("youtubePlayer.artist","Artist"),"aria-label":o("youtubePlayer.artist","Artist")}),r.jsx("input",{value:u,onChange:v=>h(v.target.value),placeholder:o("youtubePlayer.title","Title"),"aria-label":o("youtubePlayer.title","Title")}),r.jsx("button",{onClick:j,children:o("youtubePlayer.search","Search")})]}),p&&r.jsxs("div",{children:[r.jsx($a,{videoId:p,opts:{width:b.width.toString(),height:b.height.toString(),playerVars:{autoplay:1,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,annotations:0}},onReady:v=>m(v.target)}),!n&&r.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px"},children:[r.jsxs("button",{onClick:()=>y==null?void 0:y.playVideo(),children:[r.jsx(B.NtdPlay,{size:14})," ",o("youtubePlayer.play","Play")]}),r.jsxs("button",{onClick:()=>y==null?void 0:y.pauseVideo(),children:[r.jsx(B.NtdPause,{size:14})," ",o("youtubePlayer.pause","Pause")]})]})]})]})},si=e=>({name:e,dirs:new Map,files:[]}),ff=e=>(e??[]).map(t=>t instanceof File?{file:t}:t),mf=e=>e.replace(/\\/g,"/"),gf=e=>{const t=si("/");for(const n of e){const a=mf(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,si(o)),s=s.dirs.get(o)}s.files.push({file:n.file,path:a[a.length-1]??n.file.name})}return t},ba=e=>e.slice().sort((t,n)=>(t.path??t.file.name).localeCompare(n.path??n.file.name)),yf={tidal:B.NtdWave,spotify:B.NtdMusic,youtube:B.NtdPlay},xa=({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(B.NtdClose,{size:14})})]}),Sa=({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(B.NtdEdit,{size:13})," ",t("libraryExplorer.openInEditor","Edit")]}),a&&r.jsxs(ie.NiceButton,{variant:"primary",size:"sm",onClick:()=>a(s.file),children:[r.jsx(B.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")}),vl=({streams:e,t,onPlayStream:n})=>e.length?r.jsxs("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:[r.jsx("div",{style:{padding:"8px 12px",fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:t("libraryExplorer.streaming","Streaming")}),r.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:e.map(a=>r.jsxs("li",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,borderTop:"1px solid var(--nice-border, #1e293b)",padding:"8px 12px"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.title}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",display:"flex",alignItems:"center",gap:4},children:[d.createElement(yf[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(B.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]},`${a.provider}:${a.id}`))})]}):null,ra=({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})]}),vf=({variant:e="full",files:t=[],streams:n=[],enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,t:c,style:u,id:h,accessMode:p,"data-testid":g})=>{const{t:y}=xe(),m=c??y,[x,b]=d.useState(""),f=d.useMemo(()=>ff(t),[t]),j=d.useCallback(T=>{const M=x.trim().toLowerCase();return!M||T.toLowerCase().includes(M)},[x]),v=d.useMemo(()=>ba(f).filter(T=>j(`${T.path??T.file.name} ${T.file.type||""}`)),[f,j]),C=d.useMemo(()=>n.filter(T=>j(`${T.title} ${T.artist??""} ${T.provider}`)),[n,j]);return p==="hidden"?null:e==="minimal"?r.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...u},id:h,"data-testid":g,children:[r.jsx(xa,{q:x,setQ:b,t:m}),r.jsx(Sa,{files:v,t:m,onOpenInEditor:s,onPlayFile:i}),r.jsx(vl,{streams:C,t:m,onPlayStream:o})]}):e==="onlyFiles"?r.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...u},id:h,"data-testid":g,children:[r.jsx(xa,{q:x,setQ:b,t:m}),r.jsx(Sa,{files:v,t:m,onOpenInEditor:s,onPlayFile:i})]}):r.jsx(bf,{q:x,setQ:b,normFiles:f,filteredStreams:C,enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,style:u,id:h,"data-testid":g,t:m})},bf=({q:e,setQ:t,normFiles:n,filteredStreams:a,enableProviders:s,onOpenInEditor:i,onPlayFile:o,onPlayStream:l,className:c,style:u,id:h,"data-testid":p,t:g})=>{const y=d.useMemo(()=>gf(n),[n]),[m,x]=d.useState({}),[b,f]=d.useState("/"),j=M=>x(k=>({...k,[M]:!k[M]})),v=(M,k)=>{const R=k==="/"?`/${M.name}`:`${k}${M.name}/`,P=k==="/"&&M.name==="/",I=m[R]??P,A=Array.from(M.dirs.keys()).sort();return r.jsxs("div",{children:[!P&&r.jsxs("button",{type:"button",onClick:()=>{j(R),f(R)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"4px 8px",border:"none",borderRadius:6,cursor:"pointer",textAlign:"left",background:b===R?"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:I?r.jsx(B.NtdFolderOpen,{size:14}):r.jsx(B.NtdFolder,{size:14})}),r.jsx("span",{style:{fontSize:13},children:M.name})]}),(P||I)&&r.jsx("div",{style:{paddingLeft:P?0:16},children:A.map(L=>v(M.dirs.get(L),R))})]},R)},C=d.useMemo(()=>{let M;if(b==="/")M=ba(n);else{const k=b.replace(/^\//,"").split("/").filter(Boolean);let R=y;for(const P of k){const I=R.dirs.get(P);if(!I)return[];R=I}M=ba(R.files)}return e?M.filter(k=>(k.path??k.file.name).toLowerCase().includes(e.toLowerCase())):M},[b,y,n,e]),T={tidal:(s==null?void 0:s.tidal)??!0,spotify:(s==null?void 0:s.spotify)??!0,youtube:(s==null?void 0:s.youtube)??!0};return r.jsxs("div",{className:c,style:{display:"flex",gap:12,color:"var(--nice-text, #e2e8f0)",...u},id:h,"data-testid":p,children:[r.jsxs("div",{style:{flex:"0 0 220px",border:"1px solid var(--nice-border, #334155)",borderRadius:12,padding:8},children:[r.jsx("div",{style:{padding:"0 8px 8px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:g("libraryExplorer.library","Library")}),v(y,"/"),r.jsxs("div",{style:{marginTop:16,borderTop:"1px solid var(--nice-border, #1e293b)",paddingTop:8},children:[r.jsx("div",{style:{padding:"0 8px 4px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:g("libraryExplorer.streaming","Streaming")}),r.jsx(ra,{name:"Tidal",enabled:T.tidal}),r.jsx(ra,{name:"Spotify",enabled:T.spotify}),r.jsx(ra,{name:"YouTube",enabled:T.youtube})]})]}),r.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[r.jsx(xa,{q:e,setQ:t,t:g}),r.jsx(Sa,{files:C,t:g,onOpenInEditor:i,onPlayFile:o}),(T.tidal||T.spotify||T.youtube)&&r.jsx(vl,{streams:a.filter(M=>T[M.provider]),t:g,onPlayStream:l})]})]})},xf=({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"})})}},es=({data:e,display:t,callbacks:n,state:a})=>{const{id:s,index:i,artist:o,title:l,version:c,lp:u,sourcesAvailable:h=[]}=e,{allowVersion:p=!0,dragHandleProps:g}=t,{onChange:y,onRemove:m,onMoveUp:x,onMoveDown:b,onChangeLp:f,onSelectSource:j}=n,{readOnly:v=!1,canMoveUp:C=!0,canMoveDown:T=!0,activeSource:M}=a,{t:k}=xe(),R=d.useRef(null);d.useEffect(()=>{!o&&R.current&&R.current.focus()},[o]);const P=E=>{if(!v&&E.key==="Enter"){const D=E.target.closest("div.gpi-row"),Z=D==null?void 0:D.querySelectorAll("input[data-role='field']");if(!Z||Z.length===0)return;const G=Array.from(Z).indexOf(E.target),F=Z[G+1]??Z[0];F==null||F.focus()}},I=E=>{const D=h.includes(E),Z=M===E,G={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid var(--nice-border, #e5e7eb)",background:Z?"var(--nice-selected-bg, #eef2ff)":"var(--nice-bg, #fff)",opacity:D?1:.35,cursor:D&&j&&!v?"pointer":"default",transition:"transform .05s ease"},F=E==="youtube"?"var(--nice-danger, #ff0000)":E==="spotify"?"var(--nice-success, #1db954)":E==="tidal"?"var(--nice-text, #111827)":E==="hls"?"var(--nice-accent, #7c3aed)":"var(--nice-text, #374151)",q=E==="youtube"?"YouTube":E==="spotify"?"Spotify":E==="tidal"?"TIDAL":E==="hls"?"HLS":k("playlistItem.audio","Audio"),V=k("playlistItem.sourceLabel","Source")+": "+q+(Z?` ${k("playlistItem.sourceSelected","(selected)")}`:""),K=()=>{!D||!j||v||j(E)};return r.jsx("button",{type:"button",title:q,onClick:K,disabled:!D||v,style:G,"aria-pressed":Z,"aria-label":V,children:r.jsx(xf,{kind:E,color:F})},E)},A=["youtube","tidal","spotify","hls","audio"],L=typeof u=="number"?u:i+1;return r.jsxs("div",{className:"gpi-row",role:"group","aria-label":k("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:L,onChange:E=>f==null?void 0:f(Number(E.target.value)),disabled:v||!f,"aria-label":k("playlistItem.lp","Lp"),title:k("playlistItem.positionOnList","Position in the list"),style:Sf}),r.jsx("input",{ref:R,"data-role":"field",type:"text",value:o,onChange:E=>y({artist:E.target.value}),placeholder:k("playlistItem.artist","Artist"),onKeyDown:P,disabled:v,"aria-label":k("playlistItem.artist","Artist"),className:"gpi-input",style:aa}),r.jsx("input",{"data-role":"field",type:"text",value:l,onChange:E=>y({title:E.target.value}),placeholder:k("playlistItem.title","Title"),onKeyDown:P,disabled:v,"aria-label":k("playlistItem.title","Title"),className:"gpi-input",style:aa}),p&&r.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:E=>y({version:E.target.value||void 0}),placeholder:k("playlistItem.versionOptional","Version (optional)"),onKeyDown:P,disabled:v,"aria-label":k("playlistItem.version","Version"),className:"gpi-input",style:aa}),r.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":k("playlistItem.availableSources","Available sources"),children:A.map(I)}),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":k("playlistItem.dragReorder","Drag to reorder"),title:k("playlistItem.dragReorder","Drag to reorder"),style:rr,children:r.jsx(B.NtdMenu,{size:14})}),r.jsx("button",{type:"button",onClick:x,disabled:!C||v,"aria-label":k("playlistItem.moveUp","Move up"),title:k("playlistItem.moveUp","Move up"),style:rr,children:r.jsx(B.NtdArrowUp,{size:14})}),r.jsx("button",{type:"button",onClick:b,disabled:!T||v,"aria-label":k("playlistItem.moveDown","Move down"),title:k("playlistItem.moveDown","Move down"),style:rr,children:r.jsx(B.NtdArrowDown,{size:14})}),r.jsx("button",{type:"button",onClick:m,disabled:v,"aria-label":k("common.delete","Delete"),title:k("common.delete","Delete"),style:{...rr,color:"var(--nice-color-danger, #b91c1c)"},children:r.jsx(B.NtdClose,{size:14})})]})]})},Sf={width:48,border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 6px",fontSize:14,textAlign:"center"},aa={width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 10px",fontSize:14},rr={border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg, #fff)",padding:"6px 8px",borderRadius:6,cursor:"pointer"},ka=()=>Math.random().toString(36).slice(2,10),ar=e=>(e??[]).map(t=>({id:ka(),...t})),kf=e=>e.map(({id:t,...n})=>n),wf=null,Cf=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}},jf=({value:e,defaultValue:t,onChange:n,allowVersion:a=!0,maxItems:s,addButtonLabel:i,emptyState:o=wf,readOnly:l=!1,autoFocusNewItem:c=!0,enableBulkPaste:u=!0})=>{const{t:h}=xe(),p=e!==void 0,[g,y]=d.useState(()=>ar(e||t)),[m,x]=d.useState(""),b=d.useRef(null),[f,j]=d.useState(null);d.useEffect(()=>{p&&y(ar(e))},[p,JSON.stringify(e)]);const v=d.useCallback(V=>{n==null||n(kf(V))},[n]),C=d.useCallback(V=>{if(p){const K=V(ar(e));v(K)}else y(K=>{const W=V(K);return v(W),W})},[v,p,e]),T=s?g.length<s:!0,M=d.useCallback(()=>{!T||l||C(V=>[...V,{id:ka(),artist:"",title:"",version:void 0}])},[T,l,C]),k=d.useCallback((V,K)=>{C(W=>W.map(Q=>Q.id===V?{...Q,...K}:Q))},[C]),R=d.useCallback(V=>{l||C(K=>K.filter(W=>W.id!==V))},[l,C]),P=d.useCallback((V,K)=>{C(W=>{const Q=W.findIndex(O=>O.id===V);if(Q<0)return W;const w=Q+K;if(w<0||w>=W.length)return W;const N=[...W],[S]=N.splice(Q,1);return N.splice(w,0,S),N})},[C]),I=d.useCallback((V,K)=>{C(W=>{const Q=W.findIndex(O=>O.id===V);if(Q<0)return W;const w=Math.max(0,Math.min(W.length-1,K-1));if(Q===w)return W;const N=[...W],[S]=N.splice(Q,1);return N.splice(w,0,S),N})},[C]),A=V=>K=>{l||(b.current=V,K.dataTransfer.effectAllowed="move",K.dataTransfer.setData("text/plain",V))},L=V=>K=>{l||(K.preventDefault(),K.dataTransfer.dropEffect="move",j(V))},E=V=>()=>j(K=>K===V?null:K),D=V=>K=>{if(l)return;K.preventDefault();const W=b.current??K.dataTransfer.getData("text/plain");j(null),b.current=null,!(!W||W===V)&&C(Q=>{const w=Q.findIndex(Y=>Y.id===W),N=Q.findIndex(Y=>Y.id===V);if(w<0||N<0||w===N)return Q;const S=[...Q],[O]=S.splice(w,1);return S.splice(N,0,O),S})},Z=()=>{b.current=null,j(null)},G=d.useCallback(()=>{if(!u||l)return;const K=m.split(/\r?\n/).map(W=>W.trim()).filter(Boolean).map(Cf).filter(W=>!!W);K.length!==0&&(C(W=>{const Q=(s??1/0)-W.length,w=K.slice(0,Math.max(0,Q)).map(N=>({id:ka(),...N}));return[...W,...w]}),x(""))},[u,l,m,s,C]);d.useEffect(()=>{},[g.length,c]);const F=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.")}),q=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:M,disabled:!T||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":q,children:["+ ",q]})})]}),g.length===0?r.jsx("div",{className:"gp-empty",children:F}):r.jsx("ol",{className:"gp-list",style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:8},children:g.map((V,K)=>{const W=f===V.id;return r.jsx("li",{draggable:!l,onDragStart:A(V.id),onDragOver:L(V.id),onDragLeave:E(V.id),onDrop:D(V.id),onDragEnd:Z,style:{border:W?"2px dashed var(--nice-info, #6366f1)":"2px solid transparent",borderRadius:8,padding:W?4:0},children:r.jsx(es,{data:{id:V.id,index:K,lp:K+1,artist:V.artist,title:V.title,version:a?V.version??void 0:void 0,sourcesAvailable:void 0},display:{allowVersion:a,dragHandleProps:{onDragStart:A(V.id)}},callbacks:{onChange:Q=>k(V.id,Q),onRemove:()=>R(V.id),onMoveUp:()=>P(V.id,-1),onMoveDown:()=>P(V.id,1),onChangeLp:Q=>I(V.id,Q)},state:{readOnly:l,canMoveUp:K>0,canMoveDown:K<g.length-1}})},V.id)})}),u&&!l&&r.jsx("div",{style:{marginTop:12},children:r.jsxs("details",{children:[r.jsx("summary",{style:{cursor:"pointer",color:"var(--nice-text, #374151)"},children:h("genericPlaylist.bulkPasteSummary","Paste multiple items at once")}),r.jsxs("div",{style:{marginTop:6},children:[r.jsx("textarea",{value:m,onChange:V=>x(V.target.value),placeholder:h("genericPlaylist.bulkPastePlaceholder",`Paste lines in format:
|
|
65
|
+
`}),r.jsxs("div",{ref:j,style:J.container,children:[r.jsxs("div",{style:J.header,children:[r.jsxs("h1",{style:{...J.title,display:"inline-flex",alignItems:"center",gap:8},children:[r.jsx(B.NtdBarChart,{size:26})," ",f("vocalReport.title","Vocal Performance Report")]}),r.jsxs("p",{style:J.subtitle,children:[R.songArtist," — ",R.songTitle," | ",f("vocalReport.difficulty","Difficulty"),": ",r.jsx("strong",{children:R.difficulty})," "," | ",new Date(R.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, ${mt(A)}44, ${mt(A)})`,border:`3px solid ${mt(A)}`,boxShadow:`0 0 20px ${mt(A)}44`},children:r.jsx("span",{style:{fontSize:28,fontWeight:900,color:"#fff"},children:L})}),r.jsxs("div",{style:{textAlign:"left"},children:[r.jsxs("div",{style:{fontSize:14,fontWeight:700,color:mt(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:E[L]??""})]})]})]}),r.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end",marginBottom:16,flexWrap:"wrap"},children:[r.jsxs("button",{style:J.btnPrimary,onClick:T,children:[r.jsx(B.NtdDownload,{size:14})," ",f("vocalReport.downloadHtml","Download HTML")]}),r.jsxs("button",{style:J.btnSecondary,onClick:M,children:[r.jsx(B.NtdPrint,{size:14})," ",f("vocalReport.printPdf","Print / PDF")]}),r.jsxs("button",{style:J.btnSecondary,onClick:k,children:[r.jsx(B.NtdCode,{size:14})," ",f("vocalReport.exportJson","Export JSON")]}),r.jsxs("button",{style:J.btnSecondary,onClick:u,children:[r.jsx(B.NtdClose,{size:14})," ",f("vocalReport.close","Close")]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.scoreOverview","Score overview")]}),r.jsxs("div",{style:J.kpiGrid,children:[r.jsxs("div",{style:J.kpiCard,children:[r.jsx("div",{style:J.kpiValue,children:R.totalScore.toLocaleString()}),r.jsx("div",{style:J.kpiLabel,children:f("vocalReport.totalScore","Total score")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsx("div",{style:J.kpiValue,children:R.classicScore.toLocaleString()}),r.jsx("div",{style:J.kpiLabel,children:f("vocalReport.classicScore","Classic score")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsx("div",{style:J.kpiValue,children:R.bonusScore.toLocaleString()}),r.jsx("div",{style:J.kpiLabel,children:f("vocalReport.bonusScore","Bonus score")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsxs("div",{style:J.kpiValue,children:[R.maxCombo,"×"]}),r.jsx("div",{style:J.kpiLabel,children:f("vocalReport.maxCombo","Max combo")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsxs("div",{style:{...J.kpiValue,color:mt(R.intonationAccuracyPct)},children:[R.intonationAccuracyPct,"%"]}),r.jsx("div",{style:J.kpiLabel,children:f("vocalReport.intonationAccuracy","Intonation accuracy")})]}),r.jsxs("div",{style:J.kpiCard,children:[r.jsxs("div",{style:{...J.kpiValue,color:mt(R.perfectHitPct)},children:[R.perfectHitPct,"%"]}),r.jsx("div",{style:J.kpiLabel,children:f("vocalReport.perfectHits","Perfect hits")})]})]}),C.length>1&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.playerComparison","Player comparison")]}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:"#"}),r.jsx("th",{style:J.th,children:f("vocalReport.player","Player")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.classic","Classic")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.bonus","Bonus")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.total","Total")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.intonation","Intonation")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.perfect","Perfect")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.range","Range")})]})}),r.jsx("tbody",{children:C.map((S,O)=>r.jsxs("tr",{children:[r.jsx("td",{style:J.td,children:O+1}),r.jsx("td",{style:{...J.tdBold,color:S.playerColor},children:S.playerName}),r.jsx("td",{style:J.tdRight,children:S.classicScore.toLocaleString()}),r.jsx("td",{style:J.tdRight,children:S.bonusScore.toLocaleString()}),r.jsx("td",{style:{...J.tdRight,fontWeight:700,color:"var(--nice-warning, #fbbf24)"},children:S.totalScore.toLocaleString()}),r.jsx("td",{style:J.tdRight,children:r.jsxs("span",{style:J.badge(mt(S.intonationAccuracyPct)),children:[S.intonationAccuracyPct,"%"]})}),r.jsx("td",{style:J.tdRight,children:r.jsxs("span",{style:J.badge(mt(S.perfectHitPct)),children:[S.perfectHitPct,"%"]})}),r.jsxs("td",{style:J.tdRight,children:[S.lowestNote,"–",S.highestNote]})]},O))})]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.pitchAccuracy","Pitch accuracy")]}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:f("vocalReport.metric","Metric")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.value","Value")}),r.jsx("th",{style:J.th,children:f("vocalReport.description","Description")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.meanAbsDev","Mean abs. deviation")}),r.jsxs("td",{style:J.tdRight,children:[R.avgCentDeviation,r.jsxs("span",{style:J.kpiUnit,children:[" ",N]})]}),r.jsx("td",{style:J.td,children:f("vocalReport.meanAbsDevDesc","Average distance from the target pitch.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.medianDev","Median deviation")}),r.jsxs("td",{style:J.tdRight,children:[R.medianCentDeviation,r.jsxs("span",{style:J.kpiUnit,children:[" ",N]})]}),r.jsx("td",{style:J.td,children:f("vocalReport.medianDevDesc","Typical deviation, robust to outliers.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.stdDev","Std. deviation")}),r.jsxs("td",{style:J.tdRight,children:[R.stdDevCents,r.jsxs("span",{style:J.kpiUnit,children:[" ",N]})]}),r.jsx("td",{style:J.td,children:f("vocalReport.stdDevDesc","Consistency of pitch (lower = steadier).")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.intonationAccuracyLabel","Intonation accuracy")}),r.jsxs("td",{style:{...J.tdRight,color:mt(R.intonationAccuracyPct)},children:[R.intonationAccuracyPct,"%"]}),r.jsx("td",{style:J.td,children:f("vocalReport.intonationAccuracyDesc","Share of frames within tolerance.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.perfectHitRate","Perfect-hit rate")}),r.jsxs("td",{style:{...J.tdRight,color:mt(R.perfectHitPct)},children:[R.perfectHitPct,"%"]}),r.jsx("td",{style:J.td,children:f("vocalReport.perfectHitRateDesc","Notes hit dead-on.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.totalPitchSamples","Total pitch samples")}),r.jsx("td",{style:J.tdRight,children:R.totalPitchPoints.toLocaleString()}),r.jsx("td",{style:J.td,children:f("vocalReport.totalPitchSamplesDesc","Number of analysed pitch frames.")})]})]})]}),r.jsxs("div",{style:J.chartWrap,children:[r.jsx("div",{style:J.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:W.map(S=>S.centRange),series:Xs(W.map(S=>`${Q} (${S.centRange})`),W.map(S=>S.count),W.map(S=>sp(S.centRange)))})})]}),r.jsxs("div",{style:J.row,children:[r.jsxs("div",{style:{...J.chartWrap,...J.half},children:[r.jsx("div",{style:J.chartTitle,children:f("vocalReport.hitClassification","Hit classification")}),r.jsx("div",{style:{height:220},children:r.jsx(ie.NicePieChart,{width:400,height:260,data:G.map(S=>({label:S.name,value:Ht(S.value),color:S.fill}))})})]}),r.jsxs("div",{style:{...J.chartWrap,...J.half},children:[r.jsx("div",{style:J.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:Z.map(S=>S.metric),series:[{name:f("vocalReport.performanceProfile","Performance profile"),type:"radar",color:"var(--nice-info, #3b82f6)",data:Z.map(S=>Ht(S.value))},{name:"100%",type:"radar",color:"transparent",data:Z.map(S=>S.max)}]})})]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.pitchTracking","Pitch tracking")]}),r.jsxs("div",{style:J.chartWrap,children:[r.jsx("div",{style:J.chartTitle,children:f("vocalReport.sungVsExpected","Sung vs expected")}),r.jsx("div",{style:{height:260},children:r.jsx(ie.NiceChart,{width:860,height:230,categories:Js(V.map(S=>S.t)),series:[{name:f("vocalReport.expected","Expected"),type:"line",color:"var(--nice-success, #22c55e)",data:V.map(S=>Ht(S.expected))},{name:f("vocalReport.sung","Sung"),type:"line",color:"var(--nice-info, #3b82f6)",data:V.map(S=>Ht(S.sung))}]})})]}),r.jsxs("div",{style:J.chartWrap,children:[r.jsx("div",{style:J.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:Js(K.map(S=>S.t)),series:[{name:f("vocalReport.rollingAccuracy","Rolling accuracy"),type:"area",color:"var(--nice-accent, #8b5cf6)",data:K.map(S=>Ht(S.accuracy))}]})})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.vocalRange","Vocal range")]}),r.jsxs("div",{style:J.row,children:[r.jsx("div",{style:J.half,children:r.jsx("table",{style:J.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.lowestNote","Lowest note")}),r.jsx("td",{style:J.tdRight,children:f("vocalReport.hz","{lowestNote} ({lowestHz} Hz)").replace("{lowestNote}",String(R.lowestNote)).replace("{lowestHz}",String(R.lowestHz))})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.highestNote","Highest note")}),r.jsx("td",{style:J.tdRight,children:f("vocalReport.hz2","{highestNote} ({highestHz} Hz)").replace("{highestNote}",String(R.highestNote)).replace("{highestHz}",String(R.highestHz))})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.rangeLabel","Range")}),r.jsxs("td",{style:J.tdRight,children:[R.rangeInSemitones," ",f("vocalReport.semitones","semitones")]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.tessitura","Tessitura")}),r.jsxs("td",{style:J.tdRight,children:[R.tessituraLow," — ",R.tessituraHigh]})]})]})})}),r.jsxs("div",{style:{...J.chartWrap,...J.half},children:[r.jsx("div",{style:J.chartTitle,children:f("vocalReport.chromagram","Chromagram")}),r.jsx("div",{style:{height:180},children:r.jsx(ie.NiceChart,{width:400,height:180,showLegend:!1,categories:F.map(S=>S.note),series:[{name:f("vocalReport.usagePct","Usage %"),type:"bar",color:"var(--nice-primary, #6366f1)",data:F.map(S=>Ht(S.pct))}]})})]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.vibratoStability","Vibrato & stability")]}),r.jsxs("div",{style:J.row,children:[r.jsx("div",{style:J.half,children:r.jsx("table",{style:J.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.vibratoDetected","Vibrato detected")}),r.jsx("td",{style:J.tdRight,children:r.jsx("span",{style:J.badge(R.vibrato.detected?"var(--nice-success, #22c55e)":"var(--nice-text-muted, #64748b)"),children:R.vibrato.detected?f("vocalReport.yes","Yes"):f("vocalReport.no","No")})})]}),R.vibrato.detected&&r.jsxs(r.Fragment,{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.avgRate","Avg. rate")}),r.jsxs("td",{style:J.tdRight,children:[R.vibrato.avgRateHz," Hz"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.avgExtent","Avg. extent")}),r.jsxs("td",{style:J.tdRight,children:["±",R.vibrato.avgExtentCents," ",N]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.regularity","Regularity")}),r.jsxs("td",{style:J.tdRight,children:[R.vibrato.regularityPct,"%"]})]})]})]})})}),r.jsx("div",{style:J.half,children:r.jsx("table",{style:J.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.jitter","Jitter")}),r.jsxs("td",{style:J.tdRight,children:[R.jitterPct,"%"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.vocalPresence","Vocal presence")}),r.jsxs("td",{style:J.tdRight,children:[R.shimmerProxy,"%"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.avgOnsetDev","Avg. onset deviation")}),r.jsxs("td",{style:J.tdRight,children:[R.avgOnsetDeviationMs," ms"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.rhythmStability","Rhythm stability")}),r.jsx("td",{style:J.tdRight,children:r.jsxs("span",{style:J.badge(mt(R.rhythmStabilityPct)),children:[R.rhythmStabilityPct,"%"]})})]})]})})})]}),R.verseMetrics.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.verseBreakdown","Per-verse breakdown")]}),r.jsxs("div",{style:J.chartWrap,children:[r.jsx("div",{style:J.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:q.map(S=>S.verse),series:Xs(q.map(S=>`${w} (${S.verse})`),q.map(S=>S.accuracy),q.map(S=>Zs(S.label)))})})]}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:f("vocalReport.verse","Verse")}),r.jsx("th",{style:J.th,children:f("vocalReport.rating","Rating")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.hitPct","Hit %")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.avgDeviation","Avg. dev.")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.notes","Notes")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.notesHit","Hit")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.comboBonus","Combo bonus")})]})}),r.jsx("tbody",{children:R.verseMetrics.map((S,O)=>r.jsxs("tr",{children:[r.jsxs("td",{style:J.td,children:[f("vocalReport.verse","Verse")," ",S.verseIndex+1]}),r.jsx("td",{style:J.td,children:r.jsx("span",{style:J.badge(Zs(S.label)),children:S.label})}),r.jsxs("td",{style:J.tdRight,children:[(S.hitFraction*100).toFixed(1),"%"]}),r.jsxs("td",{style:J.tdRight,children:[S.avgCentDeviation," ¢"]}),r.jsx("td",{style:J.tdRight,children:S.noteCount}),r.jsx("td",{style:J.tdRight,children:S.notesHit}),r.jsxs("td",{style:J.tdRight,children:["+",S.comboBonus]})]},O))})]})]}),r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.scoringConfig","Scoring configuration")]}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:f("vocalReport.parameter","Parameter")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.value","Value")}),r.jsx("th",{style:J.th,children:f("vocalReport.description","Description")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.difficultyLevel","Difficulty level")}),r.jsx("td",{style:J.tdRight,children:R.difficulty}),r.jsx("td",{style:J.td,children:f("vocalReport.difficultyLevelDesc","Affects tolerance and multiplier.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.semitoneTolerance","Semitone tolerance")}),r.jsx("td",{style:J.tdRight,children:I.semitoneTolerance}),r.jsx("td",{style:J.td,children:f("vocalReport.semitoneToleranceDesc","Pitch window counted as a hit.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.preWindow","Pre window")}),r.jsxs("td",{style:J.tdRight,children:[I.preWindow," s"]}),r.jsx("td",{style:J.td,children:f("vocalReport.preWindowDesc","Lead-in time before a note.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.postExtra","Post extra")}),r.jsxs("td",{style:J.tdRight,children:[I.postExtra," s"]}),r.jsx("td",{style:J.td,children:f("vocalReport.postExtraDesc","Grace time after a note.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.difficultyMultiplier","Difficulty multiplier")}),r.jsxs("td",{style:J.tdRight,children:[I.difficultyMult,"×"]}),r.jsx("td",{style:J.td,children:f("vocalReport.difficultyMultiplierDesc","Score scaling for difficulty.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.songBpm","Song BPM")}),r.jsx("td",{style:J.tdRight,children:R.songBpm}),r.jsx("td",{style:J.td,children:f("vocalReport.songBpmDesc","Tempo used for note timing.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.totalNotes","Total notes")}),r.jsx("td",{style:J.tdRight,children:P}),r.jsx("td",{style:J.td,children:f("vocalReport.totalNotesDesc","Number of scored notes in the song.")})]})]})]}),C.some(S=>S.micSettings)&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:J.sectionTitle,children:[++D,". ",f("vocalReport.micConfig","Microphone configuration")]}),C.map((S,O)=>S.micSettings&&r.jsxs("div",{style:{marginBottom:16},children:[C.length>1&&r.jsx("h4",{style:{color:S.playerColor,margin:"0 0 8px",fontSize:14},children:S.playerName}),r.jsxs("table",{style:J.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:J.th,children:f("vocalReport.setting","Setting")}),r.jsx("th",{style:J.thRight,children:f("vocalReport.value","Value")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.device","Device")}),r.jsx("td",{style:J.tdRight,children:S.micSettings.deviceLabel||S.micSettings.deviceId})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.pitchAlgorithm","Pitch algorithm")}),r.jsx("td",{style:J.tdRight,children:S.micSettings.algorithm})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.inputGain","Input gain")}),r.jsxs("td",{style:J.tdRight,children:[S.micSettings.gain,"×"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.rmsThreshold","RMS threshold")}),r.jsx("td",{style:J.tdRight,children:S.micSettings.rmsThreshold})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.pitchThreshold","Pitch threshold")}),r.jsx("td",{style:J.tdRight,children:S.micSettings.pitchThreshold})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.smoothingWindow","Smoothing window")}),r.jsxs("td",{style:J.tdRight,children:[S.micSettings.smoothingWindow," ",f("vocalReport.frames","frames")]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.hysteresisFrames","Hysteresis frames")}),r.jsx("td",{style:J.tdRight,children:S.micSettings.hysteresisFrames})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.hanningWindow","Hanning window")}),r.jsx("td",{style:J.tdRight,children:S.micSettings.useHanning?f("vocalReport.enabled","Enabled"):f("vocalReport.disabled","Disabled")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.latencyOffset","Latency offset")}),r.jsxs("td",{style:J.tdRight,children:[S.micSettings.latencyOffsetMs," ms"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:J.tdBold,children:f("vocalReport.monitor","Monitor")}),r.jsx("td",{style:J.tdRight,children:S.micSettings.monitorEnabled?`${f("vocalReport.on","On")} (${Math.round(S.micSettings.monitorVolume*100)}%)`:f("vocalReport.off","Off")})]})]})]})]},O))]}),r.jsx("div",{style:J.footer,children:r.jsxs("p",{children:[f("vocalReport.footerGenerated","Report generated")," ·"," ",R.timestamp.replace(/[-:T.Z]/g,"").slice(0,14)]})})]})]})},op="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 lp(e){if(!e)return"";const t=Math.floor(e/60),n=Math.round(e%60);return`${t}:${n.toString().padStart(2,"0")}`}function ti(e){return Array.from(new Set(e.filter(t=>!!t))).sort((t,n)=>t.localeCompare(n))}const cp=Object.assign(d.memo(({song:e,index:t,active:n,coverUrl:a,topScore:s,selected:i,multiSelect:o,disabled:l,t:c,onPlay:u,onToggleSelect:h,onFocusRow:p})=>{const g=()=>{o?h(e.id):l||u==null||u(e)};return r.jsxs("div",{className:`nice-ksb-row${i?" nice-ksb-row--selected":""}${n?" nice-ksb-row--active":""}`,role:"option","aria-selected":i,"data-ksb-index":t,tabIndex:n?0:-1,onClick: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:lp(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(B.NtdTrophy,{size:11})," ",s.score.toLocaleString()]})]}),!o&&r.jsxs("button",{type:"button",className:"nice-ksb-row__play",disabled:l,onClick:y=>{y.stopPropagation(),u==null||u(e)},children:[r.jsx(B.NtdPlay,{size:13})," ",c("karaokeBrowser.play","Play")]})]})}),{displayName:"NiceKaraokeSongRow"}),dp={artist:"Artist",title:"Title",year:"Year",genre:"Genre"},up=({songs:e,fetchSongs:t,loading:n=!1,getCover:a,getTopScore:s,onPlay:i,onSelect:o,multiSelect:l=!1,maxSelections:c=0,showSidebar:u=!0,enableGamepad:h=!0,disabled:p=!1,disabledReason:g,t:y,className:m,style:x,id:b,accessMode:f,"data-testid":j})=>{const{t:v}=xe(),C=y??v,[T,M]=d.useState(""),[k,R]=d.useState(""),[P,I]=d.useState(""),[A,L]=d.useState(""),[E,D]=d.useState("artist"),[Z,G]=d.useState("asc"),[F,q]=d.useState({type:"all"}),[V,K]=d.useState(new Set),[W,Q]=d.useState([]),[w,N]=d.useState(!1);d.useEffect(()=>{const he=setTimeout(()=>R(T),300);return()=>clearTimeout(he)},[T]),d.useEffect(()=>{if(e||!t)return;let he=!1;return N(!0),Promise.resolve(t({searchQuery:k.trim()||void 0,genres:P?[P]:void 0,languages:A?[A]:void 0})).then(we=>!he&&Q(we)).catch(()=>!he&&Q([])).finally(()=>!he&&N(!1)),()=>{he=!0}},[e,t,k,P,A]);const S=e??W,O=d.useMemo(()=>ti(S.map(he=>he.genre)),[S]),Y=d.useMemo(()=>ti(S.map(he=>he.language)),[S]),_=d.useMemo(()=>{let he=S;const we=k.trim().toLowerCase();we&&(he=he.filter(Pe=>`${Pe.title} ${Pe.artist}`.toLowerCase().includes(we))),P&&(he=he.filter(Pe=>Pe.genre===P)),A&&(he=he.filter(Pe=>Pe.language===A)),F.type==="genre"&&(he=he.filter(Pe=>Pe.genre===F.value)),F.type==="language"&&(he=he.filter(Pe=>Pe.language===F.value));const je=Z==="asc"?1:-1;return[...he].sort((Pe,$e)=>{const Ye=Pe[E]??"",ue=$e[E]??"";return typeof Ye=="number"&&typeof ue=="number"?(Ye-ue)*je:String(Ye).localeCompare(String(ue))*je})},[S,k,P,A,F,E,Z]),U=he=>{K(we=>{const je=new Set(we);return je.has(he)?je.delete(he):(c===0||je.size<c)&&je.add(he),je})},$=()=>{const he=S.filter(we=>V.has(we.id));o==null||o({songs:he})},H=n||w,X=he=>{he===E?G(we=>we==="asc"?"desc":"asc"):(D(he),G("asc"))},re=d.useRef(null),[oe,se]=d.useState(0),z=d.useRef(0),ee=d.useRef(_);ee.current=_,d.useEffect(()=>{se(he=>{const we=Math.min(Math.max(0,he),Math.max(0,_.length-1));return z.current=we,we})},[_.length]);const ae=d.useCallback(he=>{var je;const we=(je=re.current)==null?void 0:je.querySelector(`[data-ksb-index="${he}"]`);we==null||we.focus(),we==null||we.scrollIntoView({block:"nearest"})},[]),ce=d.useCallback(he=>{z.current=he,se(he)},[]),le=d.useCallback((he,we=!0)=>{const je=ee.current.length;if(je===0)return;const Pe=Math.min(je-1,Math.max(0,he));z.current=Pe,se(Pe),we&&requestAnimationFrame(()=>ae(Pe))},[ae]),ne=d.useCallback(he=>le(z.current+he),[le]),pe=he=>{const we=ee.current[he];we&&(l?U(we.id):p||i==null||i(we))},fe=he=>{switch(he.key){case"ArrowDown":he.preventDefault(),ne(1);break;case"ArrowUp":he.preventDefault(),ne(-1);break;case"Home":he.preventDefault(),le(0);break;case"End":he.preventDefault(),le(ee.current.length-1);break;case"PageDown":he.preventDefault(),ne(5);break;case"PageUp":he.preventDefault(),ne(-5);break}},ge=ve.useGamepad({enabled:h,actions:{navUp:{button:"DpadUp",onPress:()=>ne(-1),repeatDelay:350,repeatRate:110},navDown:{button:"DpadDown",onPress:()=>ne(1),repeatDelay:350,repeatRate:110},stickUp:{axis:"LeftY",axisDirection:"negative",onPress:()=>ne(-1),repeatDelay:350,repeatRate:130},stickDown:{axis:"LeftY",axisDirection:"positive",onPress:()=>ne(1),repeatDelay:350,repeatRate:130},select:{button:"A",onPress:()=>pe(z.current)},confirm:{button:"Start",onPress:()=>{l&&$()}}}});return f==="hidden"?null:r.jsxs("div",{className:`nice-ksb${m?` ${m}`:""}`,style:x,id:b,"data-testid":j,children:[u&&r.jsxs("aside",{className:"nice-ksb__sidebar",children:[r.jsxs("button",{type:"button",className:`nice-ksb__node${F.type==="all"?" nice-ksb__node--active":""}`,onClick:()=>q({type:"all"}),children:[r.jsx(B.NtdMusic,{size:14})," ",C("karaokeBrowser.allSongs","All songs")," (",S.length,")"]}),O.length>0&&r.jsxs("div",{className:"nice-ksb__facet",children:[r.jsx("div",{className:"nice-ksb__facet-title",children:C("karaokeBrowser.genres","Genres")}),O.map(he=>r.jsx("button",{type:"button",className:`nice-ksb__node${F.type==="genre"&&F.value===he?" nice-ksb__node--active":""}`,onClick:()=>q({type:"genre",value:he}),children:he},he))]}),Y.length>0&&r.jsxs("div",{className:"nice-ksb__facet",children:[r.jsx("div",{className:"nice-ksb__facet-title",children:C("karaokeBrowser.languages","Languages")}),Y.map(he=>r.jsx("button",{type:"button",className:`nice-ksb__node${F.type==="language"&&F.value===he?" nice-ksb__node--active":""}`,onClick:()=>q({type:"language",value:he}),children:he},he))]})]}),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:T,placeholder:C("karaokeBrowser.search","Search title or artist…"),onChange:he=>M(he.target.value)}),r.jsx("div",{className:"nice-ksb__sort",children:["artist","title","year","genre"].map(he=>r.jsxs("button",{type:"button",className:`nice-ksb__sort-btn${E===he?" nice-ksb__sort-btn--active":""}`,onClick:()=>X(he),children:[C(`karaokeBrowser.sort.${he}`,dp[he]??he),E===he&&(Z==="asc"?r.jsx(B.NtdChevronUp,{size:12}):r.jsx(B.NtdChevronDown,{size:12}))]},he))}),r.jsxs("span",{className:`nice-ksb__navhint${ge.connected?" nice-ksb__navhint--pad":""}`,title:C("karaokeBrowser.navHint","Navigate with ↑ ↓ or the D-pad · Enter / A to play"),children:[ge.connected?r.jsx(B.NtdGamepad,{size:14}):r.jsx(B.NtdMove,{size:14}),r.jsx("span",{className:"nice-ksb__navhint-keys",children:ge.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":C("karaokeBrowser.songs","Songs"),ref:re,onKeyDown:fe,children:H?r.jsx("div",{className:"nice-ksb__empty",children:C("karaokeBrowser.loading","Loading…")}):_.length===0?r.jsx("div",{className:"nice-ksb__empty",children:C("karaokeBrowser.noResults","No songs found")}):_.map((he,we)=>r.jsx(cp,{song:he,index:we,active:we===oe,coverUrl:(a==null?void 0:a(he))||he.coverImage||he.externalCoverUrl||he.coverPath||op,topScore:s==null?void 0:s(he),selected:V.has(he.id),multiSelect:l,disabled:p,t:C,onPlay:i,onToggleSelect:U,onFocusRow:ce},he.id))}),l&&r.jsxs("div",{className:"nice-ksb__footer",children:[r.jsxs("span",{children:[V.size,c>0?` / ${c}`:""," ",C("karaokeBrowser.selected","selected")]}),r.jsx("button",{type:"button",className:"nice-ksb__confirm",disabled:V.size===0,onClick:$,children:C("karaokeBrowser.confirm","Add selected")})]})]})]})};function dl(e,t,n=50,a=30){const s=Math.round(e/1e3*t),i=Math.round(n/1e3*t),o=Math.max(1,Math.round(a/1e3*t)),l=new Float32Array(s);for(let c=0;c<o;c++){const u=.5*(1-Math.cos(2*Math.PI*c/(o-1))),h=i+c-Math.floor(o/2);h>=0&&h<s&&(l[h]=u)}return l}function ni(e,t,n=1e3){const a=Math.max(1,Math.round(t/n)),s=Math.ceil(e.length/a),i=new Float32Array(s);for(let l=0;l<s;l++){const c=l*a,u=Math.min(e.length,c+a);let h=0;for(let p=c;p<u;p++)h+=Math.abs(e[p]);i[l]=h/(u-c||1)}let o=0;for(let l=0;l<i.length;l++)i[l]>o&&(o=i[l]);if(o>0)for(let l=0;l<i.length;l++)i[l]=i[l]/o;return{env:i,factor:a}}function hp(e,t){const n=e.length,a=t.length;if(n===0||a===0)return 0;let s={lag:0,score:-1/0};const i=Math.min(2e3,a);for(let o=-i;o<=i;o++){let l=0,c=0,u=0;for(let 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,u+=x*x}const h=Math.sqrt(Math.max(1e-9,c*u)),p=l/h;p>s.score&&(s={lag:o,score:p})}return s.lag}function ul(e,t,n=50,a=30){try{const s=Math.max(300,Math.round(e.length/t*1e3)),i=dl(s,t,n,a),o=ni(e,t,1e3),l=ni(i,t,1e3),u=hp(l.env,o.env)*1e3/1e3;return Math.round(u)}catch{return null}}const pp=({deviceId:e,initialOffsetMs:t=null,onSave:n,onClose:a,rounds:s=3,t:i,className:o,style:l,id:c,accessMode:u,"data-testid":h})=>{const{t:p}=xe(),g=i??p,[y,m]=d.useState(null),[x,b]=d.useState(t),[f,j]=d.useState(!1),[v,C]=d.useState([]),[T,M]=d.useState(0),[k,R]=d.useState(!1),P=d.useRef(!1);d.useEffect(()=>{b(t??null)},[t,e]);const I=async()=>{const D=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),Z=new AudioContext,G=Z.sampleRate,F=Z.createMediaStreamSource(D),q=Z.createScriptProcessor(2048,1,1);F.connect(q),q.connect(Z.destination);const V=1200,K=Math.round(V/1e3*G),W=new Float32Array(K);let Q=0,w=!1;q.onaudioprocess=U=>{if(w)return;const $=U.inputBuffer.getChannelData(0),H=Math.min($.length,K-Q);H>0&&(W.set($.subarray(0,H),Q),Q+=H),Q>=K&&(w=!0)},await new Promise(U=>setTimeout(U,80));const N=new AudioContext,S=N.createOscillator(),O=N.createGain();S.type="sine",S.frequency.value=1e3,O.gain.value=1e-4,S.connect(O),O.connect(N.destination);const Y=N.currentTime+.05;O.gain.setValueAtTime(1e-4,Y-.01),O.gain.linearRampToValueAtTime(1,Y),O.gain.linearRampToValueAtTime(1e-4,Y+.06),S.start(Y-.02),S.stop(Y+.1),await new Promise(U=>{const $=()=>{if(w||Q>=K){U();return}setTimeout($,50)};setTimeout(()=>{w=!0,U()},V+500),$()}),q.onaudioprocess=null;try{q.disconnect()}catch{}try{F.disconnect()}catch{}try{await N.close()}catch{}try{await Z.close()}catch{}D.getTracks().forEach(U=>U.stop());const _=W.subarray(0,Q);return ul(_,G,130,30)},A=async()=>{if(!P.current){P.current=!0,R(!0),m(g("latencyCalibrator.requestingMic","Requesting microphone — click allow if prompted")),b(null),C([]),M(0);try{const D=[];for(let G=0;G<s;G++){m(`${g("latencyCalibrator.playingTone","Playing test tone and recording…")} (${G+1}/${s})`),M(Math.round(G/s*100));const F=await I();F!==null&&(D.push(Math.max(-500,Math.min(2e3,Math.round(F)))),C([...D])),G<s-1&&await new Promise(q=>setTimeout(q,400))}if(M(100),D.length===0){m(g("latencyCalibrator.noSignal","No signal detected — try louder or check the microphone"));return}let Z;if(D.length>=3){const F=[...D].sort((q,V)=>q-V).slice(1,-1);Z=Math.round(F.reduce((q,V)=>q+V,0)/F.length)}else Z=Math.round(D.reduce((G,F)=>G+F,0)/D.length);b(Z),m(`${g("latencyCalibrator.measured","Measured")} ~${Z} ms (${D.length}: ${D.join(", ")} ms)`)}catch(D){m(`${g("latencyCalibrator.calibrationError","Calibration error: ")}${D instanceof Error?D.message:String(D)}`)}finally{P.current=!1,R(!1)}}},L=async()=>{if(!(x===null||!n)){j(!0);try{await n(Math.round(x)),m(g("latencyCalibrator.saved","Saved"))}catch(D){m(`${g("latencyCalibrator.saveError","Save error: ")}${String(D)}`)}finally{j(!1)}}},E={padding:"7px 16px",border:"none",borderRadius:8,cursor:"pointer",fontWeight:600};return u==="hidden"?null:r.jsxs("div",{className:`nice-latency-calibrator${o?` ${o}`:""}`,style:{padding:12,color:"var(--nice-text, inherit)",...l},id:c,"data-testid":h,children:[r.jsxs("h5",{style:{margin:"0 0 8px",display:"flex",alignItems:"center",gap:6},children:[r.jsx(B.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:k,style:{...E,background:"var(--nice-accent, #3b82f6)",color:"var(--nice-text-on-primary, #fff)"},children:g("latencyCalibrator.calibrate","Calibrate")}),r.jsx("button",{type:"button",onClick:()=>{b(null),m(null),C([]),M(0)},style:{...E,background:"var(--nice-bg-tertiary)",color:"var(--nice-text, #e2e8f0)"},children:g("latencyCalibrator.clear","Clear")})]}),k&&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:`${T}%`,background:"var(--nice-accent, #3b82f6)",transition:"width 0.2s"}})}),v.length>0&&r.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:[g("latencyCalibrator.rounds","Rounds"),": ",v.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:L,disabled:x===null||f,style:{...E,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:{...E,background:"transparent",border:"1px solid var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)"},children:g("latencyCalibrator.close","Close")})]})]})},fp=e=>[{value:"normal",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.NtdMicrophone,{size:14})," ",e("karaokeSetup.modeMic","Mic")]})},{value:"pad",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.NtdGamepad,{size:14})," ",e("karaokeSetup.modePad","Pad")]})},{value:"demo",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.NtdStopwatch,{size:14})," ",e("karaokeSetup.modeDemo","Demo")]})}],hl=({players:e,defaultPlayers:t,onPlayersChange:n,gameMode:a="normal",onGameModeChange:s,gameModes:i,difficulty:o="normal",onDifficultyChange:l,audioInputs:c,maxPlayers:u=4,onCalibrate:h,t:p,className:g,style:y,id:m,accessMode:x,"data-testid":b})=>{const{t:f}=xe(),j=p??f,v=d.useMemo(()=>i??fp(j),[i,j]),[C,T]=ve.useControllableState({value:e,defaultValue:t,fallbackValue:[],onChange:n,componentName:"NiceKaraokeSetupPanel"}),[M,k]=d.useState([]);d.useEffect(()=>{var Z,G,F;if(c||!((Z=navigator.mediaDevices)!=null&&Z.enumerateDevices))return;let E=!1;const D=()=>navigator.mediaDevices.enumerateDevices().then(q=>!E&&k(q.filter(V=>V.kind==="audioinput"))).catch(()=>{});return D(),(F=(G=navigator.mediaDevices).addEventListener)==null||F.call(G,"devicechange",D),()=>{var q,V;E=!0,(V=(q=navigator.mediaDevices).removeEventListener)==null||V.call(q,"devicechange",D)}},[c]);const R=c??M,P=d.useMemo(()=>[{value:"",label:j("karaokeSetup.noMic","No microphone")},...R.map((E,D)=>({value:E.deviceId,label:E.label||`${j("karaokeSetup.microphone","Microphone")} ${D+1}`}))],[R,j]),I=(E,D)=>T(C.map(Z=>Z.id===E?{...Z,...D}:Z)),A=()=>{if(C.length>=u)return;const E=C.reduce((D,Z)=>Math.max(D,Z.id),0)+1;T([...C,{id:E,name:`${j("karaokeSetup.player","Player")} ${C.length+1}`,color:Xe[C.length%Xe.length],micId:null}])},L=E=>T(C.filter(D=>D.id!==E));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":b,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:j("karaokeSetup.mode","Game mode")}),r.jsx(ie.NiceSegmentedControl,{options:v,value:a,onChange:E=>s==null?void 0:s(E)})]}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:12,fontWeight:600,marginBottom:6,color:"var(--nice-text-muted, #94a3b8)"},children:j("karaokeSetup.difficulty","Difficulty")}),r.jsx(ie.NiceSegmentedControl,{options:[{value:"easy",label:j("karaokeSetup.easy","Easy")},{value:"normal",label:j("karaokeSetup.normal","Normal")},{value:"hard",label:j("karaokeSetup.hard","Hard")}],value:o,onChange:E=>l==null?void 0:l(E)})]})]}),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:[j("karaokeSetup.players","Players")," (",C.length,"/",u,")"]}),C.map(E=>r.jsx(ie.NiceCard,{children:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[r.jsx(ie.NiceColorPicker,{value:E.color||Xe[0],onChange:D=>I(E.id,{color:D})}),r.jsx("div",{style:{flex:"1 1 160px",minWidth:140},children:r.jsx(ie.NiceTextInput,{value:E.name,onChange:D=>I(E.id,{name:D}),placeholder:j("karaokeSetup.playerName","Player name"),size:"sm"})}),r.jsx("div",{style:{flex:"1 1 180px",minWidth:150},children:r.jsx(ie.NiceSelect,{options:P,value:E.micId??"",onChange:D=>I(E.id,{micId:(typeof D=="string"?D:D[0])||null}),placeholder:j("karaokeSetup.selectMic","Microphone"),size:"sm"})}),h&&E.micId&&r.jsxs(ie.NiceButton,{variant:"ghost",size:"sm",onClick:()=>h(E.micId),children:[r.jsx(B.NtdSettings,{size:14})," ",j("karaokeSetup.calibrate","Calibrate")]}),r.jsx(ie.NiceButton,{variant:"danger",size:"sm",onClick:()=>L(E.id),"aria-label":j("karaokeSetup.remove","Remove"),children:r.jsx(B.NtdClose,{size:14})})]})},E.id)),r.jsx("div",{children:r.jsxs(ie.NiceButton,{variant:"primary",onClick:A,disabled:C.length>=u,children:[r.jsx(B.NtdPlus,{size:14})," ",j("karaokeSetup.addPlayer","Add player")]})})]})]})},mp=[],gp=["freeForAll","roundRobin","hostOnly","firstCome"],yp={freeForAll:B.NtdDice,roundRobin:B.NtdRepeat,hostOnly:B.NtdCrown,firstCome:B.NtdLightning},vp={freeForAll:"success",roundRobin:"warning",hostOnly:"info",firstCome:"danger"},pl=({players:e=mp,mode:t,defaultMode:n,onModeChange:a,turnTimeSec:s=30,hostIndex:i=0,onActivePlayerChange:o,myPlayerIndex:l,t:c,className:u,style:h,id:p,accessMode:g,"data-testid":y})=>{const{t:m}=xe(),x=c??m,[b,f]=ve.useControllableState({value:t,defaultValue:n,fallbackValue:"freeForAll",onChange:a,componentName:"NiceKaraokeSelectionMode"}),j={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,C]=d.useState(0),[T,M]=d.useState(s),k=d.useRef(null),[R,P]=d.useState(null),[I,A]=d.useState(!1),[L,E]=d.useState(null),D=d.useRef(null),Z=d.useMemo(()=>b==="hostOnly"?i:b==="roundRobin"?v%Math.max(1,e.length):b==="firstCome"?I?-1:L??-1:-1,[b,v,e.length,i,I,L]);d.useEffect(()=>{o==null||o(Z)},[Z,o]),d.useEffect(()=>{if(b!=="roundRobin"||s<=0){k.current&&clearInterval(k.current);return}return M(s),k.current=setInterval(()=>{M(K=>K<=1?(C(W=>W+1),s):K-1)},1e3),()=>{k.current&&clearInterval(k.current)}},[b,s,v]);const G=d.useCallback(()=>{E(null),A(!1),P(3),D.current&&clearInterval(D.current),D.current=setInterval(()=>{P(K=>K===null||K<=1?(D.current&&clearInterval(D.current),A(!0),null):K-1)},1e3)},[]);d.useEffect(()=>()=>{D.current&&clearInterval(D.current)},[]),d.useEffect(()=>{b!=="firstCome"&&(P(null),A(!1),E(null))},[b]);const F=d.useCallback(()=>{C(K=>K+1),M(s)},[s]),q=K=>{var W;return((W=e[K])==null?void 0:W.name)||`${x("songSelection.player","Player")} ${K+1}`},V=Z>=0&&Z<e.length?e[Z]:null;return g==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-selection-mode${u?` ${u}`:""}`,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:gp.map(K=>r.jsxs(ie.NiceButton,{size:"sm",variant:b===K?vp[K]:"outline",onClick:()=>f(K),children:[d.createElement(yp[K],{size:14})," ",j[K]]},K))}),b!=="freeForAll"&&b!=="firstCome"&&V&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsxs(ie.NiceBadge,{variant:Z===l?"success":"secondary",children:[r.jsx(B.NtdMicrophone,{size:12})," ",q(Z)]}),Z===l&&r.jsx("span",{style:{color:"var(--nice-success, #4caf50)",fontSize:12,fontWeight:600},children:x("songSelection.yourTurn","Your turn!")})]}),b==="roundRobin"&&s>0&&r.jsx("div",{style:{flex:1,minWidth:120,maxWidth:200},children:r.jsx(ie.NiceProgress,{value:T,max:s,variant:T<=5?"error":T<=10?"warning":"info",showValue:!0,formatValue:K=>`${K}s`})}),b==="roundRobin"&&r.jsxs(ie.NiceButton,{size:"sm",variant:"ghost",onClick:F,children:[x("songSelection.next","Next")," ",r.jsx(B.NtdPlay,{size:12})]}),b==="firstCome"&&r.jsxs(r.Fragment,{children:[R!==null&&r.jsx("div",{style:{fontSize:32,fontWeight:900,color:"var(--nice-error, #f44336)",minWidth:60,textAlign:"center"},children:R}),I&&L===null&&r.jsxs(ie.NiceBadge,{variant:"danger",children:[r.jsx(B.NtdLightning,{size:12})," ",x("songSelection.raceGo","GO! Pick a song!")]}),L!==null&&L<e.length&&r.jsxs(ie.NiceBadge,{variant:"success",children:[r.jsx(B.NtdTrophy,{size:12})," ",q(L)," ",x("songSelection.raceWon","picks!")]}),r.jsx(ie.NiceButton,{size:"sm",variant:R!==null?"secondary":"danger",onClick:G,disabled:R!==null,children:L!==null?r.jsxs(r.Fragment,{children:[r.jsx(B.NtdRepeat,{size:12})," ",x("songSelection.raceAgain","New race")]}):r.jsxs(r.Fragment,{children:[r.jsx(B.NtdLightning,{size:12})," ",x("songSelection.raceStart","Start race")]})})]})]})};function bp(e,t,n,a){return d.useMemo(()=>e==="freeForAll"?!0:e==="firstCome"?t===-1:e==="hostOnly"?a===n:e==="roundRobin"?a===t:!1,[e,t,n,a])}const xp=({players:e,defaultPlayers:t,onPlayersChange:n,gameMode:a,onGameModeChange:s,gameModes:i,difficulty:o,onDifficultyChange:l,audioInputs:c,maxPlayers:u=4,onCalibrate:h,initialSelectionMode:p="freeForAll",turnTimeSec:g=30,hostIndex:y=0,myPlayerIndex:m,onChange:x,variant:b="bar",t:f,className:j,style:v,id:C,accessMode:T,"data-testid":M})=>{const{t:k}=xe(),R=f??k,[P,I]=ve.useControllableState({value:e,defaultValue:t,fallbackValue:[],onChange:n,componentName:"NiceKaraokeSessionJoin"}),[A,L]=d.useState([]);d.useEffect(()=>{var Y,_,U;if(c||!((Y=navigator.mediaDevices)!=null&&Y.enumerateDevices))return;let S=!1;const O=()=>navigator.mediaDevices.enumerateDevices().then($=>!S&&L($.filter(H=>H.kind==="audioinput"))).catch(()=>{});return O(),(U=(_=navigator.mediaDevices).addEventListener)==null||U.call(_,"devicechange",O),()=>{var $,H;S=!0,(H=($=navigator.mediaDevices).removeEventListener)==null||H.call($,"devicechange",O)}},[c]);const E=c??A,D=E.length===0,Z=P.some(S=>!S.micId),G=!Z,[F,q]=d.useState(p),[V,K]=d.useState(-1),W=d.useCallback((S,O)=>{x==null||x({selectionMode:S,activePickerIndex:O,allMicsAssigned:G,noInputDevices:D})},[x,G,D]),Q=d.useCallback(S=>{q(S),W(S,V)},[W,V]),w=d.useCallback(S=>{K(S),W(F,S)},[W,F]),N=d.useMemo(()=>({padding:10,borderRadius:8,fontWeight:700,marginTop:8,textAlign:"center"}),[]);return T==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-session-join${j?` ${j}`:""}`,style:b==="card"?{background:"var(--nice-bg-secondary)",borderRadius:12,padding:16,...v}:v,id:C,"data-testid":M,children:[r.jsx(hl,{players:P,onPlayersChange:I,gameMode:a,onGameModeChange:s,gameModes:i,difficulty:o,onDifficultyChange:l,audioInputs:E,maxPlayers:u,onCalibrate:h,t:R}),D&&r.jsxs("div",{style:{...N,background:"var(--nice-error, #ef4444)",color:"#fff"},children:[R("karaokeSessionJoin.noInputDevices","No microphone detected"),r.jsx("br",{}),r.jsx("span",{style:{fontWeight:400,fontSize:13},children:R("karaokeSessionJoin.noInputDevicesHint","Connect a microphone to sing.")})]}),!D&&Z&&r.jsx("div",{style:{...N,background:"var(--nice-warning, #f59e0b)",color:"var(--nice-text-on-primary, #222)",fontSize:14},children:R("karaokeSessionJoin.assignMicWarning","Assign a microphone to each player.")}),P.length>1&&r.jsx("div",{style:{marginTop:12},children:r.jsx(pl,{players:P,mode:F,onModeChange:Q,onActivePlayerChange:w,turnTimeSec:g,hostIndex:y,myPlayerIndex:m,t:R})})]})};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 Sp=[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")],Ja="nice2dev-karaoke-display",kp=(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"},...Sp.map(e=>({value:e.family,label:e.family}))]})(),fl=[{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)"}],yn={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 ri=!1;function ml(){try{const e=localStorage.getItem(Ja);if(e){const t=JSON.parse(e);return{...yn,...t}}}catch{}return{...yn}}async function wp(e){if(ri||(ri=!0,!e))return;const t=await e();if(t)try{const n=JSON.parse(t),a={...yn,...n};localStorage.setItem(Ja,JSON.stringify(a))}catch{}}function Cp(e){const t=JSON.stringify(e);localStorage.setItem(Ja,t),es(e)}function gl(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=fl.find(n=>n.id===e.presetId);return t?{sungGradient:t.sungGradient,goldGradient:t.goldGradient,glowColor:t.glowColor}:{sungGradient:yn.customSungGradient,goldGradient:yn.customGoldGradient,glowColor:yn.customGlowColor}}function es(e){const{sungGradient:t,goldGradient:n,glowColor:a}=gl(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 jp(){const e=ml();es(e)}function Mp(e){const t=(e||"").split(/\r?\n/),n=[];for(let a=0;a<t.length;a++){const s=t[a].trim();if(s&&/^[:*F]\s/.test(s)){const i=s.slice(1).trim().split(/\s+/),o=parseInt(i[0]||"0",10),l=parseInt(i[1]||"0",10),c=isNaN(o)?0:o/10,u=isNaN(l)?0:l/10;n.push({lineIndex:a,start:c,duration:u,raw:t[a]})}}return n}const Rp=({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,u=(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))",b={transition:u?`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:{...b,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})})})},Np=({ultrastarText:e,audioUrl:t,audioRef:n,animationConfig:a})=>{const{t:s}=xe(),i=d.useRef(null),o=n??i,[l,c]=d.useState(!1),u=d.useMemo(()=>Mp(e),[e]),h=d.useRef(null),p=d.useRef(null),g=d.useRef(0),y=d.useRef(0),[m,x]=d.useState(-1),b=d.useMemo(()=>(e||"").split(/\r?\n/),[e]),f=28,j=b.length*f,v=d.useMemo(()=>({lines:b,notes:u,currentIndex:m,animationConfig:a}),[b,u,m,a]),C=d.useCallback((T,M)=>r.jsx(Rp,{index:M,data:v}),[v]);return d.useEffect(()=>{const T=o.current;T&&(l?T.play().catch(()=>c(!1)):T.pause())},[l,o]),d.useEffect(()=>{const T=o.current;if(!T)return;let M=-1;const k=a??null,R=k&&typeof k.scrollSmooth=="number"?k.scrollSmooth:.18;let P=performance.now();const I=()=>{var W,Q;const A=performance.now(),L=Math.max(0,Math.min(.2,(A-P)/1e3));P=A;const E=T.currentTime||0;g.current=E;let D=-1;for(let w=0;w<u.length;w++){const N=u[w];if(E>=N.start&&E<N.start+Math.max(.001,N.duration)){D=w;break}}D!==M&&(M=D,x(D));let Z=0;if(M>=0){const w=((W=u[M])==null?void 0:W.lineIndex)??0,N=((Q=h.current)==null?void 0:Q.clientHeight)??220;Z=w*f-N/2+f/2;const S=Math.max(0,j-N);(isNaN(Z)||!isFinite(Z))&&(Z=0),Z=Math.max(0,Math.min(Z,S))}const G=1-Math.pow(Math.max(0,1-R),Math.min(4,L*60)),K=(((a==null?void 0:a.scrollEasing)||"easeOutCubic")==="linear"?w=>w:w=>1-Math.pow(1-w,3))(G);y.current=y.current+(Z-y.current)*K;try{const w=h.current;w&&typeof w.scrollTop=="number"&&(w.scrollTop=Math.round(y.current))}catch{}p.current=requestAnimationFrame(I)};return p.current=requestAnimationFrame(I),()=>{p.current&&cancelAnimationFrame(p.current)}},[o,u,j,a]),r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[r.jsx("button",{onClick:()=>c(T=>!T),disabled:!t,children:l?s("karaokeEditor.pause","Pause"):s("karaokeEditor.play","Play")}),r.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-secondary, #666)"},children:[(g.current||0).toFixed(2),"s"]}),r.jsx("div",{style:{marginLeft:"auto",fontSize:13,color:"var(--nice-text-secondary, #666)"},children:s("karaokeEditor.notes","Notes: {notes}").replace("{notes}",String(u.length))})]}),r.jsx("div",{style:{border:"1px solid var(--nice-border, #ddd)",height:220,overflow:"hidden",padding:8,position:"relative"},children:e?r.jsx(ie.NiceVirtualScroller,{ref:h,items:b,itemHeight:f,height:220,renderItem:C,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 Tp(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 Pp=new Set;function Ep({ultrastarText:e,audioUrl:t,audioRef:n,ytRef:a}){const{lines:s,notes:i}=d.useMemo(()=>Tp(e),[e]),[o,l]=d.useState(Pp),c=d.useRef(i);c.current=i;const u=d.useRef(t);return u.current=t,d.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:u.current&&(p=document.createElement("audio"),p.src=u.current,p.preload="metadata",p.style.display="none",document.body.appendChild(p),h=p)}let g=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 f=new Set;for(const v of c.current)x>=v.start&&x<v.start+Math.max(.001,v.duration)&&f.add(v.lineIndex);const j=[...f].join(",");j!==y&&(y=j,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 $p=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),ai=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")}`},ra={border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},Ap=({isPlaying:e,index:t,count:n,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek:u,onVolume:h})=>{const{t:p}=xe();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:[ai(a)," / ",ai(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:ra,children:r.jsx(B.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:ra,children:e?r.jsx(B.NtdPause,{size:16}):r.jsx(B.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:ra,children:r.jsx(B.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=>u(parseFloat(g.target.value))}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx(B.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))})]})]})]})},Ip=d.memo(Ap);function Lp(e,t,n,a,s){const o=Math.max(1,Math.floor(a.length/48)),l=t/48;for(let c=0;c<48;c++){const u=a[c*o]/255,h=u*(n-6),p=c*l,g=n-h,y=c/48*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+u*30)}%)`,e.fillRect(p+1,g,l-2,h)}}function _p(e,t,n,a,s,i){if(!i.current){const p=[];for(let y=0;y<24;y++)p.push({ang:y/24*Math.PI*2,phase:Math.random()*Math.PI*2,baseR:Math.min(t,n)*.22+Math.random()*30});i.current={nodes:p}}const o=i.current,l=t/2,c=n/2,u=26+a*80,h=[];for(const p of o.nodes){p.phase+=.02+a*.06;const g=p.baseR+Math.sin(p.phase)*u,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],b=(g+m)/2,f=(y+x)/2;p===0?e.moveTo(b,f):e.quadraticCurveTo(g,y,b,f)}e.closePath(),e.fill(),e.stroke()}function Dp(e,t,n,a,s,i){i.current||(i.current={items:[]});const o=i.current;Math.random()<.06+a*.25&&o.items.push({x:Math.random()*t,y:Math.random()*n,r:8+Math.random()*24,life:1,hue:(s+Math.random()*120)%360});const l=[];for(const c of o.items){c.r+=2+a*14,c.life*=.975-a*.02,c.life>.04&&l.push(c);const u=e.createRadialGradient(c.x,c.y,1,c.x,c.y,c.r);u.addColorStop(0,`hsla(${c.hue}, 90%, 60%, ${.35*c.life})`),u.addColorStop(.6,`hsla(${(c.hue+40)%360}, 80%, 55%, ${.18*c.life})`),u.addColorStop(1,`hsla(${(c.hue+80)%360}, 70%, 50%, 0)`),e.fillStyle=u,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}o.items=l}const zp="var(--nice-text-muted, #94a3b8)",Fp=({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:zp},children:s??a??"—"})]})});function rn(e,t){return e+Math.random()*(t-e)}function Op(e,t,n,a,s,i,o){o.current||(o.current={embers:[],t:0});const l=o.current,c=e.createLinearGradient(0,n,0,n*.4);c.addColorStop(0,`hsla(${(i+30)%360}, 90%, 50%, .35)`),c.addColorStop(1,`hsla(${(i+10)%360}, 90%, 50%, 0)`),e.fillStyle=c,e.fillRect(0,0,t,n);const u=6;for(let p=0;p<u;p++){const g=(p+.5)/u*t,y=(a[Math.floor((p+1)/(u+1)*a.length)]||0)/255,m=n*.18+(.25+s*.6+y*.7)*n*.55,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 b=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+b,n-m*.75,g+b,n-m),e.bezierCurveTo(g+25+b*.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:rn(t*.25,t*.75),y:n-rn(4,14),r:rn(1,3),vx:rn(-.15,.15),vy:-rn(.6,1.8)-s*1.2,life:rn(.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 Bp(e,t,n,a,s){const i=t/2,o=n/2,l=Math.min(t,n)*.28,c=96,u=Math.max(1,Math.floor(a.length/c));for(let h=0;h<c;h++){const p=(a[h*u]??0)/255,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,b=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(b,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 Gp(e,t,n,a,s){const l=t/14,c=n/8;for(let u=0;u<8;u++)for(let h=0;h<14;h++){const p=Math.min(a.length-1,u*14+h),g=a[p]/255,y=(s+h/14*210+u/8*90)%360,m=65+g*30,x=20+g*40,b=(1-g)*4;e.fillStyle=`hsl(${y}, ${m}%, ${x}%)`,e.fillRect(h*l+b,u*c+b,Math.max(1,l-2*b),Math.max(1,c-2*b))}}function Wp(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 Up(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 Wp(t.length?t:[]);i.loadedUrls=t,i.sprites=[],i.ready=!0;const c=u=>l[u%Math.max(1,l.length)]??new Image;for(let u=0;u<n;u++){const h=Math.random()*Math.min(a,s)*.38+40;i.sprites.push({img:c(u),x:(Math.random()-.5)*h*.4,y:(Math.random()-.5)*h*.4,z:Math.random()*600+100,ang:Math.random()*Math.PI*2,spin:(Math.random()*.03+.01)*(Math.random()<.5?-1:1),vz:Math.random()*1.2+.2,size:Math.random()*.35+.65})}}}function Vp(e,t,n,a,s,i,o,l){const c=i.current;if(!(c!=null&&c.ready))return;const u=t/2,h=n/2,p=900,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,b=u+m.x*x,f=h+m.y*x,j=64*x,v=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(b,f,j*.7,v*.7,0,0,Math.PI*2),e.fill(),e.restore(),m.img&&m.img.width?e.drawImage(m.img,b-j/2,f-v/2,j,v):(e.save(),e.fillStyle=`hsl(${(s+180)%360}, 40%, 55%)`,e.fillRect(b-j/2,f-v/2,j,v),e.restore())}}function jn(e,t){return e+Math.random()*(t-e)}function qp(e,t,n,a,s,i){i.current||(i.current={blobs:Array.from({length:7},(u,h)=>({x:jn(t*.2,t*.8),y:jn(n*.2,n*.8),r:jn(Math.min(t,n)*.05,Math.min(t,n)*.12),vx:jn(-.6,.6),vy:jn(-.6,.6),hue:(s+h*10)%360}))});const o=i.current,l=.6+a*2.2;e.save(),e.globalCompositeOperation="lighter";for(const c of o.blobs){c.x+=c.vx*l,c.y+=c.vy*l,c.vy-=.01-a*.015,c.x<c.r&&(c.x=c.r,c.vx=Math.abs(c.vx)),c.x>t-c.r&&(c.x=t-c.r,c.vx=-Math.abs(c.vx)),c.y<c.r&&(c.y=c.r,c.vy=Math.abs(c.vy)),c.y>n-c.r&&(c.y=n-c.r,c.vy=-Math.abs(c.vy));const u=(c.hue+a*120)%360,h=e.createRadialGradient(c.x,c.y,c.r*.2,c.x,c.y,c.r);h.addColorStop(0,`hsla(${u}, 95%, 70%, .8)`),h.addColorStop(1,`hsla(${(u+40)%360}, 90%, 30%, 0)`),e.fillStyle=h,e.shadowBlur=18,e.shadowColor=`hsl(${u}, 100%, 60%)`,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}e.restore(),e.strokeStyle=ve.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 Hp(e,t,n,a,s,i){i.current||(i.current={tris:[]});const o=i.current,l=6;for(;o.tris.length<l;)o.tris.push({a:Math.random()*Math.PI*2,r:30+Math.random()*Math.min(t,n)*.35,dr:(Math.random()*.6+.2)*(Math.random()<.5?-1:1)});const c=t/2,u=n/2;for(const h of o.tris){h.a+=.002+a*.02*(h.dr>0?1:-1),h.r+=Math.sin(h.a*2)*(.3+a*1.4);const p=Math.max(40,Math.min(h.r,Math.min(t,n)*.48));e.save(),e.translate(c,u),e.rotate(h.a),e.strokeStyle=`hsla(${(s+p*.2)%360}, 90%, 60%, .9)`,e.lineWidth=2.5,e.beginPath(),e.moveTo(p,0);for(let 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 Kp(e,t,n,a,s,i){const o=t/2,l=n/2,c=5,u=Math.min(t,n)*.42;i.current+=.01;for(let h=0;h<c;h++){const p=(h+1)/(c+1),g=p*u;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 b=0;b<x;b++){const f=i.current*(1+h*.15)+b/x*Math.PI*2,j=g+Math.sin(f*2)*6*m,v=o+Math.cos(f)*j,C=l+Math.sin(f)*j;e.fillStyle=`hsla(${(s+h*30+b*6)%360}, 90%, ${55+m*30}%, ${.6+m*.3})`,e.beginPath(),e.arc(v,C,2+m*4,0,Math.PI*2),e.fill()}}}function Yp(e,t,n,a,s){const l=t/12,c=n/6;for(let u=0;u<6;u++)for(let h=0;h<12;h++){const p=(u*12+h)%a.length,g=a[p]/255,y=(s+h/12*180+u/6*90)%360,m=70+g*25,x=25+g*35;e.fillStyle=`hsl(${y}, ${m}%, ${x}%)`,e.fillRect(h*l,u*c,Math.ceil(l),Math.ceil(c))}}function Zp(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 u=i.current;for(let h=u.length-1;h>=0;h--){const p=u[h];p.x+=p.vx,p.y+=p.vy,p.life+=1;const 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)&&u.splice(h,1)}u.length>1200&&u.splice(0,u.length-1200)}function Xp(e,t,n,a,s,i){e.fillStyle="rgba(10,16,28,0.25)",e.fillRect(0,0,t,n);const o=t/2,l=n/2,c=Math.min(t,n)*(.38+s*.12),u=e.createRadialGradient(o,l,c*.1,o,l,c);u.addColorStop(0,`hsla(${(i+200)%360},90%,70%,0.95)`),u.addColorStop(.5,`hsla(${(i+260)%360},80%,55%,0.6)`),u.addColorStop(1,"transparent"),e.fillStyle=u,e.beginPath(),e.arc(o,l,c,0,Math.PI*2),e.fill();const h=18+Math.floor(s*50);for(let p=0;p<h;p++){const 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 j=m/x*f,v=(Math.sin(a*3+p*.8+f)*.6+Math.cos(a*2+p+f*.7))*(8+24*s),C=j,T=v;e.lineTo(T,C)}e.globalCompositeOperation="lighter";const b=(i+p*(240/h))%360;e.strokeStyle=`hsla(${b}, 90%, ${60+s*20}%, ${.35+s*.4})`,e.lineWidth=2+s*2,e.stroke(),e.restore()}e.beginPath(),e.arc(o,l,c*(.98+.02*Math.sin(a*2)),0,Math.PI*2),e.strokeStyle=`hsla(${(i+40)%360},90%,70%,${.25+s*.25})`,e.lineWidth=1.5,e.stroke(),e.globalCompositeOperation="source-over"}function Qp(e,t,n,a,s){const o=Math.max(1,Math.floor(a.length/96)),l=t/2,c=n/2,u=Math.min(t,n)*.22,h=Math.min(t,n)*.48;for(let p=0;p<96;p++){const g=a[p*o]/255,y=p/96*Math.PI*2,m=u,x=u+g*(h-u),b=l+Math.cos(y)*m,f=c+Math.sin(y)*m,j=l+Math.cos(y)*x,v=c+Math.sin(y)*x;e.strokeStyle=`hsl(${p/96*360+s},85%,60%)`,e.lineWidth=3,e.beginPath(),e.moveTo(b,f),e.lineTo(j,v),e.stroke()}e.fillStyle=ve.resolveCssColor("var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.canvas),e.beginPath(),e.arc(l,c,u*.85,0,Math.PI*2),e.fill()}function Jp(e,t,n,a,s,i){const o=t/2,l=n/2,c=Math.min(t,n)*.5,u=si(a,0,Math.floor(a.length*.1))/255,h=si(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+u*.55)*c,x=o+Math.cos(y)*m,b=l+Math.sin(y)*m,f=e.createRadialGradient(o,l,0,o,l,m),j=g/p*360+s;f.addColorStop(0,`hsla(${j},85%,65%,0.0)`),f.addColorStop(1,`hsla(${j},85%,65%,0.9)`),e.strokeStyle=f,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,n)}function si(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 ef(e,t,n,a,s,i){e.fillStyle="rgba(10,16,28,0.35)",e.fillRect(0,0,t,n);const o=n/2,l=Math.max(8,18-s*10),c=n*.35*(.6+s*.7),u=a.length,h=t/(u-1);e.beginPath();for(let y=0;y<u;y++){const m=(a[y]-128)/128,x=Math.sin(i*1.5+y*.03)*.12,b=y*h,f=o-l-(m+x)*c;y===0?e.moveTo(b,f):e.lineTo(b,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<u;y++){const m=(a[y]-128)/128,x=Math.cos(i*1.3+y*.035)*.12,b=y*h,f=o+l+(m+x)*c;y===0?e.moveTo(b,f):e.lineTo(b,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=ve.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 tf(e,t,n,a,s,i){const o=t/2,l=n/2,c=5,u=Math.min(t,n)*.12;for(let h=0;h<c;h++){const p=Math.floor(h/c*a.length),g=a[p]/255,y=u+h*u*.55+g*u*.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 nf(e,t,n,a,s){const i=Math.min(a.length,256),o=Math.max(1,Math.floor(a.length/i)),l=t/i;for(let c=0;c<i;c++){const u=a[c*o]/255,h=u*(n-6),p=c*l,g=n-h,y=c/i*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+u*30)}%)`,e.fillRect(p+1,g,l-2,h)}}function rf(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 af(e,t,n,a,s,i){const o=i.current,l=t/2,c=n/2,u=4+a*18;e.save(),e.translate(l,c);for(const h of o.stars){h.z-=u,h.z<20&&(h.x=(Math.random()-.5)*t,h.y=(Math.random()-.5)*n,h.z=900,h.pz=h.z);const p=h.x/h.z*600,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 sf(e,t,n,a){e.lineWidth=2,e.strokeStyle=ve.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 of=({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}),yl=({modes:e=[],active:t,setActive:n,rows:a=2})=>{const{t:s}=xe(),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(of,{active:t===o,onClick:()=>n(o),title:`${s("visualizer.mode","Mode")}: ${o}`,children:o},o))})})};function lf(e,t){const[n,a]=d.useState(()=>{try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}});return d.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(n))}catch{}},[e,n]),[n,a]}const cf=({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)})})},df="var(--player-bg, #0f172a)";function uf(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 hf(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 vl=({kind:e,audioRef:t,width:n="100%",height:a=360,coverUrl:s,title:i,subtitle:o,label:l,defaultMode:c="cover",storageKey:u="gp-stage:mode",allowedModes:h,imageUrls:p,imageCount:g=14,autoAnimate:y=!1})=>{const{t:m}=xe(),x=d.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette","radial","rays","particles","rings","grid","imageTornado","colorRipples","starfield","orbitals","eqcircle","triangles","blob","plasma","lavaLamp","cozyFire","rift"],[e,h]),b=d.useMemo(()=>{const Q=x.includes(c)?c:x[0];try{const w=localStorage.getItem(u);if(!w)return Q;const N=JSON.parse(w);return x.includes(N)?N:Q}catch{return Q}},[x,c,u]),[f,j]=lf(u,b),v=d.useRef(null),C=d.useRef(null),T=d.useRef(null),M=d.useRef(null),k=d.useRef(null),R=d.useRef(null),P=d.useRef(0),I=d.useRef(0),A=d.useRef([]),[L,E]=d.useState(0),D=d.useRef(null),Z=d.useRef(null),G=d.useRef(null),F=d.useRef(null),q=d.useRef(null),V=d.useRef(null),K=d.useRef(null),W=f!=="cover"&&f!=="video";return d.useEffect(()=>{var _;if(e==="youtube"||(C.current&&(cancelAnimationFrame(C.current),C.current=null),!W))return;Xt();const Q=Yn(),w=t.current;if(!w&&!y)return;if(w&&!T.current)try{T.current=Q.createMediaElementSource(w)}catch{}if(w&&!M.current){const U=Q.createAnalyser();U.fftSize=2048,U.smoothingTimeConstant=.85,M.current=U;try{(_=T.current)==null||_.connect(U)}catch{}try{U.connect(Q.destination)}catch{}}const N=M.current;k.current=new Uint8Array(N?N.frequencyBinCount:1024),R.current=new Uint8Array(N?N.fftSize:2048);const S=()=>{const U=v.current,$=Math.max(1,Math.floor(window.devicePixelRatio||1));U.width=Math.floor(U.clientWidth*$),U.height=Math.floor(U.clientHeight*$);const H=U.getContext("2d");H==null||H.setTransform(1,0,0,1,0,0),H==null||H.scale($,$)};S();const O=()=>S();window.addEventListener("resize",O),rf(G,220,v.current.width,v.current.height);const Y=async()=>{const U=v.current;if(!U)return;const $=U.getContext("2d");if(!$)return;const H=Math.max(1,Math.floor(window.devicePixelRatio||1)),X=U.width/H,re=U.height/H,oe=performance.now()*.001,se=f==="waveform"||f==="rift";N&&(se?N.getByteTimeDomainData(R.current):N.getByteFrequencyData(k.current)),y&&(uf(k.current,oe),hf(R.current,oe));let z=0;const ee=se?R.current:k.current;for(let ae=0;ae<ee.length;ae++){const ce=se?(ee[ae]-128)/128:ee[ae]/255;z+=ce*ce}if(z=Math.sqrt(z/ee.length),E(Math.min(1,z)),$.clearRect(0,0,X,re),f==="spectrum")nf($,X,re,k.current,P.current);else if(f==="bars")Lp($,X,re,k.current,P.current);else if(f==="waveform")sf($,X,re,R.current);else if(f==="palette"){const ae=(P.current+z*120)%360;Yp($,X,re,k.current,ae)}else if(f==="radial")Qp($,X,re,k.current,P.current);else if(f==="rays")Jp($,X,re,k.current,P.current,I);else if(f==="particles")Zp($,X,re,z,P.current,A);else if(f==="rings")tf($,X,re,k.current,z,P.current);else if(f==="grid"){const ae=(P.current+z*160)%360;Gp($,X,re,k.current,ae)}else if(f==="imageTornado"){const ae=p!=null&&p.length?p:s?[s]:[];await Up(D,ae,g,X,re);const ce=(P.current+z*100)%360;Vp($,X,re,z,ce,D)}else if(f==="colorRipples"){const ae=(P.current+z*120)%360;Dp($,X,re,z,ae,Z)}else if(f==="starfield"){const ae=(P.current+60)%360;af($,X,re,z,ae,G)}else if(f==="orbitals"){const ae=(P.current+z*180)%360;Kp($,X,re,k.current,ae,I)}else if(f==="eqcircle"){const ae=(P.current+120)%360;Bp($,X,re,k.current,ae)}else if(f==="triangles"){const ae=(P.current+40)%360;Hp($,X,re,z,ae,F)}else if(f==="blob"){const ae=(P.current+90)%360;_p($,X,re,z,ae,q)}else if(f==="plasma"){const ae=(P.current+z*200)%360;Xp($,X,re,oe,z,ae)}else if(f==="rift")ef($,X,re,R.current,z,oe);else if(f==="lavaLamp"){const ae=(P.current+z*80)%360;qp($,X,re,z,ae,V)}else if(f==="cozyFire"){const ae=(P.current+z*140)%360;Op($,X,re,k.current,z,ae,K)}P.current=(P.current+.4)%360,C.current=requestAnimationFrame(Y)};return C.current=requestAnimationFrame(Y),()=>{window.removeEventListener("resize",O),C.current&&cancelAnimationFrame(C.current)}},[W,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":df},children:f==="cover"?r.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:r.jsx(Fp,{height:a,coverUrl:s,title:i,subtitle:o,label:l})}):r.jsx("canvas",{ref:v,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(yl,{modes:x,active:f,setActive:j,rows:2}),r.jsx(cf,{vu:L,hide:e==="youtube"})]})]})},pf=({height:e,autoPlay:t,track:n,source:a,ytRef:s,audioRef:i,hlsRef:o,setVol:l,onEnd:c,volume:u,extractVideoId:h})=>{const p=a==null?void 0:a.url,g=a==null?void 0:a.kind,y=a==null?void 0:a.withCredentials,m=JSON.stringify((a==null?void 0:a.headers)??null),x=d.useRef(u);x.current=u,d.useEffect(()=>{i.current&&(i.current.volume=u)},[i,u]),d.useEffect(()=>{const v=i.current;if(v){if(v.volume=x.current,v.crossOrigin=y?"use-credentials":"anonymous",g==="hls"&&$p(p)){const C=()=>{v.src=p,v.load(),t&&v.play().catch(()=>{})};if(v.canPlayType("application/vnd.apple.mpegurl")){C();return}(async()=>{const M=(await import("hls.js")).default;if(M.isSupported()){const k=JSON.parse(m),R=new M({xhrSetup:P=>{if(y&&(P.withCredentials=!0),k)for(const[I,A]of Object.entries(k))P.setRequestHeader(I,String(A))}});o.current=R,R.loadSource(p),R.attachMedia(v),R.on(M.Events.MANIFEST_PARSED,()=>t&&v.play().catch(()=>{}))}else C()})()}g==="audio"&&p&&(v.src=p,v.load(),t&&v.play().catch(()=>{}))}},[i,o,p,g,y,m,t]);const b=(a==null?void 0:a.kind)==="youtube",f=b?"video":"cover",j=`gp-stage:mode:${(a==null?void 0:a.kind)??"none"}`;return r.jsxs("div",{className:"gp-stage",style:{width:"100%",height:e,background:b?"transparent":"var(--player-bg, color-mix(in srgb, var(--nice-color-primary, #3b82f6) 14%, var(--nice-color-black, #000)))",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(a==null?void 0:a.kind)==="youtube"&&r.jsx(Aa,{videoId:a.videoId??h(a.url),onReady:v=>{s.current=v.target,l(u),t&&v.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(vl,{kind:(a==null?void 0:a.kind)==="hls"?"hls":(a==null?void 0:a.kind)??"audio",audioRef:i,hlsRef:o,height:e,coverUrl:n==null?void 0:n.coverUrl,title:n==null?void 0:n.title,subtitle:n==null?void 0:n.artist,label:(a==null?void 0:a.label)??`${(a==null?void 0:a.codec)??""} ${(a==null?void 0:a.quality)??""}`.trim(),defaultMode:f,storageKey:j},`vis-${j}`)]})},ff=({artist:e,title:t,hideControls:n=!0,isPlaying:a,onTimeUpdate:s,searchYouTubeByArtistTitle:i})=>{const{t:o}=xe(),[l,c]=d.useState(e||""),[u,h]=d.useState(t||""),[p,g]=d.useState(null),[y,m]=d.useState(null),x=d.useRef(null),[b,f]=d.useState({width:Math.min(560,window.innerWidth-32),height:Math.min(315,(window.innerWidth-32)*9/16)});d.useEffect(()=>{e&&t&&i&&i(e,t).then(g)},[e,t,i]),d.useEffect(()=>{y&&(a?y.playVideo():y.pauseVideo())},[a,y]),d.useEffect(()=>{if(y&&s){const v=setInterval(()=>{const C=y.getCurrentTime();s(C)},100);return()=>clearInterval(v)}},[y,s]),d.useEffect(()=>{const v=()=>{if(x.current){const C=x.current.clientWidth,T=Math.round(C*(9/16));f({width:C,height:T})}};return v(),window.addEventListener("resize",v),()=>window.removeEventListener("resize",v)},[]);const j=async()=>{if(!i)return;const v=await i(l,u);g(v)};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:v=>c(v.target.value),placeholder:o("youtubePlayer.artist","Artist"),"aria-label":o("youtubePlayer.artist","Artist")}),r.jsx("input",{value:u,onChange:v=>h(v.target.value),placeholder:o("youtubePlayer.title","Title"),"aria-label":o("youtubePlayer.title","Title")}),r.jsx("button",{onClick:j,children:o("youtubePlayer.search","Search")})]}),p&&r.jsxs("div",{children:[r.jsx(Aa,{videoId:p,opts:{width:b.width.toString(),height:b.height.toString(),playerVars:{autoplay:1,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,annotations:0}},onReady:v=>m(v.target)}),!n&&r.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px"},children:[r.jsxs("button",{onClick:()=>y==null?void 0:y.playVideo(),children:[r.jsx(B.NtdPlay,{size:14})," ",o("youtubePlayer.play","Play")]}),r.jsxs("button",{onClick:()=>y==null?void 0:y.pauseVideo(),children:[r.jsx(B.NtdPause,{size:14})," ",o("youtubePlayer.pause","Pause")]})]})]})]})},ii=e=>({name:e,dirs:new Map,files:[]}),mf=e=>(e??[]).map(t=>t instanceof File?{file:t}:t),gf=e=>e.replace(/\\/g,"/"),yf=e=>{const t=ii("/");for(const n of e){const a=gf(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,ii(o)),s=s.dirs.get(o)}s.files.push({file:n.file,path:a[a.length-1]??n.file.name})}return t},xa=e=>e.slice().sort((t,n)=>(t.path??t.file.name).localeCompare(n.path??n.file.name)),vf={tidal:B.NtdWave,spotify:B.NtdMusic,youtube:B.NtdPlay},Sa=({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(B.NtdClose,{size:14})})]}),ka=({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(B.NtdEdit,{size:13})," ",t("libraryExplorer.openInEditor","Edit")]}),a&&r.jsxs(ie.NiceButton,{variant:"primary",size:"sm",onClick:()=>a(s.file),children:[r.jsx(B.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")}),bl=({streams:e,t,onPlayStream:n})=>e.length?r.jsxs("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:[r.jsx("div",{style:{padding:"8px 12px",fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:t("libraryExplorer.streaming","Streaming")}),r.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:e.map(a=>r.jsxs("li",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,borderTop:"1px solid var(--nice-border, #1e293b)",padding:"8px 12px"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.title}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",display:"flex",alignItems:"center",gap:4},children:[d.createElement(vf[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(B.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]},`${a.provider}:${a.id}`))})]}):null,aa=({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})]}),bf=({variant:e="full",files:t=[],streams:n=[],enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,t:c,style:u,id:h,accessMode:p,"data-testid":g})=>{const{t:y}=xe(),m=c??y,[x,b]=d.useState(""),f=d.useMemo(()=>mf(t),[t]),j=d.useCallback(T=>{const M=x.trim().toLowerCase();return!M||T.toLowerCase().includes(M)},[x]),v=d.useMemo(()=>xa(f).filter(T=>j(`${T.path??T.file.name} ${T.file.type||""}`)),[f,j]),C=d.useMemo(()=>n.filter(T=>j(`${T.title} ${T.artist??""} ${T.provider}`)),[n,j]);return p==="hidden"?null:e==="minimal"?r.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...u},id:h,"data-testid":g,children:[r.jsx(Sa,{q:x,setQ:b,t:m}),r.jsx(ka,{files:v,t:m,onOpenInEditor:s,onPlayFile:i}),r.jsx(bl,{streams:C,t:m,onPlayStream:o})]}):e==="onlyFiles"?r.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...u},id:h,"data-testid":g,children:[r.jsx(Sa,{q:x,setQ:b,t:m}),r.jsx(ka,{files:v,t:m,onOpenInEditor:s,onPlayFile:i})]}):r.jsx(xf,{q:x,setQ:b,normFiles:f,filteredStreams:C,enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,style:u,id:h,"data-testid":g,t:m})},xf=({q:e,setQ:t,normFiles:n,filteredStreams:a,enableProviders:s,onOpenInEditor:i,onPlayFile:o,onPlayStream:l,className:c,style:u,id:h,"data-testid":p,t:g})=>{const y=d.useMemo(()=>yf(n),[n]),[m,x]=d.useState({}),[b,f]=d.useState("/"),j=M=>x(k=>({...k,[M]:!k[M]})),v=(M,k)=>{const R=k==="/"?`/${M.name}`:`${k}${M.name}/`,P=k==="/"&&M.name==="/",I=m[R]??P,A=Array.from(M.dirs.keys()).sort();return r.jsxs("div",{children:[!P&&r.jsxs("button",{type:"button",onClick:()=>{j(R),f(R)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"4px 8px",border:"none",borderRadius:6,cursor:"pointer",textAlign:"left",background:b===R?"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:I?r.jsx(B.NtdFolderOpen,{size:14}):r.jsx(B.NtdFolder,{size:14})}),r.jsx("span",{style:{fontSize:13},children:M.name})]}),(P||I)&&r.jsx("div",{style:{paddingLeft:P?0:16},children:A.map(L=>v(M.dirs.get(L),R))})]},R)},C=d.useMemo(()=>{let M;if(b==="/")M=xa(n);else{const k=b.replace(/^\//,"").split("/").filter(Boolean);let R=y;for(const P of k){const I=R.dirs.get(P);if(!I)return[];R=I}M=xa(R.files)}return e?M.filter(k=>(k.path??k.file.name).toLowerCase().includes(e.toLowerCase())):M},[b,y,n,e]),T={tidal:(s==null?void 0:s.tidal)??!0,spotify:(s==null?void 0:s.spotify)??!0,youtube:(s==null?void 0:s.youtube)??!0};return r.jsxs("div",{className:c,style:{display:"flex",gap:12,color:"var(--nice-text, #e2e8f0)",...u},id:h,"data-testid":p,children:[r.jsxs("div",{style:{flex:"0 0 220px",border:"1px solid var(--nice-border, #334155)",borderRadius:12,padding:8},children:[r.jsx("div",{style:{padding:"0 8px 8px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:g("libraryExplorer.library","Library")}),v(y,"/"),r.jsxs("div",{style:{marginTop:16,borderTop:"1px solid var(--nice-border, #1e293b)",paddingTop:8},children:[r.jsx("div",{style:{padding:"0 8px 4px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:g("libraryExplorer.streaming","Streaming")}),r.jsx(aa,{name:"Tidal",enabled:T.tidal}),r.jsx(aa,{name:"Spotify",enabled:T.spotify}),r.jsx(aa,{name:"YouTube",enabled:T.youtube})]})]}),r.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[r.jsx(Sa,{q:e,setQ:t,t:g}),r.jsx(ka,{files:C,t:g,onOpenInEditor:i,onPlayFile:o}),(T.tidal||T.spotify||T.youtube)&&r.jsx(bl,{streams:a.filter(M=>T[M.provider]),t:g,onPlayStream:l})]})]})},Sf=({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"})})}},ts=({data:e,display:t,callbacks:n,state:a})=>{const{id:s,index:i,artist:o,title:l,version:c,lp:u,sourcesAvailable:h=[]}=e,{allowVersion:p=!0,dragHandleProps:g}=t,{onChange:y,onRemove:m,onMoveUp:x,onMoveDown:b,onChangeLp:f,onSelectSource:j}=n,{readOnly:v=!1,canMoveUp:C=!0,canMoveDown:T=!0,activeSource:M}=a,{t:k}=xe(),R=d.useRef(null);d.useEffect(()=>{!o&&R.current&&R.current.focus()},[o]);const P=E=>{if(!v&&E.key==="Enter"){const D=E.target.closest("div.gpi-row"),Z=D==null?void 0:D.querySelectorAll("input[data-role='field']");if(!Z||Z.length===0)return;const G=Array.from(Z).indexOf(E.target),F=Z[G+1]??Z[0];F==null||F.focus()}},I=E=>{const D=h.includes(E),Z=M===E,G={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid var(--nice-border, #e5e7eb)",background:Z?"var(--nice-selected-bg, #eef2ff)":"var(--nice-bg, #fff)",opacity:D?1:.35,cursor:D&&j&&!v?"pointer":"default",transition:"transform .05s ease"},F=E==="youtube"?"var(--nice-danger, #ff0000)":E==="spotify"?"var(--nice-success, #1db954)":E==="tidal"?"var(--nice-text, #111827)":E==="hls"?"var(--nice-accent, #7c3aed)":"var(--nice-text, #374151)",q=E==="youtube"?"YouTube":E==="spotify"?"Spotify":E==="tidal"?"TIDAL":E==="hls"?"HLS":k("playlistItem.audio","Audio"),V=k("playlistItem.sourceLabel","Source")+": "+q+(Z?` ${k("playlistItem.sourceSelected","(selected)")}`:""),K=()=>{!D||!j||v||j(E)};return r.jsx("button",{type:"button",title:q,onClick:K,disabled:!D||v,style:G,"aria-pressed":Z,"aria-label":V,children:r.jsx(Sf,{kind:E,color:F})},E)},A=["youtube","tidal","spotify","hls","audio"],L=typeof u=="number"?u:i+1;return r.jsxs("div",{className:"gpi-row",role:"group","aria-label":k("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:L,onChange:E=>f==null?void 0:f(Number(E.target.value)),disabled:v||!f,"aria-label":k("playlistItem.lp","Lp"),title:k("playlistItem.positionOnList","Position in the list"),style:kf}),r.jsx("input",{ref:R,"data-role":"field",type:"text",value:o,onChange:E=>y({artist:E.target.value}),placeholder:k("playlistItem.artist","Artist"),onKeyDown:P,disabled:v,"aria-label":k("playlistItem.artist","Artist"),className:"gpi-input",style:sa}),r.jsx("input",{"data-role":"field",type:"text",value:l,onChange:E=>y({title:E.target.value}),placeholder:k("playlistItem.title","Title"),onKeyDown:P,disabled:v,"aria-label":k("playlistItem.title","Title"),className:"gpi-input",style:sa}),p&&r.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:E=>y({version:E.target.value||void 0}),placeholder:k("playlistItem.versionOptional","Version (optional)"),onKeyDown:P,disabled:v,"aria-label":k("playlistItem.version","Version"),className:"gpi-input",style:sa}),r.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":k("playlistItem.availableSources","Available sources"),children:A.map(I)}),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":k("playlistItem.dragReorder","Drag to reorder"),title:k("playlistItem.dragReorder","Drag to reorder"),style:ar,children:r.jsx(B.NtdMenu,{size:14})}),r.jsx("button",{type:"button",onClick:x,disabled:!C||v,"aria-label":k("playlistItem.moveUp","Move up"),title:k("playlistItem.moveUp","Move up"),style:ar,children:r.jsx(B.NtdArrowUp,{size:14})}),r.jsx("button",{type:"button",onClick:b,disabled:!T||v,"aria-label":k("playlistItem.moveDown","Move down"),title:k("playlistItem.moveDown","Move down"),style:ar,children:r.jsx(B.NtdArrowDown,{size:14})}),r.jsx("button",{type:"button",onClick:m,disabled:v,"aria-label":k("common.delete","Delete"),title:k("common.delete","Delete"),style:{...ar,color:"var(--nice-color-danger, #b91c1c)"},children:r.jsx(B.NtdClose,{size:14})})]})]})},kf={width:48,border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 6px",fontSize:14,textAlign:"center"},sa={width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 10px",fontSize:14},ar={border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg, #fff)",padding:"6px 8px",borderRadius:6,cursor:"pointer"},wa=()=>Math.random().toString(36).slice(2,10),sr=e=>(e??[]).map(t=>({id:wa(),...t})),wf=e=>e.map(({id:t,...n})=>n),Cf=null,jf=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}},Mf=({value:e,defaultValue:t,onChange:n,allowVersion:a=!0,maxItems:s,addButtonLabel:i,emptyState:o=Cf,readOnly:l=!1,autoFocusNewItem:c=!0,enableBulkPaste:u=!0})=>{const{t:h}=xe(),p=e!==void 0,[g,y]=d.useState(()=>sr(e||t)),[m,x]=d.useState(""),b=d.useRef(null),[f,j]=d.useState(null);d.useEffect(()=>{p&&y(sr(e))},[p,JSON.stringify(e)]);const v=d.useCallback(V=>{n==null||n(wf(V))},[n]),C=d.useCallback(V=>{if(p){const K=V(sr(e));v(K)}else y(K=>{const W=V(K);return v(W),W})},[v,p,e]),T=s?g.length<s:!0,M=d.useCallback(()=>{!T||l||C(V=>[...V,{id:wa(),artist:"",title:"",version:void 0}])},[T,l,C]),k=d.useCallback((V,K)=>{C(W=>W.map(Q=>Q.id===V?{...Q,...K}:Q))},[C]),R=d.useCallback(V=>{l||C(K=>K.filter(W=>W.id!==V))},[l,C]),P=d.useCallback((V,K)=>{C(W=>{const Q=W.findIndex(O=>O.id===V);if(Q<0)return W;const w=Q+K;if(w<0||w>=W.length)return W;const N=[...W],[S]=N.splice(Q,1);return N.splice(w,0,S),N})},[C]),I=d.useCallback((V,K)=>{C(W=>{const Q=W.findIndex(O=>O.id===V);if(Q<0)return W;const w=Math.max(0,Math.min(W.length-1,K-1));if(Q===w)return W;const N=[...W],[S]=N.splice(Q,1);return N.splice(w,0,S),N})},[C]),A=V=>K=>{l||(b.current=V,K.dataTransfer.effectAllowed="move",K.dataTransfer.setData("text/plain",V))},L=V=>K=>{l||(K.preventDefault(),K.dataTransfer.dropEffect="move",j(V))},E=V=>()=>j(K=>K===V?null:K),D=V=>K=>{if(l)return;K.preventDefault();const W=b.current??K.dataTransfer.getData("text/plain");j(null),b.current=null,!(!W||W===V)&&C(Q=>{const w=Q.findIndex(Y=>Y.id===W),N=Q.findIndex(Y=>Y.id===V);if(w<0||N<0||w===N)return Q;const S=[...Q],[O]=S.splice(w,1);return S.splice(N,0,O),S})},Z=()=>{b.current=null,j(null)},G=d.useCallback(()=>{if(!u||l)return;const K=m.split(/\r?\n/).map(W=>W.trim()).filter(Boolean).map(jf).filter(W=>!!W);K.length!==0&&(C(W=>{const Q=(s??1/0)-W.length,w=K.slice(0,Math.max(0,Q)).map(N=>({id:wa(),...N}));return[...W,...w]}),x(""))},[u,l,m,s,C]);d.useEffect(()=>{},[g.length,c]);const F=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.")}),q=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:M,disabled:!T||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":q,children:["+ ",q]})})]}),g.length===0?r.jsx("div",{className:"gp-empty",children:F}):r.jsx("ol",{className:"gp-list",style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:8},children:g.map((V,K)=>{const W=f===V.id;return r.jsx("li",{draggable:!l,onDragStart:A(V.id),onDragOver:L(V.id),onDragLeave:E(V.id),onDrop:D(V.id),onDragEnd:Z,style:{border:W?"2px dashed var(--nice-info, #6366f1)":"2px solid transparent",borderRadius:8,padding:W?4:0},children:r.jsx(ts,{data:{id:V.id,index:K,lp:K+1,artist:V.artist,title:V.title,version:a?V.version??void 0:void 0,sourcesAvailable:void 0},display:{allowVersion:a,dragHandleProps:{onDragStart:A(V.id)}},callbacks:{onChange:Q=>k(V.id,Q),onRemove:()=>R(V.id),onMoveUp:()=>P(V.id,-1),onMoveDown:()=>P(V.id,1),onChangeLp:Q=>I(V.id,Q)},state:{readOnly:l,canMoveUp:K>0,canMoveDown:K<g.length-1}})},V.id)})}),u&&!l&&r.jsx("div",{style:{marginTop:12},children:r.jsxs("details",{children:[r.jsx("summary",{style:{cursor:"pointer",color:"var(--nice-text, #374151)"},children:h("genericPlaylist.bulkPasteSummary","Paste multiple items at once")}),r.jsxs("div",{style:{marginTop:6},children:[r.jsx("textarea",{value:m,onChange:V=>x(V.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"}}),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:G,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")})]})]})]})})]})},bl={music:B.NtdMusic,microphone:B.NtdMicrophone,volume:B.NtdVolume,wave:B.NtdWave,megaphone:B.NtdMegaphone,star:B.NtdStar,heart:B.NtdHeart,lightning:B.NtdLightning,sparkle:B.NtdSparkle,moon:B.NtdMoon,sun:B.NtdSun,mountain:B.NtdMountain,trophy:B.NtdTrophy,crown:B.NtdCrown,target:B.NtdTarget,pin:B.NtdPin},Mf=Object.keys(bl),wa=({icon:e,size:t=14})=>{if(!e)return null;const n=bl[e];return n?r.jsx(n,{size:t}):r.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)"],sr=Mf,Rf=({tags:e,onCreateTag:t,onUpdateTag:n,onDeleteTag:a,selectedTracks:s,onAssignTag:i,onUnassignTag:o})=>{const{t:l}=xe(),[c,u]=d.useState(null),[h,p]=d.useState(""),[g,y]=d.useState(ii[8]),[m,x]=d.useState(sr[0]),[b,f]=d.useState(!1),[j,v]=d.useState(null),[C,T]=d.useState(""),[M,k]=d.useState(""),[R,P]=d.useState(""),I=d.useCallback(F=>{u(F.id),T(F.name),k(F.color),P(F.icon||sr[0])},[]),A=d.useCallback(()=>{c&&C.trim()&&(n(c,C.trim(),M,R),u(null))},[c,C,M,R,n]),L=d.useCallback(()=>{h.trim()&&(t(h.trim(),g,m),p(""),f(!1))},[h,g,m,t]),E=d.useCallback(F=>{j===F?(a(F),v(null)):(v(F),setTimeout(()=>v(null),3e3))},[j,a]),D=s&&s.length>0,Z=F=>!s||s.length===0?!1:s.every(q=>q.tags.includes(F)),G=F=>!s||s.length===0?!1:s.some(q=>q.tags.includes(F))&&!Z(F);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(B.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(!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")]})]}),r.jsxs("div",{style:{padding:12},children:[b&&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:F=>p(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:F=>F.key==="Enter"&&L()}),r.jsx("button",{onClick:L,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(B.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:ii.map(F=>r.jsx("div",{role:"button",tabIndex:0,"aria-label":F,"aria-pressed":g===F,onKeyDown:ve.clickOnActivationKey,onClick:()=>y(F),style:{width:20,height:20,borderRadius:"50%",background:F,cursor:"pointer",border:g===F?"3px solid var(--nice-color-accent, #3b82f6)":"2px solid transparent",boxSizing:"border-box"}},F))})]}),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:sr.map(F=>r.jsx("div",{role:"button",tabIndex:0,"aria-label":F,"aria-pressed":m===F,onKeyDown:ve.clickOnActivationKey,onClick:()=>x(F),style:{width:26,height:26,borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"0.85rem",background:m===F?"var(--nice-accent-tint-10, #eff6ff)":"transparent",border:m===F?"1px solid var(--nice-color-accent, #3b82f6)":"1px solid transparent"},children:r.jsx(wa,{icon:F,size:16})},F))})]})]}),D&&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(F=>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===F.id?"var(--nice-color-surface, #f9fafb)":"transparent"},children:c===F.id?r.jsxs(r.Fragment,{children:[r.jsx("select",{value:R,onChange:q=>P(q.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:sr.map(q=>r.jsx("option",{value:q,children:q},q))}),r.jsx("input",{type:"color",value:M,onChange:q=>k(q.target.value),style:{width:24,height:24,border:"none",cursor:"pointer",padding:0}}),r.jsx("input",{type:"text",value:C,onChange:q=>T(q.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:q=>q.key==="Enter"&&A()}),r.jsx("button",{onClick:A,style:ir("var(--nice-color-accent, #3b82f6)"),"aria-label":l("common.save","Save"),children:r.jsx(B.NtdCheck,{size:14})}),r.jsx("button",{onClick:()=>u(null),style:ir("var(--nice-text-secondary, #9ca3af)"),"aria-label":l("common.cancel","Cancel"),children:r.jsx(B.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:`${F.color}18`,color:F.color,fontWeight:600,fontSize:"0.78rem"},children:[r.jsx(wa,{icon:F.icon,size:12}),F.name]}),D&&i&&o&&r.jsx("input",{type:"checkbox",checked:Z(F.id),ref:q=>{q&&(q.indeterminate=G(F.id))},onChange:()=>{const q=s.map(V=>V.id);Z(F.id)?o(q,F.id):i(q,F.id)},style:{cursor:"pointer"}}),r.jsx("div",{style:{flex:1}}),r.jsx("button",{onClick:()=>I(F),style:ir("var(--nice-text-secondary, #9ca3af)"),title:l("playlistManager.editTag","Edit tag"),"aria-label":l("playlistManager.editTag","Edit tag"),children:r.jsx(B.NtdEdit,{size:14})}),r.jsx("button",{onClick:()=>E(F.id),style:ir(j===F.id?"var(--nice-color-error, #ef4444)":"var(--nice-text-secondary, #9ca3af)"),title:j===F.id?l("playlistManager.confirmDelete","Click again to delete"):l("playlistManager.deleteTag","Delete tag"),"aria-label":j===F.id?l("playlistManager.confirmDelete","Click again to delete"):l("playlistManager.deleteTag","Delete tag"),children:r.jsx(B.NtdTrash,{size:14})})]})},F.id))})]})]})},ir=e=>({background:"none",border:"none",cursor:"pointer",fontSize:"0.82rem",color:e,padding:"2px 4px"});var ts=(e=>(e.Static="static",e.Dynamic="dynamic",e))(ts||{}),xl=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(xl||{}),Sl=(e=>(e.Left="left",e.Right="right",e))(Sl||{}),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||{}),kl=(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))(kl||{}),un=(e=>(e.Asc="asc",e.Desc="desc",e))(un||{}),xt=(e=>(e.Library="library",e.Spotify="spotify",e.Tidal="tidal",e.YouTube="youtube",e.MusicBrainz="musicbrainz",e.Import="import",e.Manual="manual",e))(xt||{});const Nf="_editor_qz5p3_5",Tf="_heading_qz5p3_19",Pf="_hint_qz5p3_35",Ef="_group_qz5p3_49",$f="_groupOr_qz5p3_61",Af="_groupShaded_qz5p3_67",If="_groupHeader_qz5p3_73",Lf="_groupHint_qz5p3_87",_f="_groupActions_qz5p3_95",Df="_rule_qz5p3_107",zf="_value_qz5p3_121",Ff="_value2_qz5p3_127",Of="_dash_qz5p3_133",Bf="_limit_qz5p3_141",Gf="_limitInput_qz5p3_159",at={editor:Nf,heading:Tf,hint:Pf,group:Ef,groupOr:$f,groupShaded:Af,groupHeader:If,groupHint:Lf,groupActions:_f,rule:Df,value:zf,value2:Ff,dash:Of,limit:Bf,limitInput:Gf},Wf=[{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"}],Uf=[{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 Vf(e){return"logic"in e&&"rules"in e}function Ca(){return{id:ve.createId(),field:ot.Artist,operator:lt.Contains,value:""}}function wl(){return{id:ve.createId(),logic:"and",rules:[Ca()]}}const qf=({rule:e,onChange:t,onRemove:n})=>{const{t:a}=xe();return r.jsxs("div",{className:at.rule,children:[r.jsx(ie.NiceSelect,{size:"sm",controlWidth:150,"aria-label":a("playlistManager.ruleField","Field"),value:e.field,onChange:s=>t({...e,field:Tt(s)}),options:Wf.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:Tt(s)}),options:Uf.map(s=>({value:s.value,label:a(`playlistManager.op.${s.value}`,s.label)}))}),r.jsx(ie.NiceTextInput,{size:"sm",className:at.value,"aria-label":a("playlistManager.ruleValue","Value"),placeholder:a("playlistManager.ruleValue","Value"),value:e.value,onChange:s=>t({...e,value:s})}),e.operator===lt.Between&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:at.dash,"aria-hidden":"true",children:"–"}),r.jsx(ie.NiceTextInput,{size:"sm",className:at.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(B.NtdClose,{size:14}),ariaLabel:a("playlistManager.removeRule","Remove rule"),title:a("playlistManager.removeRule","Remove rule"),onClick:n,children:null})]})},Cl=({group:e,onChange:t,onRemove:n,depth:a=0})=>{const{t:s}=xe(),i=d.useCallback((p,g)=>{const y=[...e.rules];y[p]=g,t({...e,rules:y})},[e,t]),o=d.useCallback(p=>{const g=e.rules.filter((y,m)=>m!==p);t({...e,rules:g.length>0?g:[Ca()]})},[e,t]),l=d.useCallback(()=>{t({...e,rules:[...e.rules,Ca()]})},[e,t]),c=d.useCallback(()=>{t({...e,rules:[...e.rules,wl()]})},[e,t]),u=d.useCallback(()=>{t({...e,logic:e.logic==="and"?"or":"and"})},[e,t]),h=e.logic==="and";return r.jsxs("div",{className:`${at.group} ${h?"":at.groupOr} ${a%2===0?at.groupShaded:""}`,children:[r.jsxs("div",{className:at.groupHeader,children:[r.jsx(ie.NiceButton,{size:"sm",variant:h?"primary":"warning",onClick:u,title:s("playlistManager.toggleLogic","Toggle AND/OR"),children:h?s("playlistManager.logicAnd","AND"):s("playlistManager.logicOr","OR")}),r.jsx("span",{className:at.groupHint,children:h?s("playlistManager.matchAllRules","Match all of these rules"):s("playlistManager.matchAnyRule","Match any of these rules")}),r.jsxs("div",{className:at.groupActions,children:[r.jsx(ie.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(B.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(B.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(B.NtdClose,{size:14}),ariaLabel:s("playlistManager.removeGroup","Remove group"),title:s("playlistManager.removeGroup","Remove group"),onClick:n,children:null})]})]}),e.rules.map((p,g)=>Vf(p)?r.jsx(Cl,{group:p,onChange:y=>i(g,y),onRemove:()=>o(g),depth:a+1},p.id):r.jsx(qf,{rule:p,onChange:y=>i(g,y),onRemove:()=>o(g)},p.id))]})},Hf=({rules:e,onChange:t,limit:n,onLimitChange:a})=>{const{t:s}=xe(),[i]=d.useState(wl),o=e??i;return r.jsxs("div",{className:at.editor,children:[r.jsxs("h6",{className:at.heading,children:[r.jsx(B.NtdRepeat,{size:14})," ",s("playlistManager.dynamicRules","Dynamic Playlist Rules")]}),r.jsx("p",{className:at.hint,children:s("playlistManager.dynamicRulesHint","Tracks matching these rules will automatically be included in the playlist.")}),r.jsx(Cl,{group:o,onChange:t}),a&&r.jsx("div",{className:at.limit,children:r.jsx(ie.NiceNumberInput,{size:"sm",className:at.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")})})]})},oi=e=>{if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`},Kf={spotify:"var(--source-spotify, #1db954)",tidal:"var(--source-tidal, #000000)",youtube:"var(--source-youtube, #ff0000)",musicbrainz:"var(--source-musicbrainz, #ba478f)"},Yf=({source:e})=>{if(e==="import")return r.jsx(B.NtdDownload,{size:12});if(e==="manual")return r.jsx(B.NtdEdit,{size:12});const t=Kf[e];return t?r.jsx(B.NtdCircle,{size:10,style:{color:t}}):r.jsx(B.NtdMusic,{size:12})},jl=({tracks:e,tags:t,selectedTrackIds:n,onSelectionChange:a,onPlay:s,onRemove:i,onReorder:o,onTagTracks:l,onRateTracks:c,sortField:u,sortDir:h,onSortChange:p,filterText:g,onFilterChange:y,compact:m=!1,draggable:x=!1,onDragStart:b,dropTarget:f=!1,onDrop:j})=>{const{t:v}=xe(),[C,T]=d.useState(null),[M,k]=d.useState(null),R=d.useRef(null),P=d.useMemo(()=>{let w=e??[];if(g.trim()){const N=g.toLowerCase();w=w.filter(S=>{var O,Y;return S.title.toLowerCase().includes(N)||S.artist.toLowerCase().includes(N)||((O=S.album)==null?void 0:O.toLowerCase().includes(N))||((Y=S.genre)==null?void 0:Y.toLowerCase().includes(N))})}return[...w].sort((N,S)=>{const O=h==="asc"?1:-1;switch(u){case"title":return O*N.title.localeCompare(S.title);case"artist":return O*N.artist.localeCompare(S.artist);case"album":return O*(N.album??"").localeCompare(S.album??"");case"duration":return O*((N.duration??0)-(S.duration??0));case"year":return O*((N.year??0)-(S.year??0));case"rating":return O*((N.rating??0)-(S.rating??0));case"addedDate":return O*(N.addedAt??"").localeCompare(S.addedAt??"");case"custom":return O*((N.customOrder??0)-(S.customOrder??0));default:return 0}})},[e,g,u,h]),I=d.useCallback((w,N)=>{const S=P[w];if(S){if(N.ctrlKey||N.metaKey){const O=new Set(n);O.has(S.id)?O.delete(S.id):O.add(S.id),a(O)}else if(N.shiftKey&&R.current!==null){const O=Math.min(R.current,w),Y=Math.max(R.current,w),_=new Set(n);for(let U=O;U<=Y;U++)_.add(P[U].id);a(_)}else a(new Set([S.id]));R.current=w}},[P,n,a]),A=d.useCallback(()=>{n.size===P.length?a(new Set):a(new Set(P.map(w=>w.id)))},[P,n,a]),L=({field:w,label:N,width:S})=>{const O=u===w;return r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,style:{width:S,flex:S?void 0:1,cursor:"pointer",userSelect:"none",fontWeight:O?700:500,fontSize:"0.72rem",textTransform:"uppercase",letterSpacing:"0.04em",opacity:O?1:.6,display:"flex",alignItems:"center",gap:4},onClick:()=>{O?p(w,h===un.Asc?un.Desc:un.Asc):p(w,un.Asc)},children:[N,O&&(h==="asc"?r.jsx(B.NtdArrowUp,{size:10}):r.jsx(B.NtdArrowDown,{size:10}))]})},E=d.useCallback((w,N)=>{const S=n.has(w.id)?Array.from(n):[w.id];N.dataTransfer.setData("trackIds",JSON.stringify(S)),N.dataTransfer.effectAllowed="move",b==null||b(S,N)},[n,b]),D=d.useCallback((w,N)=>{N.preventDefault(),N.dataTransfer.dropEffect="move",T(w)},[]),Z=d.useCallback((w,N)=>{N.preventDefault(),T(null);try{const S=N.dataTransfer.getData("trackIds");if(S&&o){const O=JSON.parse(S),Y=P.filter($=>!O.includes($.id)),_=P.filter($=>O.includes($.id)),U=Math.min(w,Y.length);Y.splice(U,0,..._),o(Y.map($=>$.id))}}catch{}},[P,o]),G=d.useCallback(w=>{w.preventDefault(),T(null),j==null||j(w)},[j]),F=d.useMemo(()=>new Map(t.map(w=>[w.id,w])),[t]),q=w=>w.replace(/[^a-z0-9_-]/gi,"-"),V=m?36:48,K={display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",color:"var(--nice-text-secondary, #6b7280)"},W=(w,N)=>({display:"flex",alignItems:"center",gap:8,padding:m?"4px 12px":"6px 12px",height:V,cursor:"pointer",background:N?"var(--nice-color-accent-light, #dbeafe)":w?"var(--nice-selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--nice-border-light, #f3f4f6)",transition:"background 0.1s"}),Q=P.length>0&&n.size===P.length;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:f?w=>{w.preventDefault(),w.dataTransfer.dropEffect="copy"}:void 0,onDrop:f?G: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:w=>y(w.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)"}}),r.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[P.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":v("playlistManager.removeSelected","Remove selected"),children:[r.jsx(B.NtdTrash,{size:12})," ",n.size]})]}),r.jsxs("div",{style:K,children:[r.jsx("div",{style:{width:28},children:r.jsx("input",{type:"checkbox",checked:Q,onChange:A,style:{cursor:"pointer"}})}),r.jsx("div",{style:{width:20},children:"#"}),!m&&r.jsx("div",{style:{width:44}}),r.jsx(L,{field:"title",label:v("playlistManager.colTitle","Title")}),r.jsx(L,{field:"artist",label:v("playlistManager.colArtist","Artist")}),!m&&r.jsx(L,{field:"album",label:v("playlistManager.colAlbum","Album")}),r.jsx(L,{field:"duration",label:v("playlistManager.colDuration","Duration"),width:60}),!m&&r.jsx(L,{field:"year",label:v("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:[P.length===0&&r.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")}),P.map((w,N)=>{const S=n.has(w.id),O=C===N;return r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,style:W(S,O),onClick:Y=>I(N,Y),onDoubleClick:()=>s==null?void 0:s(w),draggable:x,onDragStart:Y=>E(w,Y),onDragOver:Y=>D(N,Y),onDrop:Y=>Z(N,Y),onDragLeave:()=>T(null),children:[r.jsx("div",{style:{width:28},children:r.jsx("input",{type:"checkbox",checked:S,onChange:()=>{const Y=new Set(n);S?Y.delete(w.id):Y.add(w.id),a(Y)},onClick:Y=>Y.stopPropagation(),style:{cursor:"pointer"}})}),r.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:N+1}),!m&&r.jsx("div",{style:{width:44,height:36,flexShrink:0},children:w.coverUrl?r.jsx("img",{src:w.coverUrl,alt:w.title||v("common.coverArt","Cover art"),style:{width:36,height:36,borderRadius:4,objectFit:"cover"},loading:"lazy"}):r.jsx("div",{style:{width:36,height:36,borderRadius:4,background:"var(--nice-color-surface, #f3f4f6)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.9rem"},children:r.jsx(B.NtdMusic,{size:16})})}),r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",fontWeight:500},children:w.title}),r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",opacity:.7},children:w.artist}),!m&&r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",opacity:.5},children:w.album}),r.jsx("div",{style:{width:60,fontSize:"0.78rem",opacity:.5,textAlign:"right"},children:oi(w.duration)}),!m&&r.jsx("div",{style:{width:50,fontSize:"0.72rem",opacity:.4,textAlign:"center"},children:w.year||""}),r.jsx("div",{style:{width:30,textAlign:"center",fontSize:"0.75rem"},title:w.source,children:r.jsx(Yf,{source:w.source})}),!m&&r.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[w.tags.slice(0,2).map(Y=>{const _=F.get(Y);if(!_)return null;const U=`--tag-${q(Y)}`;return r.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${U}-bg, ${_.color}22)`,color:`var(${U}, ${_.color})`,whiteSpace:"nowrap"},children:_.name},Y)}),w.tags.length>2&&r.jsxs("span",{style:{fontSize:"0.6rem",opacity:.4},children:["+",w.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:Y=>{Y.stopPropagation(),k(M===w.id?null:w.id)},title:v("playlistManager.morActions","More actions"),"aria-label":v("playlistManager.morActions","More actions"),children:r.jsx(B.NtdTag,{size:12})}),M===w.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:v("playlistManager.assignTag","Assign tag")}),t.map(Y=>{const _=w.tags.includes(Y.id);return r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,style:{padding:"4px 8px",borderRadius:4,cursor:"pointer",fontSize:"0.78rem",display:"flex",alignItems:"center",gap:6,background:_?`var(--tag-${q(Y.id)}-bg, ${Y.color}22)`:"transparent"},onClick:U=>{U.stopPropagation();const $=n.size>0?Array.from(n):[w.id];_||l==null||l($,[Y.id]),k(null)},children:[r.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:`var(--tag-${q(Y.id)}, ${Y.color})`,flexShrink:0}}),r.jsx("span",{children:Y.name}),_&&r.jsx(B.NtdCheck,{size:12,style:{marginLeft:"auto"}})]},Y.id)})]})]})]},w.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:[P.length," ",v("playlistManager.tracks","tracks")]}),r.jsx("span",{children:oi(P.reduce((w,N)=>w+(N.duration??0),0))}),n.size>0&&r.jsxs("span",{children:[n.size," ",v("playlistManager.selected","selected")]})]})]})},li=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),Zf=({playlists:e=[],tags:t=[],onCopyTracks:n=()=>{},onMoveTracks:a=()=>{},onRemoveTracks:s=()=>{},onReorderTracks:i=()=>{},onPlay:o=()=>{},onTagTracks:l=()=>{},initialLeftId:c,initialRightId:u})=>{const{t:h}=xe(),[p,g]=d.useState(()=>li(c??null)),[y,m]=d.useState(()=>li(u??null)),[x,b]=d.useState("left"),[f,j]=d.useState(null),[v,C]=d.useState(50),[T,M]=d.useState(!1),k=d.useMemo(()=>e.find(w=>w.id===p.playlistId),[e,p.playlistId]),R=d.useMemo(()=>e.find(w=>w.id===y.playlistId),[e,y.playlistId]),P=d.useCallback((w,N)=>{w==="left"?g(S=>({...S,...N})):m(S=>({...S,...N}))},[]),I=d.useCallback(w=>w==="left"?p:y,[p,y]),A=w=>w==="left"?"right":"left",L=d.useCallback(w=>{const N=I(w),S=I(A(w));!N.playlistId||!S.playlistId||N.selectedTrackIds.size===0||(n(N.playlistId,S.playlistId,Array.from(N.selectedTrackIds)),P(w,{selectedTrackIds:new Set}))},[I,n,P]),E=d.useCallback(w=>{const N=I(w),S=I(A(w));!N.playlistId||!S.playlistId||N.selectedTrackIds.size===0||(a(N.playlistId,S.playlistId,Array.from(N.selectedTrackIds)),P(w,{selectedTrackIds:new Set}))},[I,a,P]),D=d.useCallback(w=>{const N=I(w);!N.playlistId||N.selectedTrackIds.size===0||j({operation:"copy",sourcePlaylistId:N.playlistId,trackIds:Array.from(N.selectedTrackIds)})},[I]),Z=d.useCallback(w=>{const N=I(w);!N.playlistId||N.selectedTrackIds.size===0||j({operation:"cut",sourcePlaylistId:N.playlistId,trackIds:Array.from(N.selectedTrackIds)})},[I]),G=d.useCallback(w=>{const N=I(w);!f||!N.playlistId||(f.operation==="copy"?n(f.sourcePlaylistId,N.playlistId,f.trackIds):a(f.sourcePlaylistId,N.playlistId,f.trackIds),j(null))},[f,I,n,a]),F=d.useRef(!1),q=d.useCallback(w=>{if(w.key==="Tab"&&F.current){F.current=!1;return}["Shift","Control","Alt","Meta"].includes(w.key)||(F.current=w.key==="Escape"),w.key==="Tab"&&!w.shiftKey&&(w.preventDefault(),b(N=>A(N))),(w.ctrlKey||w.metaKey)&&w.key==="c"&&D(x),(w.ctrlKey||w.metaKey)&&w.key==="x"&&Z(x),(w.ctrlKey||w.metaKey)&&w.key==="v"&&G(x)},[x,D,Z,G]),V=d.useCallback(()=>M(!0),[]),K=d.useCallback(w=>{if(!T)return;const N=w.currentTarget.getBoundingClientRect(),S=(w.clientX-N.left)/N.width*100;C(Math.max(20,Math.min(80,S)))},[T]),W=d.useCallback(()=>M(!1),[]),Q=w=>{const N=I(w),S=w==="left"?k:R,O=x===w,_=!!I(A(w)).playlistId;return r.jsxs("div",{role:"presentation",style:{display:"flex",flexDirection:"column",height:"100%",border:O?"2px solid var(--nice-color-accent, #3b82f6)":"2px solid transparent",borderRadius:8,overflow:"hidden",background:"var(--nice-bg-elevated, #fff)"},onClick:()=>b(w),children:[r.jsx("div",{style:{padding:"8px 12px",background:O?"var(--nice-color-accent, #3b82f6)":"var(--nice-color-surface, #f3f4f6)",color:O?"var(--nice-text-on-accent, #fff)":"var(--nice-text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:r.jsxs("select",{value:N.playlistId??"",onChange:U=>P(w,{playlistId:U.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:O?"var(--nice-overlay-light-20, #ffffff30)":"var(--nice-input-bg, #fff)",color:O?"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(U=>r.jsxs("option",{value:U.id,children:[U.name," (",U.trackCount,")"]},U.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:sa(!1),onClick:()=>L(w),disabled:!N.playlistId||!_||N.selectedTrackIds.size===0,title:h("playlistManager.copyToOther","Copy to the other playlist"),children:[w==="left"?r.jsxs(r.Fragment,{children:[r.jsx(B.NtdCopy,{size:12}),r.jsx(B.NtdChevronRight,{size:12})]}):r.jsxs(r.Fragment,{children:[r.jsx(B.NtdChevronLeft,{size:12}),r.jsx(B.NtdCopy,{size:12})]})," ",h("playlistManager.copy","Copy")]}),r.jsxs("button",{style:sa(!1),onClick:()=>E(w),disabled:!N.playlistId||!_||N.selectedTrackIds.size===0,title:h("playlistManager.moveToOther","Move to the other playlist"),children:[w==="left"?r.jsxs(r.Fragment,{children:[r.jsx(B.NtdMove,{size:12}),r.jsx(B.NtdChevronRight,{size:12})]}):r.jsxs(r.Fragment,{children:[r.jsx(B.NtdChevronLeft,{size:12}),r.jsx(B.NtdMove,{size:12})]})," ",h("playlistManager.move","Move")]}),r.jsx("div",{style:{flex:1}}),f&&r.jsxs("button",{style:sa(!0),onClick:()=>G(w),disabled:!N.playlistId,children:[r.jsx(B.NtdClipboard,{size:12})," ",h("playlistManager.paste","Paste")," (",f.trackIds.length,")"]})]}),S?r.jsx(jl,{tracks:S.tracks,tags:t,selectedTrackIds:N.selectedTrackIds,onSelectionChange:U=>P(w,{selectedTrackIds:U}),onPlay:o,onRemove:U=>s(S.id,U),onReorder:U=>i(S.id,U),onTagTracks:l,sortField:N.sortField,sortDir:N.sortDir,onSortChange:(U,$)=>P(w,{sortField:U,sortDir:$}),filterText:N.filterText,onFilterChange:U=>P(w,{filterText:U}),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:T?"none":"auto"},onKeyDown:q,onMouseMove:K,onMouseUp:W,tabIndex:0,children:[r.jsx("div",{style:{width:`${v}%`,minWidth:200},children:Q("left")}),r.jsx("div",{style:{width:6,cursor:"col-resize",background:T?"var(--nice-color-accent, #3b82f6)":"var(--nice-border-color, #e5e7eb)",transition:T?"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:T?"var(--nice-color-accent, #3b82f6)":"var(--nice-bg-tertiary, #9ca3af)"}})}),r.jsx("div",{style:{flex:1,minWidth:200},children:Q("right")})]})},sa=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"}),Ml="av:local-playlists";function Xf(){try{const e=localStorage.getItem(Ml);return e?JSON.parse(e):[]}catch{return[]}}function Qf(e){const t=JSON.stringify(e);try{localStorage.setItem(Ml,t)}catch{}}function ns(){const[e,t]=d.useState(()=>Xf()),n=d.useRef(!1);return d.useEffect(()=>{n.current=!0},[]),d.useEffect(()=>{Qf(e)},[e]),d.useMemo(()=>({list:()=>e,get:s=>e.find(i=>i.id===s),create:s=>{const i=new Date().toISOString(),o={id:ve.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 Jf=st.scoped("PlaylistList"),em={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,background:"var(--nice-bg, #fff)"},tm=(function(){return{...em,padding:"8px 10px",cursor:"pointer"}})(),Rl={border:"1px solid var(--nice-border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg, #fff)",cursor:"pointer"},nm=(function(){return{...Rl,background:"var(--nice-color-primary, #4f46e5)",borderColor:"var(--nice-color-primary, #4f46e5)",color:"var(--nice-text-on-primary, #fff)"}})(),rs=({selectedId:e,onSelect:t,onCreateRemote:n})=>{const{t:a}=xe(),s=ns(),[i,o]=d.useState(""),l=d.useMemo(()=>s.list(),[s]);return r.jsxs("div",{style:{display:"grid",gap:10},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("input",{placeholder:a("playlistList.playlistName","Playlist name"),value:i,onChange:c=>o(c.target.value),style:{flex:1,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px"},"aria-label":a("playlistList.playlistName","Playlist name")}),r.jsxs("button",{type:"button",disabled:!i.trim(),style:i.trim()?nm:{...Rl,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(u){Jf.error("Remote playlist create failed:",u)}t==null||t(c)},children:["+ ",a("common.add","Add")]})]}),r.jsxs("div",{style:{display:"grid",gap:6},children:[l.map(c=>{const u=c.id===e;return r.jsxs("button",{onClick:()=>t==null?void 0:t(c),style:{...tm,background:u?"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 ↑")})]})]})},rm=st.scoped("PlaylistBrowser"),ci={display:"grid",gap:12},di=e=>({artist:(e.artists??[]).join(", "),title:e.title}),am=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:n,tracks:a,view:s,onSelect:i,onPlay:o})=>{var b;const{t:l}=xe(),c=ns(),[u,h]=d.useState(null),[p,g]=d.useState(""),[,y]=d.useState([]),m=u==null?void 0:u.id,x=(f,j)=>{if("addItems"in c){c.addItems(f.id,j);const C=c.list().find(T=>T.id===f.id)||f;h(C);return}const v=c;if("update"in c&&typeof v.update=="function"){const C=Array.from([...f.items||[],...j]);v.update({...f,items:C});const T=c.list().find(M=>M.id===f.id)||{...f,items:C};h(T);return}rm.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:ci,children:[r.jsx("h3",{style:{margin:0},children:l("playlistBrowser.playlists","Playlists")}),r.jsx(rs,{selectedId:m,onSelect:h}),u&&r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:[l("playlistBrowser.selected","Selected"),": ",r.jsx("strong",{children:u.name})," ·"," ",((b=u.items)==null?void 0:b.length)??0," ",l("playlistBrowser.tracks","tracks")]})]}),r.jsxs("div",{style:ci,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=>{u&&x(u,[di(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=>{u&&x(u,[di(f)])}}),n==null?void 0:n({onPlayNow:f=>y(f),onAddToQueue:f=>y(j=>[...j,...f]),onAddDescriptors:f=>u&&x(u,f)})]})]})};var Zt=(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))(Zt||{});const Nl=(e,t=null)=>e.filter(n=>n.parentId===t).sort((n,a)=>n.sortOrder-a.sortOrder).map(n=>({...n,children:Nl(e,n.id)})),sm={[Zt.Spotify]:{label:"Spotify",color:"var(--source-spotify, #1DB954)",bg:"var(--source-spotify-bg, #1DB95418)"},[Zt.Tidal]:{label:"Tidal",color:"var(--source-tidal, #000000)",bg:"var(--source-tidal-bg, #00000010)"},[Zt.YouTube]:{label:"YouTube",color:"var(--source-youtube, #FF0000)",bg:"var(--source-youtube-bg, #FF000010)"}},im=({folders:e,playlists:t,tags:n,services:a,activeFolderId:s,activePlaylistId:i,onSelectFolder:o,onSelectPlaylist:l,onCreateFolder:c,onRenameFolder:u,onDeleteFolder:h,onCreatePlaylist:p,onConnectService:g,onDisconnectService:y,onDragPlaylistToFolder:m,collapsed:x=!1,onToggleCollapse:b})=>{const{t:f}=xe(),[j,v]=d.useState(new Set),[C,T]=d.useState(!1),[M,k]=d.useState(""),[R,P]=d.useState(null),[I,A]=d.useState(!1),[L,E]=d.useState(""),[D,Z]=d.useState("static"),[G,F]=d.useState(null),[q,V]=d.useState(""),[K,W]=d.useState(null),[Q,w]=d.useState(!1),N=d.useMemo(()=>Nl(e),[e]),S=d.useCallback(ne=>{v(pe=>{const fe=new Set(pe);return fe.has(ne)?fe.delete(ne):fe.add(ne),fe})},[]),O=d.useCallback(()=>{M.trim()&&(c(M.trim(),R),k(""),T(!1))},[M,R,c]),Y=d.useCallback(()=>{L.trim()&&(p(L.trim(),D,s),E(""),A(!1))},[L,D,s,p]),_=d.useCallback(ne=>{q.trim()&&(u(ne,q.trim()),F(null),V(""))},[q,u]),U=d.useCallback((ne,pe)=>{ne.preventDefault(),ne.dataTransfer.dropEffect="move",W(pe)},[]),$=d.useCallback((ne,pe)=>{ne.preventDefault();const fe=ne.dataTransfer.getData("playlistId");fe&&m&&m(fe,pe),W(null)},[m]),H=d.useCallback(()=>W(null),[]),X=d.useCallback(ne=>t.filter(pe=>(pe.folderId??null)===ne),[t]),re={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)"},se=(ne,pe=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:pe?"var(--nice-color-accent-light, #dbeafe)":ne?"var(--nice-color-accent, #3b82f6)":"transparent",color:ne?"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)"},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=(ne,pe)=>{var je,Pe;const fe=j.has(ne.id),ge=s===ne.id,he=K===ne.id,we=X(ne.id);return r.jsxs("div",{children:[r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,style:{...se(ge,he),paddingLeft:12+pe*16},onClick:()=>{o(ne.id),ne.children&&ne.children.length>0&&S(ne.id)},onDragOver:$e=>U($e,ne.id),onDrop:$e=>$($e,ne.id),onDragLeave:H,children:[r.jsx("span",{style:{width:14,textAlign:"center",flexShrink:0,fontSize:"0.7rem"},children:(((je=ne.children)==null?void 0:je.length)||0)>0||we.length>0?fe?r.jsx(B.NtdChevronDown,{size:10}):r.jsx(B.NtdChevronRight,{size:10}):null}),G===ne.id?r.jsx("input",{value:q,onChange:$e=>V($e.target.value),onKeyDown:$e=>{$e.key==="Enter"&&_(ne.id),$e.key==="Escape"&&F(null)},onBlur:()=>_(ne.id),autoFocus:!0,style:{...ee,flex:1},onClick:$e=>$e.stopPropagation()}):r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{display:"inline-flex"},children:ne.icon??r.jsx(B.NtdFolder,{size:14})}),r.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:ne.name}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:we.length}),r.jsx("button",{style:z,onClick:$e=>{$e.stopPropagation(),F(ne.id),V(ne.name)},title:f("common.rename","Rename"),"aria-label":f("common.rename","Rename"),children:r.jsx(B.NtdEdit,{size:12})}),r.jsx("button",{style:{...z,color:"var(--nice-color-error, #ef4444)"},onClick:$e=>{$e.stopPropagation(),h(ne.id)},title:f("common.delete","Delete"),"aria-label":f("common.delete","Delete"),children:r.jsx(B.NtdTrash,{size:12})})]})]}),fe&&r.jsxs(r.Fragment,{children:[we.map($e=>ce($e,pe+1)),(Pe=ne.children)==null?void 0:Pe.map($e=>ae($e,pe+1))]})]},ne.id)},ce=(ne,pe)=>{const fe=i===ne.id;return r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,style:{...se(fe),paddingLeft:12+pe*16+22},onClick:()=>l(ne.id),draggable:!0,onDragStart:ge=>{ge.dataTransfer.setData("playlistId",ne.id),ge.dataTransfer.effectAllowed="move"},children:[r.jsx("span",{style:{display:"inline-flex"},children:ne.type==="dynamic"?r.jsx(B.NtdLightning,{size:12}):r.jsx(B.NtdMusic,{size:12})}),r.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:ne.name}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:ne.trackCount})]},ne.id)};if(x)return r.jsx("div",{style:re,children:r.jsx("button",{style:{...z,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:b,title:f("playlistManager.expandSidebar","Expand sidebar"),"aria-label":f("playlistManager.expandSidebar","Expand sidebar"),children:r.jsx(B.NtdChevronRight,{size:16})})});const le=X(null);return r.jsxs("div",{style:re,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(B.NtdMusic,{size:14})," ",f("playlistManager.title","Playlists")]}),r.jsx("button",{style:z,onClick:b,title:f("playlistManager.collapseSidebar","Collapse sidebar"),"aria-label":f("playlistManager.collapseSidebar","Collapse sidebar"),children:r.jsx(B.NtdChevronLeft,{size:16})})]}),r.jsxs("div",{style:{...oe,display:"flex",gap:4,flexWrap:"wrap"},children:[r.jsxs("button",{style:{...z,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:{...z,border:"1px solid var(--nice-border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{T(!0),P(s)},children:[r.jsx(B.NtdFolder,{size:12})," ",f("playlistManager.newFolder","New folder")]})]}),I&&r.jsxs("div",{style:{...oe,display:"flex",flexDirection:"column",gap:6},children:[r.jsx("input",{value:L,onChange:ne=>E(ne.target.value),placeholder:f("playlistManager.playlistName","Playlist name"),style:ee,autoFocus:!0,onKeyDown:ne=>{ne.key==="Enter"&&Y(),ne.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:D==="static",onChange:()=>Z("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:D==="dynamic",onChange:()=>Z("dynamic")}),r.jsx(B.NtdLightning,{size:12})," ",f("playlistManager.dynamic","Dynamic")]}),r.jsx("div",{style:{flex:1}}),r.jsx("button",{style:{...z,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:Y,"aria-label":f("playlistManager.confirmCreatePlaylist","Confirm create playlist"),children:r.jsx(B.NtdCheck,{size:12})}),r.jsx("button",{style:z,onClick:()=>A(!1),"aria-label":f("playlistManager.cancelCreatePlaylist","Cancel create playlist"),children:r.jsx(B.NtdClose,{size:12})})]})]}),C&&r.jsxs("div",{style:{...oe,display:"flex",gap:6},children:[r.jsx("input",{value:M,onChange:ne=>k(ne.target.value),placeholder:f("playlistManager.folderName","Folder name"),style:{...ee,flex:1},autoFocus:!0,onKeyDown:ne=>{ne.key==="Enter"&&O(),ne.key==="Escape"&&T(!1)}}),r.jsx("button",{style:{...z,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:O,"aria-label":f("playlistManager.confirmCreateFolder","Confirm create folder"),children:r.jsx(B.NtdCheck,{size:12})}),r.jsx("button",{style:z,onClick:()=>T(!1),"aria-label":f("playlistManager.cancelCreateFolder","Cancel create folder"),children:r.jsx(B.NtdClose,{size:12})})]}),r.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,style:se(s===null&&i===null,K==="__root__"),onClick:()=>o(null),onDragOver:ne=>U(ne,null),onDrop:ne=>$(ne,null),onDragLeave:H,children:[r.jsx(B.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})]}),le.map(ne=>ce(ne,0)),N.map(ne=>ae(ne,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(ne=>r.jsxs("span",{style:{fontSize:"0.7rem",padding:"2px 8px",borderRadius:12,background:ne.color+"22",color:ne.color,border:`1px solid ${ne.color}44`,cursor:"pointer"},children:[r.jsx(wa,{icon:ne.icon,size:10}),ne.icon?" ":"",ne.name]},ne.id))})]}),r.jsxs("div",{style:oe,children:[r.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":Q,onKeyDown:ve.clickOnActivationKey,style:{display:"flex",alignItems:"center",justifyContent:"space-between",cursor:"pointer",fontSize:"0.7rem",fontWeight:600,opacity:.6},onClick:()=>w(!Q),children:[r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.NtdLink,{size:12})," ",f("playlistManager.services","Services")]}),Q?r.jsx(B.NtdChevronUp,{size:12}):r.jsx(B.NtdChevronDown,{size:12})]}),Q&&r.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[Zt.Spotify,Zt.Tidal,Zt.YouTube].map(ne=>{const pe=sm[ne],fe=a.find(ge=>ge.platform===ne);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(B.NtdCircle,{size:10,style:{color:pe.color}}),r.jsx("span",{style:{flex:1},children:pe.label}),fe!=null&&fe.connected?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{fontSize:"0.65rem",opacity:.6},children:fe.username??f("playlistManager.connected","Connected")}),r.jsx("button",{style:{...z,color:"var(--nice-danger, #ef4444)"},onClick:()=>y(ne),"aria-label":f("playlistManager.disconnect","Disconnect"),children:r.jsx(B.NtdClose,{size:12})})]}):r.jsx("button",{style:{...z,background:pe.color,color:"var(--nice-color-white, #fff)",borderRadius:4,padding:"2px 8px"},onClick:()=>g(ne),children:f("playlistManager.connect","Connect")})]},ne)})})]})]})},om=({playlist:e,tags:t,onPlay:n,selectedTrackIds:a,onSelectionChange:s})=>{const{t:i}=xe(),o=d.useCallback(l=>{const c=new Set(a);c.has(l)?c.delete(l):c.add(l),s(c)},[a,s]);return e.tracks.length===0?r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:60,opacity:.3},children:[r.jsx("span",{style:{marginBottom:8,display:"inline-flex"},children:r.jsx(B.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",{role:"button",tabIndex:0,"aria-pressed":c,onKeyDown:ve.clickOnActivationKey,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(B.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)})})},lm=d.memo(om),ui=e=>e.replace(/[^a-z0-9_-]/gi,"-"),hi={background:"none",border:"none",cursor:"pointer",fontSize:"0.78rem",padding:"2px 4px",opacity:.4},cm=({playlists:e,folders:t,tags:n,activeFolderId:a,onSelectPlaylist:s,onDeletePlaylist:i,onDuplicatePlaylist:o})=>{const{t:l}=xe(),c=d.useMemo(()=>a?e.filter(u=>u.folderId===a):e,[e,a]);return c.length===0?r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:60,opacity:.4},children:[r.jsx("span",{style:{marginBottom:12,display:"inline-flex"},children:r.jsx(B.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(u=>{var p;const h=t.find(g=>g.id===u.folderId);return r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,onClick:()=>s(u.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:u.type===ts.Dynamic?r.jsx(B.NtdLightning,{size:40}):r.jsx(B.NtdMusic,{size:40})}),r.jsx("div",{style:{fontWeight:600,fontSize:"0.85rem",marginBottom:2},children:u.name}),r.jsxs("div",{style:{fontSize:"0.72rem",opacity:.5},children:[u.trackCount," ",l("playlistManager.tracks","tracks"),h&&r.jsxs(r.Fragment,{children:[" — ",r.jsx(B.NtdFolder,{size:11})," ",h.name]})]}),((p=u.tags)==null?void 0:p.length)>0&&r.jsx("div",{style:{display:"flex",gap:4,marginTop:6,flexWrap:"wrap"},children:u.tags.slice(0,3).map(g=>{const y=n.find(m=>m.id===g);return y?r.jsx("span",{style:{padding:"1px 8px",borderRadius:12,background:`var(--tag-${ui(g)}-bg, ${y.color}18)`,color:`var(--tag-${ui(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(u.id)},style:hi,title:l("playlistManager.duplicate","Duplicate"),"aria-label":l("playlistManager.duplicate","Duplicate"),children:r.jsx(B.NtdCopy,{size:14})}),r.jsx("button",{onClick:g=>{g.stopPropagation(),i(u.id)},style:hi,title:l("playlistManager.delete","Delete"),"aria-label":l("playlistManager.delete","Delete"),children:r.jsx(B.NtdTrash,{size:14})})]})]},u.id)})})},dm=d.memo(cm),pi=[{value:xt.Library,label:"Library",hex:"var(--nice-info, #6366f1)",css:"var(--source-library, #6366f1)",cssBg:"var(--source-library-bg, #6366f118)"},{value:xt.Spotify,label:"Spotify",hex:"var(--nice-success, #1db954)",css:"var(--source-spotify, #1db954)",cssBg:"var(--source-spotify-bg, #1db95418)"},{value:xt.Tidal,label:"Tidal",hex:"var(--nice-text, #000000)",css:"var(--source-tidal, #000000)",cssBg:"var(--source-tidal-bg, #00000018)"},{value:xt.YouTube,label:"YouTube",hex:"var(--nice-danger, #ff0000)",css:"var(--source-youtube, #ff0000)",cssBg:"var(--source-youtube-bg, #ff000018)"},{value:xt.MusicBrainz,label:"MusicBrainz",hex:"var(--source-musicbrainz, #ba478f)",css:"var(--source-musicbrainz, #ba478f)",cssBg:"var(--source-musicbrainz-bg, #ba478f18)"}],um=({onSearch:e,results:t,isSearching:n,onAddToPlaylist:a,onPlayPreview:s})=>{const{t:i}=xe(),[o,l]=d.useState(""),[c,u]=d.useState(new Set([xt.Library,xt.Spotify,xt.Tidal,xt.YouTube])),[h,p]=d.useState(new Set),[g,y]=d.useState(!1),m=d.useRef(null),x=d.useCallback(k=>{u(R=>{const P=new Set(R);return P.has(k)?P.delete(k):P.add(k),P})},[]),b=d.useCallback(k=>{l(k),m.current&&clearTimeout(m.current),k.trim().length>=2&&(m.current=setTimeout(()=>{e(k.trim(),Array.from(c))},350))},[c,e]),f=d.useCallback(k=>{k.preventDefault(),o.trim().length>=2&&e(o.trim(),Array.from(c))},[o,c,e]),j=d.useCallback(k=>{p(R=>{const P=new Set(R);return P.has(k)?P.delete(k):P.add(k),P})},[]),v=d.useCallback(()=>{h.size===t.length?p(new Set):p(new Set(t.map(k=>k.id)))},[h,t]),C=d.useCallback(()=>{const k=t.filter(R=>h.has(R.id));k.length>0&&(a(k),p(new Set))},[t,h,a]),T=k=>{if(!k)return"--:--";const R=Math.floor(k/60),P=k%60;return`${R}:${P.toString().padStart(2,"0")}`},M=k=>{const R=pi.find(P=>P.value===k);return r.jsx(B.NtdCircle,{size:10,style:{color:R?R.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",{role:"button",tabIndex:0,"aria-expanded":g,onKeyDown:ve.clickOnActivationKey,style:{display:"flex",alignItems:"center",padding:"8px 12px",gap:8,cursor:"pointer",background:"var(--nice-color-surface, #f9fafb)"},onClick:()=>y(!g),children:[r.jsx(B.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(B.NtdChevronUp,{size:12}):r.jsx(B.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:pi.map(k=>{const R=c.has(k.value);return r.jsxs("button",{onClick:()=>x(k.value),style:{padding:"4px 10px",borderRadius:20,border:R?`2px solid ${k.css}`:"1px solid var(--nice-border-color, #d1d5db)",background:R?k.cssBg:"transparent",color:R?k.css:"var(--nice-text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:R?600:400,transition:"all 0.15s"},children:[r.jsx(B.NtdCircle,{size:8,style:{color:k.css}})," ",k.label]},k.value)})}),r.jsxs("form",{onSubmit:f,style:{display:"flex",gap:6,marginBottom:8},children:[r.jsx("input",{type:"text",value:o,onChange:k=>b(k.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(B.NtdClock,{size:14}):r.jsx(B.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:v}),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:C,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(B.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(k=>r.jsxs("div",{role:"button",tabIndex:0,"aria-pressed":h.has(k.id),onKeyDown:ve.clickOnActivationKey,style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:"1px solid var(--nice-border-color, #f3f4f6)",background:h.has(k.id)?"var(--nice-accent-tint-10, #eff6ff)":"transparent",cursor:"pointer",fontSize:"0.78rem"},onClick:()=>j(k.id),children:[r.jsx("input",{type:"checkbox",checked:h.has(k.id),readOnly:!0}),M(k.source),k.imageUrl&&r.jsx("img",{src:k.imageUrl,alt:k.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:k.title}),r.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[k.artist,k.album?` — ${k.album}`:""]})]}),r.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:T(k.duration)}),s&&r.jsx("button",{onClick:R=>{R.stopPropagation(),s(k)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem"},title:i("playlistManager.preview","Preview"),"aria-label":i("playlistManager.preview","Preview"),children:r.jsx(B.NtdPlay,{size:14})})]},k.id))})]}),n&&r.jsxs("div",{style:{textAlign:"center",padding:20,opacity:.5,fontSize:"0.82rem"},children:[r.jsx(B.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")})]})]})},hm=[{value:1,label:"Spotify",icon:r.jsx(B.NtdMusic,{size:16}),color:"var(--source-spotify, #1db954)"},{value:2,label:"Tidal",icon:r.jsx(B.NtdMusic,{size:16}),color:"var(--source-tidal, #000000)"},{value:3,label:"Apple Music",icon:r.jsx(B.NtdMusic,{size:16}),color:"var(--source-apple, #fa243c)"},{value:4,label:"YouTube",icon:r.jsx(B.NtdMusic,{size:16}),color:"var(--source-youtube, #ff0000)"},{value:99,label:"Manual Paste",icon:r.jsx(B.NtdMusic,{size:16}),color:"var(--source-manual, #6366f1)"}],pm={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},fm={display:"flex",justifyContent:"space-between",alignItems:"center"},mm={display:"flex",gap:4,marginBottom:8},Dn={padding:"8px 20px",borderRadius:6,border:"none",background:"var(--nice-color-accent, #6366f1)",color:"var(--nice-text-on-primary, #fff)",cursor:"pointer",fontWeight:600},or=(function(){return{...Dn,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 gm(e){return Tl.indexOf(e)}function ym(e){if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const vm=({connections:e=[],onConnect:t=()=>{},onDisconnect:n=()=>{},onFetchPlaylists:a=async()=>[],onFetchTracks:s=async()=>[],onImport:i=async()=>({playlistName:"",imported:0,skipped:0,failed:0,failedTracks:[]}),onClose:o=()=>{},targetFolders:l,sources:c})=>{const{t:u}=xe(),[h,p]=d.useState("connect"),[g,y]=d.useState(null),[m,x]=d.useState([]),[b,f]=d.useState(null),[j,v]=d.useState([]),[C,T]=d.useState(new Set),[M,k]=d.useState(!1),[R,P]=d.useState(null),[I,A]=d.useState(null),[L,E]=d.useState(null),[D,Z]=d.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[G,F]=d.useState(""),q=d.useMemo(()=>new Set(e.filter(z=>z.connected).map(z=>z.platform)),[e]),V=d.useCallback(z=>e.find(ee=>ee.platform===z),[e]),K=d.useCallback(z=>{if(y(z),z===99){p("tracks"),F(""),v([]),k(!1);return}q.has(z)?(p("browse"),k(!0),E(null),a(z).then(ee=>{x(ee),k(!1)}).catch(ee=>{E(String(ee)),k(!1)})):t(z)},[q,t,a]),W=d.useCallback(z=>{f(z),p("tracks"),k(!0),E(null),s(z).then(ee=>{v(ee),T(new Set(ee.map(ae=>ae.externalId))),k(!1)}).catch(ee=>{E(String(ee)),k(!1)})},[s]),Q=d.useCallback(z=>{T(ee=>{const ae=new Set(ee);return ae.has(z)?ae.delete(z):ae.add(z),ae})},[]),w=d.useCallback(()=>{T(z=>z.size===j.length?new Set:new Set(j.map(ee=>ee.externalId)))},[j]),N=d.useCallback(async()=>{if(!b)return;const z=j.filter(ee=>C.has(ee.externalId));if(z.length!==0){p("importing"),P({total:z.length,imported:0,skipped:0,failed:0}),E(null);try{const ee=await i(b,z,D),ae=ee&&typeof ee=="object"&&"imported"in ee?ee:{playlistName:b.name,imported:z.length,skipped:0,failed:0,failedTracks:[]};A(ae),p("done")}catch(ee){E(String(ee)),p("options")}}},[b,j,C,D,i]),S=h!=="connect"&&h!=="importing"&&h!=="done",O=d.useCallback(()=>{switch(h){case"browse":p("connect");break;case"tracks":p("browse");break;case"options":p("tracks");break}},[h]),Y=()=>r.jsx("div",{style:mm,children:Tl.map((z,ee)=>r.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:ee<=gm(h)?"var(--nice-color-accent, #6366f1)":"var(--nice-border, #e2e8f0)",transition:"background 0.2s"}},z))}),_=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[r.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.selectPlatform","Select a music platform to import from")}),hm.map(z=>{const ee=V(z.value),ae=q.has(z.value);return r.jsxs("div",{style:{...fi,display:"flex",alignItems:"center",gap:12,borderColor:ae?z.color:void 0},onClick:()=>K(z.value),role:"button",tabIndex:0,onKeyDown:ce=>ce.key==="Enter"&&K(z.value),children:[r.jsx("span",{style:{color:z.color,display:"inline-flex"},"aria-hidden":"true",children:z.icon}),r.jsxs("div",{style:{flex:1},children:[r.jsx("strong",{children:z.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:z.color,fontSize:12,fontWeight:600},children:[u("importWizard.connected","Connected")," ",r.jsx(B.NtdCheck,{size:12})]}):r.jsx("span",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.clickToConnect","Click to connect")})]},z.value)})]}),U=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[r.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.selectPlaylist","Select a playlist to import")}),M?r.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.loading","Loading playlists…")}):r.jsxs("div",{style:{display:"grid",gap:8,maxHeight:320,overflowY:"auto"},children:[m.map(z=>r.jsxs("div",{style:{...fi,display:"flex",alignItems:"center",gap:12},onClick:()=>W(z),role:"button",tabIndex:0,onKeyDown:ee=>ee.key==="Enter"&&W(z),children:[z.coverUrl&&r.jsx("img",{src:z.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:z.name}),z.description&&r.jsx("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:z.description})]}),r.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)",whiteSpace:"nowrap"},children:[z.trackCount," ",u("importWizard.tracks","tracks")]})]},z.id)),m.length===0&&r.jsx("div",{style:{textAlign:"center",padding:24,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.noPlaylists","No playlists found")})]})]}),$=d.useCallback(z=>{const ae=z.split(`
|
|
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:G,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")})]})]})]})})]})},xl={music:B.NtdMusic,microphone:B.NtdMicrophone,volume:B.NtdVolume,wave:B.NtdWave,megaphone:B.NtdMegaphone,star:B.NtdStar,heart:B.NtdHeart,lightning:B.NtdLightning,sparkle:B.NtdSparkle,moon:B.NtdMoon,sun:B.NtdSun,mountain:B.NtdMountain,trophy:B.NtdTrophy,crown:B.NtdCrown,target:B.NtdTarget,pin:B.NtdPin},Rf=Object.keys(xl),Ca=({icon:e,size:t=14})=>{if(!e)return null;const n=xl[e];return n?r.jsx(n,{size:t}):r.jsx("span",{children:e})},oi=["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)"],ir=Rf,Nf=({tags:e,onCreateTag:t,onUpdateTag:n,onDeleteTag:a,selectedTracks:s,onAssignTag:i,onUnassignTag:o})=>{const{t:l}=xe(),[c,u]=d.useState(null),[h,p]=d.useState(""),[g,y]=d.useState(oi[8]),[m,x]=d.useState(ir[0]),[b,f]=d.useState(!1),[j,v]=d.useState(null),[C,T]=d.useState(""),[M,k]=d.useState(""),[R,P]=d.useState(""),I=d.useCallback(F=>{u(F.id),T(F.name),k(F.color),P(F.icon||ir[0])},[]),A=d.useCallback(()=>{c&&C.trim()&&(n(c,C.trim(),M,R),u(null))},[c,C,M,R,n]),L=d.useCallback(()=>{h.trim()&&(t(h.trim(),g,m),p(""),f(!1))},[h,g,m,t]),E=d.useCallback(F=>{j===F?(a(F),v(null)):(v(F),setTimeout(()=>v(null),3e3))},[j,a]),D=s&&s.length>0,Z=F=>!s||s.length===0?!1:s.every(q=>q.tags.includes(F)),G=F=>!s||s.length===0?!1:s.some(q=>q.tags.includes(F))&&!Z(F);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(B.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(!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")]})]}),r.jsxs("div",{style:{padding:12},children:[b&&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:F=>p(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:F=>F.key==="Enter"&&L()}),r.jsx("button",{onClick:L,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(B.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:oi.map(F=>r.jsx("div",{role:"button",tabIndex:0,"aria-label":F,"aria-pressed":g===F,onKeyDown:ve.clickOnActivationKey,onClick:()=>y(F),style:{width:20,height:20,borderRadius:"50%",background:F,cursor:"pointer",border:g===F?"3px solid var(--nice-color-accent, #3b82f6)":"2px solid transparent",boxSizing:"border-box"}},F))})]}),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:ir.map(F=>r.jsx("div",{role:"button",tabIndex:0,"aria-label":F,"aria-pressed":m===F,onKeyDown:ve.clickOnActivationKey,onClick:()=>x(F),style:{width:26,height:26,borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"0.85rem",background:m===F?"var(--nice-accent-tint-10, #eff6ff)":"transparent",border:m===F?"1px solid var(--nice-color-accent, #3b82f6)":"1px solid transparent"},children:r.jsx(Ca,{icon:F,size:16})},F))})]})]}),D&&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(F=>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===F.id?"var(--nice-color-surface, #f9fafb)":"transparent"},children:c===F.id?r.jsxs(r.Fragment,{children:[r.jsx("select",{value:R,onChange:q=>P(q.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:ir.map(q=>r.jsx("option",{value:q,children:q},q))}),r.jsx("input",{type:"color",value:M,onChange:q=>k(q.target.value),style:{width:24,height:24,border:"none",cursor:"pointer",padding:0}}),r.jsx("input",{type:"text",value:C,onChange:q=>T(q.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:q=>q.key==="Enter"&&A()}),r.jsx("button",{onClick:A,style:or("var(--nice-color-accent, #3b82f6)"),"aria-label":l("common.save","Save"),children:r.jsx(B.NtdCheck,{size:14})}),r.jsx("button",{onClick:()=>u(null),style:or("var(--nice-text-secondary, #9ca3af)"),"aria-label":l("common.cancel","Cancel"),children:r.jsx(B.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:`${F.color}18`,color:F.color,fontWeight:600,fontSize:"0.78rem"},children:[r.jsx(Ca,{icon:F.icon,size:12}),F.name]}),D&&i&&o&&r.jsx("input",{type:"checkbox",checked:Z(F.id),ref:q=>{q&&(q.indeterminate=G(F.id))},onChange:()=>{const q=s.map(V=>V.id);Z(F.id)?o(q,F.id):i(q,F.id)},style:{cursor:"pointer"}}),r.jsx("div",{style:{flex:1}}),r.jsx("button",{onClick:()=>I(F),style:or("var(--nice-text-secondary, #9ca3af)"),title:l("playlistManager.editTag","Edit tag"),"aria-label":l("playlistManager.editTag","Edit tag"),children:r.jsx(B.NtdEdit,{size:14})}),r.jsx("button",{onClick:()=>E(F.id),style:or(j===F.id?"var(--nice-color-error, #ef4444)":"var(--nice-text-secondary, #9ca3af)"),title:j===F.id?l("playlistManager.confirmDelete","Click again to delete"):l("playlistManager.deleteTag","Delete tag"),"aria-label":j===F.id?l("playlistManager.confirmDelete","Click again to delete"):l("playlistManager.deleteTag","Delete tag"),children:r.jsx(B.NtdTrash,{size:14})})]})},F.id))})]})]})},or=e=>({background:"none",border:"none",cursor:"pointer",fontSize:"0.82rem",color:e,padding:"2px 4px"});var ns=(e=>(e.Static="static",e.Dynamic="dynamic",e))(ns||{}),Sl=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(Sl||{}),kl=(e=>(e.Left="left",e.Right="right",e))(kl||{}),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||{}),wl=(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))(wl||{}),un=(e=>(e.Asc="asc",e.Desc="desc",e))(un||{}),bt=(e=>(e.Library="library",e.Spotify="spotify",e.Tidal="tidal",e.YouTube="youtube",e.MusicBrainz="musicbrainz",e.Import="import",e.Manual="manual",e))(bt||{});const Tf="_editor_qz5p3_5",Pf="_heading_qz5p3_19",Ef="_hint_qz5p3_35",$f="_group_qz5p3_49",Af="_groupOr_qz5p3_61",If="_groupShaded_qz5p3_67",Lf="_groupHeader_qz5p3_73",_f="_groupHint_qz5p3_87",Df="_groupActions_qz5p3_95",zf="_rule_qz5p3_107",Ff="_value_qz5p3_121",Of="_value2_qz5p3_127",Bf="_dash_qz5p3_133",Gf="_limit_qz5p3_141",Wf="_limitInput_qz5p3_159",at={editor:Tf,heading:Pf,hint:Ef,group:$f,groupOr:Af,groupShaded:If,groupHeader:Lf,groupHint:_f,groupActions:Df,rule:zf,value:Ff,value2:Of,dash:Bf,limit:Gf,limitInput:Wf},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"}],Vf=[{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 qf(e){return"logic"in e&&"rules"in e}function ja(){return{id:ve.createId(),field:ot.Artist,operator:lt.Contains,value:""}}function Cl(){return{id:ve.createId(),logic:"and",rules:[ja()]}}const Hf=({rule:e,onChange:t,onRemove:n})=>{const{t:a}=xe();return r.jsxs("div",{className:at.rule,children:[r.jsx(ie.NiceSelect,{size:"sm",controlWidth:150,"aria-label":a("playlistManager.ruleField","Field"),value:e.field,onChange:s=>t({...e,field:Nt(s)}),options:Uf.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:Nt(s)}),options:Vf.map(s=>({value:s.value,label:a(`playlistManager.op.${s.value}`,s.label)}))}),r.jsx(ie.NiceTextInput,{size:"sm",className:at.value,"aria-label":a("playlistManager.ruleValue","Value"),placeholder:a("playlistManager.ruleValue","Value"),value:e.value,onChange:s=>t({...e,value:s})}),e.operator===lt.Between&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:at.dash,"aria-hidden":"true",children:"–"}),r.jsx(ie.NiceTextInput,{size:"sm",className:at.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(B.NtdClose,{size:14}),ariaLabel:a("playlistManager.removeRule","Remove rule"),title:a("playlistManager.removeRule","Remove rule"),onClick:n,children:null})]})},jl=({group:e,onChange:t,onRemove:n,depth:a=0})=>{const{t:s}=xe(),i=d.useCallback((p,g)=>{const y=[...e.rules];y[p]=g,t({...e,rules:y})},[e,t]),o=d.useCallback(p=>{const g=e.rules.filter((y,m)=>m!==p);t({...e,rules:g.length>0?g:[ja()]})},[e,t]),l=d.useCallback(()=>{t({...e,rules:[...e.rules,ja()]})},[e,t]),c=d.useCallback(()=>{t({...e,rules:[...e.rules,Cl()]})},[e,t]),u=d.useCallback(()=>{t({...e,logic:e.logic==="and"?"or":"and"})},[e,t]),h=e.logic==="and";return r.jsxs("div",{className:`${at.group} ${h?"":at.groupOr} ${a%2===0?at.groupShaded:""}`,children:[r.jsxs("div",{className:at.groupHeader,children:[r.jsx(ie.NiceButton,{size:"sm",variant:h?"primary":"warning",onClick:u,title:s("playlistManager.toggleLogic","Toggle AND/OR"),children:h?s("playlistManager.logicAnd","AND"):s("playlistManager.logicOr","OR")}),r.jsx("span",{className:at.groupHint,children:h?s("playlistManager.matchAllRules","Match all of these rules"):s("playlistManager.matchAnyRule","Match any of these rules")}),r.jsxs("div",{className:at.groupActions,children:[r.jsx(ie.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(B.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(B.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(B.NtdClose,{size:14}),ariaLabel:s("playlistManager.removeGroup","Remove group"),title:s("playlistManager.removeGroup","Remove group"),onClick:n,children:null})]})]}),e.rules.map((p,g)=>qf(p)?r.jsx(jl,{group:p,onChange:y=>i(g,y),onRemove:()=>o(g),depth:a+1},p.id):r.jsx(Hf,{rule:p,onChange:y=>i(g,y),onRemove:()=>o(g)},p.id))]})},Kf=({rules:e,onChange:t,limit:n,onLimitChange:a})=>{const{t:s}=xe(),[i]=d.useState(Cl),o=e??i;return r.jsxs("div",{className:at.editor,children:[r.jsxs("h6",{className:at.heading,children:[r.jsx(B.NtdRepeat,{size:14})," ",s("playlistManager.dynamicRules","Dynamic Playlist Rules")]}),r.jsx("p",{className:at.hint,children:s("playlistManager.dynamicRulesHint","Tracks matching these rules will automatically be included in the playlist.")}),r.jsx(jl,{group:o,onChange:t}),a&&r.jsx("div",{className:at.limit,children:r.jsx(ie.NiceNumberInput,{size:"sm",className:at.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")})})]})},li=e=>{if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`},Yf={spotify:"var(--source-spotify, #1db954)",tidal:"var(--source-tidal, #000000)",youtube:"var(--source-youtube, #ff0000)",musicbrainz:"var(--source-musicbrainz, #ba478f)"},Zf=({source:e})=>{if(e==="import")return r.jsx(B.NtdDownload,{size:12});if(e==="manual")return r.jsx(B.NtdEdit,{size:12});const t=Yf[e];return t?r.jsx(B.NtdCircle,{size:10,style:{color:t}}):r.jsx(B.NtdMusic,{size:12})},Ml=({tracks:e,tags:t,selectedTrackIds:n,onSelectionChange:a,onPlay:s,onRemove:i,onReorder:o,onTagTracks:l,onRateTracks:c,sortField:u,sortDir:h,onSortChange:p,filterText:g,onFilterChange:y,compact:m=!1,draggable:x=!1,onDragStart:b,dropTarget:f=!1,onDrop:j})=>{const{t:v}=xe(),[C,T]=d.useState(null),[M,k]=d.useState(null),R=d.useRef(null),P=d.useMemo(()=>{let w=e??[];if(g.trim()){const N=g.toLowerCase();w=w.filter(S=>{var O,Y;return S.title.toLowerCase().includes(N)||S.artist.toLowerCase().includes(N)||((O=S.album)==null?void 0:O.toLowerCase().includes(N))||((Y=S.genre)==null?void 0:Y.toLowerCase().includes(N))})}return[...w].sort((N,S)=>{const O=h==="asc"?1:-1;switch(u){case"title":return O*N.title.localeCompare(S.title);case"artist":return O*N.artist.localeCompare(S.artist);case"album":return O*(N.album??"").localeCompare(S.album??"");case"duration":return O*((N.duration??0)-(S.duration??0));case"year":return O*((N.year??0)-(S.year??0));case"rating":return O*((N.rating??0)-(S.rating??0));case"addedDate":return O*(N.addedAt??"").localeCompare(S.addedAt??"");case"custom":return O*((N.customOrder??0)-(S.customOrder??0));default:return 0}})},[e,g,u,h]),I=d.useCallback((w,N)=>{const S=P[w];if(S){if(N.ctrlKey||N.metaKey){const O=new Set(n);O.has(S.id)?O.delete(S.id):O.add(S.id),a(O)}else if(N.shiftKey&&R.current!==null){const O=Math.min(R.current,w),Y=Math.max(R.current,w),_=new Set(n);for(let U=O;U<=Y;U++)_.add(P[U].id);a(_)}else a(new Set([S.id]));R.current=w}},[P,n,a]),A=d.useCallback(()=>{n.size===P.length?a(new Set):a(new Set(P.map(w=>w.id)))},[P,n,a]),L=({field:w,label:N,width:S})=>{const O=u===w;return r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,style:{width:S,flex:S?void 0:1,cursor:"pointer",userSelect:"none",fontWeight:O?700:500,fontSize:"0.72rem",textTransform:"uppercase",letterSpacing:"0.04em",opacity:O?1:.6,display:"flex",alignItems:"center",gap:4},onClick:()=>{O?p(w,h===un.Asc?un.Desc:un.Asc):p(w,un.Asc)},children:[N,O&&(h==="asc"?r.jsx(B.NtdArrowUp,{size:10}):r.jsx(B.NtdArrowDown,{size:10}))]})},E=d.useCallback((w,N)=>{const S=n.has(w.id)?Array.from(n):[w.id];N.dataTransfer.setData("trackIds",JSON.stringify(S)),N.dataTransfer.effectAllowed="move",b==null||b(S,N)},[n,b]),D=d.useCallback((w,N)=>{N.preventDefault(),N.dataTransfer.dropEffect="move",T(w)},[]),Z=d.useCallback((w,N)=>{N.preventDefault(),T(null);try{const S=N.dataTransfer.getData("trackIds");if(S&&o){const O=JSON.parse(S),Y=P.filter($=>!O.includes($.id)),_=P.filter($=>O.includes($.id)),U=Math.min(w,Y.length);Y.splice(U,0,..._),o(Y.map($=>$.id))}}catch{}},[P,o]),G=d.useCallback(w=>{w.preventDefault(),T(null),j==null||j(w)},[j]),F=d.useMemo(()=>new Map(t.map(w=>[w.id,w])),[t]),q=w=>w.replace(/[^a-z0-9_-]/gi,"-"),V=m?36:48,K={display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",color:"var(--nice-text-secondary, #6b7280)"},W=(w,N)=>({display:"flex",alignItems:"center",gap:8,padding:m?"4px 12px":"6px 12px",height:V,cursor:"pointer",background:N?"var(--nice-color-accent-light, #dbeafe)":w?"var(--nice-selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--nice-border-light, #f3f4f6)",transition:"background 0.1s"}),Q=P.length>0&&n.size===P.length;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:f?w=>{w.preventDefault(),w.dataTransfer.dropEffect="copy"}:void 0,onDrop:f?G: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:w=>y(w.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)"}}),r.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[P.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":v("playlistManager.removeSelected","Remove selected"),children:[r.jsx(B.NtdTrash,{size:12})," ",n.size]})]}),r.jsxs("div",{style:K,children:[r.jsx("div",{style:{width:28},children:r.jsx("input",{type:"checkbox",checked:Q,onChange:A,style:{cursor:"pointer"}})}),r.jsx("div",{style:{width:20},children:"#"}),!m&&r.jsx("div",{style:{width:44}}),r.jsx(L,{field:"title",label:v("playlistManager.colTitle","Title")}),r.jsx(L,{field:"artist",label:v("playlistManager.colArtist","Artist")}),!m&&r.jsx(L,{field:"album",label:v("playlistManager.colAlbum","Album")}),r.jsx(L,{field:"duration",label:v("playlistManager.colDuration","Duration"),width:60}),!m&&r.jsx(L,{field:"year",label:v("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:[P.length===0&&r.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")}),P.map((w,N)=>{const S=n.has(w.id),O=C===N;return r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,style:W(S,O),onClick:Y=>I(N,Y),onDoubleClick:()=>s==null?void 0:s(w),draggable:x,onDragStart:Y=>E(w,Y),onDragOver:Y=>D(N,Y),onDrop:Y=>Z(N,Y),onDragLeave:()=>T(null),children:[r.jsx("div",{style:{width:28},children:r.jsx("input",{type:"checkbox",checked:S,onChange:()=>{const Y=new Set(n);S?Y.delete(w.id):Y.add(w.id),a(Y)},onClick:Y=>Y.stopPropagation(),style:{cursor:"pointer"}})}),r.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:N+1}),!m&&r.jsx("div",{style:{width:44,height:36,flexShrink:0},children:w.coverUrl?r.jsx("img",{src:w.coverUrl,alt:w.title||v("common.coverArt","Cover art"),style:{width:36,height:36,borderRadius:4,objectFit:"cover"},loading:"lazy"}):r.jsx("div",{style:{width:36,height:36,borderRadius:4,background:"var(--nice-color-surface, #f3f4f6)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.9rem"},children:r.jsx(B.NtdMusic,{size:16})})}),r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",fontWeight:500},children:w.title}),r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",opacity:.7},children:w.artist}),!m&&r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",opacity:.5},children:w.album}),r.jsx("div",{style:{width:60,fontSize:"0.78rem",opacity:.5,textAlign:"right"},children:li(w.duration)}),!m&&r.jsx("div",{style:{width:50,fontSize:"0.72rem",opacity:.4,textAlign:"center"},children:w.year||""}),r.jsx("div",{style:{width:30,textAlign:"center",fontSize:"0.75rem"},title:w.source,children:r.jsx(Zf,{source:w.source})}),!m&&r.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[w.tags.slice(0,2).map(Y=>{const _=F.get(Y);if(!_)return null;const U=`--tag-${q(Y)}`;return r.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${U}-bg, ${_.color}22)`,color:`var(${U}, ${_.color})`,whiteSpace:"nowrap"},children:_.name},Y)}),w.tags.length>2&&r.jsxs("span",{style:{fontSize:"0.6rem",opacity:.4},children:["+",w.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:Y=>{Y.stopPropagation(),k(M===w.id?null:w.id)},title:v("playlistManager.morActions","More actions"),"aria-label":v("playlistManager.morActions","More actions"),children:r.jsx(B.NtdTag,{size:12})}),M===w.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:v("playlistManager.assignTag","Assign tag")}),t.map(Y=>{const _=w.tags.includes(Y.id);return r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,style:{padding:"4px 8px",borderRadius:4,cursor:"pointer",fontSize:"0.78rem",display:"flex",alignItems:"center",gap:6,background:_?`var(--tag-${q(Y.id)}-bg, ${Y.color}22)`:"transparent"},onClick:U=>{U.stopPropagation();const $=n.size>0?Array.from(n):[w.id];_||l==null||l($,[Y.id]),k(null)},children:[r.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:`var(--tag-${q(Y.id)}, ${Y.color})`,flexShrink:0}}),r.jsx("span",{children:Y.name}),_&&r.jsx(B.NtdCheck,{size:12,style:{marginLeft:"auto"}})]},Y.id)})]})]})]},w.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:[P.length," ",v("playlistManager.tracks","tracks")]}),r.jsx("span",{children:li(P.reduce((w,N)=>w+(N.duration??0),0))}),n.size>0&&r.jsxs("span",{children:[n.size," ",v("playlistManager.selected","selected")]})]})]})},ci=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),Xf=({playlists:e=[],tags:t=[],onCopyTracks:n=()=>{},onMoveTracks:a=()=>{},onRemoveTracks:s=()=>{},onReorderTracks:i=()=>{},onPlay:o=()=>{},onTagTracks:l=()=>{},initialLeftId:c,initialRightId:u})=>{const{t:h}=xe(),[p,g]=d.useState(()=>ci(c??null)),[y,m]=d.useState(()=>ci(u??null)),[x,b]=d.useState("left"),[f,j]=d.useState(null),[v,C]=d.useState(50),[T,M]=d.useState(!1),k=d.useMemo(()=>e.find(w=>w.id===p.playlistId),[e,p.playlistId]),R=d.useMemo(()=>e.find(w=>w.id===y.playlistId),[e,y.playlistId]),P=d.useCallback((w,N)=>{w==="left"?g(S=>({...S,...N})):m(S=>({...S,...N}))},[]),I=d.useCallback(w=>w==="left"?p:y,[p,y]),A=w=>w==="left"?"right":"left",L=d.useCallback(w=>{const N=I(w),S=I(A(w));!N.playlistId||!S.playlistId||N.selectedTrackIds.size===0||(n(N.playlistId,S.playlistId,Array.from(N.selectedTrackIds)),P(w,{selectedTrackIds:new Set}))},[I,n,P]),E=d.useCallback(w=>{const N=I(w),S=I(A(w));!N.playlistId||!S.playlistId||N.selectedTrackIds.size===0||(a(N.playlistId,S.playlistId,Array.from(N.selectedTrackIds)),P(w,{selectedTrackIds:new Set}))},[I,a,P]),D=d.useCallback(w=>{const N=I(w);!N.playlistId||N.selectedTrackIds.size===0||j({operation:"copy",sourcePlaylistId:N.playlistId,trackIds:Array.from(N.selectedTrackIds)})},[I]),Z=d.useCallback(w=>{const N=I(w);!N.playlistId||N.selectedTrackIds.size===0||j({operation:"cut",sourcePlaylistId:N.playlistId,trackIds:Array.from(N.selectedTrackIds)})},[I]),G=d.useCallback(w=>{const N=I(w);!f||!N.playlistId||(f.operation==="copy"?n(f.sourcePlaylistId,N.playlistId,f.trackIds):a(f.sourcePlaylistId,N.playlistId,f.trackIds),j(null))},[f,I,n,a]),F=d.useRef(!1),q=d.useCallback(w=>{if(w.key==="Tab"&&F.current){F.current=!1;return}["Shift","Control","Alt","Meta"].includes(w.key)||(F.current=w.key==="Escape"),w.key==="Tab"&&!w.shiftKey&&(w.preventDefault(),b(N=>A(N))),(w.ctrlKey||w.metaKey)&&w.key==="c"&&D(x),(w.ctrlKey||w.metaKey)&&w.key==="x"&&Z(x),(w.ctrlKey||w.metaKey)&&w.key==="v"&&G(x)},[x,D,Z,G]),V=d.useCallback(()=>M(!0),[]),K=d.useCallback(w=>{if(!T)return;const N=w.currentTarget.getBoundingClientRect(),S=(w.clientX-N.left)/N.width*100;C(Math.max(20,Math.min(80,S)))},[T]),W=d.useCallback(()=>M(!1),[]),Q=w=>{const N=I(w),S=w==="left"?k:R,O=x===w,_=!!I(A(w)).playlistId;return r.jsxs("div",{role:"presentation",style:{display:"flex",flexDirection:"column",height:"100%",border:O?"2px solid var(--nice-color-accent, #3b82f6)":"2px solid transparent",borderRadius:8,overflow:"hidden",background:"var(--nice-bg-elevated, #fff)"},onClick:()=>b(w),children:[r.jsx("div",{style:{padding:"8px 12px",background:O?"var(--nice-color-accent, #3b82f6)":"var(--nice-color-surface, #f3f4f6)",color:O?"var(--nice-text-on-accent, #fff)":"var(--nice-text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:r.jsxs("select",{value:N.playlistId??"",onChange:U=>P(w,{playlistId:U.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:O?"var(--nice-overlay-light-20, #ffffff30)":"var(--nice-input-bg, #fff)",color:O?"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(U=>r.jsxs("option",{value:U.id,children:[U.name," (",U.trackCount,")"]},U.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:ia(!1),onClick:()=>L(w),disabled:!N.playlistId||!_||N.selectedTrackIds.size===0,title:h("playlistManager.copyToOther","Copy to the other playlist"),children:[w==="left"?r.jsxs(r.Fragment,{children:[r.jsx(B.NtdCopy,{size:12}),r.jsx(B.NtdChevronRight,{size:12})]}):r.jsxs(r.Fragment,{children:[r.jsx(B.NtdChevronLeft,{size:12}),r.jsx(B.NtdCopy,{size:12})]})," ",h("playlistManager.copy","Copy")]}),r.jsxs("button",{style:ia(!1),onClick:()=>E(w),disabled:!N.playlistId||!_||N.selectedTrackIds.size===0,title:h("playlistManager.moveToOther","Move to the other playlist"),children:[w==="left"?r.jsxs(r.Fragment,{children:[r.jsx(B.NtdMove,{size:12}),r.jsx(B.NtdChevronRight,{size:12})]}):r.jsxs(r.Fragment,{children:[r.jsx(B.NtdChevronLeft,{size:12}),r.jsx(B.NtdMove,{size:12})]})," ",h("playlistManager.move","Move")]}),r.jsx("div",{style:{flex:1}}),f&&r.jsxs("button",{style:ia(!0),onClick:()=>G(w),disabled:!N.playlistId,children:[r.jsx(B.NtdClipboard,{size:12})," ",h("playlistManager.paste","Paste")," (",f.trackIds.length,")"]})]}),S?r.jsx(Ml,{tracks:S.tracks,tags:t,selectedTrackIds:N.selectedTrackIds,onSelectionChange:U=>P(w,{selectedTrackIds:U}),onPlay:o,onRemove:U=>s(S.id,U),onReorder:U=>i(S.id,U),onTagTracks:l,sortField:N.sortField,sortDir:N.sortDir,onSortChange:(U,$)=>P(w,{sortField:U,sortDir:$}),filterText:N.filterText,onFilterChange:U=>P(w,{filterText:U}),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:T?"none":"auto"},onKeyDown:q,onMouseMove:K,onMouseUp:W,tabIndex:0,children:[r.jsx("div",{style:{width:`${v}%`,minWidth:200},children:Q("left")}),r.jsx("div",{style:{width:6,cursor:"col-resize",background:T?"var(--nice-color-accent, #3b82f6)":"var(--nice-border-color, #e5e7eb)",transition:T?"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:T?"var(--nice-color-accent, #3b82f6)":"var(--nice-bg-tertiary, #9ca3af)"}})}),r.jsx("div",{style:{flex:1,minWidth:200},children:Q("right")})]})},ia=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"}),Rl="av:local-playlists";function Qf(){try{const e=localStorage.getItem(Rl);return e?JSON.parse(e):[]}catch{return[]}}function Jf(e){const t=JSON.stringify(e);try{localStorage.setItem(Rl,t)}catch{}}function rs(){const[e,t]=d.useState(()=>Qf()),n=d.useRef(!1);return d.useEffect(()=>{n.current=!0},[]),d.useEffect(()=>{Jf(e)},[e]),d.useMemo(()=>({list:()=>e,get:s=>e.find(i=>i.id===s),create:s=>{const i=new Date().toISOString(),o={id:ve.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 em=st.scoped("PlaylistList"),tm={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,background:"var(--nice-bg, #fff)"},nm=(function(){return{...tm,padding:"8px 10px",cursor:"pointer"}})(),Nl={border:"1px solid var(--nice-border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg, #fff)",cursor:"pointer"},rm=(function(){return{...Nl,background:"var(--nice-color-primary, #4f46e5)",borderColor:"var(--nice-color-primary, #4f46e5)",color:"var(--nice-text-on-primary, #fff)"}})(),as=({selectedId:e,onSelect:t,onCreateRemote:n})=>{const{t:a}=xe(),s=rs(),[i,o]=d.useState(""),l=d.useMemo(()=>s.list(),[s]);return r.jsxs("div",{style:{display:"grid",gap:10},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("input",{placeholder:a("playlistList.playlistName","Playlist name"),value:i,onChange:c=>o(c.target.value),style:{flex:1,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px"},"aria-label":a("playlistList.playlistName","Playlist name")}),r.jsxs("button",{type:"button",disabled:!i.trim(),style:i.trim()?rm:{...Nl,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(u){em.error("Remote playlist create failed:",u)}t==null||t(c)},children:["+ ",a("common.add","Add")]})]}),r.jsxs("div",{style:{display:"grid",gap:6},children:[l.map(c=>{const u=c.id===e;return r.jsxs("button",{onClick:()=>t==null?void 0:t(c),style:{...nm,background:u?"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 ↑")})]})]})},am=st.scoped("PlaylistBrowser"),di={display:"grid",gap:12},ui=e=>({artist:(e.artists??[]).join(", "),title:e.title}),sm=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:n,tracks:a,view:s,onSelect:i,onPlay:o})=>{var b;const{t:l}=xe(),c=rs(),[u,h]=d.useState(null),[p,g]=d.useState(""),[,y]=d.useState([]),m=u==null?void 0:u.id,x=(f,j)=>{if("addItems"in c){c.addItems(f.id,j);const C=c.list().find(T=>T.id===f.id)||f;h(C);return}const v=c;if("update"in c&&typeof v.update=="function"){const C=Array.from([...f.items||[],...j]);v.update({...f,items:C});const T=c.list().find(M=>M.id===f.id)||{...f,items:C};h(T);return}am.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:di,children:[r.jsx("h3",{style:{margin:0},children:l("playlistBrowser.playlists","Playlists")}),r.jsx(as,{selectedId:m,onSelect:h}),u&&r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:[l("playlistBrowser.selected","Selected"),": ",r.jsx("strong",{children:u.name})," ·"," ",((b=u.items)==null?void 0:b.length)??0," ",l("playlistBrowser.tracks","tracks")]})]}),r.jsxs("div",{style:di,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=>{u&&x(u,[ui(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=>{u&&x(u,[ui(f)])}}),n==null?void 0:n({onPlayNow:f=>y(f),onAddToQueue:f=>y(j=>[...j,...f]),onAddDescriptors:f=>u&&x(u,f)})]})]})};var Zt=(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))(Zt||{});const Tl=(e,t=null)=>e.filter(n=>n.parentId===t).sort((n,a)=>n.sortOrder-a.sortOrder).map(n=>({...n,children:Tl(e,n.id)})),im={[Zt.Spotify]:{label:"Spotify",color:"var(--source-spotify, #1DB954)",bg:"var(--source-spotify-bg, #1DB95418)"},[Zt.Tidal]:{label:"Tidal",color:"var(--source-tidal, #000000)",bg:"var(--source-tidal-bg, #00000010)"},[Zt.YouTube]:{label:"YouTube",color:"var(--source-youtube, #FF0000)",bg:"var(--source-youtube-bg, #FF000010)"}},om=({folders:e,playlists:t,tags:n,services:a,activeFolderId:s,activePlaylistId:i,onSelectFolder:o,onSelectPlaylist:l,onCreateFolder:c,onRenameFolder:u,onDeleteFolder:h,onCreatePlaylist:p,onConnectService:g,onDisconnectService:y,onDragPlaylistToFolder:m,collapsed:x=!1,onToggleCollapse:b})=>{const{t:f}=xe(),[j,v]=d.useState(new Set),[C,T]=d.useState(!1),[M,k]=d.useState(""),[R,P]=d.useState(null),[I,A]=d.useState(!1),[L,E]=d.useState(""),[D,Z]=d.useState("static"),[G,F]=d.useState(null),[q,V]=d.useState(""),[K,W]=d.useState(null),[Q,w]=d.useState(!1),N=d.useMemo(()=>Tl(e),[e]),S=d.useCallback(ne=>{v(pe=>{const fe=new Set(pe);return fe.has(ne)?fe.delete(ne):fe.add(ne),fe})},[]),O=d.useCallback(()=>{M.trim()&&(c(M.trim(),R),k(""),T(!1))},[M,R,c]),Y=d.useCallback(()=>{L.trim()&&(p(L.trim(),D,s),E(""),A(!1))},[L,D,s,p]),_=d.useCallback(ne=>{q.trim()&&(u(ne,q.trim()),F(null),V(""))},[q,u]),U=d.useCallback((ne,pe)=>{ne.preventDefault(),ne.dataTransfer.dropEffect="move",W(pe)},[]),$=d.useCallback((ne,pe)=>{ne.preventDefault();const fe=ne.dataTransfer.getData("playlistId");fe&&m&&m(fe,pe),W(null)},[m]),H=d.useCallback(()=>W(null),[]),X=d.useCallback(ne=>t.filter(pe=>(pe.folderId??null)===ne),[t]),re={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)"},se=(ne,pe=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:pe?"var(--nice-color-accent-light, #dbeafe)":ne?"var(--nice-color-accent, #3b82f6)":"transparent",color:ne?"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)"},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=(ne,pe)=>{var je,Pe;const fe=j.has(ne.id),ge=s===ne.id,he=K===ne.id,we=X(ne.id);return r.jsxs("div",{children:[r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,style:{...se(ge,he),paddingLeft:12+pe*16},onClick:()=>{o(ne.id),ne.children&&ne.children.length>0&&S(ne.id)},onDragOver:$e=>U($e,ne.id),onDrop:$e=>$($e,ne.id),onDragLeave:H,children:[r.jsx("span",{style:{width:14,textAlign:"center",flexShrink:0,fontSize:"0.7rem"},children:(((je=ne.children)==null?void 0:je.length)||0)>0||we.length>0?fe?r.jsx(B.NtdChevronDown,{size:10}):r.jsx(B.NtdChevronRight,{size:10}):null}),G===ne.id?r.jsx("input",{value:q,onChange:$e=>V($e.target.value),onKeyDown:$e=>{$e.key==="Enter"&&_(ne.id),$e.key==="Escape"&&F(null)},onBlur:()=>_(ne.id),autoFocus:!0,style:{...ee,flex:1},onClick:$e=>$e.stopPropagation()}):r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{display:"inline-flex"},children:ne.icon??r.jsx(B.NtdFolder,{size:14})}),r.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:ne.name}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:we.length}),r.jsx("button",{style:z,onClick:$e=>{$e.stopPropagation(),F(ne.id),V(ne.name)},title:f("common.rename","Rename"),"aria-label":f("common.rename","Rename"),children:r.jsx(B.NtdEdit,{size:12})}),r.jsx("button",{style:{...z,color:"var(--nice-color-error, #ef4444)"},onClick:$e=>{$e.stopPropagation(),h(ne.id)},title:f("common.delete","Delete"),"aria-label":f("common.delete","Delete"),children:r.jsx(B.NtdTrash,{size:12})})]})]}),fe&&r.jsxs(r.Fragment,{children:[we.map($e=>ce($e,pe+1)),(Pe=ne.children)==null?void 0:Pe.map($e=>ae($e,pe+1))]})]},ne.id)},ce=(ne,pe)=>{const fe=i===ne.id;return r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,style:{...se(fe),paddingLeft:12+pe*16+22},onClick:()=>l(ne.id),draggable:!0,onDragStart:ge=>{ge.dataTransfer.setData("playlistId",ne.id),ge.dataTransfer.effectAllowed="move"},children:[r.jsx("span",{style:{display:"inline-flex"},children:ne.type==="dynamic"?r.jsx(B.NtdLightning,{size:12}):r.jsx(B.NtdMusic,{size:12})}),r.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:ne.name}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:ne.trackCount})]},ne.id)};if(x)return r.jsx("div",{style:re,children:r.jsx("button",{style:{...z,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:b,title:f("playlistManager.expandSidebar","Expand sidebar"),"aria-label":f("playlistManager.expandSidebar","Expand sidebar"),children:r.jsx(B.NtdChevronRight,{size:16})})});const le=X(null);return r.jsxs("div",{style:re,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(B.NtdMusic,{size:14})," ",f("playlistManager.title","Playlists")]}),r.jsx("button",{style:z,onClick:b,title:f("playlistManager.collapseSidebar","Collapse sidebar"),"aria-label":f("playlistManager.collapseSidebar","Collapse sidebar"),children:r.jsx(B.NtdChevronLeft,{size:16})})]}),r.jsxs("div",{style:{...oe,display:"flex",gap:4,flexWrap:"wrap"},children:[r.jsxs("button",{style:{...z,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:{...z,border:"1px solid var(--nice-border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{T(!0),P(s)},children:[r.jsx(B.NtdFolder,{size:12})," ",f("playlistManager.newFolder","New folder")]})]}),I&&r.jsxs("div",{style:{...oe,display:"flex",flexDirection:"column",gap:6},children:[r.jsx("input",{value:L,onChange:ne=>E(ne.target.value),placeholder:f("playlistManager.playlistName","Playlist name"),style:ee,autoFocus:!0,onKeyDown:ne=>{ne.key==="Enter"&&Y(),ne.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:D==="static",onChange:()=>Z("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:D==="dynamic",onChange:()=>Z("dynamic")}),r.jsx(B.NtdLightning,{size:12})," ",f("playlistManager.dynamic","Dynamic")]}),r.jsx("div",{style:{flex:1}}),r.jsx("button",{style:{...z,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:Y,"aria-label":f("playlistManager.confirmCreatePlaylist","Confirm create playlist"),children:r.jsx(B.NtdCheck,{size:12})}),r.jsx("button",{style:z,onClick:()=>A(!1),"aria-label":f("playlistManager.cancelCreatePlaylist","Cancel create playlist"),children:r.jsx(B.NtdClose,{size:12})})]})]}),C&&r.jsxs("div",{style:{...oe,display:"flex",gap:6},children:[r.jsx("input",{value:M,onChange:ne=>k(ne.target.value),placeholder:f("playlistManager.folderName","Folder name"),style:{...ee,flex:1},autoFocus:!0,onKeyDown:ne=>{ne.key==="Enter"&&O(),ne.key==="Escape"&&T(!1)}}),r.jsx("button",{style:{...z,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:O,"aria-label":f("playlistManager.confirmCreateFolder","Confirm create folder"),children:r.jsx(B.NtdCheck,{size:12})}),r.jsx("button",{style:z,onClick:()=>T(!1),"aria-label":f("playlistManager.cancelCreateFolder","Cancel create folder"),children:r.jsx(B.NtdClose,{size:12})})]}),r.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,style:se(s===null&&i===null,K==="__root__"),onClick:()=>o(null),onDragOver:ne=>U(ne,null),onDrop:ne=>$(ne,null),onDragLeave:H,children:[r.jsx(B.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})]}),le.map(ne=>ce(ne,0)),N.map(ne=>ae(ne,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(ne=>r.jsxs("span",{style:{fontSize:"0.7rem",padding:"2px 8px",borderRadius:12,background:ne.color+"22",color:ne.color,border:`1px solid ${ne.color}44`,cursor:"pointer"},children:[r.jsx(Ca,{icon:ne.icon,size:10}),ne.icon?" ":"",ne.name]},ne.id))})]}),r.jsxs("div",{style:oe,children:[r.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":Q,onKeyDown:ve.clickOnActivationKey,style:{display:"flex",alignItems:"center",justifyContent:"space-between",cursor:"pointer",fontSize:"0.7rem",fontWeight:600,opacity:.6},onClick:()=>w(!Q),children:[r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.NtdLink,{size:12})," ",f("playlistManager.services","Services")]}),Q?r.jsx(B.NtdChevronUp,{size:12}):r.jsx(B.NtdChevronDown,{size:12})]}),Q&&r.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[Zt.Spotify,Zt.Tidal,Zt.YouTube].map(ne=>{const pe=im[ne],fe=a.find(ge=>ge.platform===ne);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(B.NtdCircle,{size:10,style:{color:pe.color}}),r.jsx("span",{style:{flex:1},children:pe.label}),fe!=null&&fe.connected?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{fontSize:"0.65rem",opacity:.6},children:fe.username??f("playlistManager.connected","Connected")}),r.jsx("button",{style:{...z,color:"var(--nice-danger, #ef4444)"},onClick:()=>y(ne),"aria-label":f("playlistManager.disconnect","Disconnect"),children:r.jsx(B.NtdClose,{size:12})})]}):r.jsx("button",{style:{...z,background:pe.color,color:"var(--nice-color-white, #fff)",borderRadius:4,padding:"2px 8px"},onClick:()=>g(ne),children:f("playlistManager.connect","Connect")})]},ne)})})]})]})},lm=({playlist:e,tags:t,onPlay:n,selectedTrackIds:a,onSelectionChange:s})=>{const{t:i}=xe(),o=d.useCallback(l=>{const c=new Set(a);c.has(l)?c.delete(l):c.add(l),s(c)},[a,s]);return e.tracks.length===0?r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:60,opacity:.3},children:[r.jsx("span",{style:{marginBottom:8,display:"inline-flex"},children:r.jsx(B.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",{role:"button",tabIndex:0,"aria-pressed":c,onKeyDown:ve.clickOnActivationKey,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(B.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)})})},cm=d.memo(lm),hi=e=>e.replace(/[^a-z0-9_-]/gi,"-"),pi={background:"none",border:"none",cursor:"pointer",fontSize:"0.78rem",padding:"2px 4px",opacity:.4},dm=({playlists:e,folders:t,tags:n,activeFolderId:a,onSelectPlaylist:s,onDeletePlaylist:i,onDuplicatePlaylist:o})=>{const{t:l}=xe(),c=d.useMemo(()=>a?e.filter(u=>u.folderId===a):e,[e,a]);return c.length===0?r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:60,opacity:.4},children:[r.jsx("span",{style:{marginBottom:12,display:"inline-flex"},children:r.jsx(B.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(u=>{var p;const h=t.find(g=>g.id===u.folderId);return r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,onClick:()=>s(u.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:u.type===ns.Dynamic?r.jsx(B.NtdLightning,{size:40}):r.jsx(B.NtdMusic,{size:40})}),r.jsx("div",{style:{fontWeight:600,fontSize:"0.85rem",marginBottom:2},children:u.name}),r.jsxs("div",{style:{fontSize:"0.72rem",opacity:.5},children:[u.trackCount," ",l("playlistManager.tracks","tracks"),h&&r.jsxs(r.Fragment,{children:[" — ",r.jsx(B.NtdFolder,{size:11})," ",h.name]})]}),((p=u.tags)==null?void 0:p.length)>0&&r.jsx("div",{style:{display:"flex",gap:4,marginTop:6,flexWrap:"wrap"},children:u.tags.slice(0,3).map(g=>{const y=n.find(m=>m.id===g);return y?r.jsx("span",{style:{padding:"1px 8px",borderRadius:12,background:`var(--tag-${hi(g)}-bg, ${y.color}18)`,color:`var(--tag-${hi(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(u.id)},style:pi,title:l("playlistManager.duplicate","Duplicate"),"aria-label":l("playlistManager.duplicate","Duplicate"),children:r.jsx(B.NtdCopy,{size:14})}),r.jsx("button",{onClick:g=>{g.stopPropagation(),i(u.id)},style:pi,title:l("playlistManager.delete","Delete"),"aria-label":l("playlistManager.delete","Delete"),children:r.jsx(B.NtdTrash,{size:14})})]})]},u.id)})})},um=d.memo(dm),fi=[{value:bt.Library,label:"Library",hex:"var(--nice-info, #6366f1)",css:"var(--source-library, #6366f1)",cssBg:"var(--source-library-bg, #6366f118)"},{value:bt.Spotify,label:"Spotify",hex:"var(--nice-success, #1db954)",css:"var(--source-spotify, #1db954)",cssBg:"var(--source-spotify-bg, #1db95418)"},{value:bt.Tidal,label:"Tidal",hex:"var(--nice-text, #000000)",css:"var(--source-tidal, #000000)",cssBg:"var(--source-tidal-bg, #00000018)"},{value:bt.YouTube,label:"YouTube",hex:"var(--nice-danger, #ff0000)",css:"var(--source-youtube, #ff0000)",cssBg:"var(--source-youtube-bg, #ff000018)"},{value:bt.MusicBrainz,label:"MusicBrainz",hex:"var(--source-musicbrainz, #ba478f)",css:"var(--source-musicbrainz, #ba478f)",cssBg:"var(--source-musicbrainz-bg, #ba478f18)"}],hm=({onSearch:e,results:t,isSearching:n,onAddToPlaylist:a,onPlayPreview:s})=>{const{t:i}=xe(),[o,l]=d.useState(""),[c,u]=d.useState(new Set([bt.Library,bt.Spotify,bt.Tidal,bt.YouTube])),[h,p]=d.useState(new Set),[g,y]=d.useState(!1),m=d.useRef(null),x=d.useCallback(k=>{u(R=>{const P=new Set(R);return P.has(k)?P.delete(k):P.add(k),P})},[]),b=d.useCallback(k=>{l(k),m.current&&clearTimeout(m.current),k.trim().length>=2&&(m.current=setTimeout(()=>{e(k.trim(),Array.from(c))},350))},[c,e]),f=d.useCallback(k=>{k.preventDefault(),o.trim().length>=2&&e(o.trim(),Array.from(c))},[o,c,e]),j=d.useCallback(k=>{p(R=>{const P=new Set(R);return P.has(k)?P.delete(k):P.add(k),P})},[]),v=d.useCallback(()=>{h.size===t.length?p(new Set):p(new Set(t.map(k=>k.id)))},[h,t]),C=d.useCallback(()=>{const k=t.filter(R=>h.has(R.id));k.length>0&&(a(k),p(new Set))},[t,h,a]),T=k=>{if(!k)return"--:--";const R=Math.floor(k/60),P=k%60;return`${R}:${P.toString().padStart(2,"0")}`},M=k=>{const R=fi.find(P=>P.value===k);return r.jsx(B.NtdCircle,{size:10,style:{color:R?R.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",{role:"button",tabIndex:0,"aria-expanded":g,onKeyDown:ve.clickOnActivationKey,style:{display:"flex",alignItems:"center",padding:"8px 12px",gap:8,cursor:"pointer",background:"var(--nice-color-surface, #f9fafb)"},onClick:()=>y(!g),children:[r.jsx(B.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(B.NtdChevronUp,{size:12}):r.jsx(B.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:fi.map(k=>{const R=c.has(k.value);return r.jsxs("button",{onClick:()=>x(k.value),style:{padding:"4px 10px",borderRadius:20,border:R?`2px solid ${k.css}`:"1px solid var(--nice-border-color, #d1d5db)",background:R?k.cssBg:"transparent",color:R?k.css:"var(--nice-text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:R?600:400,transition:"all 0.15s"},children:[r.jsx(B.NtdCircle,{size:8,style:{color:k.css}})," ",k.label]},k.value)})}),r.jsxs("form",{onSubmit:f,style:{display:"flex",gap:6,marginBottom:8},children:[r.jsx("input",{type:"text",value:o,onChange:k=>b(k.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(B.NtdClock,{size:14}):r.jsx(B.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:v}),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:C,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(B.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(k=>r.jsxs("div",{role:"button",tabIndex:0,"aria-pressed":h.has(k.id),onKeyDown:ve.clickOnActivationKey,style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:"1px solid var(--nice-border-color, #f3f4f6)",background:h.has(k.id)?"var(--nice-accent-tint-10, #eff6ff)":"transparent",cursor:"pointer",fontSize:"0.78rem"},onClick:()=>j(k.id),children:[r.jsx("input",{type:"checkbox",checked:h.has(k.id),readOnly:!0}),M(k.source),k.imageUrl&&r.jsx("img",{src:k.imageUrl,alt:k.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:k.title}),r.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[k.artist,k.album?` — ${k.album}`:""]})]}),r.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:T(k.duration)}),s&&r.jsx("button",{onClick:R=>{R.stopPropagation(),s(k)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem"},title:i("playlistManager.preview","Preview"),"aria-label":i("playlistManager.preview","Preview"),children:r.jsx(B.NtdPlay,{size:14})})]},k.id))})]}),n&&r.jsxs("div",{style:{textAlign:"center",padding:20,opacity:.5,fontSize:"0.82rem"},children:[r.jsx(B.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")})]})]})},pm=[{value:1,label:"Spotify",icon:r.jsx(B.NtdMusic,{size:16}),color:"var(--source-spotify, #1db954)"},{value:2,label:"Tidal",icon:r.jsx(B.NtdMusic,{size:16}),color:"var(--source-tidal, #000000)"},{value:3,label:"Apple Music",icon:r.jsx(B.NtdMusic,{size:16}),color:"var(--source-apple, #fa243c)"},{value:4,label:"YouTube",icon:r.jsx(B.NtdMusic,{size:16}),color:"var(--source-youtube, #ff0000)"},{value:99,label:"Manual Paste",icon:r.jsx(B.NtdMusic,{size:16}),color:"var(--source-manual, #6366f1)"}],fm={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},mm={display:"flex",justifyContent:"space-between",alignItems:"center"},gm={display:"flex",gap:4,marginBottom:8},Dn={padding:"8px 20px",borderRadius:6,border:"none",background:"var(--nice-color-accent, #6366f1)",color:"var(--nice-text-on-primary, #fff)",cursor:"pointer",fontWeight:600},lr=(function(){return{...Dn,background:"transparent",color:"var(--nice-text-primary, #334155)",border:"1px solid var(--nice-border, #e2e8f0)"}})(),mi={padding:12,borderRadius:8,border:"1px solid var(--nice-border, #e2e8f0)",cursor:"pointer",transition:"border-color 0.15s"},Pl=["connect","browse","tracks","options","importing","done"];function ym(e){return Pl.indexOf(e)}function vm(e){if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const bm=({connections:e=[],onConnect:t=()=>{},onDisconnect:n=()=>{},onFetchPlaylists:a=async()=>[],onFetchTracks:s=async()=>[],onImport:i=async()=>({playlistName:"",imported:0,skipped:0,failed:0,failedTracks:[]}),onClose:o=()=>{},targetFolders:l,sources:c})=>{const{t:u}=xe(),[h,p]=d.useState("connect"),[g,y]=d.useState(null),[m,x]=d.useState([]),[b,f]=d.useState(null),[j,v]=d.useState([]),[C,T]=d.useState(new Set),[M,k]=d.useState(!1),[R,P]=d.useState(null),[I,A]=d.useState(null),[L,E]=d.useState(null),[D,Z]=d.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[G,F]=d.useState(""),q=d.useMemo(()=>new Set(e.filter(z=>z.connected).map(z=>z.platform)),[e]),V=d.useCallback(z=>e.find(ee=>ee.platform===z),[e]),K=d.useCallback(z=>{if(y(z),z===99){p("tracks"),F(""),v([]),k(!1);return}q.has(z)?(p("browse"),k(!0),E(null),a(z).then(ee=>{x(ee),k(!1)}).catch(ee=>{E(String(ee)),k(!1)})):t(z)},[q,t,a]),W=d.useCallback(z=>{f(z),p("tracks"),k(!0),E(null),s(z).then(ee=>{v(ee),T(new Set(ee.map(ae=>ae.externalId))),k(!1)}).catch(ee=>{E(String(ee)),k(!1)})},[s]),Q=d.useCallback(z=>{T(ee=>{const ae=new Set(ee);return ae.has(z)?ae.delete(z):ae.add(z),ae})},[]),w=d.useCallback(()=>{T(z=>z.size===j.length?new Set:new Set(j.map(ee=>ee.externalId)))},[j]),N=d.useCallback(async()=>{if(!b)return;const z=j.filter(ee=>C.has(ee.externalId));if(z.length!==0){p("importing"),P({total:z.length,imported:0,skipped:0,failed:0}),E(null);try{const ee=await i(b,z,D),ae=ee&&typeof ee=="object"&&"imported"in ee?ee:{playlistName:b.name,imported:z.length,skipped:0,failed:0,failedTracks:[]};A(ae),p("done")}catch(ee){E(String(ee)),p("options")}}},[b,j,C,D,i]),S=h!=="connect"&&h!=="importing"&&h!=="done",O=d.useCallback(()=>{switch(h){case"browse":p("connect");break;case"tracks":p("browse");break;case"options":p("tracks");break}},[h]),Y=()=>r.jsx("div",{style:gm,children:Pl.map((z,ee)=>r.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:ee<=ym(h)?"var(--nice-color-accent, #6366f1)":"var(--nice-border, #e2e8f0)",transition:"background 0.2s"}},z))}),_=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[r.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.selectPlatform","Select a music platform to import from")}),pm.map(z=>{const ee=V(z.value),ae=q.has(z.value);return r.jsxs("div",{style:{...mi,display:"flex",alignItems:"center",gap:12,borderColor:ae?z.color:void 0},onClick:()=>K(z.value),role:"button",tabIndex:0,onKeyDown:ce=>ce.key==="Enter"&&K(z.value),children:[r.jsx("span",{style:{color:z.color,display:"inline-flex"},"aria-hidden":"true",children:z.icon}),r.jsxs("div",{style:{flex:1},children:[r.jsx("strong",{children:z.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:z.color,fontSize:12,fontWeight:600},children:[u("importWizard.connected","Connected")," ",r.jsx(B.NtdCheck,{size:12})]}):r.jsx("span",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.clickToConnect","Click to connect")})]},z.value)})]}),U=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[r.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.selectPlaylist","Select a playlist to import")}),M?r.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.loading","Loading playlists…")}):r.jsxs("div",{style:{display:"grid",gap:8,maxHeight:320,overflowY:"auto"},children:[m.map(z=>r.jsxs("div",{style:{...mi,display:"flex",alignItems:"center",gap:12},onClick:()=>W(z),role:"button",tabIndex:0,onKeyDown:ee=>ee.key==="Enter"&&W(z),children:[z.coverUrl&&r.jsx("img",{src:z.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:z.name}),z.description&&r.jsx("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:z.description})]}),r.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)",whiteSpace:"nowrap"},children:[z.trackCount," ",u("importWizard.tracks","tracks")]})]},z.id)),m.length===0&&r.jsx("div",{style:{textAlign:"center",padding:24,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.noPlaylists","No playlists found")})]})]}),$=d.useCallback(z=>{const ae=z.split(`
|
|
69
69
|
`).map(ce=>ce.trim()).filter(Boolean).map((ce,le)=>{const ne=ce.match(/^(.+?)\s*[-–—]\s*(.+)$/);return ne?{externalId:`paste-${le}`,title:ne[2].trim(),artist:ne[1].trim(),album:void 0,duration:0}:{externalId:`paste-${le}`,title:ce,artist:"",album:void 0,duration:0}});v(ae),T(new Set(ae.map(ce=>ce.externalId)))},[]),H=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[g===99&&j.length===0&&r.jsxs("div",{style:{display:"grid",gap:8},children:[r.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.pasteInstructions",'Paste your track list below (one track per line). Use "Artist - Title" format for best results.')}),r.jsx("textarea",{value:G,onChange:z=>F(z.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"}}),r.jsx("button",{style:{...Dn,opacity:G.trim().length===0?.5:1},disabled:G.trim().length===0,onClick:()=>$(G),type:"button",children:u("importWizard.parseTracks","Parse Tracks")})]}),(g!==99||j.length>0)&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[r.jsxs("p",{style:{margin:0,fontWeight:600},children:[b==null?void 0:b.name," — ",C.size,"/",j.length," ",u("importWizard.selected","selected")]}),r.jsx("button",{style:or,onClick:w,type:"button",children:C.size===j.length?u("importWizard.deselectAll","Deselect All"):u("importWizard.selectAll","Select All")})]}),M?r.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.loadingTracks","Loading tracks…")}):r.jsx("div",{style:{maxHeight:320,overflowY:"auto"},children:r.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[r.jsx("thead",{children:r.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-border, #e2e8f0)",textAlign:"left"},children:[r.jsx("th",{style:{padding:"4px 8px",width:32}}),r.jsx("th",{style:{padding:"4px 8px"},children:u("importWizard.colTitle","Title")}),r.jsx("th",{style:{padding:"4px 8px"},children:u("importWizard.artist","Artist")}),r.jsx("th",{style:{padding:"4px 8px"},children:u("importWizard.album","Album")}),r.jsx("th",{style:{padding:"4px 8px",textAlign:"right"},children:u("importWizard.duration","Duration")})]})}),r.jsx("tbody",{children:j.map(z=>{const ee=C.has(z.externalId);return r.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-border, #e2e8f0)",opacity:ee?1:.5,cursor:"pointer"},onClick:()=>Q(z.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:z.title}),r.jsx("td",{style:{padding:"6px 8px",color:"var(--nice-text-dim, #64748b)"},children:z.artist}),r.jsx("td",{style:{padding:"6px 8px",color:"var(--nice-text-dim, #64748b)"},children:z.album??"—"}),r.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--nice-text-dim, #64748b)"},children:ym(z.duration)})]},z.externalId)})})]})}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:r.jsxs("button",{style:{...Dn,opacity:C.size===0?.5:1},disabled:C.size===0,onClick:()=>p("options"),type:"button",children:[u("importWizard.next","Next")," ",r.jsx(B.NtdArrowRight,{size:12})]})})]})]}),X=()=>r.jsxs("div",{style:{display:"grid",gap:16},children:[r.jsx("p",{style:{margin:0,fontWeight:600},children:u("importWizard.importOptions","Import options")}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:D.mergeTags,onChange:z=>Z(ee=>({...ee,mergeTags:z.target.checked}))}),u("importWizard.mergeTags","Merge tags from source playlist")]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:D.mergeFolders,onChange:z=>Z(ee=>({...ee,mergeFolders:z.target.checked}))}),u("importWizard.mergeFolders","Merge into existing folder structure")]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:D.overwriteExisting,onChange:z=>Z(ee=>({...ee,overwriteExisting:z.target.checked}))}),u("importWizard.overwrite","Overwrite existing tracks (match by ISRC)")]}),l&&l.length>0&&r.jsxs("div",{style:{display:"grid",gap:4},children:[r.jsx("label",{style:{fontSize:13,fontWeight:500},children:u("importWizard.targetFolder","Target folder")}),r.jsxs("select",{style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #e2e8f0)"},value:D.targetFolderId??"",onChange:z=>Z(ee=>({...ee,targetFolderId:z.target.value||void 0})),children:[r.jsx("option",{value:"",children:u("importWizard.root","— Root —")}),l.map(z=>r.jsx("option",{value:z.id,children:z.name},z.id))]})]}),r.jsx("div",{style:{marginTop:8,padding:12,borderRadius:8,background:"var(--nice-info-bg, #eff6ff)",fontSize:13},children:u("importWizard.summary",'Ready to import {count} tracks from "{name}"').replace("{count}",String(C.size)).replace("{name}",(b==null?void 0:b.name)??"")}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[r.jsxs("button",{style:or,onClick:O,type:"button",children:[r.jsx(B.NtdArrowLeft,{size:12})," ",u("importWizard.back","Back")]}),r.jsx("button",{style:Dn,onClick:N,type:"button",children:u("importWizard.startImport","Start Import")})]})]}),re=()=>{const z=R?Math.round(R.imported/R.total*100):0;return r.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[r.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:u("importWizard.importing","Importing…")}),r.jsx("div",{style:{height:8,borderRadius:4,background:"var(--nice-border, #e2e8f0)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${z}%`,background:"var(--nice-color-accent, #6366f1)",borderRadius:4,transition:"width 0.3s"}})}),R&&r.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-dim, #64748b)"},children:[R.imported," / ",R.total," ",u("importWizard.tracks","tracks"),R.currentTrack&&r.jsxs("div",{style:{marginTop:4},children:[r.jsx(B.NtdMusic,{size:12})," ",R.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(B.NtdCheck,{size:48})}),r.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:u("importWizard.complete","Import Complete")}),I&&r.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[r.jsxs("div",{children:[r.jsx("strong",{children:I.imported})," ",u("importWizard.imported","imported")]}),I.skipped>0&&r.jsxs("div",{style:{color:"var(--nice-color-warning, #f59e0b)"},children:[I.skipped," ",u("importWizard.skipped","skipped (duplicates)")]}),I.failed>0&&r.jsxs("div",{style:{color:"var(--nice-color-error, #ef4444)"},children:[I.failed," ",u("importWizard.failed","failed")]}),I.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:u("importWizard.showFailed","Show failed tracks")}),r.jsx("ul",{style:{marginTop:4,paddingLeft:20},children:I.failedTracks.map((z,ee)=>r.jsx("li",{children:z},ee))})]})]}),r.jsx("button",{style:Dn,onClick:o,type:"button",children:u("importWizard.done","Done")})]}),se={connect:u("importWizard.stepConnect","Connect"),browse:u("importWizard.stepBrowse","Browse"),tracks:u("importWizard.stepTracks","Select Tracks"),options:u("importWizard.stepOptions","Options"),importing:u("importWizard.stepImporting","Importing"),done:u("importWizard.stepDone","Done")};return r.jsxs("div",{style:pm,children:[Y(),r.jsxs("div",{style:fm,children:[r.jsxs("h2",{style:{margin:0,fontSize:18},children:[u("importWizard.title","Import Playlist")," — ",se[h]]}),S&&r.jsxs("button",{style:or,onClick:O,type:"button",children:[r.jsx(B.NtdArrowLeft,{size:12})," ",u("importWizard.back","Back")]}),h==="connect"&&r.jsx("button",{style:or,onClick:o,type:"button","aria-label":u("importWizard.close","Close"),title:u("importWizard.close","Close"),children:r.jsx(B.NtdClose,{size:14})})]}),L&&r.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--nice-error-bg, #fef2f2)",color:"var(--nice-color-error, #ef4444)",fontSize:13},children:L}),h==="connect"&&_(),h==="browse"&&U(),h==="tracks"&&H(),h==="options"&&X(),h==="importing"&&re(),h==="done"&&oe()]})},bm=[{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}],xm="concert-harp",as=Object.fromEntries(bm.map(e=>[e.id,e])),Sm="nice2dev-note-sound-set";function Pl(){try{const e=localStorage.getItem(Sm);if(e&&as[e])return e}catch{}return xm}const _r=["quarter","eighth","sixteenth","beamed"];function El(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,u=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;u(h),u(p),c.rect(h+a-i,l-o,p-h+i,n*.12)}else{const h=-a*.5;u(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 mi(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 ia(e,t){const n=$l(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function km(e){const t=$l(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function Al(){const e=mi("--text-primary")||ve.resolveCssColor("var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))"),t=mi("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",s=km(e)<.45;return{base:ia(e,.92),staffLine:ia(e,.22),outline:ve.resolveCssColor(s?"var(--nice-overlay-light-75, rgba(255, 255, 255, 0.75))":"var(--nice-overlay-55, rgba(0, 0, 0, 0.55))"),accents:[ia(t,.95)],isDark:n,notesDark:s}}const Ur=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),Il=46,St=5,yr=4,wm=(Il-(St-1)*yr)/2,Cm=6,jm=18,Mm=110,Rm=50,Vr=Ur?Rm:Mm,Nm=Ur?4:2,Tm=Ur?2:4,gi=Ur?1:0,Pm=180,yi=2.8,vi=40,Em=14,bi=1.2,$m=16,oa=[64,67,71,74,77],cn=64,zn=77;function Am(e){const t=Math.max(0,Math.min(St-1,e)),n=Math.floor(t),a=Math.min(n+1,St-1),s=t-n;return Math.round(oa[n]+(oa[a]-oa[n])*s)}function Im(e){return(Math.max(cn-1*(zn-cn)/(St-1),Math.min(zn+1*(zn-cn)/(St-1),e))-cn)/(zn-cn)*(St-1)}const xi=2.5,Si=.72,Lm=.55,Fn=new Map;let vr=null;async function _m(e){const t=e??Pl(),n=as[t];if(!n||!n.dir){Fn.clear(),vr=t;return}if(vr===t&&Fn.size>0)return;Fn.clear(),vr=t;const a=Yn(),s=[];for(let i=cn;i<=zn;i++)s.push(fetch(`/assets/soundfonts/notes/${n.dir}/note-${i}.mp3`).then(o=>o.arrayBuffer()).then(o=>a.decodeAudioData(o)).then(o=>{Fn.set(i,o)}).catch(()=>{}));await Promise.all(s)}function ki(e){const t=Fn.get(e);if(!t)return;const n=Yn(),a=n.createBufferSource();a.buffer=t;const s=n.createGain();s.gain.value=.7,a.connect(s).connect(n.destination),a.start()}function Dm(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 zm(e){const t=Dm(42),n=[];for(let a=0;a<e;a++){const i=t()<.15?0:-1;n.push({x:t(),lineIdx:t()*(St+1)-.5,shape:_r[Math.floor(t()*_r.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:i})}return n.sort((a,s)=>a.x-s.x),n}const ut=zm(Vr),Mn=new Float32Array(Vr),lr=new Float32Array(Vr),On=new Float32Array(Vr);let ja=!1;const Fm=(St-1)/2;function Om(){if(!ja){ja=!0;for(let e=0;e<ut.length;e++)On[e]=ut[e].lineIdx}}let Ma=[],wi="";function Bm(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function Gm(e){const t=Bm(e);t===wi&&Ma.length===ut.length||(wi=t,Ma=ut.map(n=>{const a=Math.ceil(n.size*1.6),s=a*2,i=document.createElement("canvas");i.width=s,i.height=s;const o=i.getContext("2d");return o.translate(a,a),o.rotate(n.rot*Math.PI/180),o.lineWidth=1.8,o.strokeStyle=e.outline,o.fillStyle=n.colorIdx<0?e.base:e.accents[n.colorIdx%e.accents.length],El(o,n.shape,n.size*1.3),{canvas:i,ox:a,oy:a}}))}function Wm({pitchMidiRef:e}={}){const{t}=xe(),n=d.useRef(null),a=d.useRef(0),s=d.useRef(0),i=d.useRef(0),o=d.useRef(null),l=d.useRef(0),c=d.useRef(0),u=d.useRef(null),h=d.useRef(null),p=d.useRef(!1),g=d.useCallback((b,f,j)=>{const v=wm+b*yr,C=f/j*Math.PI*2;return v+Math.sin(C)*Cm},[]),y=d.useCallback(b=>{const f=n.current;if(!f)return;if(c.current++,gi>0&&c.current%(gi+1)!==0){i.current=b,a.current=requestAnimationFrame(y);return}const j=f.getContext("2d");if(!j)return;const v=Math.min(window.devicePixelRatio||1,Tm),C=f.getBoundingClientRect(),T=C.width,M=C.height;(f.width!==Math.round(T*v)||f.height!==Math.round(M*v))&&(f.width=Math.round(T*v),f.height=Math.round(M*v),j.setTransform(v,0,0,v,0,0));const k=i.current?(b-i.current)/1e3:0;i.current=b,s.current=(s.current+jm*k)%T,j.clearRect(0,0,T,M),l.current++,(!o.current||l.current%60===0)&&(o.current=Al());const R=o.current;Gm(R),j.strokeStyle=R.staffLine,j.lineWidth=.7;for(let L=0;L<St;L++){j.beginPath();for(let E=0;E<=T;E+=Nm){const D=g(L,E,T);E===0?j.moveTo(E,D):j.lineTo(E,D)}j.stroke()}const P=s.current,I=(e==null?void 0:e.current)??null;if(I!==null){Om();const L=Im(I),E=xi*k;for(let D=0;D<ut.length;D++){const G=(ut[D].lineIdx-Fm)*Lm,q=L*Si+(L+G)*(1-Si)-On[D];On[D]+=q>0?Math.min(E,q):Math.max(-E,q)}}else if(ja){const L=xi*.4*k;for(let E=0;E<ut.length;E++){const Z=ut[E].lineIdx-On[E];On[E]+=Z>0?Math.min(L,Z):Math.max(-L,Z)}}const A=u.current;A&&(A.timer-=k,A.timer<=0&&(u.current=null));for(let L=0;L<ut.length;L++){const E=ut[L];if(lr[L]>0){lr[L]-=k;const G=Math.max(0,lr[L]/yi);Mn[L]+=Pm*G*k,Mn[L]>T&&(Mn[L]-=T)}const D=Ma[L];if(!D)continue;const Z=E.lineIdx;for(let G=0;G<2;G++){let q=((E.x*T-P-Mn[L]+G*T)%T+T)%T;const V=g(Math.max(0,Math.min(St-1,Math.round(Z))),q,T),K=(Z-Math.round(Z))*yr;let W=V+K;if(A&&A.timer>0){const Q=q-A.x,w=W-A.y,N=Math.sqrt(Q*Q+w*w);if(N<vi&&N>.1){const S=A.timer/bi,O=Em*(1-N/vi)*S;q+=Q/N*O,W+=w/N*O}}j.drawImage(D.canvas,q-D.ox,W-D.oy)}}a.current=requestAnimationFrame(y)},[g,e]),m=d.useCallback(b=>{const f=n.current;if(!f)return;const j=f.getBoundingClientRect(),v=b.clientX-j.left,C=b.clientY-j.top,T=j.width,M=s.current;let k=1/0,R=-1;for(let P=0;P<ut.length;P++){const I=ut[P],L=((I.x*T-M-Mn[P])%T+T)%T,E=g(Math.max(0,Math.min(St-1,Math.round(I.lineIdx))),L,T),D=(I.lineIdx-Math.round(I.lineIdx))*yr,Z=E+D,G=L-v,F=Z-C,q=G*G+F*F;q<k&&(k=q,R=P)}if(R>=0&&Math.sqrt(k)<$m){lr[R]=yi;const P=ut[R],I=Am(P.lineIdx);try{Xt();const A=Pl(),L=as[A];L!=null&&L.dir&&(vr!==A||!p.current?(p.current=!0,_m(A).then(()=>ki(I))):ki(I))}catch{}}u.current={x:v,y:C,timer:bi}},[g]),x=d.useCallback(b=>{const f=n.current;if(!f)return;const j=f.getBoundingClientRect(),v=b.clientX-j.left,C=b.clientY-j.top;h.current={x:v,y:C},u.current&&u.current.timer>0&&(u.current.x=v,u.current.y=C)},[]);return d.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:Il,marginBottom:5,cursor:"pointer",background:"transparent"}})}const Um=14,Vm=.9,qm=320,Hm=160,Km=6,Ci=8,Ym=14;function Zm(){const{t:e}=xe(),t=d.useRef(null),n=d.useRef([]),a=d.useRef(0),s=d.useRef(0),i=d.useRef([]),o=d.useRef(null),l=d.useRef(0),c=d.useCallback((h,p)=>{for(let g=0;g<Um;g++){const y=Math.random()*Math.PI*2,m=Hm*(.4+Math.random()*.6),x=Vm*(.6+Math.random()*.4),b=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)*Km*2,size:Ci+Math.random()*(Ym-Ci),shape:_r[Math.floor(Math.random()*_r.length)],life:x,maxLife:x,colorIdx:b})}},[]),u=d.useCallback(h=>{const p=t.current;if(!p){a.current=requestAnimationFrame(u);return}const g=p.getContext("2d");if(!g){a.current=requestAnimationFrame(u);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 b=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=Al());const f=o.current;{const v=ve.getInputEngine().gamepadSnapshot;for(let C=0;C<v.length;C++){const T=v[C];for(let M=0;M<T.buttons.length;M++){const k=T.index*100+M,R=T.buttons[M].pressed;R&&!i.current[k]&&c(m/2,x/2),i.current[k]=R}}}const j=[];for(const v of n.current){if(v.life-=b,v.life<=0)continue;v.vy+=qm*b,v.x+=v.vx*b,v.y+=v.vy*b,v.rot+=v.vr*b;const C=Math.max(0,v.life/v.maxLife),T=.5+.5*C;g.save(),g.globalAlpha=C,g.translate(v.x,v.y),g.rotate(v.rot),g.lineWidth=1.4,g.strokeStyle=f.notesDark?`rgba(255,255,255,${C*.8})`:`rgba(0,0,0,${C*.55})`;const M=v.colorIdx<0?f.base:f.accents[v.colorIdx%f.accents.length];g.fillStyle=M.replace(/[\d.]+\)$/,`${C})`),El(g,v.shape,v.size*T*1.3),g.restore(),j.push(v)}n.current=j,a.current=requestAnimationFrame(u)},[c]);return d.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(u),()=>{window.removeEventListener("click",h,!0),window.removeEventListener("keydown",p,!0),cancelAnimationFrame(a.current)}},[u,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 br={type:"gain",enabled:!0,mix:1,gain:0},Bn={type:"compressor",enabled:!0,mix:1,threshold:-24,ratio:4,attack:10,release:100,knee:6,makeupGain:0},Gn={type:"reverb",enabled:!0,mix:.3,decay:2,preDelay:10,damping:.5,roomSize:.5},Wn={type:"delay",enabled:!0,mix:.3,time:250,feedback:.4,pingPong:!1,highCut:8e3},xr={type:"chorus",enabled:!0,mix:.5,rate:1.5,depth:.5,delay:7,voices:3},Sr={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"}]},kr={type:"filter",enabled:!0,mix:1,filterType:"lowpass",frequency:1e3,q:1,gain:0},wr={type:"distortion",enabled:!0,mix:.5,drive:.5,tone:.5,curve:"soft"},Cr={type:"tremolo",enabled:!0,mix:1,rate:5,depth:.5,waveform:"sine"},jr={type:"phaser",enabled:!0,mix:.5,rate:.5,depth:.5,feedback:.5,stages:4,frequency:1e3},Xm=(function(){return{gain:{unity:{...br,gain:0},boost:{...br,gain:6},cut:{...br,gain:-6}},compressor:{gentle:{...Bn,threshold:-20,ratio:2,attack:30,release:200},moderate:{...Bn,threshold:-24,ratio:4,attack:10,release:100},aggressive:{...Bn,threshold:-30,ratio:8,attack:1,release:50},limiter:{...Bn,threshold:-3,ratio:20,attack:.1,release:100}},reverb:{small_room:{...Gn,decay:.5,roomSize:.2,damping:.7},large_hall:{...Gn,decay:3,roomSize:.8,damping:.3},plate:{...Gn,decay:1.5,roomSize:.5,damping:.4},cathedral:{...Gn,decay:5,roomSize:.9,damping:.2,mix:.4}},delay:{slapback:{...Wn,time:80,feedback:.1,mix:.3},quarter_note:{...Wn,time:500,feedback:.4,mix:.3},dotted_eighth:{...Wn,time:375,feedback:.5,mix:.3},long_ambient:{...Wn,time:750,feedback:.6,highCut:3e3,mix:.4}},chorus:{subtle:{...xr,rate:.5,depth:.2,voices:2,mix:.3},vintage:{...xr,rate:1,depth:.4,voices:2,delay:10,mix:.4},ensemble:{...xr,rate:2,depth:.6,voices:4,mix:.5}},eq:{vocal_presence:{...Sr,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:{...Sr,bands:[{frequency:60,gain:6,q:1,type:"lowshelf"},{frequency:200,gain:2,q:1,type:"peaking"}]},brightness:{...Sr,bands:[{frequency:4e3,gain:3,q:1,type:"peaking"},{frequency:1e4,gain:4,q:1,type:"highshelf"}]}},filter:{low_pass_warm:{...kr,filterType:"lowpass",frequency:2e3,q:.7},high_pass_clean:{...kr,filterType:"highpass",frequency:100,q:.7},telephone:{...kr,filterType:"bandpass",frequency:1500,q:2}},distortion:{overdrive:{...wr,drive:.3,tone:.6,curve:"soft",mix:.7},crunch:{...wr,drive:.5,tone:.5,curve:"tube",mix:.8},fuzz:{...wr,drive:.8,tone:.4,curve:"fuzz",mix:1}},tremolo:{slow:{...Cr,rate:3,depth:.4,waveform:"sine"},fast:{...Cr,rate:8,depth:.6,waveform:"sine"},choppy:{...Cr,rate:6,depth:.9,waveform:"square"}},phaser:{subtle:{...jr,rate:.3,depth:.3,feedback:.3,stages:4},jet:{...jr,rate:.1,depth:.8,feedback:.7,stages:8},rotary:{...jr,rate:1,depth:.5,feedback:.4,stages:6}}}})();function ji(e){return Math.pow(10,e/20)}function Qm(e,t,n,a){const s=e.sampleRate,i=Math.floor(s*t),o=e.createBuffer(2,i,s);for(let l=0;l<2;l++){const c=o.getChannelData(l);for(let u=0;u<i;u++){const h=u/s,p=Math.exp(-h/n),g=1-a*(u/i);c[u]=(Math.random()*2-1)*p*g}}return o}function Jm(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 e0{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=ji(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=ji(n.makeupGain),l.connect(c),s.push(l,c),i=l,o=c;break}case"reverb":{const l=a.createConvolver();l.buffer=Qm(a,n.decay,n.decay,n.damping);const c=a.createGain(),u=a.createGain(),h=a.createGain(),p=a.createGain();c.gain.value=n.mix,u.gain.value=1-n.mix,h.connect(l),h.connect(u),l.connect(c),c.connect(p),u.connect(p),s.push(h,l,c,u,p),i=h,o=p;break}case"delay":{const l=a.createDelay(5);l.delayTime.value=n.time/1e3;const c=a.createGain();c.gain.value=n.feedback;const u=a.createBiquadFilter();u.type="lowpass",u.frequency.value=n.highCut;const h=a.createGain(),p=a.createGain(),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(u),u.connect(c),c.connect(l),u.connect(h),h.connect(y),p.connect(y),s.push(g,l,u,c,h,p,y),i=g,o=y;break}case"eq":{const l=[];let c=null;for(const u of n.bands){const h=a.createBiquadFilter();h.type=u.type,h.frequency.value=u.frequency,h.Q.value=u.q,h.gain.value=u.gain,c&&c.connect(h),c=h,l.push(h)}s.push(...l),i=l[0]||a.createGain(),o=l[l.length-1]||i;break}case"filter":{const l=a.createBiquadFilter();l.type=n.filterType,l.frequency.value=n.frequency,l.Q.value=n.q,l.gain.value=n.gain,s.push(l),i=o=l;break}case"distortion":{const l=a.createWaveShaper();l.curve=Jm(n.drive,n.curve),l.oversample="4x";const c=a.createBiquadFilter();c.type="lowpass",c.frequency.value=1e3+n.tone*1e4;const u=a.createGain(),h=a.createGain(),p=a.createGain(),g=a.createGain();u.gain.value=n.mix,h.gain.value=1-n.mix,p.connect(l),p.connect(h),l.connect(c),c.connect(u),u.connect(g),h.connect(g),s.push(p,l,c,u,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 u=a.createGain();u.gain.value=1-n.depth*.5,l.connect(c),c.connect(u.gain),l.start(),s.push(l,c,u),i=o=u;break}case"phaser":{const l=[],c=a.createOscillator();c.type="sine",c.frequency.value=n.rate;const u=a.createGain();u.gain.value=n.depth*n.frequency;let h=null;for(let x=0;x<n.stages;x++){const b=a.createBiquadFilter();b.type="allpass",b.frequency.value=n.frequency,b.Q.value=.5,c.connect(u),u.connect(b.frequency),h&&h.connect(b),h=b,l.push(b)}const p=a.createGain(),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,u,...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 Ll={gain:r.jsx(B.NtdVolume,{size:16}),compressor:r.jsx(B.NtdSettings,{size:16}),reverb:r.jsx(B.NtdMountain,{size:16}),delay:r.jsx(B.NtdStopwatch,{size:16}),chorus:r.jsx(B.NtdSparkle,{size:16}),eq:r.jsx(B.NtdBarChart,{size:16}),filter:r.jsx(B.NtdFilter,{size:16}),distortion:r.jsx(B.NtdLightning,{size:16}),tremolo:r.jsx(B.NtdWave,{size:16}),phaser:r.jsx(B.NtdMagicWand,{size:16})},_l={gain:"Gain",compressor:"Compressor",reverb:"Reverb",delay:"Delay",chorus:"Chorus",eq:"EQ",filter:"Filter",distortion:"Distortion",tremolo:"Tremolo",phaser:"Phaser"},t0={gain:br,compressor:Bn,reverb:Gn,delay:Wn,chorus:xr,eq:Sr,filter:kr,distortion:wr,tremolo:Cr,phaser:jr},n0=["gain","compressor","reverb","delay","chorus","eq","filter","distortion","tremolo","phaser"],Fe=({value:e,min:t,max:n,step:a=1,label:s,unit:i="",onChange:o,disabled:l})=>{const c=d.useRef(null),[u,h]=d.useState(!1),p=d.useRef(0),g=d.useRef(e),y=d.useCallback(x=>{l||(x.preventDefault(),h(!0),p.current=x.clientY,g.current=e)},[l,e]);d.useEffect(()=>{if(!u)return;const x=f=>{const j=p.current-f.clientY,v=n-t,T=j/200*v,M=Math.min(n,Math.max(t,g.current+T));o(a<1?M:Math.round(M/a)*a)},b=()=>{h(!1)};return document.addEventListener("mousemove",x),document.addEventListener("mouseup",b),()=>{document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",b)}},[u,t,n,a,o]);const m=(e-t)/(n-t)*270-135;return r.jsxs("div",{className:`nice-fx-knob ${l?"nice-fx-knob--disabled":""}`,ref:c,children:[r.jsx("div",{className:`nice-fx-knob__dial ${u?"nice-fx-knob__dial--active":""}`,onMouseDown:y,style:{transform:`rotate(${m}deg)`},children:r.jsx("div",{className:"nice-fx-knob__indicator"})}),r.jsx("div",{className:"nice-fx-knob__label",children:s}),r.jsxs("div",{className:"nice-fx-knob__value",children:[typeof e=="number"&&a<1?e.toFixed(2):e,i]})]})};function r0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:u}=xe();return r.jsx(kt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsx(Fe,{value:e.gain,min:-60,max:12,step:.1,label:u("audioEffectsRack.gain","Gain"),unit:"dB",onChange:h=>t({...e,gain:h}),disabled:!e.enabled})})}function a0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:u}=xe();return r.jsx(kt,{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(Fe,{value:e.threshold,min:-60,max:0,label:u("audioEffectsRack.threshold","Threshold"),unit:"dB",onChange:h=>t({...e,threshold:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.ratio,min:1,max:20,label:u("audioEffectsRack.ratio","Ratio"),onChange:h=>t({...e,ratio:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.attack,min:.1,max:200,label:u("audioEffectsRack.attack","Attack"),unit:"ms",onChange:h=>t({...e,attack:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.release,min:10,max:1e3,label:u("audioEffectsRack.release","Release"),unit:"ms",onChange:h=>t({...e,release:h}),disabled:!e.enabled}),!c&&r.jsxs(r.Fragment,{children:[r.jsx(Fe,{value:e.knee,min:0,max:40,label:u("audioEffectsRack.knee","Knee"),unit:"dB",onChange:h=>t({...e,knee:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.makeupGain,min:0,max:24,label:u("audioEffectsRack.makeup","Makeup"),unit:"dB",onChange:h=>t({...e,makeupGain:h}),disabled:!e.enabled})]})]})})}function s0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:u}=xe();return r.jsx(kt,{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(Fe,{value:e.decay,min:.1,max:10,step:.1,label:u("audioEffectsRack.decay","Decay"),unit:"s",onChange:h=>t({...e,decay:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.damping,min:0,max:1,step:.01,label:u("audioEffectsRack.damping","Damping"),onChange:h=>t({...e,damping:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.roomSize,min:0,max:1,step:.01,label:u("audioEffectsRack.room","Room"),onChange:h=>t({...e,roomSize:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.mix,min:0,max:1,step:.01,label:u("audioEffectsRack.mix","Mix"),onChange:h=>t({...e,mix:h}),disabled:!e.enabled})]})})}function i0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:u}=xe();return r.jsx(kt,{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(Fe,{value:e.time,min:0,max:2e3,label:u("audioEffectsRack.time","Time"),unit:"ms",onChange:h=>t({...e,time:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.feedback,min:0,max:1,step:.01,label:u("audioEffectsRack.feedback","Feedback"),onChange:h=>t({...e,feedback:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.highCut,min:200,max:2e4,label:u("audioEffectsRack.hicut","HiCut"),unit:"Hz",onChange:h=>t({...e,highCut:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.mix,min:0,max:1,step:.01,label:u("audioEffectsRack.mix","Mix"),onChange:h=>t({...e,mix:h}),disabled:!e.enabled})]})})}function o0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:u}=xe();return r.jsx(kt,{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(Fe,{value:e.drive,min:0,max:1,step:.01,label:u("audioEffectsRack.drive","Drive"),onChange:h=>t({...e,drive:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.tone,min:0,max:1,step:.01,label:u("audioEffectsRack.tone","Tone"),onChange:h=>t({...e,tone:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.mix,min:0,max:1,step:.01,label:u("audioEffectsRack.mix","Mix"),onChange:h=>t({...e,mix:h}),disabled:!e.enabled})]})})}function kt({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:u}){const{t:h}=xe(),[p,g]=d.useState(!1);return r.jsxs("div",{className:`nice-fx-card ${e.enabled?"":"nice-fx-card--disabled"} ${i?"nice-fx-card--drop-target":""} ${c?"nice-fx-card--compact":""}`,draggable:!0,onDragStart:a,onDragEnd:s,children:[r.jsxs("div",{className:"nice-fx-card__header",children:[r.jsx("span",{className:"nice-fx-card__icon",children:Ll[e.type]}),r.jsx("span",{className:"nice-fx-card__title",children:_l[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?h("audioEffectsRack.disable","Disable"):h("audioEffectsRack.enable","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(B.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(ve.NiceIcon,{name:"close",size:14})})]}),r.jsx("div",{className:"nice-fx-card__body",children:u})]})}function l0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:u}=xe();return r.jsx(kt,{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(Fe,{value:e.mix,min:0,max:1,step:.01,label:u("audioEffectsRack.mix","Mix"),onChange:h=>t({...e,mix:h}),disabled:!e.enabled})})})}function c0({effect:e,onChange:t,...n}){const{t:a}=xe(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(kt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Fe,{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(Fe,{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(Fe,{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(Fe,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}function d0({effect:e,onChange:t,...n}){const{t:a}=xe(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(kt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Fe,{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(Fe,{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(Fe,{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(Fe,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}function u0({effect:e,onChange:t,...n}){const{t:a}=xe(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(kt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Fe,{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(Fe,{value:s.Q??1,min:.1,max:20,step:.1,label:"Q",onChange:o=>i("Q",o),disabled:!e.enabled}),r.jsx(Fe,{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(Fe,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}function h0({effect:e,onChange:t,...n}){const{t:a}=xe(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(kt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Fe,{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(Fe,{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(Fe,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}function p0({effect:e,onChange:t,...n}){const{t:a}=xe(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(kt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Fe,{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(Fe,{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(Fe,{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(Fe,{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(Fe,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}const f0=({audioContext:e,chain:t,effects:n,onChange:a,onChainUpdate:s,maxEffects:i=10,availableEffects:o=n0,showPresets:l=!0,compact:c=!1,className:u=""})=>{const{t:h}=xe(),[p,g]=d.useState((n==null?void 0:n.map(P=>P.params))||[]),[y,m]=d.useState({isDragging:!1,dragIndex:-1,dropIndex:-1}),[x,b]=d.useState(!1),f=d.useMemo(()=>t||(e?new e0(e):null),[e,t]),j=d.useCallback((P,I)=>{const A=[...p];A[P]=I,g(A),a==null||a(A),f&&(s==null||s(f))},[p,a,f,s]),v=d.useCallback(P=>{if(p.length>=i)return;const I={...t0[P]},A=[...p,I];g(A),a==null||a(A),b(!1)},[p,i,a]),C=d.useCallback(P=>{const I=p.filter((A,L)=>L!==P);g(I),a==null||a(I)},[p,a]),T=d.useCallback(P=>{m({isDragging:!0,dragIndex:P,dropIndex:-1})},[]),M=d.useCallback(()=>{if(y.dragIndex!==-1&&y.dropIndex!==-1&&y.dragIndex!==y.dropIndex){const P=[...p],[I]=P.splice(y.dragIndex,1);P.splice(y.dropIndex,0,I),g(P),a==null||a(P)}m({isDragging:!1,dragIndex:-1,dropIndex:-1})},[y,p,a]),k=d.useCallback((P,I)=>{P.preventDefault(),y.isDragging&&m(A=>({...A,dropIndex:I}))},[y.isDragging]),R=(P,I)=>{const A={onRemove:()=>C(I),onDragStart:()=>T(I),onDragEnd:M,isDragTarget:y.dropIndex===I,presets:Xm[P.type]||{},showPresets:l,compact:c};switch(P.type){case"gain":return r.jsx(r0,{effect:P,onChange:L=>j(I,L),...A},I);case"compressor":return r.jsx(a0,{effect:P,onChange:L=>j(I,L),...A},I);case"reverb":return r.jsx(s0,{effect:P,onChange:L=>j(I,L),...A},I);case"delay":return r.jsx(i0,{effect:P,onChange:L=>j(I,L),...A},I);case"distortion":return r.jsx(o0,{effect:P,onChange:L=>j(I,L),...A},I);case"chorus":return r.jsx(c0,{effect:P,onChange:L=>j(I,L),...A},I);case"eq":return r.jsx(d0,{effect:P,onChange:L=>j(I,L),...A},I);case"filter":return r.jsx(u0,{effect:P,onChange:L=>j(I,L),...A},I);case"tremolo":return r.jsx(h0,{effect:P,onChange:L=>j(I,L),...A},I);case"phaser":return r.jsx(p0,{effect:P,onChange:L=>j(I,L),...A},I);default:return r.jsx(l0,{effect:P,onChange:L=>j(I,L),...A},I)}};return r.jsxs("div",{className:`nice-fx-rack ${c?"nice-fx-rack--compact":""} ${u}`,children:[r.jsxs("div",{className:"nice-fx-rack__header",children:[r.jsx("h3",{className:"nice-fx-rack__title",children: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:h("audioEffectsRack.noEffectsClickToAdd","No effects. Click + to add.")}):p.map((P,I)=>r.jsxs("div",{className:"nice-fx-rack__slot",onDragOver:A=>k(A,I),children:[R(P,I),I<p.length-1&&r.jsx("div",{className:"nice-fx-rack__connector","aria-hidden":"true",children:r.jsx(B.NtdArrowRight,{size:14})})]},I))}),p.length<i&&r.jsxs("div",{className:"nice-fx-rack__add",children:[r.jsx("button",{type:"button",className:"nice-fx-rack__add-btn",onClick:()=>b(!x),children:h("audioEffectsRack.addEffect","+ Add Effect")}),x&&r.jsx("div",{className:"nice-fx-rack__add-menu",children:o.map(P=>r.jsxs("button",{type:"button",className:"nice-fx-rack__add-item",onClick:()=>v(P),children:[r.jsx("span",{className:"nice-fx-rack__add-icon",children:Ll[P]}),r.jsx("span",{className:"nice-fx-rack__add-label",children:_l[P]})]},P))})]})]})},Dl=[{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,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 cr(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),u=t.createDelay(1),h=t.createOscillator(),p=t.createOscillator(),g=t.createGain(),y=t.createGain(),m=n-1,x=Math.abs(m)*5+2,b=Math.abs(m)*.015;h.type="sawtooth",h.frequency.value=x,g.gain.value=b,h.connect(g),g.connect(c.delayTime),c.delayTime.value=.02,p.type="sawtooth",p.frequency.value=x,y.gain.value=b,p.connect(y),y.connect(u.delayTime),u.delayTime.value=.02+b;const f=t.createGain();f.gain.value=.5;const j=t.createGain();return j.gain.value=.5,s.connect(c),s.connect(u),c.connect(f),u.connect(j),f.connect(o),j.connect(o),s.connect(l),o.connect(i),l.connect(i),h.start(),p.start(),{type:"chipmunk",nodes:[s,c,u,h,p,g,y,f,j,o,l,i],input:s,output:i}}buildRobot(t,n){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=.6+n*.4;const o=t.createGain();o.gain.value=1-n*.6;const l=t.createOscillator();l.type="square",l.frequency.value=50+n*200;const c=t.createGain();return c.gain.value=0,l.connect(c.gain),a.connect(c),c.connect(i),a.connect(o),i.connect(s),o.connect(s),l.start(),{type:"robot",nodes:[a,l,c,i,o,s],input:a,output:s}}buildAlien(t,n){const a=t.createGain(),s=t.createGain(),i=t.createOscillator();i.type="sine",i.frequency.value=300+n*700;const o=t.createGain();o.gain.value=0,i.connect(o.gain),a.connect(o);const l=t.createDelay(.1);l.delayTime.value=.005;const c=t.createOscillator();c.type="sine",c.frequency.value=3+n*10;const u=t.createGain();u.gain.value=.004,c.connect(u),u.connect(l.delayTime),o.connect(l),l.connect(s);const h=t.createGain();return h.gain.value=.3,a.connect(h),h.connect(s),i.start(),c.start(),{type:"alien",nodes:[a,i,o,l,c,u,h,s],input:a,output:s}}buildDelay(t,n,a,s){const i=t.createGain(),o=t.createGain(),l=t.createDelay(2);l.delayTime.value=n;const c=t.createGain();c.gain.value=Math.min(.85,a);const u=t.createGain();u.gain.value=.5+s*.5;const h=t.createGain();return h.gain.value=1,i.connect(l),l.connect(c),c.connect(l),l.connect(u),i.connect(h),u.connect(o),h.connect(o),{type:"echo",nodes:[i,l,c,u,h,o],input:i,output:o}}buildCave(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(2);i.delayTime.value=.2+n*.3;const o=t.createDelay(2);o.delayTime.value=.35+n*.25;const l=t.createDelay(2);l.delayTime.value=.55+n*.3;const c=t.createGain();c.gain.value=.5;const u=t.createGain();u.gain.value=.35;const h=t.createGain();h.gain.value=.25;const p=t.createConvolver();p.buffer=Mi(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(u),u.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,u,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=Mi(t,n,a);const c=t.createGain();c.gain.value=.4+s*.5;const u=t.createGain();return u.gain.value=1,i.connect(l),l.connect(c),i.connect(u),c.connect(o),u.connect(o),{type:"reverb",nodes:[i,l,c,u,o],input:i,output:o}}buildChorus(t,n){const a=t.createGain(),s=t.createGain(),i=[{delayMs:20,lfoFreq:.5,depth:.003},{delayMs:25,lfoFreq:.7,depth:.004},{delayMs:30,lfoFreq:1.1,depth:.005}],o=[a,s],l=t.createGain();l.gain.value=.7,a.connect(l),l.connect(s),o.push(l);for(const c of i){const u=t.createDelay(.1);u.delayTime.value=c.delayMs/1e3;const h=t.createOscillator();h.type="sine",h.frequency.value=c.lfoFreq;const p=t.createGain();p.gain.value=c.depth*(.5+n),h.connect(p),p.connect(u.delayTime);const g=t.createGain();g.gain.value=.3+n*.2,a.connect(u),u.connect(g),g.connect(s),h.start(),o.push(u,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 u=t.createGain();u.gain.value=.5+n*.3;const h=t.createGain();return h.gain.value=1,a.connect(i),i.connect(c),c.connect(i),i.connect(u),a.connect(h),u.connect(s),h.connect(s),o.start(),{type:"flanger",nodes:[a,i,o,l,c,u,h,s],input:a,output:s}}buildDistortion(t,n,a){const s=t.createGain(),i=t.createGain(),o=t.createWaveShaper();o.curve=cr(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=cr(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=cr(10),a.connect(i),i.connect(o),o.connect(l),l.connect(c),c.connect(s),{type:"radio",nodes:[a,i,o,l,c,s],input:a,output:s}}buildUnderwater(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="lowpass",i.frequency.value=300+(1-n)*400,i.Q.value=5+n*10;const o=t.createOscillator();o.type="sine",o.frequency.value=.5+n*2;const l=t.createGain();l.gain.value=100+n*200,o.connect(l),l.connect(i.frequency);const c=t.createGain();c.gain.value=.7+n*.3;const u=t.createGain();return u.gain.value=.3-n*.2,a.connect(i),i.connect(c),a.connect(u),c.connect(s),u.connect(s),o.start(),{type:"underwater",nodes:[a,i,o,l,c,u,s],input:a,output:s}}buildWhisper(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500+n*500,i.Q.value=.5;const o=t.createWaveShaper(),l=new Float32Array(256);for(let u=0;u<256;u++){const h=u/255*2-1;l[u]=Math.sign(h)*Math.pow(Math.abs(h),.3+n*.5)}o.curve=l;const c=t.createBiquadFilter();return c.type="highshelf",c.frequency.value=3e3,c.gain.value=6+n*6,a.connect(i),i.connect(o),o.connect(c),c.connect(s),{type:"whisper",nodes:[a,i,o,c,s],input:a,output:s}}buildDemon(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.1);i.delayTime.value=.03;const o=t.createOscillator();o.type="sawtooth",o.frequency.value=2+n*3;const l=t.createGain();l.gain.value=.02+n*.015,o.connect(l),l.connect(i.delayTime);const c=t.createWaveShaper();c.curve=cr(20+n*50),c.oversample="2x";const u=t.createBiquadFilter();u.type="lowshelf",u.frequency.value=200,u.gain.value=8+n*8;const h=t.createGain();h.gain.value=.7+n*.3;const p=t.createGain();return p.gain.value=.3,a.connect(i),i.connect(c),c.connect(u),u.connect(h),a.connect(p),h.connect(s),p.connect(s),o.start(),{type:"demon",nodes:[a,i,o,l,c,u,h,p,s],input:a,output:s}}buildTremolo(t,n){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=1;const o=t.createOscillator();o.type="sine",o.frequency.value=3+n*12;const l=t.createGain();return l.gain.value=.3+n*.5,o.connect(l),l.connect(i.gain),a.connect(i),i.connect(s),o.start(),{type:"tremolo",nodes:[a,i,o,l,s],input:a,output:s}}buildAutotune(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.05);i.delayTime.value=.005;const o=t.createOscillator();o.type="sine",o.frequency.value=6+n*8;const l=t.createGain();l.gain.value=.002+n*.002,o.connect(l),l.connect(i.delayTime);const c=[],u=[261.6,293.7,329.6,349.2,392,440,493.9,523.3],h=t.createGain();h.gain.value=.15;for(const y of u){const m=t.createBiquadFilter();m.type="peaking",m.frequency.value=y,m.Q.value=8+n*15,m.gain.value=4+n*8,a.connect(m),m.connect(h),c.push(m)}const p=t.createGain();p.gain.value=.7;const 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],u=t.createGain();u.gain.value=.5+n*.5,c.push(u);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(u),c.push(y,m,x)}u.connect(s);const h=t.createGain();return h.gain.value=.3-n*.2,a.connect(h),h.connect(s),c.push(h),i.start(),{type:"vocoder",nodes:c,input:a,output:s}}}const m0={sparkle:B.NtdSparkle,music:B.NtdMusic,skull:B.NtdSkull,robot:B.NtdRobot,ghost:B.NtdGhost,mountain:B.NtdMountain,wave:B.NtdWave,lightning:B.NtdLightning,phone:B.NtdPhone,megaphone:B.NtdMegaphone,"volume-mute":B.NtdVolumeMute,microphone:B.NtdMicrophone,volume:B.NtdVolume},g0=({deviceId:e,mediaStream:t,compact:n=!1,t:a,className:s,style:i,id:o,accessMode:l,"data-testid":c})=>{const{t:u}=xe(),h=a??u,p=d.useRef(null),[g,y]=d.useState(!1),[m,x]=d.useState(()=>Dl.map(F=>({...F}))),[b,f]=d.useState(!0),[j,v]=d.useState(80),[C,T]=d.useState(100),[M,k]=d.useState(0),R=d.useRef(0),P=d.useCallback(()=>{const F=()=>{var q;(q=p.current)!=null&&q.isStarted&&(k(p.current.getLevel()),R.current=requestAnimationFrame(F))};R.current=requestAnimationFrame(F)},[]),I=d.useCallback(()=>{R.current&&cancelAnimationFrame(R.current)},[]),A=d.useCallback(async()=>{const F=new zl;p.current=F;try{t?await F.startWithStream(t):await F.start(e),F.setMonitoring(b),F.setVolume(j/100),F.setInputGain(C/100);for(const q of m)q.enabled&&F.addEffect(q.type,q.intensity);y(!0),P()}catch(q){typeof console<"u"&&console.warn("[VocalEffectsRack] start error",q)}},[e,t,b,j,C,m,P]),L=d.useCallback(()=>{var F;I(),(F=p.current)==null||F.stop(),p.current=null,y(!1),k(0)},[I]);d.useEffect(()=>()=>{var F;I(),(F=p.current)==null||F.stop(),p.current=null},[I]);const E=d.useCallback(F=>{x(q=>q.map(V=>{var W;if(V.type!==F)return V;const K={...V,enabled:!V.enabled};return(W=p.current)!=null&&W.isStarted&&(K.enabled?p.current.addEffect(F,K.intensity):p.current.removeEffect(F)),K}))},[]),D=d.useCallback((F,q)=>{x(V=>V.map(K=>{var W;return K.type!==F?K:(K.enabled&&((W=p.current)!=null&&W.isStarted)&&p.current.updateIntensity(F,q),{...K,intensity:q})}))},[]);d.useEffect(()=>{var F;(F=p.current)==null||F.setVolume(j/100)},[j]),d.useEffect(()=>{var F;(F=p.current)==null||F.setInputGain(C/100)},[C]),d.useEffect(()=>{var F;(F=p.current)==null||F.setMonitoring(b)},[b]);const Z=d.useCallback(()=>{var F;(F=p.current)==null||F.clearAllEffects(),x(q=>q.map(V=>({...V,enabled:!1})))},[]),G=m.filter(F=>F.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(B.NtdMicrophone,{size:n?16:20})," ",h("vocalEffects.title","Vocal effects")]}),r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[G>0&&r.jsxs(ie.NiceBadge,{variant:"primary",children:[G," ",h("vocalEffects.active","active")]}),g?r.jsx(ie.NiceButton,{variant:"danger",size:"sm",onClick:L,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:b,onChange:f,label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.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:j,onChange:v,min:0,max:200})}),r.jsxs("span",{style:{minWidth:36,fontSize:12},children:[j,"%"]})]}),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:C,onChange:T,min:0,max:300})}),r.jsxs("span",{style:{minWidth:36,fontSize:12},children:[C,"%"]})]}),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,M*300)}%`,background:M>.5?"var(--nice-danger, #ef4444)":M>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})}),G>0&&r.jsx(ie.NiceButton,{variant:"ghost",size:"sm",onClick:Z,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(F=>r.jsxs("div",{style:{border:F.enabled?"2px solid var(--nice-accent, #3b82f6)":"1px solid var(--nice-border, #e2e8f0)",borderRadius:10,padding:n?"6px 8px":"10px 12px",background:F.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:()=>E(F.type),style:{display:"flex",alignItems:"center",gap:6,width:"100%",marginBottom:F.enabled?6:0,background:"transparent",border:"none",cursor:"pointer",color:"inherit",textAlign:"left"},children:[(()=>{const q=m0[F.icon]??B.NtdMusic;return r.jsx(q,{size:n?18:22})})(),r.jsx("span",{style:{fontSize:n?12:14,fontWeight:F.enabled?700:500,color:F.enabled?"var(--nice-accent, #3b82f6)":"inherit"},children:F.label})]}),F.enabled&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},onClick:q=>q.stopPropagation(),onKeyDown:q=>{q.key!=="Escape"&&q.stopPropagation()},children:[r.jsx("div",{style:{flex:1},children:r.jsx(ie.NiceSlider,{value:F.intensity,onChange:q=>D(F.type,q),min:0,max:100})}),r.jsx("span",{style:{fontSize:11,minWidth:24,color:"var(--nice-text-muted, #64748b)"},children:F.intensity})]})]},F.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.")})]})},Fl={algorithm:"pitchy",gain:1,rmsThreshold:.02,pitchThreshold:.6,smoothingWindow:3,hysteresisFrames:2,useHanning:!1,offsetMs:0},y0=[{value:"pitchy",label:"Pitchy (fast)"},{value:"autocorrelation",label:"Autocorrelation"},{value:"librosa",label:"Librosa (server)"},{value:"crepe",label:"CREPE (AI, server)"}],v0=({deviceId:e,onDeviceChange:t,settings:n,onSettingsChange:a,audioInputs:s,algorithms:i=y0,showLevelMeter:o=!0,onCalibrate:l,compact:c=!1,t:u})=>{const{t:h}=xe(),p=u??h,g=d.useMemo(()=>({...Fl,...n}),[n]),y=A=>a==null?void 0:a({...g,...A}),[m,x]=d.useState([]);d.useEffect(()=>{var E,D,Z;if(s||!((E=navigator.mediaDevices)!=null&&E.enumerateDevices))return;let A=!1;const L=()=>navigator.mediaDevices.enumerateDevices().then(G=>!A&&x(G.filter(F=>F.kind==="audioinput"))).catch(()=>{});return L(),(Z=(D=navigator.mediaDevices).addEventListener)==null||Z.call(D,"devicechange",L),()=>{var G,F;A=!0,(F=(G=navigator.mediaDevices).removeEventListener)==null||F.call(G,"devicechange",L)}},[s]);const b=s??m,f=d.useMemo(()=>b.map((A,L)=>({value:A.deviceId,label:A.label||`${p("audioInput.microphone","Microphone")} ${L+1}`})),[b,p]),[j,v]=d.useState(!1),[C,T]=d.useState(0),M=d.useRef(null),k=()=>{const A=M.current;A&&(cancelAnimationFrame(A.raf),A.stream.getTracks().forEach(L=>L.stop()),A.ctx.close().catch(()=>{}),M.current=null),v(!1),T(0)},R=async()=>{try{const A=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0}}),L=new AudioContext,E=L.createMediaStreamSource(A),D=L.createAnalyser();D.fftSize=1024,E.connect(D);const Z=new Float32Array(D.fftSize),G=()=>{D.getFloatTimeDomainData(Z);let F=0;for(let q=0;q<Z.length;q++)F+=Z[q]*Z[q];T(Math.sqrt(F/Z.length)*(g.gain||1)),M.current.raf=requestAnimationFrame(G)};M.current={ctx:L,stream:A,raf:requestAnimationFrame(G)},v(!0)}catch{}};d.useEffect(()=>()=>k(),[]);const P={fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:4,display:"block"},I=(A,L,E)=>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:L}),r.jsx("span",{style:{flex:"0 0 48px",textAlign:"right",fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:E})]});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:{...P,display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.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:P,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:[I(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)}%`),I(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)),I(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&&I(p("audioInput.smoothing","Smoothing"),r.jsx(ie.NiceSlider,{value:g.smoothingWindow,onChange:A=>y({smoothingWindow:A}),min:0,max:12}),`${g.smoothingWindow}`),!c&&I(p("audioInput.hysteresis","Hysteresis"),r.jsx(ie.NiceSlider,{value:g.hysteresisFrames,onChange:A=>y({hysteresisFrames:A}),min:0,max:12}),`${g.hysteresisFrames}`),!c&&I(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:j?"danger":"secondary",size:"sm",onClick:j?k:R,children:j?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,C*300)}%`,background:C>.5?"var(--nice-danger, #ef4444)":C>.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(B.NtdSettings,{size:14})," ",p("audioInput.calibrate","Calibrate latency")]})]})]})};class Ol{constructor(t,n){this.activeNotes=new Map,this.audioContext=t,this.masterGain=t.createGain(),this.masterGain.gain.value=.3,this.masterGain.connect(n)}applyCC(t,n,a){}midiToFreq(t){return 440*Math.pow(2,(t-69)/12)}playNote(t,n=100,a=1,s="sine"){const i=this.midiToFreq(t),o=this.audioContext.createOscillator(),l=this.audioContext.createGain();o.type=s,o.frequency.value=i;const c=n/127*.8;l.gain.value=c,o.connect(l),l.connect(this.masterGain);const u=this.audioContext.currentTime;return l.gain.setValueAtTime(0,u),l.gain.linearRampToValueAtTime(c,u+.01),l.gain.exponentialRampToValueAtTime(c*.7,u+.1),l.gain.setValueAtTime(c*.7,u+a-.05),l.gain.exponentialRampToValueAtTime(.001,u+a),o.start(u),o.stop(u+a),o.onended=()=>{l.disconnect(),o.disconnect()},{osc:o,gain:l}}scheduleNote(t,n,a,s=100,i="sine"){const o=this.midiToFreq(t),l=this.audioContext.createOscillator(),c=this.audioContext.createGain();l.type=i,l.frequency.value=o;const u=s/127*.8;l.connect(c),c.connect(this.masterGain);const h=n;return c.gain.setValueAtTime(0,h),c.gain.linearRampToValueAtTime(u,h+.01),c.gain.exponentialRampToValueAtTime(u*.7,h+.1),c.gain.setValueAtTime(u*.7,h+a-.05),c.gain.exponentialRampToValueAtTime(.001,h+a),l.start(h),l.stop(h+a),l.onended=()=>{c.disconnect(),l.disconnect()},{osc:l,gain:c}}setVolume(t){this.masterGain.gain.value=Math.max(0,Math.min(1,t))}stopAll(){this.activeNotes.forEach(({osc:t,gain:n})=>{try{t.stop(),n.disconnect(),t.disconnect()}catch{}}),this.activeNotes.clear()}dispose(){this.stopAll(),this.masterGain.disconnect()}}const Ri=st.scoped("AudioPlaybackEngine");class b0{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){Ri.error("Failed to initialize AudioContext:",t)}}createEffectNode(t){if(!this.audioContext||t.bypass)return null;try{switch(t.type){case"eq3":{const n=this.audioContext.createBiquadFilter(),a=this.audioContext.createBiquadFilter(),s=this.audioContext.createBiquadFilter();return n.type="lowshelf",n.frequency.value=t.params.lowFreq||250,n.gain.value=t.params.lowGain||0,a.type="peaking",a.frequency.value=1e3,a.Q.value=1,a.gain.value=t.params.midGain||0,s.type="highshelf",s.frequency.value=t.params.highFreq||4e3,s.gain.value=t.params.highGain||0,n.connect(a),a.connect(s),{input:n,output:s}}case"compressor":{const n=this.audioContext.createDynamicsCompressor();return n.threshold.value=t.params.threshold||-24,n.ratio.value=t.params.ratio||4,n.attack.value=t.params.attack||.003,n.release.value=t.params.release||.25,n.knee.value=t.params.knee||30,n}case"delay":{const n=this.audioContext.createDelay(5);n.delayTime.value=t.params.time||.25;const a=this.audioContext.createGain();a.gain.value=t.params.feedback||.3;const s=this.audioContext.createGain();s.gain.value=t.params.mix||.3;const i=this.audioContext.createGain();return i.gain.value=1-(t.params.mix||.3),n.connect(a),a.connect(n),n.connect(s),{input:n,output:s,dry:i,connect:function(o){s.connect(o),i.connect(o)}}}case"reverb":{const n=this.audioContext.createConvolver(),a=this.audioContext.sampleRate*(t.params.decay||2),s=this.audioContext.createBuffer(2,a,this.audioContext.sampleRate);for(let l=0;l<2;l++){const c=s.getChannelData(l);for(let u=0;u<a;u++)c[u]=(Math.random()*2-1)*Math.pow(1-u/a,2)}n.buffer=s;const i=this.audioContext.createGain();i.gain.value=t.params.mix||.3;const o=this.audioContext.createGain();return o.gain.value=1-(t.params.mix||.3),n.connect(i),{input:n,output:i,dry:o,connect:function(l){i.connect(l),o.connect(l)}}}case"distortion":{const n=this.audioContext.createWaveShaper(),a=t.params.amount||20,s=44100,i=new Float32Array(s),o=Math.PI/180;for(let u=0;u<s;u++){const h=u*2/s-1;i[u]=(3+a)*h*20*o/(Math.PI+a*Math.abs(h))}n.curve=i,n.oversample="4x";const l=this.audioContext.createGain();l.gain.value=t.params.mix||.5;const c=this.audioContext.createGain();return c.gain.value=1-(t.params.mix||.5),n.connect(l),{input:n,output:l,dry:c,connect:function(u){l.connect(u),c.connect(u)}}}default:return null}}catch(n){return Ri.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 Ol(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),u=this.audioContext.currentTime+(l-this.currentTime);u>=this.audioContext.currentTime&&(a.start(u,t.offset+c,t.duration-c),this.scheduledSources.set(t.id,a),a.onended=()=>{this.scheduledSources.delete(t.id)})})}stopClip(t){const n=this.scheduledSources.get(t);if(n){try{n.stop()}catch{}this.scheduledSources.delete(t)}}stopAllSources(){this.scheduledSources.forEach(t=>{try{t.stop()}catch{}}),this.scheduledSources.clear(),this.synths.forEach(t=>t.stopAll())}scheduleMidiNotes(){this.audioContext&&this.midiTracks.forEach(t=>{const n=this.synths.get(t.layerId);if(n&&(t.notes.forEach(a=>{if(a.start+a.duration<=this.currentTime)return;const i=Math.max(0,this.currentTime-a.start),o=this.audioContext.currentTime+(a.start-this.currentTime);o>=this.audioContext.currentTime&&n.scheduleNote(a.pitch,o,a.duration-i,a.velocity,t.instrument)}),t.ccEvents&&Array.isArray(t.ccEvents)&&t.ccEvents.length>0)){const a=[...t.ccEvents].sort((o,l)=>o.time-l.time);let i=a[0];for(let o=1;o<a.length;++o){const l=a[o],c=i.time,u=l.time,h=i.value,p=l.value,g=i.handleType||"linear",y=Math.max(2,Math.ceil((u-c)*20));for(let m=0;m<=y;++m){const x=m/y;let b=h;if(g==="linear")b=h+(p-h)*x;else if(g==="step")b=x<1?h:p;else if(g==="exp"){const C=Math.max(h/127,.001),T=Math.max(p/127,.001);b=C*Math.pow(T/C,x)*127}const f=c+(u-c)*x,j=this.audioContext.currentTime+(f-this.currentTime);j>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(l.cc,b,j)}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 x0=[{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 qr(e={}){const{channelFilter:t,sysex:n=!1,onEvent:a,inputNameIncludes:s,onInputsChanged:i}=e,[o,l]=d.useState(null),[c,u]=d.useState(!1),[h,p]=d.useState([]),g=d.useRef(null),y=d.useCallback((m,x)=>{const b=m.data??new Uint8Array(0),f=b[0]??0,j=b[1]??0,v=b[2]??0,C=m.timeStamp,T=f&240,M=f&15,k=x.id,R=x.name??"MIDI Input",P=t===void 0||t===M;if((T===144||T===128)&&P){const I=T===144&&v>0;return{type:I?"noteon":"noteoff",note:j,velocity:I?v:0,channel:M,ts:C,deviceId:k,deviceName:R}}return T===176&&P?{type:"cc",controller:j,value:v,channel:M,ts:C,deviceId:k,deviceName:R}:T===208&&P?{type:"aftertouch",pressure:j,channel:M,ts:C,deviceId:k,deviceName:R}:T===224&&P?{type:"pitchbend",value:(j|v<<7)-8192,channel:M,ts:C,deviceId:k,deviceName:R}:T===192&&P?{type:"program",program:j,channel:M,ts:C,deviceId:k,deviceName:R}:{type:"unknown",status:f,data1:j,data2:v,channel:M,ts:C,deviceId:k,deviceName:R}},[t]);return d.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,u(!0);const b=()=>{const f=Array.from(x.inputs.values()),j=s?f.filter(v=>(v.name||"").toUpperCase().includes(s.toUpperCase())):f;p(j),i==null||i(j),f.forEach(v=>v.onmidimessage=null),j.forEach(v=>{v.onmidimessage=C=>a==null?void 0:a(y(C,v))})};b(),x.onstatechange=()=>b()}),()=>{m=!0;const x=g.current;x&&(x.inputs.forEach(b=>b.onmidimessage=null),x.onstatechange=null)}},[s,a,i,y,n]),{supported:o,granted:c,inputs:h}}const ss="nice2dev.midiLearn";function S0(){try{const e=localStorage.getItem(ss);return e?JSON.parse(e):{}}catch{return{}}}function Ni(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(ss,JSON.stringify(t))}function k0(e){const{parameters:t,onParameterChange:n}=e,[a,s]=d.useState(()=>{const v=S0();return t.map(C=>{const T=v[C.id];return{id:C.id,paramName:C.name,type:(T==null?void 0:T.type)??"cc",number:T==null?void 0:T.number,channel:T==null?void 0:T.channel,min:(T==null?void 0:T.min)??C.min??0,max:(T==null?void 0:T.max)??C.max??127,value:0}})}),[i,o]=d.useState({learning:!1,targetId:null}),[l,c]=d.useState(null),u=d.useRef(a);u.current=a;const h=d.useRef(n);h.current=n;const p=d.useRef(i);p.current=i;const g=d.useCallback(v=>{var T;c(v);const C=p.current;if(C.learning&&C.targetId){if(!u.current.find(R=>R.id===C.targetId))return;let k={};switch(v.type){case"cc":k={type:"cc",number:v.controller,channel:v.channel};break;case"noteon":k={type:"note",number:v.note,channel:v.channel};break;case"pitchbend":k={type:"pitchbend",channel:v.channel};break;case"aftertouch":k={type:"aftertouch",channel:v.channel};break;default:return}s(R=>{const P=R.map(I=>I.id===C.targetId?{...I,...k}:I);return Ni(P),P}),o({learning:!1,targetId:null});return}for(const M of u.current){if(M.number===void 0&&M.type!=="pitchbend"&&M.type!=="aftertouch"||M.channel!==void 0&&v.channel!==M.channel)continue;let k=null,R=127;if(M.type==="cc"&&v.type==="cc"&&v.controller===M.number?k=v.value:M.type==="note"&&v.type==="noteon"&&v.note===M.number?k=v.velocity:M.type==="pitchbend"&&v.type==="pitchbend"?(k=v.value+8192,R=16383):M.type==="aftertouch"&&v.type==="aftertouch"&&(k=v.pressure),k!==null){const P=k/R,I=M.min+P*(M.max-M.min);s(A=>A.map(L=>L.id===M.id?{...L,value:P}:L)),(T=h.current)==null||T.call(h,M.id,I,P)}}},[]),{supported:y,granted:m}=qr({onEvent:g}),x=d.useCallback(v=>{o({learning:!0,targetId:v})},[]),b=d.useCallback(()=>{o({learning:!1,targetId:null})},[]),f=d.useCallback(v=>{s(C=>{const T=C.map(M=>M.id===v?{...M,type:"cc",number:void 0,channel:void 0}:M);return Ni(T),T})},[]),j=d.useCallback(()=>{s(v=>{const C=v.map(T=>({...T,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(ss),C})},[]);return{bindings:a,startLearn:x,cancelLearn:b,removeBinding:f,clearAll:j,learnState:i,midiSupported:y,midiGranted:m,lastEvent:l}}const w0={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function C0(e={}){const{lowerZone:t=w0,onNoteExpression:n,onNoteOn:a,onNoteOff:s}=e,[i,o]=d.useState([]),l=d.useRef(new Map),c=d.useRef(n);c.current=n;const u=d.useRef(a);u.current=a;const h=d.useRef(s);h.current=s;const p=d.useRef(new Set(t.memberChannels));d.useEffect(()=>{p.current=new Set(t.memberChannels)},[t.memberChannels]);const g=d.useCallback(x=>{var f,j,v,C,T;if(!p.current.has(x.channel??-1))return;const b=`${x.channel}`;switch(x.type){case"noteon":{const M={note:x.note,channel:x.channel,velocity:x.velocity,pitchBend:0,pressure:0,slide:0,lastUpdate:x.ts};l.current.set(b,M),o(Array.from(l.current.values())),(f=u.current)==null||f.call(u,M);break}case"noteoff":{l.current.delete(b),o(Array.from(l.current.values())),(j=h.current)==null||j.call(h,x.channel,x.note);break}case"pitchbend":{const M=l.current.get(b);M&&(M.pitchBend=x.value,M.lastUpdate=x.ts,(v=c.current)==null||v.call(c,M),o(Array.from(l.current.values())));break}case"aftertouch":{const M=l.current.get(b);M&&(M.pressure=x.pressure,M.lastUpdate=x.ts,(C=c.current)==null||C.call(c,M),o(Array.from(l.current.values())));break}case"cc":{if(x.controller===74){const M=l.current.get(b);M&&(M.slide=x.value,M.lastUpdate=x.ts,(T=c.current)==null||T.call(c,M),o(Array.from(l.current.values())))}break}}},[]),{supported:y,granted:m}=qr({onEvent:g,sysex:!1});return{activeNotes:i,midiSupported:y,midiGranted:m}}const j0={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 M0(e={},t=j0){const{t:n}=xe(),[a,s]=d.useState(()=>{const m=localStorage.getItem("oxygen25.layout");return m?JSON.parse(m):t}),[i,o]=d.useState([]),l=d.useRef({mode:"idle"}),c=d.useCallback(m=>{s(x=>{const b={...x,...m};return localStorage.setItem("oxygen25.layout",JSON.stringify(b)),b})},[]),u=d.useCallback(m=>{var f,j,v,C,T,M,k,R,P;const x=m.deviceName||"MIDI";o(I=>I.includes(x)?I:[...I,x]);const b=l.current;if(b.mode!=="idle"){if(b.mode==="knob"&&m.type==="cc"){const I=b.index;c({knobs:a.knobs.map(A=>A.index===I?{...A,cc:m.controller}:A)}),l.current={mode:"idle"};return}if(b.mode==="fader"&&m.type==="cc"){c({fader:{cc:m.controller,label:n("useOxygen25.fader","Fader")}}),l.current={mode:"idle"};return}if(b.mode==="pad"&&m.type==="noteon"){const I=a.pads.slice();I[b.padIdx]={...I[b.padIdx],note:m.note},c({pads:I}),l.current={mode:"idle"};return}if(b.mode==="transport"&&m.type==="cc"){const I={...a.transport};I[b.action]=m.controller,c({transport:I}),l.current={mode:"idle"};return}}switch(m.type){case"noteon":{a.pads.findIndex(A=>A.note===m.note)>=0?(f=e.onPad)==null||f.call(e,{note:m.note,velocity:m.velocity,ts:m.ts,device:x}):(j=e.onKey)==null||j.call(e,{note:m.note,velocity:m.velocity,ts:m.ts,device:x});break}case"cc":{if(a.fader&&m.controller===a.fader.cc){(v=e.onFader)==null||v.call(e,{cc:m.controller,value:m.value,ts:m.ts,device:x});break}const I=a.knobs.find(L=>L.cc===m.controller);if(I){(C=e.onKnob)==null||C.call(e,{index:I.index,cc:m.controller,value:m.value,ts:m.ts,device:x});break}const A=Object.keys(a.transport).find(L=>a.transport[L]===m.controller);if(A){(T=e.onTransport)==null||T.call(e,{action:A,value:m.value,ts:m.ts,device:x});break}(M=e.onUnknown)==null||M.call(e,m);break}case"pitchbend":(k=e.onPitchBend)==null||k.call(e,{value:m.value,ts:m.ts,device:x});break;case"aftertouch":(R=e.onAftertouch)==null||R.call(e,{pressure:m.pressure,ts:m.ts,device:x});break;default:(P=e.onUnknown)==null||P.call(e,m)}},[c,e,a,n]),{supported:h,granted:p,inputs:g}=qr({inputNameIncludes:void 0,onEvent:u,sysex:!1,channelFilter:void 0,onInputsChanged:m=>o(m.map(x=>x.name||"MIDI"))}),y=d.useMemo(()=>({knob:m=>l.current={mode:"knob",index:m},fader:()=>l.current={mode:"fader"},pad:m=>l.current={mode:"pad",padIdx:m},transport:m=>l.current={mode:"transport",action:m},cancel:()=>l.current={mode:"idle"},state:()=>l.current}),[]);return{supported:h,granted:p,inputs:g,layout:a,setLayout:c,learn:y,inputsInfo:i}}const Ra={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]},R0=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Na={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]]},an=36,Rn=38,Rt=42,sn=51,N0=49,Ta={basic:[{step:0,pitch:an,vel:110},{step:0,pitch:Rt,vel:80},{step:2,pitch:Rt,vel:70},{step:4,pitch:Rn,vel:100},{step:4,pitch:Rt,vel:80},{step:6,pitch:Rt,vel:70},{step:8,pitch:an,vel:100},{step:10,pitch:Rt,vel:70},{step:12,pitch:Rn,vel:100},{step:12,pitch:Rt,vel:80},{step:14,pitch:Rt,vel:70}],rock:[{step:0,pitch:an,vel:120},{step:0,pitch:N0,vel:90},{step:4,pitch:Rn,vel:110},{step:4,pitch:Rt,vel:80},{step:8,pitch:an,vel:110},{step:8,pitch:Rt,vel:80},{step:10,pitch:an,vel:90},{step:12,pitch:Rn,vel:110},{step:12,pitch:Rt,vel:80}],swing:[{step:0,pitch:sn,vel:90},{step:3,pitch:sn,vel:70},{step:4,pitch:sn,vel:80},{step:8,pitch:sn,vel:90},{step:11,pitch:sn,vel:70},{step:12,pitch:sn,vel:80},{step:4,pitch:an,vel:80},{step:12,pitch:Rn,vel:70}]},Bl={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function T0(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 Gl=1;const dr=()=>Gl++,Wl=e=>60/e,P0=e=>Wl(e)/4;function la(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 Ul(e=Bl){Gl=1;const t=e.seed>0?T0(e.seed):Math.random,n=Ra[e.scale]??Ra.pentatonic,a=Na[e.progression]??Na.pop,s=Ta[e.drumPattern]??Ta.basic,i=Wl(e.tempo),o=P0(e.tempo),l=Math.max(1,e.bars),c=16,u=[],h=[],p=[],g=[];let y=0;for(let m=0;m<l;m++){const x=m*4*i,b=m%a.length,f=a[b];for(const v of f)p.push({id:dr(),pitch:la(e.root,n,v,e.octave-1),start:x,duration:4*i-.01,velocity:70+Math.floor(t()*20)});const j=f[0];for(let v=0;v<4;v++){const C=v===2?j+(t()>.5?2:0):j;h.push({id:dr(),pitch:la(e.root,n,C,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 C=x+v*o,T=t()>.8?t()>.5?2:-2:t()>.5?1:-1;y=Math.max(-3,Math.min(n.length+3,y+T));const M=1+Math.floor(t()*3);u.push({id:dr(),pitch:la(e.root,n,y,e.octave),start:C,duration:M*o*.95,velocity:85+Math.floor(t()*30)})}for(const v of s)g.push({id:dr(),pitch:v.pitch,start:x+v.step*o,duration:o*.8,velocity:v.vel+Math.floor(t()*10-5)})}return{melody:u,bass:h,chords:p,drums:g,config:e}}const E0=Object.keys(Ra),$0=Object.keys(Na),A0=Object.keys(Ta),I0=Ul;function qe(e,t,n){return{cc:e,paramId:n,label:`Knob ${t}`,controlType:"knob",min:0,max:127,inverted:!1}}function Kn(e,t,n){return{cc:e,paramId:n,label:t,controlType:"fader",min:0,max:127,inverted:!1}}function on(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:[qe(21,1,"mixer.volume"),qe(22,2,"mixer.pan"),qe(23,3,"fx.reverb"),qe(24,4,"fx.delay"),qe(25,5,"fx.chorus"),qe(26,6,"fx.filter"),qe(27,7,"fx.drive"),qe(28,8,"fx.eq"),Kn(7,"Master Fader","mixer.master"),on(115,"Play","transport.play"),on(114,"Stop","transport.stop"),on(117,"Record","transport.record"),on(112,"Rewind","transport.rewind"),on(113,"Forward","transport.forward"),on(116,"Loop","transport.loop")]},ql={id:"mpk-mini",name:"Akai MPK Mini",deviceMatch:"MPK",mappings:[qe(1,1,"mixer.volume"),qe(2,2,"mixer.pan"),qe(3,3,"fx.reverb"),qe(4,4,"fx.delay"),qe(5,5,"fx.chorus"),qe(6,6,"fx.filter"),qe(7,7,"fx.drive"),qe(8,8,"fx.eq")]},Hl={id:"minilab",name:"Arturia MiniLab",deviceMatch:"Arturia MiniLab",mappings:[qe(7,1,"mixer.volume"),qe(74,2,"mixer.pan"),qe(71,3,"fx.reverb"),qe(76,4,"fx.delay"),qe(77,5,"fx.chorus"),qe(93,6,"fx.filter"),qe(73,7,"fx.drive"),qe(75,8,"fx.eq"),Kn(1,"Mod Wheel","mixer.master")]},Kl=(function(){return{id:"launch-control-xl",name:"Novation Launch Control XL",deviceMatch:"Launch Control",mappings:[...Array.from({length:8},(e,t)=>qe(13+t,t+1,`mixer.send${t+1}`)),...Array.from({length:8},(e,t)=>Kn(77+t,`Fader ${t+1}`,`mixer.track${t+1}`))]}})(),is={id:"generic",name:"Generic MIDI Controller",deviceMatch:"",mappings:[qe(1,1,"mixer.modWheel"),Kn(7,"Volume","mixer.volume"),qe(10,2,"mixer.pan"),Kn(11,"Expression","mixer.expression")]},Yl=[Vl,ql,Hl,Kl,is];class L0{constructor(t){this.ccMap=new Map,this.onChange=null,this.profile=t??is,this.rebuildMap()}setProfile(t){this.profile=t,this.rebuildMap()}getProfile(){return this.profile}autoDetect(t){const n=t.toUpperCase(),a=Yl.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 os(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function Qt(e="New Pattern",t=16,n=120){return{name:e,length:t,steps:Array.from({length:t},()=>os()),bpm:n,swing:0,rootNote:60}}function Zl(e,t){const n=e.steps.map((a,s)=>s===t?{...a,active:!a.active}:a);return{...e,steps:n}}function Xl(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 Ql(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 Jl(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 ec(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 tc(e,t){const n=e.steps.map((a,s)=>s===t?{...a,slide:!a.slide}:a);return{...e,steps:n}}function nc(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 rc(e){return{...e,steps:[...e.steps].reverse()}}function ac(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 sc(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 ic(e){return{...e,steps:e.steps.map(()=>os(e.rootNote))}}function ls(e,t=4){return 60/e/t}function oc(e,t,n=0,a=4){const s=ls(t,a),i=e*s;return e%2===1&&n>0?i+s*n*.5:i}function lc(e){return e.active&&Math.random()<e.probability}function _0(){const e=Qt("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function D0(){const e=Qt("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function z0(){const e=Qt("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 F0(e=60){const t=Qt("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 O0(e=36){const t=Qt("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 B0(e){return JSON.stringify(e,null,2)}function G0(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function W0(e={}){const{onTrigger:t,onLFOOutput:n,initialPattern:a}=e,[s,i]=d.useState(()=>a??Qt()),[o,l]=d.useState(-1),[c,u]=d.useState(!1),[h,p]=d.useState([]),g=d.useRef(s);g.current=s;const y=d.useRef(h);y.current=h;const m=d.useRef(c);m.current=c;const x=d.useRef(t);x.current=t;const b=d.useRef(n);b.current=n;const f=d.useRef(null),j=d.useRef(0),v=d.useRef(0),C=d.useCallback(()=>{var H,X;if(!m.current)return;const S=g.current,O=j.current%S.length,Y=S.steps[O];if(lc(Y)){const re=oc(j.current,S.bpm,S.swing);(H=x.current)==null||H.call(x,Y,O,re)}const _=(Date.now()-v.current)/1e3;for(let re=0;re<y.current.length;re++){const oe=y.current[re];if(oe.enabled&&oe.targetCC!==void 0){const se=_a(oe,_,S.bpm);(X=b.current)==null||X.call(b,re,oe.targetCC,se)}}l(O),j.current++;const U=ls(S.bpm)*1e3,$=O%2===0?0:U*S.swing*.5;f.current=setTimeout(C,U+$)},[]),T=d.useCallback(()=>{m.current||(j.current=0,v.current=Date.now(),u(!0),m.current=!0,C())},[C]),M=d.useCallback(()=>{u(!1),m.current=!1,l(-1),f.current&&(clearTimeout(f.current),f.current=null)},[]),k=d.useCallback(()=>{m.current?M():T()},[T,M]);d.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const R=d.useCallback(S=>i(O=>Zl(O,S)),[]),P=d.useCallback((S,O)=>i(Y=>Xl(Y,S,O)),[]),I=d.useCallback((S,O)=>i(Y=>Ql(Y,S,O)),[]),A=d.useCallback((S,O)=>i(Y=>Jl(Y,S,O)),[]),L=d.useCallback((S,O)=>i(Y=>ec(Y,S,O)),[]),E=d.useCallback(S=>i(O=>tc(O,S)),[]),D=d.useCallback(S=>i(O=>nc(O,S)),[]),Z=d.useCallback(()=>i(S=>rc(S)),[]),G=d.useCallback(S=>i(O=>ac(O,S)),[]),F=d.useCallback((S,O)=>i(Y=>sc(Y,S,O)),[]),q=d.useCallback(()=>i(S=>ic(S)),[]),V=d.useCallback(S=>i(O=>({...O,bpm:Math.max(20,Math.min(300,S))})),[]),K=d.useCallback(S=>i(O=>({...O,swing:Math.max(0,Math.min(1,S))})),[]),W=d.useCallback(S=>{i(O=>{if(O.length===S)return O;const Y=Array.from({length:S},(_,U)=>U<O.steps.length?O.steps[U]:{active:!1,note:O.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...O,length:S,steps:Y}})},[]),Q=d.useCallback(S=>{p(O=>[...O,S??zr()])},[]),w=d.useCallback(S=>{p(O=>O.filter((Y,_)=>_!==S))},[]),N=d.useCallback((S,O)=>{p(Y=>Y.map((_,U)=>U===S?{..._,...O}:_))},[]);return{pattern:s,currentStep:o,playing:c,lfos:h,play:T,stop:M,togglePlayback:k,toggle:R,setNote:P,setVelocity:I,setGate:A,setProbability:L,toggleSlide:E,transpose:D,reverse:Z,shift:G,randomizeVel:F,clear:q,setPattern:i,setBpm:V,setSwing:K,setLength:W,addLFO:Q,removeLFO:w,updateLFO:N}}function cs(e){const t=d.useRef(null),n=d.useRef(new Map),a=d.useRef(1),s=d.useCallback(()=>{if(!t.current){const o=e();o.onmessage=l=>{const{id:c}=l.data,u=n.current.get(c);u&&(n.current.delete(c),u.resolve(l.data))},o.onerror=l=>{console.error("[useWorker] Worker error:",l.message);for(const[c,u]of n.current)u.reject(new Error(`Worker error: ${l.message}`));n.current.clear(),o.terminate(),t.current=null},t.current=o}return t.current},[e]);return d.useEffect(()=>{const o=n.current;return()=>{var l;(l=t.current)==null||l.terminate(),t.current=null;for(const[,c]of o)c.reject(new Error("Worker terminated on unmount"));o.clear()}},[]),d.useCallback((o,l)=>{const c=a.current++,u=s();return new Promise((h,p)=>{n.current.set(c,{resolve:h,reject:p}),u.postMessage({...o,id:c},l??[])})},[s])}function U0(){const e=cs(d.useCallback(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/pitchWorker-BgAp5Z97.js").href:new URL("assets/pitchWorker-BgAp5Z97.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:vt&&vt.tagName.toUpperCase()==="SCRIPT"&&vt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return d.useCallback(async(n,a,s=.01)=>(await e({buffer:n,sampleRate:a,rmsThreshold:s})).hz,[e])}function V0(){const e=cs(d.useCallback(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/scoringWorker-3JjtDDtu.js").href:new URL("assets/scoringWorker-3JjtDDtu.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:vt&&vt.tagName.toUpperCase()==="SCRIPT"&&vt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return d.useCallback(async(n,a,s)=>(await e({notes:n,points:a,params:s})).result,[e])}const q0={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function cc(){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:{...Dn,opacity:G.trim().length===0?.5:1},disabled:G.trim().length===0,onClick:()=>$(G),type:"button",children:u("importWizard.parseTracks","Parse Tracks")})]}),(g!==99||j.length>0)&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[r.jsxs("p",{style:{margin:0,fontWeight:600},children:[b==null?void 0:b.name," — ",C.size,"/",j.length," ",u("importWizard.selected","selected")]}),r.jsx("button",{style:lr,onClick:w,type:"button",children:C.size===j.length?u("importWizard.deselectAll","Deselect All"):u("importWizard.selectAll","Select All")})]}),M?r.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.loadingTracks","Loading tracks…")}):r.jsx("div",{style:{maxHeight:320,overflowY:"auto"},children:r.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[r.jsx("thead",{children:r.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-border, #e2e8f0)",textAlign:"left"},children:[r.jsx("th",{style:{padding:"4px 8px",width:32}}),r.jsx("th",{style:{padding:"4px 8px"},children:u("importWizard.colTitle","Title")}),r.jsx("th",{style:{padding:"4px 8px"},children:u("importWizard.artist","Artist")}),r.jsx("th",{style:{padding:"4px 8px"},children:u("importWizard.album","Album")}),r.jsx("th",{style:{padding:"4px 8px",textAlign:"right"},children:u("importWizard.duration","Duration")})]})}),r.jsx("tbody",{children:j.map(z=>{const ee=C.has(z.externalId);return r.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-border, #e2e8f0)",opacity:ee?1:.5,cursor:"pointer"},onClick:()=>Q(z.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:z.title}),r.jsx("td",{style:{padding:"6px 8px",color:"var(--nice-text-dim, #64748b)"},children:z.artist}),r.jsx("td",{style:{padding:"6px 8px",color:"var(--nice-text-dim, #64748b)"},children:z.album??"—"}),r.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--nice-text-dim, #64748b)"},children:vm(z.duration)})]},z.externalId)})})]})}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:r.jsxs("button",{style:{...Dn,opacity:C.size===0?.5:1},disabled:C.size===0,onClick:()=>p("options"),type:"button",children:[u("importWizard.next","Next")," ",r.jsx(B.NtdArrowRight,{size:12})]})})]})]}),X=()=>r.jsxs("div",{style:{display:"grid",gap:16},children:[r.jsx("p",{style:{margin:0,fontWeight:600},children:u("importWizard.importOptions","Import options")}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:D.mergeTags,onChange:z=>Z(ee=>({...ee,mergeTags:z.target.checked}))}),u("importWizard.mergeTags","Merge tags from source playlist")]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:D.mergeFolders,onChange:z=>Z(ee=>({...ee,mergeFolders:z.target.checked}))}),u("importWizard.mergeFolders","Merge into existing folder structure")]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:D.overwriteExisting,onChange:z=>Z(ee=>({...ee,overwriteExisting:z.target.checked}))}),u("importWizard.overwrite","Overwrite existing tracks (match by ISRC)")]}),l&&l.length>0&&r.jsxs("div",{style:{display:"grid",gap:4},children:[r.jsx("label",{style:{fontSize:13,fontWeight:500},children:u("importWizard.targetFolder","Target folder")}),r.jsxs("select",{style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #e2e8f0)"},value:D.targetFolderId??"",onChange:z=>Z(ee=>({...ee,targetFolderId:z.target.value||void 0})),children:[r.jsx("option",{value:"",children:u("importWizard.root","— Root —")}),l.map(z=>r.jsx("option",{value:z.id,children:z.name},z.id))]})]}),r.jsx("div",{style:{marginTop:8,padding:12,borderRadius:8,background:"var(--nice-info-bg, #eff6ff)",fontSize:13},children:u("importWizard.summary",'Ready to import {count} tracks from "{name}"').replace("{count}",String(C.size)).replace("{name}",(b==null?void 0:b.name)??"")}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[r.jsxs("button",{style:lr,onClick:O,type:"button",children:[r.jsx(B.NtdArrowLeft,{size:12})," ",u("importWizard.back","Back")]}),r.jsx("button",{style:Dn,onClick:N,type:"button",children:u("importWizard.startImport","Start Import")})]})]}),re=()=>{const z=R?Math.round(R.imported/R.total*100):0;return r.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[r.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:u("importWizard.importing","Importing…")}),r.jsx("div",{style:{height:8,borderRadius:4,background:"var(--nice-border, #e2e8f0)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${z}%`,background:"var(--nice-color-accent, #6366f1)",borderRadius:4,transition:"width 0.3s"}})}),R&&r.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-dim, #64748b)"},children:[R.imported," / ",R.total," ",u("importWizard.tracks","tracks"),R.currentTrack&&r.jsxs("div",{style:{marginTop:4},children:[r.jsx(B.NtdMusic,{size:12})," ",R.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(B.NtdCheck,{size:48})}),r.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:u("importWizard.complete","Import Complete")}),I&&r.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[r.jsxs("div",{children:[r.jsx("strong",{children:I.imported})," ",u("importWizard.imported","imported")]}),I.skipped>0&&r.jsxs("div",{style:{color:"var(--nice-color-warning, #f59e0b)"},children:[I.skipped," ",u("importWizard.skipped","skipped (duplicates)")]}),I.failed>0&&r.jsxs("div",{style:{color:"var(--nice-color-error, #ef4444)"},children:[I.failed," ",u("importWizard.failed","failed")]}),I.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:u("importWizard.showFailed","Show failed tracks")}),r.jsx("ul",{style:{marginTop:4,paddingLeft:20},children:I.failedTracks.map((z,ee)=>r.jsx("li",{children:z},ee))})]})]}),r.jsx("button",{style:Dn,onClick:o,type:"button",children:u("importWizard.done","Done")})]}),se={connect:u("importWizard.stepConnect","Connect"),browse:u("importWizard.stepBrowse","Browse"),tracks:u("importWizard.stepTracks","Select Tracks"),options:u("importWizard.stepOptions","Options"),importing:u("importWizard.stepImporting","Importing"),done:u("importWizard.stepDone","Done")};return r.jsxs("div",{style:fm,children:[Y(),r.jsxs("div",{style:mm,children:[r.jsxs("h2",{style:{margin:0,fontSize:18},children:[u("importWizard.title","Import Playlist")," — ",se[h]]}),S&&r.jsxs("button",{style:lr,onClick:O,type:"button",children:[r.jsx(B.NtdArrowLeft,{size:12})," ",u("importWizard.back","Back")]}),h==="connect"&&r.jsx("button",{style:lr,onClick:o,type:"button","aria-label":u("importWizard.close","Close"),title:u("importWizard.close","Close"),children:r.jsx(B.NtdClose,{size:14})})]}),L&&r.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--nice-error-bg, #fef2f2)",color:"var(--nice-color-error, #ef4444)",fontSize:13},children:L}),h==="connect"&&_(),h==="browse"&&U(),h==="tracks"&&H(),h==="options"&&X(),h==="importing"&&re(),h==="done"&&oe()]})},xm=[{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}],Sm="concert-harp",ss=Object.fromEntries(xm.map(e=>[e.id,e])),km="nice2dev-note-sound-set";function El(){try{const e=localStorage.getItem(km);if(e&&ss[e])return e}catch{}return Sm}const Dr=["quarter","eighth","sixteenth","beamed"];function $l(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,u=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;u(h),u(p),c.rect(h+a-i,l-o,p-h+i,n*.12)}else{const h=-a*.5;u(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 gi(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 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 oa(e,t){const n=Al(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function wm(e){const t=Al(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function Il(){const e=gi("--text-primary")||ve.resolveCssColor("var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))"),t=gi("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",s=wm(e)<.45;return{base:oa(e,.92),staffLine:oa(e,.22),outline:ve.resolveCssColor(s?"var(--nice-overlay-light-75, rgba(255, 255, 255, 0.75))":"var(--nice-overlay-55, rgba(0, 0, 0, 0.55))"),accents:[oa(t,.95)],isDark:n,notesDark:s}}const Vr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),Ll=46,xt=5,vr=4,Cm=(Ll-(xt-1)*vr)/2,jm=6,Mm=18,Rm=110,Nm=50,qr=Vr?Nm:Rm,Tm=Vr?4:2,Pm=Vr?2:4,yi=Vr?1:0,Em=180,vi=2.8,bi=40,$m=14,xi=1.2,Am=16,la=[64,67,71,74,77],cn=64,zn=77;function Im(e){const t=Math.max(0,Math.min(xt-1,e)),n=Math.floor(t),a=Math.min(n+1,xt-1),s=t-n;return Math.round(la[n]+(la[a]-la[n])*s)}function Lm(e){return(Math.max(cn-1*(zn-cn)/(xt-1),Math.min(zn+1*(zn-cn)/(xt-1),e))-cn)/(zn-cn)*(xt-1)}const Si=2.5,ki=.72,_m=.55,Fn=new Map;let br=null;async function Dm(e){const t=e??El(),n=ss[t];if(!n||!n.dir){Fn.clear(),br=t;return}if(br===t&&Fn.size>0)return;Fn.clear(),br=t;const a=Yn(),s=[];for(let i=cn;i<=zn;i++)s.push(fetch(`/assets/soundfonts/notes/${n.dir}/note-${i}.mp3`).then(o=>o.arrayBuffer()).then(o=>a.decodeAudioData(o)).then(o=>{Fn.set(i,o)}).catch(()=>{}));await Promise.all(s)}function wi(e){const t=Fn.get(e);if(!t)return;const n=Yn(),a=n.createBufferSource();a.buffer=t;const s=n.createGain();s.gain.value=.7,a.connect(s).connect(n.destination),a.start()}function zm(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 Fm(e){const t=zm(42),n=[];for(let a=0;a<e;a++){const i=t()<.15?0:-1;n.push({x:t(),lineIdx:t()*(xt+1)-.5,shape:Dr[Math.floor(t()*Dr.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:i})}return n.sort((a,s)=>a.x-s.x),n}const ut=Fm(qr),Mn=new Float32Array(qr),cr=new Float32Array(qr),On=new Float32Array(qr);let Ma=!1;const Om=(xt-1)/2;function Bm(){if(!Ma){Ma=!0;for(let e=0;e<ut.length;e++)On[e]=ut[e].lineIdx}}let Ra=[],Ci="";function Gm(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function Wm(e){const t=Gm(e);t===Ci&&Ra.length===ut.length||(Ci=t,Ra=ut.map(n=>{const a=Math.ceil(n.size*1.6),s=a*2,i=document.createElement("canvas");i.width=s,i.height=s;const o=i.getContext("2d");return o.translate(a,a),o.rotate(n.rot*Math.PI/180),o.lineWidth=1.8,o.strokeStyle=e.outline,o.fillStyle=n.colorIdx<0?e.base:e.accents[n.colorIdx%e.accents.length],$l(o,n.shape,n.size*1.3),{canvas:i,ox:a,oy:a}}))}function Um({pitchMidiRef:e}={}){const{t}=xe(),n=d.useRef(null),a=d.useRef(0),s=d.useRef(0),i=d.useRef(0),o=d.useRef(null),l=d.useRef(0),c=d.useRef(0),u=d.useRef(null),h=d.useRef(null),p=d.useRef(!1),g=d.useCallback((b,f,j)=>{const v=Cm+b*vr,C=f/j*Math.PI*2;return v+Math.sin(C)*jm},[]),y=d.useCallback(b=>{const f=n.current;if(!f)return;if(c.current++,yi>0&&c.current%(yi+1)!==0){i.current=b,a.current=requestAnimationFrame(y);return}const j=f.getContext("2d");if(!j)return;const v=Math.min(window.devicePixelRatio||1,Pm),C=f.getBoundingClientRect(),T=C.width,M=C.height;(f.width!==Math.round(T*v)||f.height!==Math.round(M*v))&&(f.width=Math.round(T*v),f.height=Math.round(M*v),j.setTransform(v,0,0,v,0,0));const k=i.current?(b-i.current)/1e3:0;i.current=b,s.current=(s.current+Mm*k)%T,j.clearRect(0,0,T,M),l.current++,(!o.current||l.current%60===0)&&(o.current=Il());const R=o.current;Wm(R),j.strokeStyle=R.staffLine,j.lineWidth=.7;for(let L=0;L<xt;L++){j.beginPath();for(let E=0;E<=T;E+=Tm){const D=g(L,E,T);E===0?j.moveTo(E,D):j.lineTo(E,D)}j.stroke()}const P=s.current,I=(e==null?void 0:e.current)??null;if(I!==null){Bm();const L=Lm(I),E=Si*k;for(let D=0;D<ut.length;D++){const G=(ut[D].lineIdx-Om)*_m,q=L*ki+(L+G)*(1-ki)-On[D];On[D]+=q>0?Math.min(E,q):Math.max(-E,q)}}else if(Ma){const L=Si*.4*k;for(let E=0;E<ut.length;E++){const Z=ut[E].lineIdx-On[E];On[E]+=Z>0?Math.min(L,Z):Math.max(-L,Z)}}const A=u.current;A&&(A.timer-=k,A.timer<=0&&(u.current=null));for(let L=0;L<ut.length;L++){const E=ut[L];if(cr[L]>0){cr[L]-=k;const G=Math.max(0,cr[L]/vi);Mn[L]+=Em*G*k,Mn[L]>T&&(Mn[L]-=T)}const D=Ra[L];if(!D)continue;const Z=E.lineIdx;for(let G=0;G<2;G++){let q=((E.x*T-P-Mn[L]+G*T)%T+T)%T;const V=g(Math.max(0,Math.min(xt-1,Math.round(Z))),q,T),K=(Z-Math.round(Z))*vr;let W=V+K;if(A&&A.timer>0){const Q=q-A.x,w=W-A.y,N=Math.sqrt(Q*Q+w*w);if(N<bi&&N>.1){const S=A.timer/xi,O=$m*(1-N/bi)*S;q+=Q/N*O,W+=w/N*O}}j.drawImage(D.canvas,q-D.ox,W-D.oy)}}a.current=requestAnimationFrame(y)},[g,e]),m=d.useCallback(b=>{const f=n.current;if(!f)return;const j=f.getBoundingClientRect(),v=b.clientX-j.left,C=b.clientY-j.top,T=j.width,M=s.current;let k=1/0,R=-1;for(let P=0;P<ut.length;P++){const I=ut[P],L=((I.x*T-M-Mn[P])%T+T)%T,E=g(Math.max(0,Math.min(xt-1,Math.round(I.lineIdx))),L,T),D=(I.lineIdx-Math.round(I.lineIdx))*vr,Z=E+D,G=L-v,F=Z-C,q=G*G+F*F;q<k&&(k=q,R=P)}if(R>=0&&Math.sqrt(k)<Am){cr[R]=vi;const P=ut[R],I=Im(P.lineIdx);try{Xt();const A=El(),L=ss[A];L!=null&&L.dir&&(br!==A||!p.current?(p.current=!0,Dm(A).then(()=>wi(I))):wi(I))}catch{}}u.current={x:v,y:C,timer:xi}},[g]),x=d.useCallback(b=>{const f=n.current;if(!f)return;const j=f.getBoundingClientRect(),v=b.clientX-j.left,C=b.clientY-j.top;h.current={x:v,y:C},u.current&&u.current.timer>0&&(u.current.x=v,u.current.y=C)},[]);return d.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:Ll,marginBottom:5,cursor:"pointer",background:"transparent"}})}const Vm=14,qm=.9,Hm=320,Km=160,Ym=6,ji=8,Zm=14;function Xm(){const{t:e}=xe(),t=d.useRef(null),n=d.useRef([]),a=d.useRef(0),s=d.useRef(0),i=d.useRef([]),o=d.useRef(null),l=d.useRef(0),c=d.useCallback((h,p)=>{for(let g=0;g<Vm;g++){const y=Math.random()*Math.PI*2,m=Km*(.4+Math.random()*.6),x=qm*(.6+Math.random()*.4),b=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)*Ym*2,size:ji+Math.random()*(Zm-ji),shape:Dr[Math.floor(Math.random()*Dr.length)],life:x,maxLife:x,colorIdx:b})}},[]),u=d.useCallback(h=>{const p=t.current;if(!p){a.current=requestAnimationFrame(u);return}const g=p.getContext("2d");if(!g){a.current=requestAnimationFrame(u);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 b=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=Il());const f=o.current;{const v=ve.getInputEngine().gamepadSnapshot;for(let C=0;C<v.length;C++){const T=v[C];for(let M=0;M<T.buttons.length;M++){const k=T.index*100+M,R=T.buttons[M].pressed;R&&!i.current[k]&&c(m/2,x/2),i.current[k]=R}}}const j=[];for(const v of n.current){if(v.life-=b,v.life<=0)continue;v.vy+=Hm*b,v.x+=v.vx*b,v.y+=v.vy*b,v.rot+=v.vr*b;const C=Math.max(0,v.life/v.maxLife),T=.5+.5*C;g.save(),g.globalAlpha=C,g.translate(v.x,v.y),g.rotate(v.rot),g.lineWidth=1.4,g.strokeStyle=f.notesDark?`rgba(255,255,255,${C*.8})`:`rgba(0,0,0,${C*.55})`;const M=v.colorIdx<0?f.base:f.accents[v.colorIdx%f.accents.length];g.fillStyle=M.replace(/[\d.]+\)$/,`${C})`),$l(g,v.shape,v.size*T*1.3),g.restore(),j.push(v)}n.current=j,a.current=requestAnimationFrame(u)},[c]);return d.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(u),()=>{window.removeEventListener("click",h,!0),window.removeEventListener("keydown",p,!0),cancelAnimationFrame(a.current)}},[u,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 xr={type:"gain",enabled:!0,mix:1,gain:0},Bn={type:"compressor",enabled:!0,mix:1,threshold:-24,ratio:4,attack:10,release:100,knee:6,makeupGain:0},Gn={type:"reverb",enabled:!0,mix:.3,decay:2,preDelay:10,damping:.5,roomSize:.5},Wn={type:"delay",enabled:!0,mix:.3,time:250,feedback:.4,pingPong:!1,highCut:8e3},Sr={type:"chorus",enabled:!0,mix:.5,rate:1.5,depth:.5,delay:7,voices:3},kr={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"}]},wr={type:"filter",enabled:!0,mix:1,filterType:"lowpass",frequency:1e3,q:1,gain:0},Cr={type:"distortion",enabled:!0,mix:.5,drive:.5,tone:.5,curve:"soft"},jr={type:"tremolo",enabled:!0,mix:1,rate:5,depth:.5,waveform:"sine"},Mr={type:"phaser",enabled:!0,mix:.5,rate:.5,depth:.5,feedback:.5,stages:4,frequency:1e3},Qm=(function(){return{gain:{unity:{...xr,gain:0},boost:{...xr,gain:6},cut:{...xr,gain:-6}},compressor:{gentle:{...Bn,threshold:-20,ratio:2,attack:30,release:200},moderate:{...Bn,threshold:-24,ratio:4,attack:10,release:100},aggressive:{...Bn,threshold:-30,ratio:8,attack:1,release:50},limiter:{...Bn,threshold:-3,ratio:20,attack:.1,release:100}},reverb:{small_room:{...Gn,decay:.5,roomSize:.2,damping:.7},large_hall:{...Gn,decay:3,roomSize:.8,damping:.3},plate:{...Gn,decay:1.5,roomSize:.5,damping:.4},cathedral:{...Gn,decay:5,roomSize:.9,damping:.2,mix:.4}},delay:{slapback:{...Wn,time:80,feedback:.1,mix:.3},quarter_note:{...Wn,time:500,feedback:.4,mix:.3},dotted_eighth:{...Wn,time:375,feedback:.5,mix:.3},long_ambient:{...Wn,time:750,feedback:.6,highCut:3e3,mix:.4}},chorus:{subtle:{...Sr,rate:.5,depth:.2,voices:2,mix:.3},vintage:{...Sr,rate:1,depth:.4,voices:2,delay:10,mix:.4},ensemble:{...Sr,rate:2,depth:.6,voices:4,mix:.5}},eq:{vocal_presence:{...kr,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:{...kr,bands:[{frequency:60,gain:6,q:1,type:"lowshelf"},{frequency:200,gain:2,q:1,type:"peaking"}]},brightness:{...kr,bands:[{frequency:4e3,gain:3,q:1,type:"peaking"},{frequency:1e4,gain:4,q:1,type:"highshelf"}]}},filter:{low_pass_warm:{...wr,filterType:"lowpass",frequency:2e3,q:.7},high_pass_clean:{...wr,filterType:"highpass",frequency:100,q:.7},telephone:{...wr,filterType:"bandpass",frequency:1500,q:2}},distortion:{overdrive:{...Cr,drive:.3,tone:.6,curve:"soft",mix:.7},crunch:{...Cr,drive:.5,tone:.5,curve:"tube",mix:.8},fuzz:{...Cr,drive:.8,tone:.4,curve:"fuzz",mix:1}},tremolo:{slow:{...jr,rate:3,depth:.4,waveform:"sine"},fast:{...jr,rate:8,depth:.6,waveform:"sine"},choppy:{...jr,rate:6,depth:.9,waveform:"square"}},phaser:{subtle:{...Mr,rate:.3,depth:.3,feedback:.3,stages:4},jet:{...Mr,rate:.1,depth:.8,feedback:.7,stages:8},rotary:{...Mr,rate:1,depth:.5,feedback:.4,stages:6}}}})();function Mi(e){return Math.pow(10,e/20)}function Jm(e,t,n,a){const s=e.sampleRate,i=Math.floor(s*t),o=e.createBuffer(2,i,s);for(let l=0;l<2;l++){const c=o.getChannelData(l);for(let u=0;u<i;u++){const h=u/s,p=Math.exp(-h/n),g=1-a*(u/i);c[u]=(Math.random()*2-1)*p*g}}return o}function e0(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 t0{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=Mi(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=Mi(n.makeupGain),l.connect(c),s.push(l,c),i=l,o=c;break}case"reverb":{const l=a.createConvolver();l.buffer=Jm(a,n.decay,n.decay,n.damping);const c=a.createGain(),u=a.createGain(),h=a.createGain(),p=a.createGain();c.gain.value=n.mix,u.gain.value=1-n.mix,h.connect(l),h.connect(u),l.connect(c),c.connect(p),u.connect(p),s.push(h,l,c,u,p),i=h,o=p;break}case"delay":{const l=a.createDelay(5);l.delayTime.value=n.time/1e3;const c=a.createGain();c.gain.value=n.feedback;const u=a.createBiquadFilter();u.type="lowpass",u.frequency.value=n.highCut;const h=a.createGain(),p=a.createGain(),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(u),u.connect(c),c.connect(l),u.connect(h),h.connect(y),p.connect(y),s.push(g,l,u,c,h,p,y),i=g,o=y;break}case"eq":{const l=[];let c=null;for(const u of n.bands){const h=a.createBiquadFilter();h.type=u.type,h.frequency.value=u.frequency,h.Q.value=u.q,h.gain.value=u.gain,c&&c.connect(h),c=h,l.push(h)}s.push(...l),i=l[0]||a.createGain(),o=l[l.length-1]||i;break}case"filter":{const l=a.createBiquadFilter();l.type=n.filterType,l.frequency.value=n.frequency,l.Q.value=n.q,l.gain.value=n.gain,s.push(l),i=o=l;break}case"distortion":{const l=a.createWaveShaper();l.curve=e0(n.drive,n.curve),l.oversample="4x";const c=a.createBiquadFilter();c.type="lowpass",c.frequency.value=1e3+n.tone*1e4;const u=a.createGain(),h=a.createGain(),p=a.createGain(),g=a.createGain();u.gain.value=n.mix,h.gain.value=1-n.mix,p.connect(l),p.connect(h),l.connect(c),c.connect(u),u.connect(g),h.connect(g),s.push(p,l,c,u,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 u=a.createGain();u.gain.value=1-n.depth*.5,l.connect(c),c.connect(u.gain),l.start(),s.push(l,c,u),i=o=u;break}case"phaser":{const l=[],c=a.createOscillator();c.type="sine",c.frequency.value=n.rate;const u=a.createGain();u.gain.value=n.depth*n.frequency;let h=null;for(let x=0;x<n.stages;x++){const b=a.createBiquadFilter();b.type="allpass",b.frequency.value=n.frequency,b.Q.value=.5,c.connect(u),u.connect(b.frequency),h&&h.connect(b),h=b,l.push(b)}const p=a.createGain(),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,u,...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 _l={gain:r.jsx(B.NtdVolume,{size:16}),compressor:r.jsx(B.NtdSettings,{size:16}),reverb:r.jsx(B.NtdMountain,{size:16}),delay:r.jsx(B.NtdStopwatch,{size:16}),chorus:r.jsx(B.NtdSparkle,{size:16}),eq:r.jsx(B.NtdBarChart,{size:16}),filter:r.jsx(B.NtdFilter,{size:16}),distortion:r.jsx(B.NtdLightning,{size:16}),tremolo:r.jsx(B.NtdWave,{size:16}),phaser:r.jsx(B.NtdMagicWand,{size:16})},Dl={gain:"Gain",compressor:"Compressor",reverb:"Reverb",delay:"Delay",chorus:"Chorus",eq:"EQ",filter:"Filter",distortion:"Distortion",tremolo:"Tremolo",phaser:"Phaser"},n0={gain:xr,compressor:Bn,reverb:Gn,delay:Wn,chorus:Sr,eq:kr,filter:wr,distortion:Cr,tremolo:jr,phaser:Mr},r0=["gain","compressor","reverb","delay","chorus","eq","filter","distortion","tremolo","phaser"],Fe=({value:e,min:t,max:n,step:a=1,label:s,unit:i="",onChange:o,disabled:l})=>{const c=d.useRef(null),[u,h]=d.useState(!1),p=d.useRef(0),g=d.useRef(e),y=d.useCallback(x=>{l||(x.preventDefault(),h(!0),p.current=x.clientY,g.current=e)},[l,e]);d.useEffect(()=>{if(!u)return;const x=f=>{const j=p.current-f.clientY,v=n-t,T=j/200*v,M=Math.min(n,Math.max(t,g.current+T));o(a<1?M:Math.round(M/a)*a)},b=()=>{h(!1)};return document.addEventListener("mousemove",x),document.addEventListener("mouseup",b),()=>{document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",b)}},[u,t,n,a,o]);const m=(e-t)/(n-t)*270-135;return r.jsxs("div",{className:`nice-fx-knob ${l?"nice-fx-knob--disabled":""}`,ref:c,children:[r.jsx("div",{className:`nice-fx-knob__dial ${u?"nice-fx-knob__dial--active":""}`,onMouseDown:y,style:{transform:`rotate(${m}deg)`},children:r.jsx("div",{className:"nice-fx-knob__indicator"})}),r.jsx("div",{className:"nice-fx-knob__label",children:s}),r.jsxs("div",{className:"nice-fx-knob__value",children:[typeof e=="number"&&a<1?e.toFixed(2):e,i]})]})};function a0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:u}=xe();return r.jsx(St,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsx(Fe,{value:e.gain,min:-60,max:12,step:.1,label:u("audioEffectsRack.gain","Gain"),unit:"dB",onChange:h=>t({...e,gain:h}),disabled:!e.enabled})})}function s0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:u}=xe();return r.jsx(St,{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(Fe,{value:e.threshold,min:-60,max:0,label:u("audioEffectsRack.threshold","Threshold"),unit:"dB",onChange:h=>t({...e,threshold:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.ratio,min:1,max:20,label:u("audioEffectsRack.ratio","Ratio"),onChange:h=>t({...e,ratio:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.attack,min:.1,max:200,label:u("audioEffectsRack.attack","Attack"),unit:"ms",onChange:h=>t({...e,attack:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.release,min:10,max:1e3,label:u("audioEffectsRack.release","Release"),unit:"ms",onChange:h=>t({...e,release:h}),disabled:!e.enabled}),!c&&r.jsxs(r.Fragment,{children:[r.jsx(Fe,{value:e.knee,min:0,max:40,label:u("audioEffectsRack.knee","Knee"),unit:"dB",onChange:h=>t({...e,knee:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.makeupGain,min:0,max:24,label:u("audioEffectsRack.makeup","Makeup"),unit:"dB",onChange:h=>t({...e,makeupGain:h}),disabled:!e.enabled})]})]})})}function i0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:u}=xe();return r.jsx(St,{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(Fe,{value:e.decay,min:.1,max:10,step:.1,label:u("audioEffectsRack.decay","Decay"),unit:"s",onChange:h=>t({...e,decay:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.damping,min:0,max:1,step:.01,label:u("audioEffectsRack.damping","Damping"),onChange:h=>t({...e,damping:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.roomSize,min:0,max:1,step:.01,label:u("audioEffectsRack.room","Room"),onChange:h=>t({...e,roomSize:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.mix,min:0,max:1,step:.01,label:u("audioEffectsRack.mix","Mix"),onChange:h=>t({...e,mix:h}),disabled:!e.enabled})]})})}function o0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:u}=xe();return r.jsx(St,{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(Fe,{value:e.time,min:0,max:2e3,label:u("audioEffectsRack.time","Time"),unit:"ms",onChange:h=>t({...e,time:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.feedback,min:0,max:1,step:.01,label:u("audioEffectsRack.feedback","Feedback"),onChange:h=>t({...e,feedback:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.highCut,min:200,max:2e4,label:u("audioEffectsRack.hicut","HiCut"),unit:"Hz",onChange:h=>t({...e,highCut:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.mix,min:0,max:1,step:.01,label:u("audioEffectsRack.mix","Mix"),onChange:h=>t({...e,mix:h}),disabled:!e.enabled})]})})}function l0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:u}=xe();return r.jsx(St,{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(Fe,{value:e.drive,min:0,max:1,step:.01,label:u("audioEffectsRack.drive","Drive"),onChange:h=>t({...e,drive:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.tone,min:0,max:1,step:.01,label:u("audioEffectsRack.tone","Tone"),onChange:h=>t({...e,tone:h}),disabled:!e.enabled}),r.jsx(Fe,{value:e.mix,min:0,max:1,step:.01,label:u("audioEffectsRack.mix","Mix"),onChange:h=>t({...e,mix:h}),disabled:!e.enabled})]})})}function St({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:u}){const{t:h}=xe(),[p,g]=d.useState(!1);return r.jsxs("div",{className:`nice-fx-card ${e.enabled?"":"nice-fx-card--disabled"} ${i?"nice-fx-card--drop-target":""} ${c?"nice-fx-card--compact":""}`,draggable:!0,onDragStart:a,onDragEnd:s,children:[r.jsxs("div",{className:"nice-fx-card__header",children:[r.jsx("span",{className:"nice-fx-card__icon",children:_l[e.type]}),r.jsx("span",{className:"nice-fx-card__title",children:Dl[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?h("audioEffectsRack.disable","Disable"):h("audioEffectsRack.enable","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(B.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(ve.NiceIcon,{name:"close",size:14})})]}),r.jsx("div",{className:"nice-fx-card__body",children:u})]})}function c0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){const{t:u}=xe();return r.jsx(St,{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(Fe,{value:e.mix,min:0,max:1,step:.01,label:u("audioEffectsRack.mix","Mix"),onChange:h=>t({...e,mix:h}),disabled:!e.enabled})})})}function d0({effect:e,onChange:t,...n}){const{t:a}=xe(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(St,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Fe,{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(Fe,{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(Fe,{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(Fe,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}function u0({effect:e,onChange:t,...n}){const{t:a}=xe(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(St,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Fe,{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(Fe,{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(Fe,{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(Fe,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}function h0({effect:e,onChange:t,...n}){const{t:a}=xe(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(St,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Fe,{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(Fe,{value:s.Q??1,min:.1,max:20,step:.1,label:"Q",onChange:o=>i("Q",o),disabled:!e.enabled}),r.jsx(Fe,{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(Fe,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}function p0({effect:e,onChange:t,...n}){const{t:a}=xe(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(St,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Fe,{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(Fe,{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(Fe,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}function f0({effect:e,onChange:t,...n}){const{t:a}=xe(),s=e.params||{},i=(o,l)=>t({...e,params:{...s,[o]:l}});return r.jsx(St,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Fe,{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(Fe,{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(Fe,{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(Fe,{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(Fe,{value:e.mix,min:0,max:1,step:.01,label:a("audioEffectsRack.mix","Mix"),onChange:o=>t({...e,mix:o}),disabled:!e.enabled})]})})}const m0=({audioContext:e,chain:t,effects:n,onChange:a,onChainUpdate:s,maxEffects:i=10,availableEffects:o=r0,showPresets:l=!0,compact:c=!1,className:u=""})=>{const{t:h}=xe(),[p,g]=d.useState((n==null?void 0:n.map(P=>P.params))||[]),[y,m]=d.useState({isDragging:!1,dragIndex:-1,dropIndex:-1}),[x,b]=d.useState(!1),f=d.useMemo(()=>t||(e?new t0(e):null),[e,t]),j=d.useCallback((P,I)=>{const A=[...p];A[P]=I,g(A),a==null||a(A),f&&(s==null||s(f))},[p,a,f,s]),v=d.useCallback(P=>{if(p.length>=i)return;const I={...n0[P]},A=[...p,I];g(A),a==null||a(A),b(!1)},[p,i,a]),C=d.useCallback(P=>{const I=p.filter((A,L)=>L!==P);g(I),a==null||a(I)},[p,a]),T=d.useCallback(P=>{m({isDragging:!0,dragIndex:P,dropIndex:-1})},[]),M=d.useCallback(()=>{if(y.dragIndex!==-1&&y.dropIndex!==-1&&y.dragIndex!==y.dropIndex){const P=[...p],[I]=P.splice(y.dragIndex,1);P.splice(y.dropIndex,0,I),g(P),a==null||a(P)}m({isDragging:!1,dragIndex:-1,dropIndex:-1})},[y,p,a]),k=d.useCallback((P,I)=>{P.preventDefault(),y.isDragging&&m(A=>({...A,dropIndex:I}))},[y.isDragging]),R=(P,I)=>{const A={onRemove:()=>C(I),onDragStart:()=>T(I),onDragEnd:M,isDragTarget:y.dropIndex===I,presets:Qm[P.type]||{},showPresets:l,compact:c};switch(P.type){case"gain":return r.jsx(a0,{effect:P,onChange:L=>j(I,L),...A},I);case"compressor":return r.jsx(s0,{effect:P,onChange:L=>j(I,L),...A},I);case"reverb":return r.jsx(i0,{effect:P,onChange:L=>j(I,L),...A},I);case"delay":return r.jsx(o0,{effect:P,onChange:L=>j(I,L),...A},I);case"distortion":return r.jsx(l0,{effect:P,onChange:L=>j(I,L),...A},I);case"chorus":return r.jsx(d0,{effect:P,onChange:L=>j(I,L),...A},I);case"eq":return r.jsx(u0,{effect:P,onChange:L=>j(I,L),...A},I);case"filter":return r.jsx(h0,{effect:P,onChange:L=>j(I,L),...A},I);case"tremolo":return r.jsx(p0,{effect:P,onChange:L=>j(I,L),...A},I);case"phaser":return r.jsx(f0,{effect:P,onChange:L=>j(I,L),...A},I);default:return r.jsx(c0,{effect:P,onChange:L=>j(I,L),...A},I)}};return r.jsxs("div",{className:`nice-fx-rack ${c?"nice-fx-rack--compact":""} ${u}`,children:[r.jsxs("div",{className:"nice-fx-rack__header",children:[r.jsx("h3",{className:"nice-fx-rack__title",children: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:h("audioEffectsRack.noEffectsClickToAdd","No effects. Click + to add.")}):p.map((P,I)=>r.jsxs("div",{className:"nice-fx-rack__slot",onDragOver:A=>k(A,I),children:[R(P,I),I<p.length-1&&r.jsx("div",{className:"nice-fx-rack__connector","aria-hidden":"true",children:r.jsx(B.NtdArrowRight,{size:14})})]},I))}),p.length<i&&r.jsxs("div",{className:"nice-fx-rack__add",children:[r.jsx("button",{type:"button",className:"nice-fx-rack__add-btn",onClick:()=>b(!x),children:h("audioEffectsRack.addEffect","+ Add Effect")}),x&&r.jsx("div",{className:"nice-fx-rack__add-menu",children:o.map(P=>r.jsxs("button",{type:"button",className:"nice-fx-rack__add-item",onClick:()=>v(P),children:[r.jsx("span",{className:"nice-fx-rack__add-icon",children:_l[P]}),r.jsx("span",{className:"nice-fx-rack__add-label",children:Dl[P]})]},P))})]})]})},zl=[{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 Ri(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 dr(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 Fl{constructor(){this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.activeEffects=new Map,this.effectOrder=[],this.monitoring=!0,this._volume=1,this._inputVolume=1,this.started=!1,this.externalStream=!1,this.analyser=null}get isStarted(){return this.started}get context(){return this.audioCtx}get activeEffectTypes(){return[...this.effectOrder]}async start(t){this.started||(this.audioCtx=new AudioContext,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),this.sourceNode=this.audioCtx.createMediaStreamSource(this.mediaStream),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}async startWithStream(t){this.started||(this.externalStream=!0,this.audioCtx=new AudioContext,this.mediaStream=t,this.sourceNode=this.audioCtx.createMediaStreamSource(t),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}stop(){var t,n,a,s,i,o;this.clearAllEffects();try{(t=this.analyser)==null||t.disconnect()}catch{}try{(n=this.outputGain)==null||n.disconnect()}catch{}try{(a=this.inputGain)==null||a.disconnect()}catch{}try{(s=this.sourceNode)==null||s.disconnect()}catch{}try{(i=this.audioCtx)==null||i.close()}catch{}if(!this.externalStream)try{(o=this.mediaStream)==null||o.getTracks().forEach(l=>l.stop())}catch{}this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.analyser=null,this.started=!1}setMonitoring(t){this.monitoring=t,this.outputGain&&(this.outputGain.gain.value=t?this._volume:0)}setVolume(t){this._volume=Math.max(0,Math.min(2,t)),this.outputGain&&this.monitoring&&(this.outputGain.gain.value=this._volume)}setInputGain(t){this._inputVolume=Math.max(0,Math.min(3,t)),this.inputGain&&(this.inputGain.gain.value=this._inputVolume)}getLevel(){if(!this.analyser)return 0;const t=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(t);let n=0;for(let a=0;a<t.length;a++){const s=(t[a]-128)/128;n+=s*s}return Math.sqrt(n/t.length)}addEffect(t,n=50){if(!this.audioCtx||!this.inputGain||!this.outputGain||this.activeEffects.has(t))return;const a=this.buildEffectChain(t,n);a&&(this.activeEffects.set(t,a),this.effectOrder.push(t),this.reconnectChain())}removeEffect(t){const n=this.activeEffects.get(t);if(n){for(const a of n.nodes)try{a.disconnect()}catch{}this.activeEffects.delete(t),this.effectOrder=this.effectOrder.filter(a=>a!==t),this.reconnectChain()}}toggleEffect(t,n=50){return this.activeEffects.has(t)?(this.removeEffect(t),!1):(this.addEffect(t,n),!0)}updateIntensity(t,n){this.activeEffects.has(t)&&(this.removeEffect(t),this.addEffect(t,n))}clearAllEffects(){for(const[t]of this.activeEffects){const n=this.activeEffects.get(t);if(n)for(const a of n.nodes)try{a.disconnect()}catch{}}this.activeEffects.clear(),this.effectOrder=[],this.reconnectChain()}reconnectChain(){if(!this.inputGain||!this.outputGain)return;try{this.inputGain.disconnect()}catch{}for(const[,n]of this.activeEffects)try{n.output.disconnect()}catch{}if(this.effectOrder.length===0){this.inputGain.connect(this.outputGain);return}let t=this.inputGain;for(const n of this.effectOrder){const a=this.activeEffects.get(n);a&&(t.connect(a.input),t=a.output)}t.connect(this.outputGain)}buildEffectChain(t,n){const a=this.audioCtx,s=n/100;switch(t){case"chipmunk":return this.buildPitchShift(a,1+s*.8,s);case"helium":return this.buildPitchShift(a,1.5+s*1,s);case"deep":return this.buildPitchShift(a,1/(1+s*.5),s);case"demon":return this.buildDemon(a,s);case"robot":return this.buildRobot(a,s);case"alien":return this.buildAlien(a,s);case"echo":return this.buildDelay(a,.15+s*.35,.3+s*.4,s);case"cave":return this.buildCave(a,s);case"reverb":return this.buildReverb(a,1.5+s*3,2+s*4,s);case"chorus":return this.buildChorus(a,s);case"flanger":return this.buildFlanger(a,s);case"distortion":return this.buildDistortion(a,20+s*100,s);case"telephone":return this.buildBandpass(a,400,3500,s);case"megaphone":return this.buildMegaphone(a,s);case"radio":return this.buildRadio(a,s);case"underwater":return this.buildUnderwater(a,s);case"whisper":return this.buildWhisper(a,s);case"tremolo":return this.buildTremolo(a,s);case"autotune":return this.buildAutotune(a,s);case"vocoder":return this.buildVocoder(a,s);default:return null}}buildPitchShift(t,n,a){const s=t.createGain();s.gain.value=1;const i=t.createGain();i.gain.value=1;const o=t.createGain();o.gain.value=.7+a*.3;const l=t.createGain();l.gain.value=1-a*.5;const c=t.createDelay(1),u=t.createDelay(1),h=t.createOscillator(),p=t.createOscillator(),g=t.createGain(),y=t.createGain(),m=n-1,x=Math.abs(m)*5+2,b=Math.abs(m)*.015;h.type="sawtooth",h.frequency.value=x,g.gain.value=b,h.connect(g),g.connect(c.delayTime),c.delayTime.value=.02,p.type="sawtooth",p.frequency.value=x,y.gain.value=b,p.connect(y),y.connect(u.delayTime),u.delayTime.value=.02+b;const f=t.createGain();f.gain.value=.5;const j=t.createGain();return j.gain.value=.5,s.connect(c),s.connect(u),c.connect(f),u.connect(j),f.connect(o),j.connect(o),s.connect(l),o.connect(i),l.connect(i),h.start(),p.start(),{type:"chipmunk",nodes:[s,c,u,h,p,g,y,f,j,o,l,i],input:s,output:i}}buildRobot(t,n){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=.6+n*.4;const o=t.createGain();o.gain.value=1-n*.6;const l=t.createOscillator();l.type="square",l.frequency.value=50+n*200;const c=t.createGain();return c.gain.value=0,l.connect(c.gain),a.connect(c),c.connect(i),a.connect(o),i.connect(s),o.connect(s),l.start(),{type:"robot",nodes:[a,l,c,i,o,s],input:a,output:s}}buildAlien(t,n){const a=t.createGain(),s=t.createGain(),i=t.createOscillator();i.type="sine",i.frequency.value=300+n*700;const o=t.createGain();o.gain.value=0,i.connect(o.gain),a.connect(o);const l=t.createDelay(.1);l.delayTime.value=.005;const c=t.createOscillator();c.type="sine",c.frequency.value=3+n*10;const u=t.createGain();u.gain.value=.004,c.connect(u),u.connect(l.delayTime),o.connect(l),l.connect(s);const h=t.createGain();return h.gain.value=.3,a.connect(h),h.connect(s),i.start(),c.start(),{type:"alien",nodes:[a,i,o,l,c,u,h,s],input:a,output:s}}buildDelay(t,n,a,s){const i=t.createGain(),o=t.createGain(),l=t.createDelay(2);l.delayTime.value=n;const c=t.createGain();c.gain.value=Math.min(.85,a);const u=t.createGain();u.gain.value=.5+s*.5;const h=t.createGain();return h.gain.value=1,i.connect(l),l.connect(c),c.connect(l),l.connect(u),i.connect(h),u.connect(o),h.connect(o),{type:"echo",nodes:[i,l,c,u,h,o],input:i,output:o}}buildCave(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(2);i.delayTime.value=.2+n*.3;const o=t.createDelay(2);o.delayTime.value=.35+n*.25;const l=t.createDelay(2);l.delayTime.value=.55+n*.3;const c=t.createGain();c.gain.value=.5;const u=t.createGain();u.gain.value=.35;const h=t.createGain();h.gain.value=.25;const p=t.createConvolver();p.buffer=Ri(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(u),u.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,u,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=Ri(t,n,a);const c=t.createGain();c.gain.value=.4+s*.5;const u=t.createGain();return u.gain.value=1,i.connect(l),l.connect(c),i.connect(u),c.connect(o),u.connect(o),{type:"reverb",nodes:[i,l,c,u,o],input:i,output:o}}buildChorus(t,n){const a=t.createGain(),s=t.createGain(),i=[{delayMs:20,lfoFreq:.5,depth:.003},{delayMs:25,lfoFreq:.7,depth:.004},{delayMs:30,lfoFreq:1.1,depth:.005}],o=[a,s],l=t.createGain();l.gain.value=.7,a.connect(l),l.connect(s),o.push(l);for(const c of i){const u=t.createDelay(.1);u.delayTime.value=c.delayMs/1e3;const h=t.createOscillator();h.type="sine",h.frequency.value=c.lfoFreq;const p=t.createGain();p.gain.value=c.depth*(.5+n),h.connect(p),p.connect(u.delayTime);const g=t.createGain();g.gain.value=.3+n*.2,a.connect(u),u.connect(g),g.connect(s),h.start(),o.push(u,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 u=t.createGain();u.gain.value=.5+n*.3;const h=t.createGain();return h.gain.value=1,a.connect(i),i.connect(c),c.connect(i),i.connect(u),a.connect(h),u.connect(s),h.connect(s),o.start(),{type:"flanger",nodes:[a,i,o,l,c,u,h,s],input:a,output:s}}buildDistortion(t,n,a){const s=t.createGain(),i=t.createGain(),o=t.createWaveShaper();o.curve=dr(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=dr(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=dr(10),a.connect(i),i.connect(o),o.connect(l),l.connect(c),c.connect(s),{type:"radio",nodes:[a,i,o,l,c,s],input:a,output:s}}buildUnderwater(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="lowpass",i.frequency.value=300+(1-n)*400,i.Q.value=5+n*10;const o=t.createOscillator();o.type="sine",o.frequency.value=.5+n*2;const l=t.createGain();l.gain.value=100+n*200,o.connect(l),l.connect(i.frequency);const c=t.createGain();c.gain.value=.7+n*.3;const u=t.createGain();return u.gain.value=.3-n*.2,a.connect(i),i.connect(c),a.connect(u),c.connect(s),u.connect(s),o.start(),{type:"underwater",nodes:[a,i,o,l,c,u,s],input:a,output:s}}buildWhisper(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500+n*500,i.Q.value=.5;const o=t.createWaveShaper(),l=new Float32Array(256);for(let u=0;u<256;u++){const h=u/255*2-1;l[u]=Math.sign(h)*Math.pow(Math.abs(h),.3+n*.5)}o.curve=l;const c=t.createBiquadFilter();return c.type="highshelf",c.frequency.value=3e3,c.gain.value=6+n*6,a.connect(i),i.connect(o),o.connect(c),c.connect(s),{type:"whisper",nodes:[a,i,o,c,s],input:a,output:s}}buildDemon(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.1);i.delayTime.value=.03;const o=t.createOscillator();o.type="sawtooth",o.frequency.value=2+n*3;const l=t.createGain();l.gain.value=.02+n*.015,o.connect(l),l.connect(i.delayTime);const c=t.createWaveShaper();c.curve=dr(20+n*50),c.oversample="2x";const u=t.createBiquadFilter();u.type="lowshelf",u.frequency.value=200,u.gain.value=8+n*8;const h=t.createGain();h.gain.value=.7+n*.3;const p=t.createGain();return p.gain.value=.3,a.connect(i),i.connect(c),c.connect(u),u.connect(h),a.connect(p),h.connect(s),p.connect(s),o.start(),{type:"demon",nodes:[a,i,o,l,c,u,h,p,s],input:a,output:s}}buildTremolo(t,n){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=1;const o=t.createOscillator();o.type="sine",o.frequency.value=3+n*12;const l=t.createGain();return l.gain.value=.3+n*.5,o.connect(l),l.connect(i.gain),a.connect(i),i.connect(s),o.start(),{type:"tremolo",nodes:[a,i,o,l,s],input:a,output:s}}buildAutotune(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.05);i.delayTime.value=.005;const o=t.createOscillator();o.type="sine",o.frequency.value=6+n*8;const l=t.createGain();l.gain.value=.002+n*.002,o.connect(l),l.connect(i.delayTime);const c=[],u=[261.6,293.7,329.6,349.2,392,440,493.9,523.3],h=t.createGain();h.gain.value=.15;for(const y of u){const m=t.createBiquadFilter();m.type="peaking",m.frequency.value=y,m.Q.value=8+n*15,m.gain.value=4+n*8,a.connect(m),m.connect(h),c.push(m)}const p=t.createGain();p.gain.value=.7;const 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],u=t.createGain();u.gain.value=.5+n*.5,c.push(u);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(u),c.push(y,m,x)}u.connect(s);const h=t.createGain();return h.gain.value=.3-n*.2,a.connect(h),h.connect(s),c.push(h),i.start(),{type:"vocoder",nodes:c,input:a,output:s}}}const g0={sparkle:B.NtdSparkle,music:B.NtdMusic,skull:B.NtdSkull,robot:B.NtdRobot,ghost:B.NtdGhost,mountain:B.NtdMountain,wave:B.NtdWave,lightning:B.NtdLightning,phone:B.NtdPhone,megaphone:B.NtdMegaphone,"volume-mute":B.NtdVolumeMute,microphone:B.NtdMicrophone,volume:B.NtdVolume},y0=({deviceId:e,mediaStream:t,compact:n=!1,t:a,className:s,style:i,id:o,accessMode:l,"data-testid":c})=>{const{t:u}=xe(),h=a??u,p=d.useRef(null),[g,y]=d.useState(!1),[m,x]=d.useState(()=>zl.map(F=>({...F}))),[b,f]=d.useState(!0),[j,v]=d.useState(80),[C,T]=d.useState(100),[M,k]=d.useState(0),R=d.useRef(0),P=d.useCallback(()=>{const F=()=>{var q;(q=p.current)!=null&&q.isStarted&&(k(p.current.getLevel()),R.current=requestAnimationFrame(F))};R.current=requestAnimationFrame(F)},[]),I=d.useCallback(()=>{R.current&&cancelAnimationFrame(R.current)},[]),A=d.useCallback(async()=>{const F=new Fl;p.current=F;try{t?await F.startWithStream(t):await F.start(e),F.setMonitoring(b),F.setVolume(j/100),F.setInputGain(C/100);for(const q of m)q.enabled&&F.addEffect(q.type,q.intensity);y(!0),P()}catch(q){typeof console<"u"&&console.warn("[VocalEffectsRack] start error",q)}},[e,t,b,j,C,m,P]),L=d.useCallback(()=>{var F;I(),(F=p.current)==null||F.stop(),p.current=null,y(!1),k(0)},[I]);d.useEffect(()=>()=>{var F;I(),(F=p.current)==null||F.stop(),p.current=null},[I]);const E=d.useCallback(F=>{x(q=>q.map(V=>{var W;if(V.type!==F)return V;const K={...V,enabled:!V.enabled};return(W=p.current)!=null&&W.isStarted&&(K.enabled?p.current.addEffect(F,K.intensity):p.current.removeEffect(F)),K}))},[]),D=d.useCallback((F,q)=>{x(V=>V.map(K=>{var W;return K.type!==F?K:(K.enabled&&((W=p.current)!=null&&W.isStarted)&&p.current.updateIntensity(F,q),{...K,intensity:q})}))},[]);d.useEffect(()=>{var F;(F=p.current)==null||F.setVolume(j/100)},[j]),d.useEffect(()=>{var F;(F=p.current)==null||F.setInputGain(C/100)},[C]),d.useEffect(()=>{var F;(F=p.current)==null||F.setMonitoring(b)},[b]);const Z=d.useCallback(()=>{var F;(F=p.current)==null||F.clearAllEffects(),x(q=>q.map(V=>({...V,enabled:!1})))},[]),G=m.filter(F=>F.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(B.NtdMicrophone,{size:n?16:20})," ",h("vocalEffects.title","Vocal effects")]}),r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[G>0&&r.jsxs(ie.NiceBadge,{variant:"primary",children:[G," ",h("vocalEffects.active","active")]}),g?r.jsx(ie.NiceButton,{variant:"danger",size:"sm",onClick:L,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:b,onChange:f,label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.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:j,onChange:v,min:0,max:200})}),r.jsxs("span",{style:{minWidth:36,fontSize:12},children:[j,"%"]})]}),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:C,onChange:T,min:0,max:300})}),r.jsxs("span",{style:{minWidth:36,fontSize:12},children:[C,"%"]})]}),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,M*300)}%`,background:M>.5?"var(--nice-danger, #ef4444)":M>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})}),G>0&&r.jsx(ie.NiceButton,{variant:"ghost",size:"sm",onClick:Z,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(F=>r.jsxs("div",{style:{border:F.enabled?"2px solid var(--nice-accent, #3b82f6)":"1px solid var(--nice-border, #e2e8f0)",borderRadius:10,padding:n?"6px 8px":"10px 12px",background:F.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:()=>E(F.type),style:{display:"flex",alignItems:"center",gap:6,width:"100%",marginBottom:F.enabled?6:0,background:"transparent",border:"none",cursor:"pointer",color:"inherit",textAlign:"left"},children:[(()=>{const q=g0[F.icon]??B.NtdMusic;return r.jsx(q,{size:n?18:22})})(),r.jsx("span",{style:{fontSize:n?12:14,fontWeight:F.enabled?700:500,color:F.enabled?"var(--nice-accent, #3b82f6)":"inherit"},children:F.label})]}),F.enabled&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},onClick:q=>q.stopPropagation(),onKeyDown:q=>{q.key!=="Escape"&&q.stopPropagation()},children:[r.jsx("div",{style:{flex:1},children:r.jsx(ie.NiceSlider,{value:F.intensity,onChange:q=>D(F.type,q),min:0,max:100})}),r.jsx("span",{style:{fontSize:11,minWidth:24,color:"var(--nice-text-muted, #64748b)"},children:F.intensity})]})]},F.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.")})]})},Ol={algorithm:"pitchy",gain:1,rmsThreshold:.02,pitchThreshold:.6,smoothingWindow:3,hysteresisFrames:2,useHanning:!1,offsetMs:0},v0=[{value:"pitchy",label:"Pitchy (fast)"},{value:"autocorrelation",label:"Autocorrelation"},{value:"librosa",label:"Librosa (server)"},{value:"crepe",label:"CREPE (AI, server)"}],b0=({deviceId:e,onDeviceChange:t,settings:n,onSettingsChange:a,audioInputs:s,algorithms:i=v0,showLevelMeter:o=!0,onCalibrate:l,compact:c=!1,t:u})=>{const{t:h}=xe(),p=u??h,g=d.useMemo(()=>({...Ol,...n}),[n]),y=A=>a==null?void 0:a({...g,...A}),[m,x]=d.useState([]);d.useEffect(()=>{var E,D,Z;if(s||!((E=navigator.mediaDevices)!=null&&E.enumerateDevices))return;let A=!1;const L=()=>navigator.mediaDevices.enumerateDevices().then(G=>!A&&x(G.filter(F=>F.kind==="audioinput"))).catch(()=>{});return L(),(Z=(D=navigator.mediaDevices).addEventListener)==null||Z.call(D,"devicechange",L),()=>{var G,F;A=!0,(F=(G=navigator.mediaDevices).removeEventListener)==null||F.call(G,"devicechange",L)}},[s]);const b=s??m,f=d.useMemo(()=>b.map((A,L)=>({value:A.deviceId,label:A.label||`${p("audioInput.microphone","Microphone")} ${L+1}`})),[b,p]),[j,v]=d.useState(!1),[C,T]=d.useState(0),M=d.useRef(null),k=()=>{const A=M.current;A&&(cancelAnimationFrame(A.raf),A.stream.getTracks().forEach(L=>L.stop()),A.ctx.close().catch(()=>{}),M.current=null),v(!1),T(0)},R=async()=>{try{const A=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0}}),L=new AudioContext,E=L.createMediaStreamSource(A),D=L.createAnalyser();D.fftSize=1024,E.connect(D);const Z=new Float32Array(D.fftSize),G=()=>{D.getFloatTimeDomainData(Z);let F=0;for(let q=0;q<Z.length;q++)F+=Z[q]*Z[q];T(Math.sqrt(F/Z.length)*(g.gain||1)),M.current.raf=requestAnimationFrame(G)};M.current={ctx:L,stream:A,raf:requestAnimationFrame(G)},v(!0)}catch{}};d.useEffect(()=>()=>k(),[]);const P={fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:4,display:"block"},I=(A,L,E)=>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:L}),r.jsx("span",{style:{flex:"0 0 48px",textAlign:"right",fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:E})]});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:{...P,display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.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:P,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:[I(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)}%`),I(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)),I(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&&I(p("audioInput.smoothing","Smoothing"),r.jsx(ie.NiceSlider,{value:g.smoothingWindow,onChange:A=>y({smoothingWindow:A}),min:0,max:12}),`${g.smoothingWindow}`),!c&&I(p("audioInput.hysteresis","Hysteresis"),r.jsx(ie.NiceSlider,{value:g.hysteresisFrames,onChange:A=>y({hysteresisFrames:A}),min:0,max:12}),`${g.hysteresisFrames}`),!c&&I(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:j?"danger":"secondary",size:"sm",onClick:j?k:R,children:j?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,C*300)}%`,background:C>.5?"var(--nice-danger, #ef4444)":C>.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(B.NtdSettings,{size:14})," ",p("audioInput.calibrate","Calibrate latency")]})]})]})};class Bl{constructor(t,n){this.activeNotes=new Map,this.audioContext=t,this.masterGain=t.createGain(),this.masterGain.gain.value=.3,this.masterGain.connect(n)}applyCC(t,n,a){}midiToFreq(t){return 440*Math.pow(2,(t-69)/12)}playNote(t,n=100,a=1,s="sine"){const i=this.midiToFreq(t),o=this.audioContext.createOscillator(),l=this.audioContext.createGain();o.type=s,o.frequency.value=i;const c=n/127*.8;l.gain.value=c,o.connect(l),l.connect(this.masterGain);const u=this.audioContext.currentTime;return l.gain.setValueAtTime(0,u),l.gain.linearRampToValueAtTime(c,u+.01),l.gain.exponentialRampToValueAtTime(c*.7,u+.1),l.gain.setValueAtTime(c*.7,u+a-.05),l.gain.exponentialRampToValueAtTime(.001,u+a),o.start(u),o.stop(u+a),o.onended=()=>{l.disconnect(),o.disconnect()},{osc:o,gain:l}}scheduleNote(t,n,a,s=100,i="sine"){const o=this.midiToFreq(t),l=this.audioContext.createOscillator(),c=this.audioContext.createGain();l.type=i,l.frequency.value=o;const u=s/127*.8;l.connect(c),c.connect(this.masterGain);const h=n;return c.gain.setValueAtTime(0,h),c.gain.linearRampToValueAtTime(u,h+.01),c.gain.exponentialRampToValueAtTime(u*.7,h+.1),c.gain.setValueAtTime(u*.7,h+a-.05),c.gain.exponentialRampToValueAtTime(.001,h+a),l.start(h),l.stop(h+a),l.onended=()=>{c.disconnect(),l.disconnect()},{osc:l,gain:c}}setVolume(t){this.masterGain.gain.value=Math.max(0,Math.min(1,t))}stopAll(){this.activeNotes.forEach(({osc:t,gain:n})=>{try{t.stop(),n.disconnect(),t.disconnect()}catch{}}),this.activeNotes.clear()}dispose(){this.stopAll(),this.masterGain.disconnect()}}const Ni=st.scoped("AudioPlaybackEngine");class x0{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){Ni.error("Failed to initialize AudioContext:",t)}}createEffectNode(t){if(!this.audioContext||t.bypass)return null;try{switch(t.type){case"eq3":{const n=this.audioContext.createBiquadFilter(),a=this.audioContext.createBiquadFilter(),s=this.audioContext.createBiquadFilter();return n.type="lowshelf",n.frequency.value=t.params.lowFreq||250,n.gain.value=t.params.lowGain||0,a.type="peaking",a.frequency.value=1e3,a.Q.value=1,a.gain.value=t.params.midGain||0,s.type="highshelf",s.frequency.value=t.params.highFreq||4e3,s.gain.value=t.params.highGain||0,n.connect(a),a.connect(s),{input:n,output:s}}case"compressor":{const n=this.audioContext.createDynamicsCompressor();return n.threshold.value=t.params.threshold||-24,n.ratio.value=t.params.ratio||4,n.attack.value=t.params.attack||.003,n.release.value=t.params.release||.25,n.knee.value=t.params.knee||30,n}case"delay":{const n=this.audioContext.createDelay(5);n.delayTime.value=t.params.time||.25;const a=this.audioContext.createGain();a.gain.value=t.params.feedback||.3;const s=this.audioContext.createGain();s.gain.value=t.params.mix||.3;const i=this.audioContext.createGain();return i.gain.value=1-(t.params.mix||.3),n.connect(a),a.connect(n),n.connect(s),{input:n,output:s,dry:i,connect:function(o){s.connect(o),i.connect(o)}}}case"reverb":{const n=this.audioContext.createConvolver(),a=this.audioContext.sampleRate*(t.params.decay||2),s=this.audioContext.createBuffer(2,a,this.audioContext.sampleRate);for(let l=0;l<2;l++){const c=s.getChannelData(l);for(let u=0;u<a;u++)c[u]=(Math.random()*2-1)*Math.pow(1-u/a,2)}n.buffer=s;const i=this.audioContext.createGain();i.gain.value=t.params.mix||.3;const o=this.audioContext.createGain();return o.gain.value=1-(t.params.mix||.3),n.connect(i),{input:n,output:i,dry:o,connect:function(l){i.connect(l),o.connect(l)}}}case"distortion":{const n=this.audioContext.createWaveShaper(),a=t.params.amount||20,s=44100,i=new Float32Array(s),o=Math.PI/180;for(let u=0;u<s;u++){const h=u*2/s-1;i[u]=(3+a)*h*20*o/(Math.PI+a*Math.abs(h))}n.curve=i,n.oversample="4x";const l=this.audioContext.createGain();l.gain.value=t.params.mix||.5;const c=this.audioContext.createGain();return c.gain.value=1-(t.params.mix||.5),n.connect(l),{input:n,output:l,dry:c,connect:function(u){l.connect(u),c.connect(u)}}}default:return null}}catch(n){return Ni.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 Bl(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),u=this.audioContext.currentTime+(l-this.currentTime);u>=this.audioContext.currentTime&&(a.start(u,t.offset+c,t.duration-c),this.scheduledSources.set(t.id,a),a.onended=()=>{this.scheduledSources.delete(t.id)})})}stopClip(t){const n=this.scheduledSources.get(t);if(n){try{n.stop()}catch{}this.scheduledSources.delete(t)}}stopAllSources(){this.scheduledSources.forEach(t=>{try{t.stop()}catch{}}),this.scheduledSources.clear(),this.synths.forEach(t=>t.stopAll())}scheduleMidiNotes(){this.audioContext&&this.midiTracks.forEach(t=>{const n=this.synths.get(t.layerId);if(n&&(t.notes.forEach(a=>{if(a.start+a.duration<=this.currentTime)return;const i=Math.max(0,this.currentTime-a.start),o=this.audioContext.currentTime+(a.start-this.currentTime);o>=this.audioContext.currentTime&&n.scheduleNote(a.pitch,o,a.duration-i,a.velocity,t.instrument)}),t.ccEvents&&Array.isArray(t.ccEvents)&&t.ccEvents.length>0)){const a=[...t.ccEvents].sort((o,l)=>o.time-l.time);let i=a[0];for(let o=1;o<a.length;++o){const l=a[o],c=i.time,u=l.time,h=i.value,p=l.value,g=i.handleType||"linear",y=Math.max(2,Math.ceil((u-c)*20));for(let m=0;m<=y;++m){const x=m/y;let b=h;if(g==="linear")b=h+(p-h)*x;else if(g==="step")b=x<1?h:p;else if(g==="exp"){const C=Math.max(h/127,.001),T=Math.max(p/127,.001);b=C*Math.pow(T/C,x)*127}const f=c+(u-c)*x,j=this.audioContext.currentTime+(f-this.currentTime);j>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(l.cc,b,j)}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 S0=[{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 Hr(e={}){const{channelFilter:t,sysex:n=!1,onEvent:a,inputNameIncludes:s,onInputsChanged:i}=e,[o,l]=d.useState(null),[c,u]=d.useState(!1),[h,p]=d.useState([]),g=d.useRef(null),y=d.useCallback((m,x)=>{const b=m.data??new Uint8Array(0),f=b[0]??0,j=b[1]??0,v=b[2]??0,C=m.timeStamp,T=f&240,M=f&15,k=x.id,R=x.name??"MIDI Input",P=t===void 0||t===M;if((T===144||T===128)&&P){const I=T===144&&v>0;return{type:I?"noteon":"noteoff",note:j,velocity:I?v:0,channel:M,ts:C,deviceId:k,deviceName:R}}return T===176&&P?{type:"cc",controller:j,value:v,channel:M,ts:C,deviceId:k,deviceName:R}:T===208&&P?{type:"aftertouch",pressure:j,channel:M,ts:C,deviceId:k,deviceName:R}:T===224&&P?{type:"pitchbend",value:(j|v<<7)-8192,channel:M,ts:C,deviceId:k,deviceName:R}:T===192&&P?{type:"program",program:j,channel:M,ts:C,deviceId:k,deviceName:R}:{type:"unknown",status:f,data1:j,data2:v,channel:M,ts:C,deviceId:k,deviceName:R}},[t]);return d.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,u(!0);const b=()=>{const f=Array.from(x.inputs.values()),j=s?f.filter(v=>(v.name||"").toUpperCase().includes(s.toUpperCase())):f;p(j),i==null||i(j),f.forEach(v=>v.onmidimessage=null),j.forEach(v=>{v.onmidimessage=C=>a==null?void 0:a(y(C,v))})};b(),x.onstatechange=()=>b()}),()=>{m=!0;const x=g.current;x&&(x.inputs.forEach(b=>b.onmidimessage=null),x.onstatechange=null)}},[s,a,i,y,n]),{supported:o,granted:c,inputs:h}}const is="nice2dev.midiLearn";function k0(){try{const e=localStorage.getItem(is);return e?JSON.parse(e):{}}catch{return{}}}function Ti(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(is,JSON.stringify(t))}function w0(e){const{parameters:t,onParameterChange:n}=e,[a,s]=d.useState(()=>{const v=k0();return t.map(C=>{const T=v[C.id];return{id:C.id,paramName:C.name,type:(T==null?void 0:T.type)??"cc",number:T==null?void 0:T.number,channel:T==null?void 0:T.channel,min:(T==null?void 0:T.min)??C.min??0,max:(T==null?void 0:T.max)??C.max??127,value:0}})}),[i,o]=d.useState({learning:!1,targetId:null}),[l,c]=d.useState(null),u=d.useRef(a);u.current=a;const h=d.useRef(n);h.current=n;const p=d.useRef(i);p.current=i;const g=d.useCallback(v=>{var T;c(v);const C=p.current;if(C.learning&&C.targetId){if(!u.current.find(R=>R.id===C.targetId))return;let k={};switch(v.type){case"cc":k={type:"cc",number:v.controller,channel:v.channel};break;case"noteon":k={type:"note",number:v.note,channel:v.channel};break;case"pitchbend":k={type:"pitchbend",channel:v.channel};break;case"aftertouch":k={type:"aftertouch",channel:v.channel};break;default:return}s(R=>{const P=R.map(I=>I.id===C.targetId?{...I,...k}:I);return Ti(P),P}),o({learning:!1,targetId:null});return}for(const M of u.current){if(M.number===void 0&&M.type!=="pitchbend"&&M.type!=="aftertouch"||M.channel!==void 0&&v.channel!==M.channel)continue;let k=null,R=127;if(M.type==="cc"&&v.type==="cc"&&v.controller===M.number?k=v.value:M.type==="note"&&v.type==="noteon"&&v.note===M.number?k=v.velocity:M.type==="pitchbend"&&v.type==="pitchbend"?(k=v.value+8192,R=16383):M.type==="aftertouch"&&v.type==="aftertouch"&&(k=v.pressure),k!==null){const P=k/R,I=M.min+P*(M.max-M.min);s(A=>A.map(L=>L.id===M.id?{...L,value:P}:L)),(T=h.current)==null||T.call(h,M.id,I,P)}}},[]),{supported:y,granted:m}=Hr({onEvent:g}),x=d.useCallback(v=>{o({learning:!0,targetId:v})},[]),b=d.useCallback(()=>{o({learning:!1,targetId:null})},[]),f=d.useCallback(v=>{s(C=>{const T=C.map(M=>M.id===v?{...M,type:"cc",number:void 0,channel:void 0}:M);return Ti(T),T})},[]),j=d.useCallback(()=>{s(v=>{const C=v.map(T=>({...T,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(is),C})},[]);return{bindings:a,startLearn:x,cancelLearn:b,removeBinding:f,clearAll:j,learnState:i,midiSupported:y,midiGranted:m,lastEvent:l}}const C0={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function j0(e={}){const{lowerZone:t=C0,onNoteExpression:n,onNoteOn:a,onNoteOff:s}=e,[i,o]=d.useState([]),l=d.useRef(new Map),c=d.useRef(n);c.current=n;const u=d.useRef(a);u.current=a;const h=d.useRef(s);h.current=s;const p=d.useRef(new Set(t.memberChannels));d.useEffect(()=>{p.current=new Set(t.memberChannels)},[t.memberChannels]);const g=d.useCallback(x=>{var f,j,v,C,T;if(!p.current.has(x.channel??-1))return;const b=`${x.channel}`;switch(x.type){case"noteon":{const M={note:x.note,channel:x.channel,velocity:x.velocity,pitchBend:0,pressure:0,slide:0,lastUpdate:x.ts};l.current.set(b,M),o(Array.from(l.current.values())),(f=u.current)==null||f.call(u,M);break}case"noteoff":{l.current.delete(b),o(Array.from(l.current.values())),(j=h.current)==null||j.call(h,x.channel,x.note);break}case"pitchbend":{const M=l.current.get(b);M&&(M.pitchBend=x.value,M.lastUpdate=x.ts,(v=c.current)==null||v.call(c,M),o(Array.from(l.current.values())));break}case"aftertouch":{const M=l.current.get(b);M&&(M.pressure=x.pressure,M.lastUpdate=x.ts,(C=c.current)==null||C.call(c,M),o(Array.from(l.current.values())));break}case"cc":{if(x.controller===74){const M=l.current.get(b);M&&(M.slide=x.value,M.lastUpdate=x.ts,(T=c.current)==null||T.call(c,M),o(Array.from(l.current.values())))}break}}},[]),{supported:y,granted:m}=Hr({onEvent:g,sysex:!1});return{activeNotes:i,midiSupported:y,midiGranted:m}}const M0={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 R0(e={},t=M0){const{t:n}=xe(),[a,s]=d.useState(()=>{const m=localStorage.getItem("oxygen25.layout");return m?JSON.parse(m):t}),[i,o]=d.useState([]),l=d.useRef({mode:"idle"}),c=d.useCallback(m=>{s(x=>{const b={...x,...m};return localStorage.setItem("oxygen25.layout",JSON.stringify(b)),b})},[]),u=d.useCallback(m=>{var f,j,v,C,T,M,k,R,P;const x=m.deviceName||"MIDI";o(I=>I.includes(x)?I:[...I,x]);const b=l.current;if(b.mode!=="idle"){if(b.mode==="knob"&&m.type==="cc"){const I=b.index;c({knobs:a.knobs.map(A=>A.index===I?{...A,cc:m.controller}:A)}),l.current={mode:"idle"};return}if(b.mode==="fader"&&m.type==="cc"){c({fader:{cc:m.controller,label:n("useOxygen25.fader","Fader")}}),l.current={mode:"idle"};return}if(b.mode==="pad"&&m.type==="noteon"){const I=a.pads.slice();I[b.padIdx]={...I[b.padIdx],note:m.note},c({pads:I}),l.current={mode:"idle"};return}if(b.mode==="transport"&&m.type==="cc"){const I={...a.transport};I[b.action]=m.controller,c({transport:I}),l.current={mode:"idle"};return}}switch(m.type){case"noteon":{a.pads.findIndex(A=>A.note===m.note)>=0?(f=e.onPad)==null||f.call(e,{note:m.note,velocity:m.velocity,ts:m.ts,device:x}):(j=e.onKey)==null||j.call(e,{note:m.note,velocity:m.velocity,ts:m.ts,device:x});break}case"cc":{if(a.fader&&m.controller===a.fader.cc){(v=e.onFader)==null||v.call(e,{cc:m.controller,value:m.value,ts:m.ts,device:x});break}const I=a.knobs.find(L=>L.cc===m.controller);if(I){(C=e.onKnob)==null||C.call(e,{index:I.index,cc:m.controller,value:m.value,ts:m.ts,device:x});break}const A=Object.keys(a.transport).find(L=>a.transport[L]===m.controller);if(A){(T=e.onTransport)==null||T.call(e,{action:A,value:m.value,ts:m.ts,device:x});break}(M=e.onUnknown)==null||M.call(e,m);break}case"pitchbend":(k=e.onPitchBend)==null||k.call(e,{value:m.value,ts:m.ts,device:x});break;case"aftertouch":(R=e.onAftertouch)==null||R.call(e,{pressure:m.pressure,ts:m.ts,device:x});break;default:(P=e.onUnknown)==null||P.call(e,m)}},[c,e,a,n]),{supported:h,granted:p,inputs:g}=Hr({inputNameIncludes:void 0,onEvent:u,sysex:!1,channelFilter:void 0,onInputsChanged:m=>o(m.map(x=>x.name||"MIDI"))}),y=d.useMemo(()=>({knob:m=>l.current={mode:"knob",index:m},fader:()=>l.current={mode:"fader"},pad:m=>l.current={mode:"pad",padIdx:m},transport:m=>l.current={mode:"transport",action:m},cancel:()=>l.current={mode:"idle"},state:()=>l.current}),[]);return{supported:h,granted:p,inputs:g,layout:a,setLayout:c,learn:y,inputsInfo:i}}const Na={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]},N0=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Ta={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]]},an=36,Rn=38,Mt=42,sn=51,T0=49,Pa={basic:[{step:0,pitch:an,vel:110},{step:0,pitch:Mt,vel:80},{step:2,pitch:Mt,vel:70},{step:4,pitch:Rn,vel:100},{step:4,pitch:Mt,vel:80},{step:6,pitch:Mt,vel:70},{step:8,pitch:an,vel:100},{step:10,pitch:Mt,vel:70},{step:12,pitch:Rn,vel:100},{step:12,pitch:Mt,vel:80},{step:14,pitch:Mt,vel:70}],rock:[{step:0,pitch:an,vel:120},{step:0,pitch:T0,vel:90},{step:4,pitch:Rn,vel:110},{step:4,pitch:Mt,vel:80},{step:8,pitch:an,vel:110},{step:8,pitch:Mt,vel:80},{step:10,pitch:an,vel:90},{step:12,pitch:Rn,vel:110},{step:12,pitch:Mt,vel:80}],swing:[{step:0,pitch:sn,vel:90},{step:3,pitch:sn,vel:70},{step:4,pitch:sn,vel:80},{step:8,pitch:sn,vel:90},{step:11,pitch:sn,vel:70},{step:12,pitch:sn,vel:80},{step:4,pitch:an,vel:80},{step:12,pitch:Rn,vel:70}]},Gl={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function P0(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 Wl=1;const ur=()=>Wl++,Ul=e=>60/e,E0=e=>Ul(e)/4;function ca(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 Vl(e=Gl){Wl=1;const t=e.seed>0?P0(e.seed):Math.random,n=Na[e.scale]??Na.pentatonic,a=Ta[e.progression]??Ta.pop,s=Pa[e.drumPattern]??Pa.basic,i=Ul(e.tempo),o=E0(e.tempo),l=Math.max(1,e.bars),c=16,u=[],h=[],p=[],g=[];let y=0;for(let m=0;m<l;m++){const x=m*4*i,b=m%a.length,f=a[b];for(const v of f)p.push({id:ur(),pitch:ca(e.root,n,v,e.octave-1),start:x,duration:4*i-.01,velocity:70+Math.floor(t()*20)});const j=f[0];for(let v=0;v<4;v++){const C=v===2?j+(t()>.5?2:0):j;h.push({id:ur(),pitch:ca(e.root,n,C,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 C=x+v*o,T=t()>.8?t()>.5?2:-2:t()>.5?1:-1;y=Math.max(-3,Math.min(n.length+3,y+T));const M=1+Math.floor(t()*3);u.push({id:ur(),pitch:ca(e.root,n,y,e.octave),start:C,duration:M*o*.95,velocity:85+Math.floor(t()*30)})}for(const v of s)g.push({id:ur(),pitch:v.pitch,start:x+v.step*o,duration:o*.8,velocity:v.vel+Math.floor(t()*10-5)})}return{melody:u,bass:h,chords:p,drums:g,config:e}}const $0=Object.keys(Na),A0=Object.keys(Ta),I0=Object.keys(Pa),L0=Vl;function qe(e,t,n){return{cc:e,paramId:n,label:`Knob ${t}`,controlType:"knob",min:0,max:127,inverted:!1}}function Kn(e,t,n){return{cc:e,paramId:n,label:t,controlType:"fader",min:0,max:127,inverted:!1}}function on(e,t,n){return{cc:e,paramId:n,label:t,controlType:"button",min:0,max:127,inverted:!1}}const ql={id:"oxygen25",name:"M-Audio Oxygen 25 (MkIV)",deviceMatch:"OXYGEN",mappings:[qe(21,1,"mixer.volume"),qe(22,2,"mixer.pan"),qe(23,3,"fx.reverb"),qe(24,4,"fx.delay"),qe(25,5,"fx.chorus"),qe(26,6,"fx.filter"),qe(27,7,"fx.drive"),qe(28,8,"fx.eq"),Kn(7,"Master Fader","mixer.master"),on(115,"Play","transport.play"),on(114,"Stop","transport.stop"),on(117,"Record","transport.record"),on(112,"Rewind","transport.rewind"),on(113,"Forward","transport.forward"),on(116,"Loop","transport.loop")]},Hl={id:"mpk-mini",name:"Akai MPK Mini",deviceMatch:"MPK",mappings:[qe(1,1,"mixer.volume"),qe(2,2,"mixer.pan"),qe(3,3,"fx.reverb"),qe(4,4,"fx.delay"),qe(5,5,"fx.chorus"),qe(6,6,"fx.filter"),qe(7,7,"fx.drive"),qe(8,8,"fx.eq")]},Kl={id:"minilab",name:"Arturia MiniLab",deviceMatch:"Arturia MiniLab",mappings:[qe(7,1,"mixer.volume"),qe(74,2,"mixer.pan"),qe(71,3,"fx.reverb"),qe(76,4,"fx.delay"),qe(77,5,"fx.chorus"),qe(93,6,"fx.filter"),qe(73,7,"fx.drive"),qe(75,8,"fx.eq"),Kn(1,"Mod Wheel","mixer.master")]},Yl=(function(){return{id:"launch-control-xl",name:"Novation Launch Control XL",deviceMatch:"Launch Control",mappings:[...Array.from({length:8},(e,t)=>qe(13+t,t+1,`mixer.send${t+1}`)),...Array.from({length:8},(e,t)=>Kn(77+t,`Fader ${t+1}`,`mixer.track${t+1}`))]}})(),os={id:"generic",name:"Generic MIDI Controller",deviceMatch:"",mappings:[qe(1,1,"mixer.modWheel"),Kn(7,"Volume","mixer.volume"),qe(10,2,"mixer.pan"),Kn(11,"Expression","mixer.expression")]},Zl=[ql,Hl,Kl,Yl,os];class _0{constructor(t){this.ccMap=new Map,this.onChange=null,this.profile=t??os,this.rebuildMap()}setProfile(t){this.profile=t,this.rebuildMap()}getProfile(){return this.profile}autoDetect(t){const n=t.toUpperCase(),a=Zl.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 ls(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function Qt(e="New Pattern",t=16,n=120){return{name:e,length:t,steps:Array.from({length:t},()=>ls()),bpm:n,swing:0,rootNote:60}}function Xl(e,t){const n=e.steps.map((a,s)=>s===t?{...a,active:!a.active}:a);return{...e,steps:n}}function Ql(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 Jl(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 ec(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 tc(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 nc(e,t){const n=e.steps.map((a,s)=>s===t?{...a,slide:!a.slide}:a);return{...e,steps:n}}function rc(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 ac(e){return{...e,steps:[...e.steps].reverse()}}function sc(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 ic(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 oc(e){return{...e,steps:e.steps.map(()=>ls(e.rootNote))}}function cs(e,t=4){return 60/e/t}function lc(e,t,n=0,a=4){const s=cs(t,a),i=e*s;return e%2===1&&n>0?i+s*n*.5:i}function cc(e){return e.active&&Math.random()<e.probability}function D0(){const e=Qt("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function z0(){const e=Qt("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function F0(){const e=Qt("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 O0(e=60){const t=Qt("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 B0(e=36){const t=Qt("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 G0(e){return JSON.stringify(e,null,2)}function W0(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function U0(e={}){const{onTrigger:t,onLFOOutput:n,initialPattern:a}=e,[s,i]=d.useState(()=>a??Qt()),[o,l]=d.useState(-1),[c,u]=d.useState(!1),[h,p]=d.useState([]),g=d.useRef(s);g.current=s;const y=d.useRef(h);y.current=h;const m=d.useRef(c);m.current=c;const x=d.useRef(t);x.current=t;const b=d.useRef(n);b.current=n;const f=d.useRef(null),j=d.useRef(0),v=d.useRef(0),C=d.useCallback(()=>{var H,X;if(!m.current)return;const S=g.current,O=j.current%S.length,Y=S.steps[O];if(cc(Y)){const re=lc(j.current,S.bpm,S.swing);(H=x.current)==null||H.call(x,Y,O,re)}const _=(Date.now()-v.current)/1e3;for(let re=0;re<y.current.length;re++){const oe=y.current[re];if(oe.enabled&&oe.targetCC!==void 0){const se=Da(oe,_,S.bpm);(X=b.current)==null||X.call(b,re,oe.targetCC,se)}}l(O),j.current++;const U=cs(S.bpm)*1e3,$=O%2===0?0:U*S.swing*.5;f.current=setTimeout(C,U+$)},[]),T=d.useCallback(()=>{m.current||(j.current=0,v.current=Date.now(),u(!0),m.current=!0,C())},[C]),M=d.useCallback(()=>{u(!1),m.current=!1,l(-1),f.current&&(clearTimeout(f.current),f.current=null)},[]),k=d.useCallback(()=>{m.current?M():T()},[T,M]);d.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const R=d.useCallback(S=>i(O=>Xl(O,S)),[]),P=d.useCallback((S,O)=>i(Y=>Ql(Y,S,O)),[]),I=d.useCallback((S,O)=>i(Y=>Jl(Y,S,O)),[]),A=d.useCallback((S,O)=>i(Y=>ec(Y,S,O)),[]),L=d.useCallback((S,O)=>i(Y=>tc(Y,S,O)),[]),E=d.useCallback(S=>i(O=>nc(O,S)),[]),D=d.useCallback(S=>i(O=>rc(O,S)),[]),Z=d.useCallback(()=>i(S=>ac(S)),[]),G=d.useCallback(S=>i(O=>sc(O,S)),[]),F=d.useCallback((S,O)=>i(Y=>ic(Y,S,O)),[]),q=d.useCallback(()=>i(S=>oc(S)),[]),V=d.useCallback(S=>i(O=>({...O,bpm:Math.max(20,Math.min(300,S))})),[]),K=d.useCallback(S=>i(O=>({...O,swing:Math.max(0,Math.min(1,S))})),[]),W=d.useCallback(S=>{i(O=>{if(O.length===S)return O;const Y=Array.from({length:S},(_,U)=>U<O.steps.length?O.steps[U]:{active:!1,note:O.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...O,length:S,steps:Y}})},[]),Q=d.useCallback(S=>{p(O=>[...O,S??Fr()])},[]),w=d.useCallback(S=>{p(O=>O.filter((Y,_)=>_!==S))},[]),N=d.useCallback((S,O)=>{p(Y=>Y.map((_,U)=>U===S?{..._,...O}:_))},[]);return{pattern:s,currentStep:o,playing:c,lfos:h,play:T,stop:M,togglePlayback:k,toggle:R,setNote:P,setVelocity:I,setGate:A,setProbability:L,toggleSlide:E,transpose:D,reverse:Z,shift:G,randomizeVel:F,clear:q,setPattern:i,setBpm:V,setSwing:K,setLength:W,addLFO:Q,removeLFO:w,updateLFO:N}}function ds(e){const t=d.useRef(null),n=d.useRef(new Map),a=d.useRef(1),s=d.useCallback(()=>{if(!t.current){const o=e();o.onmessage=l=>{const{id:c}=l.data,u=n.current.get(c);u&&(n.current.delete(c),u.resolve(l.data))},o.onerror=l=>{console.error("[useWorker] Worker error:",l.message);for(const[c,u]of n.current)u.reject(new Error(`Worker error: ${l.message}`));n.current.clear(),o.terminate(),t.current=null},t.current=o}return t.current},[e]);return d.useEffect(()=>{const o=n.current;return()=>{var l;(l=t.current)==null||l.terminate(),t.current=null;for(const[,c]of o)c.reject(new Error("Worker terminated on unmount"));o.clear()}},[]),d.useCallback((o,l)=>{const c=a.current++,u=s();return new Promise((h,p)=>{n.current.set(c,{resolve:h,reject:p}),u.postMessage({...o,id:c},l??[])})},[s])}function V0(){const e=ds(d.useCallback(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/pitchWorker-BgAp5Z97.js").href:new URL("assets/pitchWorker-BgAp5Z97.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:yt&&yt.tagName.toUpperCase()==="SCRIPT"&&yt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return d.useCallback(async(n,a,s=.01)=>(await e({buffer:n,sampleRate:a,rmsThreshold:s})).hz,[e])}function q0(){const e=ds(d.useCallback(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/scoringWorker-3JjtDDtu.js").href:new URL("assets/scoringWorker-3JjtDDtu.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:yt&&yt.tagName.toUpperCase()==="SCRIPT"&&yt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return d.useCallback(async(n,a,s)=>(await e({notes:n,points:a,params:s})).result,[e])}const H0={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function dc(){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 Pi=!1,hr=null;async function uc(e){if(!Pi)return hr||(hr=(async()=>{const t=dc(),n=new Blob([t],{type:"application/javascript"}),a=URL.createObjectURL(n);try{await e.audioWorklet.addModule(a),Pi=!0}finally{URL.revokeObjectURL(a)}})(),hr)}function hc(e,t,n){const a=new AudioWorkletNode(e,"nice-audio-processor",{processorOptions:{...H0,...t}});return n&&(a.port.onmessage=s=>{s.data.type==="analysis"&&n(s.data.payload)}),a}function pc(e,t=1){const n=new AudioWorkletNode(e,"nice-gain-processor");return n.parameters.get("gain").value=t,n}function fc(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 mc(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 K0(e={}){const{enableAnalysis:t=!0,analysisOptions:n,enableGain:a=!1,initialGain:s=1,enableCompressor:i=!1,compressorOptions:o,enableVocoder:l=!1,vocoderOptions:c,onAnalysis:u}=e,[h,p]=d.useState(!1),[g,y]=d.useState(null),[m,x]=d.useState(null),b=d.useRef(null),f=d.useRef(null),j=d.useRef(null),v=d.useRef(null),C=d.useRef(null),T=d.useRef(null),M=d.useRef(null),k=d.useRef(null),R=d.useRef({analysisOptions:n,initialGain:s,compressorOptions:o,vocoderOptions:c});R.current={analysisOptions:n,initialGain:s,compressorOptions:o,vocoderOptions:c};const P=d.useRef(u);P.current=u,d.useEffect(()=>{let G=!0;return(async()=>{try{const q=R.current,V=new AudioContext;if(b.current=V,await uc(V),!G){V.close();return}const K=[];if(t){const W=hc(V,q.analysisOptions,Q=>{var w;G&&(x(Q),(w=P.current)==null||w.call(P,Q))});f.current=W,K.push(W)}if(a){const W=pc(V,q.initialGain);j.current=W,K.push(W)}if(i){const W=fc(V,q.compressorOptions);v.current=W,K.push(W)}if(l){const W=mc(V,q.vocoderOptions);C.current=W,K.push(W)}if(K.length>0){M.current=K[0],k.current=K[K.length-1];for(let W=0;W<K.length-1;W++)K[W].connect(K[W+1])}p(!0)}catch(q){G&&y(q)}})(),()=>{var q,V,K,W,Q;G=!1,(q=f.current)==null||q.disconnect(),(V=j.current)==null||V.disconnect(),(K=v.current)==null||K.disconnect(),(W=C.current)==null||W.disconnect(),(Q=b.current)==null||Q.close()}},[t,a,i,l]);const I=d.useCallback(G=>{T.current&&T.current.disconnect(),T.current=G,M.current&&G.connect(M.current)},[]),A=d.useCallback(()=>{T.current&&(T.current.disconnect(),T.current=null)},[]),L=d.useCallback(()=>k.current,[]),E=d.useCallback(G=>{var q;const F=(q=j.current)==null?void 0:q.parameters.get("gain");F&&(F.value=Math.max(0,Math.min(2,G)))},[]),D=d.useCallback((G,F)=>{var V;const q=(V=v.current)==null?void 0:V.parameters.get(G);q&&(q.value=F)},[]),Z=d.useCallback((G,F)=>{var V;const q=(V=C.current)==null?void 0:V.parameters.get(G);q&&(q.value=F)},[]);return{isReady:h,error:g,analysis:m,connectSource:I,disconnectSource:A,getOutputNode:L,setGain:E,setCompressorParam:D,setVocoderParam:Z,audioContext:b.current}}function Y0(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 Z0(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 X0(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 Q0(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 J0(e,t,n,a,s,i,o=.5,l=100){const c={id:Date.now()+Math.floor(Math.random()*1e3),pitch:s,start:i,duration:o,velocity:l};t(u=>({...u,[a]:[...u[a]||[],c]})),n({layerId:a,noteId:c.id})}function eg(e,t,n,a){e(s=>({...s,[n]:(s[n]||[]).filter(i=>i.id!==a)})),t(null)}function tg(e,t,n){e(a=>({...a,[n]:[]})),t(null)}function ng(e,t,n){e(a=>({...a,[t]:n}))}function rg(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 ag(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 sg(e,t,n){e(a=>({...a,[t]:(a[t]||[]).filter(s=>s.id!==n)}))}function pr(e){if(!e||e<=0)return null;const t=12*Math.log2(e/440)+69;return Math.round(t-12)}function ig(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 og(e,t,n=.01){const a=Math.floor(t/50);let s=-1,i=0,o=0;for(let c=0;c<e.length;c++)o+=e[c]*e[c];if(o=Math.sqrt(o/e.length),o<n)return 0;let l=1;for(let c=50;c<a;c++){let u=0;for(let h=0;h<a;h++)u+=Math.abs(e[h]-e[h+c]);u=1-u/a,u>i&&u>.9&&u>l&&(i=u,s=c),l=u}return s===-1?0:t/s}async function lg(e,t,n){const{signal:a,onProgress:s,rmsThreshold:i,useHanning:o,postPitch:l,postLibrosaPitchTrack:c}=n||{},u=await e.arrayBuffer();if(a!=null&&a.aborted)throw new Error("aborted");const p=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(u),g=p.getChannelData(0),y=p.sampleRate,m=Math.floor(y*.1),x=m,b=[];if(t==="pitchy"){const f=ua.PitchDetector.forFloat32Array(m),j=Math.max(1,Math.floor((g.length-m)/x));let v=0;for(let C=0;C<g.length-m;C+=x){if(a!=null&&a.aborted)throw new Error("aborted");const T=g.slice(C,C+m);if(o)for(let A=0;A<T.length;A++)T[A]*=.5*(1-Math.cos(2*Math.PI*A/(T.length-1)));const[M,k]=f.findPitch(T,y),R=pr(M);let P=0;for(let A=0;A<T.length;A++)P+=T[A]*T[A];P=Math.sqrt(P/T.length);const I=typeof i=="number"?i:.01;R&&M>50&&M<2e3&&k>.7&&P>I&&b.push({start:C/y,duration:m/y,pitch:R,freq:M}),v++,s&&s(v/j)}}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 j=Array.isArray(f.track)?f.track:[];j.length>0&&j.forEach((v,C)=>{var M;const T=pr(v.hz);if(T&&v.hz>50&&v.hz<2e3){const k=((M=j[C+1])==null?void 0:M.t)??v.t+.1;b.push({start:v.t,duration:C<j.length-1?k-v.t:.1,pitch:T,freq:v.hz})}}),s&&s(1)}else if(t==="ultrastar-wp"){const f=Math.max(1,Math.floor((g.length-m)/x));let j=0;for(let v=0;v<g.length-m;v+=x){if(a!=null&&a.aborted)throw new Error("aborted");const C=g.slice(v,v+m);if(o)for(let R=0;R<C.length;R++)C[R]*=.5*(1-Math.cos(2*Math.PI*R/(C.length-1)));const M=og(C,y,typeof i=="number"?i:.01),k=pr(M);k&&M>50&&M<2e3&&b.push({start:v/y,duration:m/y,pitch:k,freq:M}),j++,s&&s(j/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 j=Array.isArray(f.track)?f.track:[];j.length>0&&j.forEach((v,C)=>{var M;const T=pr(v.hz);if(T&&v.hz>50&&v.hz<2e3){const k=((M=j[C+1])==null?void 0:M.t)??v.t+.1;b.push({start:v.t,duration:C<j.length-1?k-v.t:.1,pitch:T,freq:v.hz})}}),s&&s(1)}return ig(b)}function cg(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 cg(e,t){return`${e}:${t}`}function dg(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 ug(e){return e.length===0?[]:e.flat()}function hg(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const ds=[{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 pg(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function mc(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 gc(e,t){const n=t.seed!=null?pg(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 yc(e,t,n=1){const a=4/t.stepsPerBar;return e.map(s=>{const i=s.time/a,o=Math.round(i)%t.stepsPerBar,l=t.timingOffsets[o]*a*n,c=1+(t.velocityScales[o]-1)*n,u=1+(t.durationScales[o]-1)*n;return{...s,time:Math.max(0,s.time+l),velocity:Math.max(1,Math.min(127,Math.round(s.velocity*c))),duration:Math.max(.01,s.duration*u)}})}function fg(e,t){let n=[...e.map(a=>({...a}))];return t.template&&t.grooveStrength>0&&(n=yc(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=mc(n,t.swing)),t.humanize&&(n=gc(n,t.humanize)),n}function mg(e){return ds.find(t=>t.id===e)}function gg(){return ds.map(({id:e,name:t})=>({id:e,name:t}))}function vc(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 us(e,t){return vc(e)*60/t}function Pa(e,t,n){const a=us(t,n);return Math.round(e/a)*a}function yg(e,t){const{value:n,bpm:a,strength:s=1,quantizeStarts:i=!0,quantizeDurations:o=!1}=t,l=us(n,a);return e.map(c=>{let{start:u,duration:h}=c;if(i){const p=Math.round(u/l)*l;u=u+(p-u)*s}if(o){const p=Math.max(l,Math.round(h/l)*l);h=h+(p-h)*s}return u===c.start&&h===c.duration?c:{...c,start:u,duration:h}})}function vg(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function bg(e,t={}){const{timingRange:n=.02,velocityRange:a=10,seed:s}=t,i=s!=null?vg(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 xg(){return{start:0,end:0,enabled:!1}}function Sg(e,t){return{...e<t?{start:e,end:t}:{start:t,end:e},enabled:!0}}function kg(e,t,n){return{start:Pa(e.start,t,n),end:Pa(e.end,t,n),enabled:e.enabled}}function wg(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function Cg(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 Ea(e){return e.length===1?e.toLowerCase():e}function Mr(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(Ea(e.key)),t.join("+")}function jg(e,t){var l,c,u,h;const n=Ea(e.key)===Ea(t.key),a=!!e.ctrlKey==!!((l=t.modifiers)!=null&&l.ctrl),s=!!e.shiftKey==!!((c=t.modifiers)!=null&&c.shift),i=!!e.altKey==!!((u=t.modifiers)!=null&&u.alt),o=!!e.metaKey==!!((h=t.modifiers)!=null&&h.meta);return n&&a&&s&&i&&o}class bc{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];Mr(i.binding)===Mr(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?Mr(n.binding):""}handleKeyDown(t){if(!this.enabled)return!1;for(const n of this.actions.values())if(n.enabled&&this.activeScopes.has(n.scope)&&jg(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 Mg(e={}){const t=new bc,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 Rg(e){return Mr(e)}const Ng=["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"],Tg=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],Pg=500*1024*1024,Eg=20;function Wt(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function $g(e,t){return!!(e.type&&t.some(n=>e.type.startsWith(n.replace("*","")))||e.type.startsWith("audio/"))}function Ag(e,t){const n=Wt(e.name);return n!==""&&t.includes(n)}function hs(e,t={}){const n=t.maxSize??Pg,a=t.allowedTypes??Ng,s=t.allowedExtensions??Tg,i=t.maxFiles??Eg,o=[],l=[];for(let c=0;c<e.length;c++){const u=e[c];if(c>=i){l.push({file:u,reason:"limit",message:`Exceeded maximum of ${i} files`});continue}if(u.size>n){l.push({file:u,reason:"size",message:`File exceeds ${Math.round(n/1024/1024)}MB limit`});continue}if(!$g(u,a)&&!Ag(u,s)){l.push({file:u,reason:"type",message:`Unsupported file type: ${u.type||Wt(u.name)}`});continue}o.push(u)}return{valid:o,errors:l}}async function xc(e){const t={file:e,name:e.name.replace(/\.[^.]+$/,""),extension:Wt(e.name),sizeBytes:e.size,mimeType:e.type||`audio/${Wt(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 Ig(e){let t=0;return{onDragEnter:n=>{var a;n.preventDefault(),n.stopPropagation(),t++,t===1&&((a=e.onDragEnter)==null||a.call(e))},onDragOver:n=>{n.preventDefault(),n.stopPropagation(),(n instanceof DragEvent&&n.dataTransfer||"dataTransfer"in n&&n.dataTransfer)&&(n.dataTransfer.dropEffect="copy")},onDragLeave:n=>{var a;n.preventDefault(),n.stopPropagation(),t--,t===0&&((a=e.onDragLeave)==null||a.call(e))},onDrop:async n=>{var u,h;n.preventDefault(),n.stopPropagation(),t=0,(u=e.onDragLeave)==null||u.call(e);const a="dataTransfer"in n?n.dataTransfer:null;if(!((h=a==null?void 0:a.files)!=null&&h.length))return;const s=Array.from(a.files),{valid:i,errors:o}=hs(s,e.validation),l=[],c=[...o];for(const p of i)if(e.probe)try{l.push(await xc(p))}catch{c.push({file:p,reason:"decode",message:"Failed to decode audio"})}else l.push({file:p,name:p.name.replace(/\.[^.]+$/,""),extension:Wt(p.name),sizeBytes:p.size,mimeType:p.type||`audio/${Wt(p.name)}`});e.onDrop({accepted:l,rejected:c})}}}function Lg(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}=hs(a,e.validation),o=s.map(c=>({file:c,name:c.name.replace(/\.[^.]+$/,""),extension:Wt(c.name),sizeBytes:c.size,mimeType:c.type||`audio/${Wt(c.name)}`}));t({accepted:o,rejected:i})},n.click()})}var Bt=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(Bt||{}),Sc=(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))(Sc||{}),kc=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(kc||{});const _g=["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)"],Dr=["off","no function","brak"],Dg=e=>e.segments.some(t=>t.isOff||Dr.some(n=>t.name.toLowerCase().includes(n))),zg=e=>e.segments.find(t=>t.isOff||Dr.some(n=>t.name.toLowerCase().includes(n))),wc=e=>Math.floor((e.valueFrom+e.valueTo)/2),Fg=e=>{const t=zg(e);return t?wc(t):0},Og=(e,t)=>e.segments.find(n=>t>=n.valueFrom&&t<=n.valueTo),Nn=(e,t=0,n=255)=>Math.max(t,Math.min(n,Math.round(e))),Hn=({channel:e,value:t,onChange:n,onCommit:a,showDirectionHint:s})=>{const{t:i}=xe(),[o,l]=d.useState(Nn(t)),c=d.useMemo(()=>Og(e,o),[e,o]);d.useEffect(()=>l(Nn(t)),[t]);const u=h=>{const p=Nn(h);l(p),n(p),a==null||a(p)};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&&c&&r.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:c.name})]}),r.jsx("input",{type:"range",min:0,max:255,value:o,onChange:h=>{const p=Nn(Number(h.target.value));l(p),n(p)},onMouseUp:()=>a==null?void 0:a(o),onTouchEnd:()=>a==null?void 0:a(o),style:{width:"100%"}}),r.jsx("div",{style:{marginTop:6},children:r.jsx("input",{type:"number",min:0,max:255,value:o,onChange:h=>{const p=Nn(Number(h.target.value));l(p),n(p)},onBlur:()=>a==null?void 0:a(o),style:{width:80,padding:6,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:6}})}),Dg(e)&&r.jsx("button",{type:"button",onClick:()=>u(Fg(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:i("dmxChannelControls.off","OFF")})]})},ps=({channel:e,value:t,onChange:n,onCommit:a})=>{const s=d.useMemo(()=>{const o=[...e.segments];return o.sort((l,c)=>{const u=(l.isOff?-1:0)+(Dr.some(p=>l.name.toLowerCase().includes(p))?-1:0),h=(c.isOff?-1:0)+(Dr.some(p=>c.name.toLowerCase().includes(p))?-1:0);return u!==h?u-h:l.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),o},[e]),i=o=>{const l=wc(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}`)})})]})},fs=e=>{switch(e.channel.type){case Bt.Dimmer:case Bt.DimmerWithOff:return r.jsx(Hn,{...e});case Bt.RotationWithOff:case Bt.RotationWithOffAndCcw:return r.jsx(Hn,{...e,showDirectionHint:!0});case Bt.Options:return r.jsx(ps,{...e});default:return r.jsx(Hn,{...e})}},ca=e=>Math.max(0,Math.min(255,Math.round(e))),Bg=[{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 Cc({service:e,...t}){const{t:n}=xe();return e?r.jsx(Gg,{service:e,...t}):r.jsx("div",{className:t.className,style:t.style,children:r.jsx("small",{children:n("dmxEditor.provideAServicePropDmxservice","Provide a `service` prop (DmxService) to control hardware.")})})}function Gg({service:e,pollInterval:t=500,className:n,style:a,tutorial:s}){const{t:i}=xe(),[o,l]=d.useState([]),[c,u]=d.useState(null),[h,p]=d.useState(()=>Array(513).fill(0)),[g,y]=d.useState(30),[m,x]=d.useState(0),[b,f]=d.useState(!1),j=d.useRef(null);d.useEffect(()=>{let A=!1;return e.getDevices().then(L=>{A||(l(L),L.length>0&&u(L[0]))}).catch(()=>{}),()=>{A=!0}},[e]),d.useEffect(()=>{if(j.current&&window.clearInterval(j.current),!(t<=0))return j.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),()=>{j.current&&window.clearInterval(j.current)}},[e,t]);const v=async()=>{c&&(await e.openPort(c.serialNumber||c.description),f(!0))},C=async()=>{await e.closePort(),f(!1)},T=async()=>{await e.blackout(),p(A=>{const L=[...A];for(let E=1;E<L.length;E++)L[E]=0;return L})},M=()=>e.configure(g,m),k=(A,L)=>{const E=ca(L);p(D=>{const Z=[...D];return Z[A]=E,Z})},R=(A,L)=>e.setChannel(A,ca(L)),P=(c==null?void 0:c.deviceInfo)??null,I=d.useMemo(()=>{var A;return(A=P==null?void 0:P.channels)!=null&&A.length?P.channels:Array.from({length:16},(L,E)=>({channel:E+1,name:`Channel ${E+1}`,type:Bt.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[P]);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(ve.NiceTutorialButton,{steps:ve.resolveTutorial(s,Bg)})}),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=>u(o.find(L=>L.serialNumber===A.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"},children:o.map(A=>{var L,E;return r.jsxs("option",{value:A.serialNumber,children:[((L=A.deviceInfo)==null?void 0:L.manufacturer)??""," ",((E=A.deviceInfo)==null?void 0:E.model)??A.description," (",A.serialNumber||A.description,")"]},A.serialNumber||A.description)})}),P&&r.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:[i("dmxEditor.mode","Mode:")," ",r.jsx("b",{children:P.modeName}),i("dmxEditor.footprint",", footprint:")," ",r.jsx("b",{children:P.footprint})]})]}),r.jsx("button",{onClick:v,disabled:!c||b,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:C,disabled:!b,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:T,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(ca(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:M,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:I.map(A=>r.jsx(fs,{channel:A,value:h[A.channel]??0,onChange:L=>k(A.channel,L),onCommit:L=>R(A.channel,L)},A.channel))})]})]})}const jc=[{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 Mc{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,jc.forEach(t=>this.profiles.set(t.id,t)),this.createUniverse(1,"Universe 1")}createUniverse(t,n){const a={id:String(t),name:n,channels:new Uint8Array(512)};return this.universes.set(t,a),a}getUniverse(t){return this.universes.get(t)}addFixture(t){this.fixtures.set(t.id,t)}removeFixture(t){this.fixtures.delete(t)}getFixture(t){return this.fixtures.get(t)}getAllFixtures(){return Array.from(this.fixtures.values())}getProfile(t){return this.profiles.get(t)}registerProfile(t){this.profiles.set(t.id,t)}setChannel(t,n,a){const s=this.universes.get(t);s&&n>=1&&n<=512&&(s.channels[n-1]=Math.max(0,Math.min(255,a)))}getChannel(t,n){const a=this.universes.get(t);return a&&n>=1&&n<=512?a.channels[n-1]:0}setFixtureValues(t,n){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);if(s)for(let i=0;i<Math.min(n.length,s.channelCount);i++)a.values[i]=n[i],this.setChannel(a.universe,a.startChannel+i,n[i])}setFixtureColor(t,n,a,s,i=0){const o=this.fixtures.get(t);if(!o)return;const l=this.profiles.get(o.profileId);if(!l)return;const c=[...o.values];l.channels.forEach((u,h)=>{u.name.toLowerCase().includes("red")?c[h]=n:u.name.toLowerCase().includes("green")?c[h]=a:u.name.toLowerCase().includes("blue")?c[h]=s:u.name.toLowerCase().includes("white")&&(c[h]=i)}),this.setFixtureValues(t,c)}setFixtureDimmer(t,n){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);s&&s.channels.forEach((i,o)=>{i.type==="dimmer"&&(a.values[o]=Math.max(0,Math.min(255,Math.round(n*255))),this.setChannel(a.universe,a.startChannel+o,a.values[o]))})}fadeFixture(t,n,a,s="linear"){return new Promise(i=>{const o=this.fixtures.get(t);if(!o){i();return}const l=[...o.values],c=performance.now(),u=()=>{const h=performance.now()-c,p=Math.min(1,h/a);let 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 b=n[x]??m;return Math.round(m+(b-m)*g)});this.setFixtureValues(t,y),p<1?requestAnimationFrame(u):i()};u()})}setOutputCallback(t){this.outputCallback=t}start(){this.running||(this.running=!0,this.intervalId=window.setInterval(()=>{this.sendOutput()},1e3/this.frameRate))}stop(){this.running=!1,this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null)}sendOutput(){this.outputCallback&&this.universes.forEach((t,n)=>{this.outputCallback(n,t.channels)})}blackout(){this.universes.forEach(t=>{t.channels.fill(0)}),this.fixtures.forEach(t=>{t.values.fill(0)})}fullOn(){this.fixtures.forEach(t=>{this.setFixtureDimmer(t.id,1)})}}const Wg=6454,Ug=new Uint8Array([65,114,116,45,78,101,116,0]);function Vg(e,t){const n=new Uint8Array(18+t.length);return n.set(Ug,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 qg=5568;function Hg(e,t,n,a=100,s="Nice2Dev DMX"){const i=Math.min(t.length,512),o=126+i,l=new Uint8Array(o),c=new DataView(l.buffer);c.setUint16(0,16,!1),c.setUint16(2,0,!1);const u=[65,83,67,45,69,49,46,49,55,0,0,0];for(let m=0;m<u.length;m++)l[4+m]=u[m];const h=o-16;c.setUint16(16,28672|h&4095,!1),c.setUint32(18,4,!1);for(let m=0;m<16;m++)l[22+m]=m+1;const p=o-38;c.setUint16(38,28672|p&4095,!1),c.setUint32(40,2,!1);const 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 Kg(e){const t=e>>8&255,n=e&255;return`239.255.${t}.${n}`}class Yg{constructor(t,n){this.config=t,this.scenes=n,this.currentStep=0,this.direction=1,this.isRunning=!1,this.timer=null,this.fadeStartTime=0,this.fadeFromValues=new Uint8Array(512),this.fadeToValues=new Uint8Array(512),this.onOutput=null}setOutputCallback(t){this.onOutput=t}start(){this.isRunning||(this.isRunning=!0,this.currentStep=this.config.direction==="backward"?this.config.steps.length-1:0,this.direction=this.config.direction==="backward"?-1:1,this.executeStep())}stop(){this.isRunning=!1,this.timer&&(clearTimeout(this.timer),this.timer=null)}executeStep(){var o;if(!this.isRunning)return;const t=this.config.steps[this.currentStep];if(!t)return;const n=this.scenes.get(t.sceneId);if(!n){this.advanceStep();return}const a=new Uint8Array(512);if(n.channels)for(const l of n.channels)l.channel>=1&&l.channel<=512&&(a[l.channel-1]=l.value);this.fadeFromValues.set(this.fadeToValues),this.fadeToValues.set(a),this.fadeStartTime=performance.now();const s=t.fadeTime/this.config.speed,i=t.holdTime/this.config.speed;s>0?this.runFade(s,()=>{var l;(l=this.onOutput)==null||l.call(this,this.fadeToValues),this.timer=setTimeout(()=>this.advanceStep(),i)}):((o=this.onOutput)==null||o.call(this,a),this.timer=setTimeout(()=>this.advanceStep(),i))}runFade(t,n){const a=performance.now(),s=new Uint8Array(512),i=()=>{var c;if(!this.isRunning)return;const o=performance.now()-a,l=Math.min(o/t,1);for(let u=0;u<512;u++)s[u]=Math.round(this.fadeFromValues[u]+(this.fadeToValues[u]-this.fadeFromValues[u])*l);(c=this.onOutput)==null||c.call(this,s),l<1?requestAnimationFrame(i):n()};requestAnimationFrame(i)}advanceStep(){if(!this.isRunning)return;const{steps:t,loop:n,direction:a}=this.config;if(this.currentStep+=this.direction,a==="bounce"){if(this.currentStep>=t.length?(this.direction=-1,this.currentStep=t.length-2):this.currentStep<0&&(this.direction=1,this.currentStep=1),this.currentStep<0||this.currentStep>=t.length){if(!n){this.stop();return}this.currentStep=0,this.direction=1}}else if(this.currentStep>=t.length||this.currentStep<0){if(!n){this.stop();return}this.currentStep=a==="backward"?t.length-1:0}this.executeStep()}}const Zg=({engine:e,tracks:t=[],scenes:n=[],duration:a=3e5,currentTime:s=0,bpm:i=120,onTimeChange:o,onCueAdd:l,onCueUpdate:c,onCueDelete:u,onTrackAdd:h,onTrackUpdate:p,onPlay:g,onPause:y,onStop:m,className:x=""})=>{const{t:b}=xe(),[f,j]=d.useState(1),[v,C]=d.useState(0),[T,M]=d.useState(!1),[k,R]=d.useState(null),[P,I]=d.useState(null),[A,L]=d.useState(!0),[E,D]=d.useState(1e3),Z=d.useRef(null),G=d.useRef(null),F=d.useRef(0),q=d.useMemo(()=>.1*f,[f]),V=d.useCallback($=>$*q,[q]),K=d.useCallback($=>$/q,[q]),W=d.useCallback($=>{if(!A)return $;const H=6e4/i;return Math.round($/H)*H},[A,i]),Q=d.useRef(()=>{});d.useEffect(()=>{if(!T)return;const $=performance.now(),H=s,X=()=>{const re=performance.now()-$,oe=H+re;if(oe>=a){M(!1),o==null||o(0),m==null||m();return}Q.current(oe),o==null||o(oe),G.current=requestAnimationFrame(X)};return G.current=requestAnimationFrame(X),()=>{G.current!==null&&(cancelAnimationFrame(G.current),G.current=null)}},[T,s,a,o,m]);const w=d.useRef(!1);d.useEffect(()=>{T!==w.current&&(w.current=T,T?g==null||g():y==null||y())},[T,g,y]);const N=d.useCallback($=>{t.forEach(H=>{H.muted||H.cues.forEach(X=>{const re=X.startTime,oe=re+X.duration;if($>=re&&$<oe&&F.current<re){const se=n.find(z=>z.id===X.sceneId);se&&se.fixtures.forEach(z=>{X.fadeIn&&X.fadeIn>0?e.fadeFixture(z.fixtureId,z.values,X.fadeIn):e.setFixtureValues(z.fixtureId,z.values)})}if(F.current<oe&&$>=oe){const se=n.find(z=>z.id===X.sceneId);se&&se.fixtures.forEach(z=>{if(e.getFixture(z.fixtureId)&&X.fadeOut&&X.fadeOut>0){const ae=new Array(z.values.length).fill(0);e.fadeFixture(z.fixtureId,ae,X.fadeOut)}})}})}),F.current=$},[t,n,e]);Q.current=N;const S=$=>{const H=Math.floor($/1e3),X=Math.floor(H/60),re=H%60,oe=Math.floor($%1e3/(1e3/30));return`${X}:${re.toString().padStart(2,"0")}:${oe.toString().padStart(2,"0")}`},O=d.useCallback($=>{if(!Z.current)return;const H=Z.current.getBoundingClientRect(),X=$.clientX-H.left+v,re=W(K(X));o==null||o(Math.max(0,Math.min(a,re)))},[v,K,W,a,o]),Y=d.useCallback(($,H,X)=>{const re=t.find(z=>z.id===H),oe=re==null?void 0:re.cues.find(z=>z.id===$);if(!oe)return;const se=W(Math.max(0,oe.startTime+K(X)));c==null||c({...oe,startTime:se})},[t,K,W,c]),_=()=>{const $=6e4/i,H=Math.ceil(a/$),X=[];for(let re=0;re<=H;re++){const oe=re*$,se=V(oe),z=re%4===0;X.push(r.jsx("div",{className:`nice-dmx-timeline__beat ${z?"nice-dmx-timeline__beat--measure":""}`,style:{left:se},children:z&&r.jsx("span",{className:"nice-dmx-timeline__beat-label",children:re/4+1})},re))}return X},U=($,H)=>{const X=V($.startTime),re=V($.duration),oe=n.find(se=>se.id===$.sceneId);return r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,className:`nice-dmx-timeline__cue ${k===$.id?"nice-dmx-timeline__cue--selected":""}`,style:{left:X,width:re,backgroundColor:(oe==null?void 0:oe.color)||H.color||"var(--nice-accent, #8b5cf6)"},onClick:se=>{se.stopPropagation(),R($.id)},draggable:!H.locked,onDragEnd:se=>{var ee;const z=(ee=se.target.parentElement)==null?void 0:ee.getBoundingClientRect();z&&Y($.id,H.id,se.clientX-z.left-X)},children:[r.jsx("span",{className:"nice-dmx-timeline__cue-name",children:$.name||(oe==null?void 0:oe.name)}),$.fadeIn&&$.fadeIn>0&&r.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--in",style:{width:V($.fadeIn)}}),$.fadeOut&&$.fadeOut>0&&r.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--out",style:{width:V($.fadeOut)}})]},$.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:b("dmxTimeline.goToStart","Go to start"),"aria-label":b("dmxTimeline.goToStart","Go to start"),children:r.jsx(B.NtdSkipBack,{size:14})}),r.jsx("button",{type:"button",onClick:()=>M(!T),title:T?b("dmxTimeline.pause","Pause"):b("dmxTimeline.play","Play"),"aria-label":T?b("dmxTimeline.pause","Pause"):b("dmxTimeline.play","Play"),children:T?r.jsx(B.NtdPause,{size:14}):r.jsx(B.NtdPlay,{size:14})}),r.jsx("button",{type:"button",onClick:()=>{M(!1),o==null||o(0),e.blackout(),m==null||m()},title:b("dmxTimeline.stop","Stop"),"aria-label":b("dmxTimeline.stop","Stop"),children:r.jsx(B.NtdStop,{size:14})})]}),r.jsx("div",{className:"nice-dmx-timeline__time",children:S(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:()=>L(!A),title:b("dmxTimeline.snapToGrid","Snap to grid"),"aria-label":b("dmxTimeline.snapToGrid","Snap to grid"),children:r.jsx(B.NtdGrid,{size:14})}),r.jsx("button",{type:"button",onClick:()=>j(Math.max(.25,f-.25)),title:b("dmxTimeline.zoomOut","Zoom out"),"aria-label":b("dmxTimeline.zoomOut","Zoom out"),children:r.jsx(B.NtdZoomOut,{size:14})}),r.jsxs("span",{className:"nice-dmx-timeline__zoom",children:[Math.round(f*100),"%"]}),r.jsx("button",{type:"button",onClick:()=>j(Math.min(4,f+.25)),title:b("dmxTimeline.zoomIn","Zoom in"),"aria-label":b("dmxTimeline.zoomIn","Zoom in"),children:r.jsx(B.NtdZoomIn,{size:14})})]}),r.jsxs("div",{className:"nice-dmx-timeline__bpm",children:[r.jsx("label",{children:b("dmxTimeline.bpm","BPM:")}),r.jsx("span",{children:i})]}),r.jsx("button",{type:"button",className:"nice-dmx-timeline__blackout",onClick:()=>e.blackout(),title:b("dmxTimeline.blackout","Blackout"),"aria-label":b("dmxTimeline.blackout","Blackout"),children:r.jsx(B.NtdMoon,{size:14})})]}),r.jsxs("div",{className:"nice-dmx-timeline__content",children:[r.jsxs("div",{className:"nice-dmx-timeline__headers",children:[t.map($=>r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,className:`nice-dmx-timeline__header ${P===$.id?"nice-dmx-timeline__header--selected":""}`,onClick:()=>I($.id),children:[r.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:$.color||"var(--nice-accent, #8b5cf6)"}}),r.jsx("span",{className:"nice-dmx-timeline__track-name",children:$.name}),r.jsxs("div",{className:"nice-dmx-timeline__track-controls",children:[r.jsx("button",{type:"button",className:`nice-dmx-timeline__track-toggle ${$.muted?"nice-dmx-timeline__track-toggle--active":""}`,onClick:H=>{H.stopPropagation(),p==null||p({...$,muted:!$.muted})},title:b("dmxTimeline.mute","Mute"),children:"M"}),r.jsx("button",{type:"button",className:`nice-dmx-timeline__track-toggle ${$.locked?"nice-dmx-timeline__track-toggle--active":""}`,onClick:H=>{H.stopPropagation(),p==null||p({...$,locked:!$.locked})},title:b("dmxTimeline.lock","Lock"),"aria-label":b("dmxTimeline.lock","Lock"),children:r.jsx(B.NtdLock,{size:14})})]})]},$.id)),r.jsxs("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:[r.jsx(B.NtdPlus,{size:14})," ",b("dmxTimeline.addTrack","Add Track")]})]}),r.jsxs("div",{role:"presentation",className:"nice-dmx-timeline__tracks",ref:Z,onClick:O,onScroll:$=>C($.currentTarget.scrollLeft),children:[r.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:V(a)},children:_()}),t.map($=>r.jsx("div",{className:`nice-dmx-timeline__track ${$.muted?"nice-dmx-timeline__track--muted":""}`,style:{width:V(a)},children:$.cues.map(H=>U(H,$))},$.id)),r.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:V(s)}})]})]})]})};function Xg(){const[e]=d.useState(()=>new Mc);return d.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function Qg(e,t,n=120){const[a,s]=d.useState(0),i=d.useRef(0);return d.useEffect(()=>{if(!t)return;const o=60/n,l=()=>{const c=t.currentTime,u=Math.floor(c/o);u!==i.current&&(i.current=u,s(u))};return t.addEventListener("timeupdate",l),()=>t.removeEventListener("timeupdate",l)},[t,n]),{currentBeat:a}}const Jg=[],ey=[],ty=[{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 Rc(){const{t:e}=xe(),[t,n]=d.useState(!1),[a,s]=d.useState(.8),[i,o]=d.useState(!1),[l,c]=d.useState(null),[u,h]=d.useState(null),[p,g]=d.useState(null),y=d.useRef(null),m=d.useRef(null),x=d.useRef(null),b=d.useRef(null),f=d.useRef([]),j=d.useRef(null),v=d.useRef(null),C=d.useRef(a),T=d.useCallback(()=>{if(m.current)return;const G=new AudioContext;m.current=G;const F=G.createGain();F.gain.value=C.current,b.current=F;const q=G.createAnalyser();q.fftSize=256,j.current=q,F.connect(q).connect(G.destination)},[]),M=d.useCallback(()=>{const G=y.current,F=m.current,q=b.current;if(!G||!F||!q||x.current)return;const V=F.createMediaElementSource(G);x.current=V,f.current.length>0?(V.connect(f.current[0]),f.current[f.current.length-1].connect(q)):V.connect(q)},[]),k=d.useCallback(()=>{var F;const G=y.current;!G||!v.current||(Xt(),T(),M(),((F=m.current)==null?void 0:F.state)==="suspended"&&m.current.resume(),G.play().catch(q=>h(String(q))))},[T,M]),R=d.useCallback(()=>{var G;(G=y.current)==null||G.pause()},[]),P=d.useCallback(()=>{t?R():k()},[t,k,R]),I=d.useCallback(G=>{const F=Math.max(0,Math.min(1,G));s(F),C.current=F,b.current&&(b.current.gain.value=F),y.current&&(y.current.volume=F)},[]),A=d.useCallback(G=>{v.current=G,h(null),c(null),o(!0),x.current&&(x.current.disconnect(),x.current=null),y.current||(y.current=new Audio,y.current.crossOrigin="anonymous",y.current.addEventListener("playing",()=>{n(!0),o(!1)}),y.current.addEventListener("pause",()=>n(!1)),y.current.addEventListener("waiting",()=>o(!0)),y.current.addEventListener("canplay",()=>o(!1)),y.current.addEventListener("error",()=>h(e("radioPlayer.failedToLoadStream","Failed to load stream")))),y.current.src=G.streamUrl,y.current.load(),c({genre:G.genre,bitrate:G.bitrate})},[e]),L=d.useCallback(G=>{m.current||T();const q=m.current;f.current.forEach(K=>K.disconnect());const V=G.bands.map(K=>{const W=q.createBiquadFilter();return W.type="peaking",W.frequency.value=K.frequency,W.gain.value=K.gain,W.Q.value=K.Q??1.4,W});for(let K=0;K<V.length-1;K++)V[K].connect(V[K+1]);f.current=V,x.current&&b.current&&(x.current.disconnect(),x.current.connect(V[0]),V[V.length-1].connect(b.current)),g(G.name)},[T]),E=d.useCallback(()=>{f.current.forEach(G=>G.disconnect()),f.current=[],x.current&&b.current&&(x.current.disconnect(),x.current.connect(b.current)),g(null)},[]);return d.useEffect(()=>()=>{var G,F,q;(G=y.current)==null||G.pause(),y.current=null,f.current.forEach(V=>V.disconnect()),(F=x.current)==null||F.disconnect(),(q=m.current)==null||q.close()},[]),[{isPlaying:t,volume:a,isBuffering:i,metadata:l,error:u,activePreset:p},{play:k,pause:R,toggle:P,setVolume:I,setStation:A,applyEQPreset:L,clearEQ:E}]}function Nc({stations:e=Jg,activeStationId:t,onSelect:n,onToggleFavorite:a,className:s}){const{t:i}=xe(),[o,l]=d.useState(""),[c,u]=d.useState(null),[h,p]=d.useState(!1),g=d.useMemo(()=>[...new Set(e.map(m=>m.genre).filter(Boolean))],[e]),y=d.useMemo(()=>e.filter(m=>{var x,b;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)||(((b=m.country)==null?void 0:b.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=>u(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(B.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.jsx("span",{className:"nice-station-browser__bitrate",children:i("radioPlayer.kbps","{bitrate}kbps").replace("{bitrate}",String(m.bitrate))}),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(B.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 ny({stations:e=ey,initialStationId:t,autoPlay:n=!1,eqPresets:a=ty,onStationChange:s,onPlayingChange:i,onMetadata:o,onToggleFavorite:l,onRecordingStart:c,onRecordingStop:u,showBrowser:h=!0,showEqualizer:p=!1,showVisualizer:g=!1,showMetadataHistory:y=!1,showRecording:m=!1,showSleepTimer:x=!1,className:b,style:f}){var O,Y;const{t:j}=xe(),[v,C]=Rc(),[T,M]=d.useState(()=>t?e.find(_=>_.id===t)??null:null),[k,R]=d.useState(p),P=d.useRef(null),I=d.useRef(0),[A,L]=d.useState([]),[E,D]=d.useState(!1),Z=d.useRef(null),G=d.useRef([]),[F,q]=d.useState(0),V=d.useRef(null),[K,W]=d.useState(0),[Q,w]=d.useState(null),N=d.useRef(null);d.useEffect(()=>{i==null||i(v.isPlaying)},[v.isPlaying,i]),d.useEffect(()=>{v.metadata&&(o==null||o(v.metadata),(v.metadata.title||v.metadata.artist)&&L(_=>[{time:new Date,meta:v.metadata},..._.slice(0,49)]))},[v.metadata,o]);const S=d.useCallback(_=>{M(_),C.setStation(_),s==null||s(_),n&&setTimeout(()=>C.play(),100)},[C,s,n]);return d.useEffect(()=>{if(t&&!T){const _=e.find(U=>U.id===t);_&&S(_)}},[t,e,T,S]),d.useEffect(()=>{if(!g||!P.current)return;const _=P.current,U=_.getContext("2d");if(!U)return;const $=()=>{I.current=requestAnimationFrame($),U.clearRect(0,0,_.width,_.height);const H=U.createLinearGradient(0,_.height,0,0);if(H.addColorStop(0,ve.resolveCssColor("var(--nice-accent-tint-80, rgba(99, 102, 241, 0.8))",U.canvas)),H.addColorStop(.5,ve.resolveCssColor("var(--nice-accent-tint-50, rgba(168,85,247,0.6))",U.canvas)),H.addColorStop(1,"rgba(236,72,153,0.4)"),!v.isPlaying){const se=_.width/32;for(let z=0;z<32;z++){const ee=4+Math.sin(Date.now()/1e3+z*.3)*3;U.fillStyle=H,U.fillRect(z*se+1,_.height-ee,se-2,ee)}return}const X=32,re=_.width/X;for(let oe=0;oe<X;oe++){const se=oe/X,ee=(Math.sin(Date.now()/200+oe*.5)*.3+.5)*_.height*(1-se*.5)*(.5+Math.random()*.5);U.fillStyle=H,U.fillRect(oe*re+1,_.height-ee,re-2,ee)}};return $(),()=>cancelAnimationFrame(I.current)},[g,v.isPlaying]),d.useCallback(()=>{if(v.isPlaying)try{const U=new AudioContext().createMediaStreamDestination();G.current=[];const $=new MediaRecorder(U.stream,{mimeType:"audio/webm"});$.ondataavailable=H=>{H.data.size>0&&G.current.push(H.data)},$.onstop=()=>{const H=new Blob(G.current,{type:"audio/webm"});u==null||u(H),q(0),V.current&&window.clearInterval(V.current)},$.start(1e3),Z.current=$,D(!0),q(0),V.current=window.setInterval(()=>{q(H=>H+1)},1e3),c==null||c()}catch{}},[v.isPlaying,c,u]),d.useCallback(()=>{Z.current&&E&&(Z.current.stop(),D(!1),V.current&&window.clearInterval(V.current))},[E]),d.useCallback(_=>{N.current&&window.clearInterval(N.current),W(_),w(_*60),N.current=window.setInterval(()=>{w(U=>!U||U<=1?(N.current&&window.clearInterval(N.current),N.current=null,C.pause(),null):U-1)},1e3)},[C]),d.useCallback(()=>{N.current&&window.clearInterval(N.current),N.current=null,w(null),W(0)},[]),d.useEffect(()=>()=>{V.current&&window.clearInterval(V.current),N.current&&window.clearInterval(N.current),cancelAnimationFrame(I.current)},[]),r.jsxs("div",{className:`nice-radio-player${b?` ${b}`:""}`,style:f,children:[r.jsx("div",{className:"nice-radio-player__now-playing",children:T?r.jsxs(r.Fragment,{children:[T.logoUrl&&r.jsx("img",{className:"nice-radio-player__cover",src:T.logoUrl,alt:T.name}),r.jsxs("div",{className:"nice-radio-player__info",children:[r.jsx("span",{className:"nice-radio-player__station-name",children:T.name}),((O=v.metadata)==null?void 0:O.title)&&r.jsx("span",{className:"nice-radio-player__track",children:v.metadata.artist?`${v.metadata.artist} — ${v.metadata.title}`:v.metadata.title}),((Y=v.metadata)==null?void 0:Y.genre)&&r.jsx("span",{className:"nice-radio-player__genre",children:v.metadata.genre}),v.isBuffering&&r.jsx("span",{className:"nice-radio-player__buffering",children:j("radioPlayer.buffering","Buffering…")})]})]}):r.jsx("div",{className:"nice-radio-player__placeholder",children:j("radioPlayer.selectStation","Select a station")})}),r.jsxs("div",{className:"nice-radio-player__controls",children:[r.jsx("button",{className:"nice-radio-player__play-btn",onClick:C.toggle,disabled:!T,"aria-label":v.isPlaying?j("radioPlayer.pause","Pause"):j("radioPlayer.play","Play"),children:v.isPlaying?r.jsx(B.NtdPause,{size:16}):r.jsx(B.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(B.NtdVolume,{size:16})}),r.jsx("input",{type:"range",min:0,max:1,step:.01,value:v.volume,onChange:_=>C.setVolume(parseFloat(_.target.value)),className:"nice-radio-player__volume-slider","aria-label":j("radioPlayer.volume","Volume")})]}),r.jsx("button",{className:`nice-radio-player__eq-btn${k?" nice-radio-player__eq-btn--active":""}`,onClick:()=>R(!k),title:j("radioPlayer.equalizer","Equalizer"),children:"EQ"})]}),v.error&&r.jsx("div",{className:"nice-radio-player__error",children:v.error}),k&&r.jsx("div",{className:"nice-radio-player__equalizer",children:r.jsxs("div",{className:"nice-radio-player__eq-presets",children:[a.map(_=>r.jsx("button",{className:`nice-radio-player__eq-preset${v.activePreset===_.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>C.applyEQPreset(_),children:_.name},_.name)),v.activePreset&&r.jsx("button",{className:"nice-radio-player__eq-preset",onClick:C.clearEQ,children:j("clear","Clear")})]})}),h&&r.jsx(Nc,{stations:e,activeStationId:T==null?void 0:T.id,onSelect:S})]})}const ry=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],ay={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class Tc{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??ry,audioConstraints:{...ay,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 sy(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function iy(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function oy(){return new AudioContext({sampleRate:48e3,latencyHint:"interactive"})}const ms=d.forwardRef(function(t,n){const{t:a}=xe(),{mode:s="bars",width:i=300,height:o=100,barCount:l=32,barColor:c="var(--nice-primary, #3b82f6)",backgroundColor:u="transparent",fftSize:h=256,smoothing:p=.8,minDecibels:g=-90,maxDecibels:y=-10,deviceId:m,autoStart:x=!1,onStart:b,onStop:f,onAudioLevel:j,onError:v,className:C,style:T,barBorderRadius:M=2,barGap:k=2,lineWidth:R=2}=t,P=d.useRef(null),I=d.useRef(null),A=d.useRef(null),L=d.useRef(null),E=d.useRef(0),D=d.useRef(null),Z=d.useRef(0),[G,F]=d.useState(!1),q=Array.isArray(c)?c.join("|"):c,V=d.useMemo(()=>q.split("|").map(_=>ve.resolveCssColor(_,P.current)),[q]),K=d.useCallback((_,U,$=!0)=>{const H=$?_.createLinearGradient(0,o,0,0):_.createLinearGradient(0,0,i,0);return U.forEach((X,re)=>{H.addColorStop(re/(U.length-1),X)}),H},[i,o]),W=d.useCallback((_,U)=>{const H=(i-(l-1)*k)/l,X=Math.floor(U.length/l),re=V,oe=re.length>1?K(_,re):re[0];_.fillStyle=oe;for(let se=0;se<l;se++){const ee=U[se*X]/255*o,ae=se*(H+k),ce=o-ee;M>0?(_.beginPath(),_.roundRect(ae,ce,H,ee,M),_.fill()):_.fillRect(ae,ce,H,ee)}},[l,V,k,M,i,o,K]),Q=d.useCallback((_,U)=>{const $=o/2,X=(i-(l-1)*k)/l,re=Math.floor(U.length/l),oe=V,se=oe.length>1?K(_,oe):oe[0];_.fillStyle=se;for(let z=0;z<l;z++){const ae=U[z*re]/255*$,ce=z*(X+k);M>0?(_.beginPath(),_.roundRect(ce,$-ae,X,ae,M),_.fill(),_.beginPath(),_.roundRect(ce,$,X,ae,M),_.fill()):(_.fillRect(ce,$-ae,X,ae),_.fillRect(ce,$,X,ae))}},[l,V,k,M,i,o,K]),w=d.useCallback((_,U)=>{const $=V;_.strokeStyle=$.length>1?K(_,$,!1):$[0],_.lineWidth=R,_.lineCap="round",_.lineJoin="round",_.beginPath();const H=i/U.length;let X=0;for(let re=0;re<U.length;re++){const se=U[re]/128*o/2;re===0?_.moveTo(X,se):_.lineTo(X,se),X+=H}_.stroke()},[V,R,i,o,K]),N=d.useCallback((_,U)=>{const $=i/2,H=o/2,X=Math.min(i,o)/3,re=V;_.strokeStyle=re.length>1?K(_,re):re[0],_.lineWidth=R;const oe=Math.floor(U.length/64),se=Math.PI*2/64;_.beginPath();for(let z=0;z<64;z++){const ee=U[z*oe]/255,ae=X+ee*X*.5,ce=z*se-Math.PI/2,le=$+Math.cos(ce)*ae,ne=H+Math.sin(ce)*ae;z===0?_.moveTo(le,ne):_.lineTo(le,ne)}_.closePath(),_.stroke()},[V,R,i,o,K]),S=d.useCallback(()=>{const _=P.current,U=A.current,$=D.current;if(!_||!U||!$)return;const H=_.getContext("2d");if(!H)return;s==="waveform"?U.getByteTimeDomainData($):U.getByteFrequencyData($);let X=0;for(let re=0;re<$.length;re++)X+=$[re];switch(Z.current=X/($.length*255),j==null||j(Z.current),H.clearRect(0,0,i,o),u!=="transparent"&&(H.fillStyle=ve.resolveCssColor(u,H.canvas),H.fillRect(0,0,i,o)),s){case"bars":W(H,$);break;case"mirror-bars":Q(H,$);break;case"waveform":w(H,$);break;case"circle":N(H,$);break}E.current=requestAnimationFrame(S)},[s,i,o,u,W,Q,w,N,j]),O=d.useCallback(async()=>{try{if(G)return;const _=await navigator.mediaDevices.getUserMedia({audio:m?{deviceId:{exact:m}}:!0,video:!1});L.current=_;const U=new AudioContext;I.current=U;const $=U.createMediaStreamSource(_),H=U.createAnalyser();H.fftSize=h,H.smoothingTimeConstant=p,H.minDecibels=g,H.maxDecibels=y,$.connect(H),A.current=H,D.current=new Uint8Array(H.frequencyBinCount),F(!0),b==null||b(),S()}catch(_){v==null||v(_ instanceof Error?_:new Error(String(_)))}},[G,m,h,p,g,y,b,v,S]),Y=d.useCallback(()=>{cancelAnimationFrame(E.current),L.current&&(L.current.getTracks().forEach(U=>U.stop()),L.current=null),I.current&&(I.current.close(),I.current=null),A.current=null,D.current=null,Z.current=0,F(!1),f==null||f();const _=P.current;if(_){const U=_.getContext("2d");U&&(U.clearRect(0,0,i,o),u!=="transparent"&&(U.fillStyle=ve.resolveCssColor(u,U.canvas),U.fillRect(0,0,i,o)))}},[i,o,u,f]);return d.useImperativeHandle(n,()=>({start:O,stop:Y,isCapturing:()=>G,getAudioLevel:()=>Z.current}),[O,Y,G]),d.useEffect(()=>(x&&O(),()=>{Y()}),[x]),r.jsx("canvas",{ref:P,width:i,height:o,className:C,style:{display:"block",...T},"aria-label":a("streamingVisualizer.audioVisualizer","Audio visualizer")})}),Pi=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}}},ly={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"},cy={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))"},dy={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))"},Pc=d.forwardRef(function(t,n){const{t:a}=xe(),{userId:s,userName:i,userAvatarUrl:o,participants:l=[],rtcConfig:c,position:u="bottom-right",expanded:h=!0,onSignalingMessage:p,onMuteToggle:g,onLeave:y,onSpeakingChange:m,speakingThreshold:x=.1,theme:b="auto",className:f,style:j,zIndex:v=1e3}=t,C=d.useRef(null),T=d.useRef(null),M=d.useRef(new Map);d.useRef(new Map);const[k,R]=d.useState(!1),[P,I]=d.useState(!1),[A,L]=d.useState(!1),[E,D]=d.useState(h),G=d.useMemo(()=>b==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":b,[b])==="dark"?dy:cy;d.useEffect(()=>{const w=new Tc(s,c);w.onRemoteStream=(S,O)=>{let Y=M.current.get(S);Y||(Y=new Audio,Y.autoplay=!0,M.current.set(S,Y)),Y.srcObject=O},w.onSignalingMessage=S=>{p==null||p(S)},w.onPeerStateChange=(S,O)=>{O==="connected"&&I(!0)},C.current=w,w.initialize().then(()=>{var S;(S=T.current)==null||S.start()});const N=M.current;return()=>{w.disconnect(),N.forEach(S=>{S.srcObject=null}),N.clear()}},[s,c,p]);const F=d.useCallback(()=>{var N;const w=!k;R(w),(N=C.current)==null||N.setMuted(w),g==null||g(w)},[k,g]),q=d.useCallback(()=>{var w,N;(w=C.current)==null||w.disconnect(),(N=T.current)==null||N.stop(),I(!1),y==null||y()},[y]),V=d.useCallback(w=>{const N=w>x;N!==A&&(L(N),m==null||m(s,N))},[x,A,s,m]),K=d.useCallback(async w=>{var N;await((N=C.current)==null?void 0:N.createOffer(w))},[]),W=d.useCallback(async w=>{var N;await((N=C.current)==null?void 0:N.handleSignalingMessage(w))},[]);d.useImperativeHandle(n,()=>({connectToPeer:K,handleSignalingMessage:W,toggleMute:F,isMuted:()=>k,leave:q,getManager:()=>C.current}),[K,W,F,k,q]);const Q=({participant:w,isLocal:N,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:G.hoverBg,border:`2px solid ${S?G.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:G.text,transition:"border-color 0.15s ease"},children:w.avatarUrl?r.jsx("img",{src:w.avatarUrl,alt:w.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):w.name.charAt(0).toUpperCase()}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsxs("div",{style:{color:G.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[w.name,N&&r.jsxs("span",{style:{color:G.textSecondary,fontWeight:400},children:[" ",a("voiceChatOverlay.you","(You)")]})]})}),w.isMuted&&r.jsx(B.NtdMicrophoneOff,{size:16,variant:"outline",primaryColor:G.mutedIcon})]});return E?r.jsxs("div",{className:f,style:{...ly,...Pi(u),backgroundColor:G.background,border:`1px solid ${G.border}`,zIndex:v,...j},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${G.border}`},children:[r.jsx("span",{style:{color:G.text,fontWeight:600},children:a("voiceChatOverlay.voiceChat","Voice Chat")}),r.jsx("button",{onClick:()=>D(!1),style:{background:"none",border:"none",cursor:"pointer",padding:4,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:4},"aria-label":a("voiceChatOverlay.collapse","Collapse"),children:r.jsx(B.NtdMinimize,{size:16,variant:"outline",primaryColor:G.textSecondary})})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[r.jsx(Q,{participant:{id:s,name:i,avatarUrl:o,isMuted:k},isLocal:!0,isSpeaking:A&&!k}),l.map(w=>r.jsx(Q,{participant:w,isSpeaking:w.isSpeaking},w.id))]}),r.jsx(ms,{ref:T,mode:"bars",width:256,height:32,barCount:24,barColor:k?"var(--nice-text-muted, #9ca3af)":["var(--nice-primary, #3b82f6)","var(--nice-accent, #8b5cf6)"],barGap:3,barBorderRadius:2,autoStart:!1,onAudioLevel:V,style:{borderRadius:4,opacity:k?.5:1}}),r.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[r.jsx("button",{onClick:F,style:{flex:1,padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:k?G.mutedBg:G.activeBg,color:k?G.mutedIcon:G.activeIcon,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":k?a("voiceChatOverlay.unmute","Unmute"):a("voiceChatOverlay.mute","Mute"),children:k?r.jsxs(r.Fragment,{children:[r.jsx(B.NtdMicrophoneOff,{size:16,variant:"outline"}),a("voiceChatOverlay.muted","Muted")]}):r.jsxs(r.Fragment,{children:[r.jsx(B.NtdMicrophone,{size:16,variant:"outline"}),a("voiceChatOverlay.micOn","Mic On")]})}),r.jsx("button",{onClick:q,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(B.NtdLogOut,{size:16,variant:"outline"})})]})]}):r.jsx("div",{className:f,style:{position:"fixed",...Pi(u),zIndex:v,...j},children:r.jsxs("button",{onClick:()=>D(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:G.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(B.NtdMicrophone,{size:24,variant:"outline",primaryColor:G.text}),l.length>0&&r.jsx("span",{style:{position:"absolute",top:-4,right:-4,width:20,height:20,borderRadius:"50%",backgroundColor:G.speakingRing,color:"var(--nice-color-white, #fff)",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:l.length+1})]})})});function uy(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 hy(e){return e.undoIndex<0?e:{...e,undoIndex:e.undoIndex-1}}function py(e){return e.undoIndex>=e.operations.length-1?e:{...e,undoIndex:e.undoIndex+1}}function fy(e,t,n){const s=({"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":.6666666666666666,"1/8T":.3333333333333333,"1/16T":.16666666666666666,"1/4D":1.5,"1/8D":.75}[t.grid]??1)*n,i=t.strength/100;return e.map(o=>{const l=Math.round(o.startTick/s)*s,c=o.startTick+(l-o.startTick)*i,u=(Math.random()-.5)*2*t.humanize;return{...o,startTick:Math.max(0,Math.round(c+u))}})}function my(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 Ec={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 gy(e,t,n){const a=Ec[n],s=(e-t+120)%12;let i=a[0],o=999;for(const c of a){const u=Math.min(Math.abs(s-c),12-Math.abs(s-c));u<o&&(o=u,i=c)}const l=Math.floor((e-t)/12);return t+l*12+i}function yy(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 vy(e){return e>=95?"S":e>=85?"A":e>=70?"B":e>=55?"C":e>=40?"D":"F"}const by={"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]}},xy={"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=qn;exports.ALL_EFFECTS=Dl;exports.ALL_TEXTURES=Ao;exports.ARTNET_PORT=Wg;exports.ASYMMETRIC_CAPS=Co;exports.AudioEffectType=Sc;exports.AudioPlaybackEngine=b0;exports.AudioRecorder=Da;exports.AutoSavePanel=Di;exports.CONTROLLER_PROFILES=Yl;exports.ChaseRunner=Yg;exports.CollaboratorPermission=kc;exports.DEFAULT_ARP_CONFIG=pa;exports.DEFAULT_AUDIO_INPUT_SETTINGS=Fl;exports.DEFAULT_BAR_FILL=Ut;exports.DEFAULT_CAP_STYLE=Mo;exports.DEFAULT_EMPTY_BAR_FILL=Or;exports.DEFAULT_FONT_SETTINGS=Wr;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=Br;exports.DEFAULT_GOLD_FILLED_BAR_FILL=Gr;exports.DEFAULT_KARAOKE_SETTINGS=Ro;exports.DEFAULT_SEED_CONFIG=Bl;exports.DMXEngine=Mc;exports.DRUM_PATTERN_NAMES=A0;exports.DefaultScoringPresets=Oa;exports.DmxChannelControl=fs;exports.DmxChannelType=Bt;exports.DmxEditor=Cc;exports.DmxOptionsControl=ps;exports.DmxSliderControl=Hn;exports.DynamicRuleField=ot;exports.DynamicRuleOperator=lt;exports.EditorTrackProvider=za;exports.EditorUndoManager=Cu;exports.FIXTURE_PROFILES=jc;exports.GENERIC_PROFILE=is;exports.GM_DRUM_MAP=xy;exports.GRADIENT_PRESETS=pl;exports.GROOVE_TEMPLATES=ds;exports.GenericPlaylistItem=es;exports.KARAOKE_FONT_OPTIONS=Sp;exports.KEY_MAPS=Ko;exports.KaraokeFormat=Xa;exports.LANE_COLORS=_n;exports.LAUNCH_CONTROL_PROFILE=Kl;exports.LAYER_COLORS=_g;exports.MINILAB_PROFILE=Hl;exports.MPK_MINI_PROFILE=ql;exports.MasterFXPanel=Fi;exports.MidiCCMapper=L0;exports.NOTE_NAMES=R0;exports.NiceArpeggiatorPanel=du;exports.NiceAudioEffectsRack=f0;exports.NiceAudioErrorBoundary=Bc;exports.NiceAudioInputPicker=v0;exports.NiceAudioPitchAnalyzer=bh;exports.NiceAudioStudio=Wd;exports.NiceAudioTimeline=_i;exports.NiceAutoSavePanel=Di;exports.NiceBarFillEditor=vh;exports.NiceCCAutomationLaneEditor=ou;exports.NiceCCLane=Jc;exports.NiceDMXTimeline=Zg;exports.NiceDmxChannelControl=fs;exports.NiceDmxEditor=Cc;exports.NiceDmxOptionsControl=ps;exports.NiceDmxSliderControl=Hn;exports.NiceDynamicRuleEditor=Hf;exports.NiceEditorTrackProvider=za;exports.NiceGenericPlayer=_o;exports.NiceGenericPlayerControls=Ap;exports.NiceGenericPlayerStage=hf;exports.NiceGenericPlaylist=jf;exports.NiceGenericPlaylistItem=es;exports.NiceI18nProvider=Fc;exports.NiceKaraokeEditorManager=Rp;exports.NiceKaraokeLyrics=mo;exports.NiceKaraokeManager=ep;exports.NiceKaraokePhaserRenderer=Pp;exports.NiceKaraokeSelectionMode=hl;exports.NiceKaraokeSessionJoin=bp;exports.NiceKaraokeSetupPanel=ul;exports.NiceKaraokeSongBrowser=dp;exports.NiceKaraokeSummaryOverlay=Io;exports.NiceKaraokeTimeline=Eo;exports.NiceKaraokeUploader=qo;exports.NiceLFOPanel=pu;exports.NiceLatencyCalibrator=hp;exports.NiceMasterFXPanel=Fi;exports.NiceModeSwitcher=gl;exports.NiceMusicLibraryExplorer=vf;exports.NiceNoteParticles=Zm;exports.NiceNoteRiver=Wm;exports.NicePadKaraokeOverlay=Ho;exports.NicePianoRoll=Aa;exports.NicePitchMeter=Fu;exports.NicePlaylistBrowser=am;exports.NicePlaylistDualPane=Zf;exports.NicePlaylistGridView=lm;exports.NicePlaylistImportWizard=vm;exports.NicePlaylistList=rs;exports.NicePlaylistOverview=dm;exports.NicePlaylistSearchBar=um;exports.NicePlaylistSidebar=im;exports.NicePlaylistTagEditor=Rf;exports.NicePlaylistTrackList=jl;exports.NiceRadioPlayer=ny;exports.NiceRecordingOptionsPanel=Oi;exports.NiceSampleBrowser=Vd;exports.NiceStageVisualizer=yl;exports.NiceStationBrowser=Nc;exports.NiceStepSequencerPanel=yu;exports.NiceStreamingVisualizer=ms;exports.NiceUndoRedoPanel=zi;exports.NiceVocalEffectsRack=g0;exports.NiceVocalPerformanceReport=sp;exports.NiceVoiceChatOverlay=Pc;exports.NiceWaveform=$i;exports.NiceYouTubePlayer=pf;exports.NiceZoomSnapControls=Ia;exports.OVERLAY_PATTERNS=$r;exports.OXYGEN25_PROFILE=Vl;exports.PLAYER_COLORS=Xe;exports.PLAYER_COLOR_VARS=pr;exports.PROGRESSION_NAMES=$0;exports.PadNotePlayer=Qo;exports.PaneSide=Sl;exports.PianoRoll=Aa;exports.PlaylistList=rs;exports.PlaylistType=ts;exports.RecordingOptionsPanel=Oi;exports.SACN_PORT=qg;exports.SCALE_INTERVALS=Ec;exports.SCALE_NAMES=E0;exports.SKEW_CAPS=jo;exports.STANDARD_TUNINGS=by;exports.SYMMETRIC_CAPS=qa;exports.ShortcutManager=bc;exports.SimpleSynth=Ol;exports.SortDirection=un;exports.SortField=kl;exports.StreamingVisualizer=ms;exports.TEXTURE_CATEGORIES=Ya;exports.TrackSource=xt;exports.UndoRedoPanel=zi;exports.ViewMode=xl;exports.VocalEffectsEngine=zl;exports.VoiceChatOverlay=Pc;exports.WebRTCAudioManager=Tc;exports.ZoomSnapControls=Ia;exports.addEffectToLayer=K0;exports.addMidiNote=Q0;exports.analyzeAudioFileWithAlgorithm=og;exports.applyGroove=fg;exports.applyGrooveTemplate=yc;exports.applyHumanize=gc;exports.applyKaraokeDisplayVars=Ja;exports.applyMidiTransform=yy;exports.applySwing=mc;exports.arrow_L=Gt;exports.arrow_R=Nt;exports.autoCorrelate=Fo;exports.bracket_L=Ga;exports.bracket_R=ko;exports.buildArpSequence=oo;exports.buildLanes=Yo;exports.buildNoteDescriptors=Za;exports.buildPadNoteEvents=Xo;exports.buildSegmentScores=Oo;exports.canRedo=Hi;exports.canUndo=qi;exports.chamfer_L=Nr;exports.chamfer_R=mn;exports.clearMidiNotes=eg;exports.clearPattern=ic;exports.computeGrade=vy;exports.computeTheoreticalMax=al;exports.computeVocalPerformanceReport=ll;exports.convertBrowserSongToKaraokeSongFile=zh;exports.copyCCEvents=ha;exports.createAnalyserNode=uc;exports.createArpPattern=F0;exports.createArtNetPacket=Vg;exports.createBasslinePattern=O0;exports.createCCHistory=Gi;exports.createCompressorNode=pc;exports.createDefaultLFO=zr;exports.createDefaultShortcuts=Mg;exports.createDropZoneHandlers=Ig;exports.createEmptyPattern=Qt;exports.createEmptyStep=os;exports.createGainNode=hc;exports.createHiHatPattern=z0;exports.createKickPattern=_0;exports.createLoopRegion=xg;exports.createSACNPacket=Hg;exports.createSnarePattern=D0;exports.createVocoderNode=fc;exports.createVoiceChatAudioContext=oy;exports.cutCCEvents=Yi;exports.deleteCCEventsInRange=Zi;exports.deserializeLFO=ru;exports.deserializePattern=G0;exports.detectChord=my;exports.downsampleAndQuantizePitchPoints=Bo;exports.drawGlossyBarOnCanvas=En;exports.drawTimeline=ya;exports.estimateLatencyMs=Go;exports.estimateLatencyMsFromRecording=dl;exports.evaluateLFO=La;exports.evaluateLFOAsCC=_a;exports.exportCCLane=Ji;exports.extractBpmFromNotes=go;exports.findTextureByUrl=mh;exports.formatShortcut=Rg;exports.generateArpEvents=cu;exports.generatePlaceholderWaveform=hg;exports.generateSeed=Ul;exports.generateUltrastarText=lg;exports.getActiveGradient=ml;exports.getActiveLyrics=Pu;exports.getActiveWords=Eu;exports.getAlgorithmColor=_h;exports.getAlgorithmCssVar=Dh;exports.getAlgorithmLabel=Lh;exports.getArpModes=lo;exports.getArpRates=co;exports.getAudioContext=Yn;exports.getAudioInputDevices=iy;exports.getAudioWorkletProcessorCode=cc;exports.getBackgroundUrl=Ih;exports.getCachedImage=hh;exports.getCapStyleByName=Tn;exports.getComboMultiplier=nl;exports.getCoverUrl=Ah;exports.getGrooveTemplate=mg;exports.getGrooveTemplateNames=gg;exports.getLaneForPitch=Zo;exports.getNextPlayerColor=id;exports.getNextPlayerColorCss=od;exports.getOverlayCanvasPattern=Ln;exports.getPatternByName=Pn;exports.getSACNMulticastAddress=Kg;exports.getScoringPreset=Fr;exports.getTexturePattern=An;exports.getVerseRatingLabel=tl;exports.handleAddCCEvent=ng;exports.handleRedo=wu;exports.handleRemoveCCEvent=ag;exports.handleSelectCCLane=tg;exports.handleUndo=ku;exports.handleUpdateCCEvent=rg;exports.hexToHsl=Ar;exports.humanizeMidiNotes=bg;exports.hydrateKaraokeDisplayFromBackend=kp;exports.hydratePlayerKaraokeSettingsFromBackend=qu;exports.hzToMidi=Lt;exports.hzToUltrastarPitch=yo;exports.importCCLane=eo;exports.initKaraokeDisplaySettings=Cp;exports.instrumentPresets=x0;exports.isAudioContextRunning=Ai;exports.isInLoopRegion=wg;exports.isWebRTCSupported=sy;exports.loadAllKaraokeSettings=Hu;exports.loadAudioWorkletModule=dc;exports.loadKaraokeDisplaySettings=fl;exports.loadKaraokeSettings=Ha;exports.loadRemoteScoringPresets=Wu;exports.makeClickReference=cl;exports.makeClipSelectionId=cg;exports.mergeWaveforms=ug;exports.midiSeedGenerator=I0;exports.midiToHz=va;exports.midiToNoteName=_t;exports.normalizeHex=Ir;exports.openAudioFilePicker=Lg;exports.ornate_L=Ua;exports.ornate_R=Er;exports.parseLyrics=Nu;exports.parseNotes=Zn;exports.parseUltraStarText=Vo;exports.parseVersesWithSyllables=fo;exports.parseVersesWithWords=Tu;exports.parseVideoMetadata=zo;exports.pasteCCEvents=Ki;exports.pill_L=Kt;exports.pill_R=Ot;exports.preloadTexture=Ka;exports.preloadTextures=ph;exports.probeAudioFile=xc;exports.pushCCState=Wi;exports.pushOperation=uy;exports.quantizeMidiNotes=yg;exports.quantizeNotes=fy;exports.quantizeStepInBeats=vc;exports.quantizeStepInSeconds=us;exports.randomizeVelocity=sc;exports.recordCCEvent=Xi;exports.redoCC=Vi;exports.redoOperation=py;exports.removeEffectFromLayer=Y0;exports.removeMidiNote=J0;exports.renderGlossyBarSvg=No;exports.resumeAudioContext=Xt;exports.reversePattern=rc;exports.sampleLFOForDisplay=so;exports.sampleLFOToCCEvents=ao;exports.saveKaraokeDisplaySettings=wp;exports.saveKaraokeSettings=Vu;exports.scaleResult=il;exports.scaleTo10k=sl;exports.scoreNotesWithPitchPoints=rl;exports.selectCCEventsInRange=qd;exports.semitoneOffset=Vn;exports.serializeLFO=nu;exports.serializePattern=B0;exports.setLoopFromSelection=Sg;exports.setProjectWithUndo=ho;exports.setStepGate=Jl;exports.setStepNote=Xl;exports.setStepProbability=ec;exports.setStepVelocity=Ql;exports.sharp_L=pn;exports.sharp_R=fn;exports.shield_L=Tr;exports.shield_R=So;exports.shiftPattern=ac;exports.shouldTrigger=lc;exports.skewTL_L=fr;exports.skewTL_R=ga;exports.skewTR_L=ma;exports.skewTR_R=mr;exports.snapLoopToGrid=kg;exports.snapTimeToQuantize=Pa;exports.snapToGrid=dg;exports.snapToScale=gy;exports.soft_L=Ba;exports.soft_R=xo;exports.stepDuration=ls;exports.stepTimeOffset=oc;exports.syncDivisionToHz=no;exports.tab_L=Wa;exports.tab_R=wo;exports.thinCCEvents=Qi;exports.toTrack=Uo;exports.toggleEffectBypass=Z0;exports.toggleStep=Zl;exports.toggleStepSlide=tc;exports.transposePattern=nc;exports.undoCC=Ui;exports.undoOperation=hy;exports.updateEffectParams=X0;exports.useAudioWorklet=H0;exports.useAutoSave=vu;exports.useCCAutomation=to;exports.useCanPickSong=vp;exports.useDMXAudioSync=Qg;exports.useDMXEngine=Xg;exports.useEditorTrack=Ru;exports.useKaraokePitch=el;exports.useKaraokeScoring=ol;exports.useLocalPlaylists=ns;exports.useMPE=C0;exports.useMidiLearn=k0;exports.useNiceTranslation=xe;exports.useOxygen25=M0;exports.usePitchWorker=U0;exports.usePlaybackEngine=bu;exports.useProjectCRUD=Mu;exports.useRadioStream=Rc;exports.useRecording=xu;exports.useScoringWorker=V0;exports.useStepSequencer=W0;exports.useWebMidi=qr;exports.useWorker=cs;exports.validateAudioFiles=hs;exports.wave_L=Pr;exports.wave_R=Va;exports.waveformValue=ro;exports.wrapTimeInLoop=Cg;
|
|
430
|
+
E`}}function dg(e,t){return`${e}:${t}`}function ug(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 hg(e){return e.length===0?[]:e.flat()}function pg(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const us=[{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 fg(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function gc(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 yc(e,t){const n=t.seed!=null?fg(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 vc(e,t,n=1){const a=4/t.stepsPerBar;return e.map(s=>{const i=s.time/a,o=Math.round(i)%t.stepsPerBar,l=t.timingOffsets[o]*a*n,c=1+(t.velocityScales[o]-1)*n,u=1+(t.durationScales[o]-1)*n;return{...s,time:Math.max(0,s.time+l),velocity:Math.max(1,Math.min(127,Math.round(s.velocity*c))),duration:Math.max(.01,s.duration*u)}})}function mg(e,t){let n=[...e.map(a=>({...a}))];return t.template&&t.grooveStrength>0&&(n=vc(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=gc(n,t.swing)),t.humanize&&(n=yc(n,t.humanize)),n}function gg(e){return us.find(t=>t.id===e)}function yg(){return us.map(({id:e,name:t})=>({id:e,name:t}))}function bc(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 hs(e,t){return bc(e)*60/t}function Ea(e,t,n){const a=hs(t,n);return Math.round(e/a)*a}function vg(e,t){const{value:n,bpm:a,strength:s=1,quantizeStarts:i=!0,quantizeDurations:o=!1}=t,l=hs(n,a);return e.map(c=>{let{start:u,duration:h}=c;if(i){const p=Math.round(u/l)*l;u=u+(p-u)*s}if(o){const p=Math.max(l,Math.round(h/l)*l);h=h+(p-h)*s}return u===c.start&&h===c.duration?c:{...c,start:u,duration:h}})}function bg(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function xg(e,t={}){const{timingRange:n=.02,velocityRange:a=10,seed:s}=t,i=s!=null?bg(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 Sg(){return{start:0,end:0,enabled:!1}}function kg(e,t){return{...e<t?{start:e,end:t}:{start:t,end:e},enabled:!0}}function wg(e,t,n){return{start:Ea(e.start,t,n),end:Ea(e.end,t,n),enabled:e.enabled}}function Cg(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function jg(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 $a(e){return e.length===1?e.toLowerCase():e}function Rr(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($a(e.key)),t.join("+")}function Mg(e,t){var l,c,u,h;const n=$a(e.key)===$a(t.key),a=!!e.ctrlKey==!!((l=t.modifiers)!=null&&l.ctrl),s=!!e.shiftKey==!!((c=t.modifiers)!=null&&c.shift),i=!!e.altKey==!!((u=t.modifiers)!=null&&u.alt),o=!!e.metaKey==!!((h=t.modifiers)!=null&&h.meta);return n&&a&&s&&i&&o}class xc{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];Rr(i.binding)===Rr(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?Rr(n.binding):""}handleKeyDown(t){if(!this.enabled)return!1;for(const n of this.actions.values())if(n.enabled&&this.activeScopes.has(n.scope)&&Mg(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 Rg(e={}){const t=new xc,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 Ng(e){return Rr(e)}const Tg=["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"],Pg=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],Eg=500*1024*1024,$g=20;function Wt(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function Ag(e,t){return!!(e.type&&t.some(n=>e.type.startsWith(n.replace("*","")))||e.type.startsWith("audio/"))}function Ig(e,t){const n=Wt(e.name);return n!==""&&t.includes(n)}function ps(e,t={}){const n=t.maxSize??Eg,a=t.allowedTypes??Tg,s=t.allowedExtensions??Pg,i=t.maxFiles??$g,o=[],l=[];for(let c=0;c<e.length;c++){const u=e[c];if(c>=i){l.push({file:u,reason:"limit",message:`Exceeded maximum of ${i} files`});continue}if(u.size>n){l.push({file:u,reason:"size",message:`File exceeds ${Math.round(n/1024/1024)}MB limit`});continue}if(!Ag(u,a)&&!Ig(u,s)){l.push({file:u,reason:"type",message:`Unsupported file type: ${u.type||Wt(u.name)}`});continue}o.push(u)}return{valid:o,errors:l}}async function Sc(e){const t={file:e,name:e.name.replace(/\.[^.]+$/,""),extension:Wt(e.name),sizeBytes:e.size,mimeType:e.type||`audio/${Wt(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 Lg(e){let t=0;return{onDragEnter:n=>{var a;n.preventDefault(),n.stopPropagation(),t++,t===1&&((a=e.onDragEnter)==null||a.call(e))},onDragOver:n=>{n.preventDefault(),n.stopPropagation(),(n instanceof DragEvent&&n.dataTransfer||"dataTransfer"in n&&n.dataTransfer)&&(n.dataTransfer.dropEffect="copy")},onDragLeave:n=>{var a;n.preventDefault(),n.stopPropagation(),t--,t===0&&((a=e.onDragLeave)==null||a.call(e))},onDrop:async n=>{var u,h;n.preventDefault(),n.stopPropagation(),t=0,(u=e.onDragLeave)==null||u.call(e);const a="dataTransfer"in n?n.dataTransfer:null;if(!((h=a==null?void 0:a.files)!=null&&h.length))return;const s=Array.from(a.files),{valid:i,errors:o}=ps(s,e.validation),l=[],c=[...o];for(const p of i)if(e.probe)try{l.push(await Sc(p))}catch{c.push({file:p,reason:"decode",message:"Failed to decode audio"})}else l.push({file:p,name:p.name.replace(/\.[^.]+$/,""),extension:Wt(p.name),sizeBytes:p.size,mimeType:p.type||`audio/${Wt(p.name)}`});e.onDrop({accepted:l,rejected:c})}}}function _g(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}=ps(a,e.validation),o=s.map(c=>({file:c,name:c.name.replace(/\.[^.]+$/,""),extension:Wt(c.name),sizeBytes:c.size,mimeType:c.type||`audio/${Wt(c.name)}`}));t({accepted:o,rejected:i})},n.click()})}var Bt=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(Bt||{}),kc=(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))(kc||{}),wc=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(wc||{});const Dg=["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)"],zr=["off","no function","brak"],zg=e=>e.segments.some(t=>t.isOff||zr.some(n=>t.name.toLowerCase().includes(n))),Fg=e=>e.segments.find(t=>t.isOff||zr.some(n=>t.name.toLowerCase().includes(n))),Cc=e=>Math.floor((e.valueFrom+e.valueTo)/2),Og=e=>{const t=Fg(e);return t?Cc(t):0},Bg=(e,t)=>e.segments.find(n=>t>=n.valueFrom&&t<=n.valueTo),Nn=(e,t=0,n=255)=>Math.max(t,Math.min(n,Math.round(e))),Hn=({channel:e,value:t,onChange:n,onCommit:a,showDirectionHint:s})=>{const{t:i}=xe(),[o,l]=d.useState(Nn(t)),c=d.useMemo(()=>Bg(e,o),[e,o]);d.useEffect(()=>l(Nn(t)),[t]);const u=h=>{const p=Nn(h);l(p),n(p),a==null||a(p)};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&&c&&r.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:c.name})]}),r.jsx("input",{type:"range",min:0,max:255,value:o,onChange:h=>{const p=Nn(Number(h.target.value));l(p),n(p)},onMouseUp:()=>a==null?void 0:a(o),onTouchEnd:()=>a==null?void 0:a(o),style:{width:"100%"}}),r.jsx("div",{style:{marginTop:6},children:r.jsx("input",{type:"number",min:0,max:255,value:o,onChange:h=>{const p=Nn(Number(h.target.value));l(p),n(p)},onBlur:()=>a==null?void 0:a(o),style:{width:80,padding:6,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:6}})}),zg(e)&&r.jsx("button",{type:"button",onClick:()=>u(Og(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:i("dmxChannelControls.off","OFF")})]})},fs=({channel:e,value:t,onChange:n,onCommit:a})=>{const s=d.useMemo(()=>{const o=[...e.segments];return o.sort((l,c)=>{const u=(l.isOff?-1:0)+(zr.some(p=>l.name.toLowerCase().includes(p))?-1:0),h=(c.isOff?-1:0)+(zr.some(p=>c.name.toLowerCase().includes(p))?-1:0);return u!==h?u-h:l.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),o},[e]),i=o=>{const l=Cc(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}`)})})]})},ms=e=>{switch(e.channel.type){case Bt.Dimmer:case Bt.DimmerWithOff:return r.jsx(Hn,{...e});case Bt.RotationWithOff:case Bt.RotationWithOffAndCcw:return r.jsx(Hn,{...e,showDirectionHint:!0});case Bt.Options:return r.jsx(fs,{...e});default:return r.jsx(Hn,{...e})}},da=e=>Math.max(0,Math.min(255,Math.round(e))),Gg=[{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 jc({service:e,...t}){const{t:n}=xe();return e?r.jsx(Wg,{service:e,...t}):r.jsx("div",{className:t.className,style:t.style,children:r.jsx("small",{children:n("dmxEditor.provideAServicePropDmxservice","Provide a `service` prop (DmxService) to control hardware.")})})}function Wg({service:e,pollInterval:t=500,className:n,style:a,tutorial:s}){const{t:i}=xe(),[o,l]=d.useState([]),[c,u]=d.useState(null),[h,p]=d.useState(()=>Array(513).fill(0)),[g,y]=d.useState(30),[m,x]=d.useState(0),[b,f]=d.useState(!1),j=d.useRef(null);d.useEffect(()=>{let A=!1;return e.getDevices().then(L=>{A||(l(L),L.length>0&&u(L[0]))}).catch(()=>{}),()=>{A=!0}},[e]),d.useEffect(()=>{if(j.current&&window.clearInterval(j.current),!(t<=0))return j.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),()=>{j.current&&window.clearInterval(j.current)}},[e,t]);const v=async()=>{c&&(await e.openPort(c.serialNumber||c.description),f(!0))},C=async()=>{await e.closePort(),f(!1)},T=async()=>{await e.blackout(),p(A=>{const L=[...A];for(let E=1;E<L.length;E++)L[E]=0;return L})},M=()=>e.configure(g,m),k=(A,L)=>{const E=da(L);p(D=>{const Z=[...D];return Z[A]=E,Z})},R=(A,L)=>e.setChannel(A,da(L)),P=(c==null?void 0:c.deviceInfo)??null,I=d.useMemo(()=>{var A;return(A=P==null?void 0:P.channels)!=null&&A.length?P.channels:Array.from({length:16},(L,E)=>({channel:E+1,name:`Channel ${E+1}`,type:Bt.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[P]);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(ve.NiceTutorialButton,{steps:ve.resolveTutorial(s,Gg)})}),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=>u(o.find(L=>L.serialNumber===A.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"},children:o.map(A=>{var L,E;return r.jsxs("option",{value:A.serialNumber,children:[((L=A.deviceInfo)==null?void 0:L.manufacturer)??""," ",((E=A.deviceInfo)==null?void 0:E.model)??A.description," (",A.serialNumber||A.description,")"]},A.serialNumber||A.description)})}),P&&r.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:[i("dmxEditor.mode","Mode:")," ",r.jsx("b",{children:P.modeName}),i("dmxEditor.footprint",", footprint:")," ",r.jsx("b",{children:P.footprint})]})]}),r.jsx("button",{onClick:v,disabled:!c||b,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:C,disabled:!b,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:T,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(da(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:M,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:I.map(A=>r.jsx(ms,{channel:A,value:h[A.channel]??0,onChange:L=>k(A.channel,L),onCommit:L=>R(A.channel,L)},A.channel))})]})]})}const Mc=[{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 Rc{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,Mc.forEach(t=>this.profiles.set(t.id,t)),this.createUniverse(1,"Universe 1")}createUniverse(t,n){const a={id:String(t),name:n,channels:new Uint8Array(512)};return this.universes.set(t,a),a}getUniverse(t){return this.universes.get(t)}addFixture(t){this.fixtures.set(t.id,t)}removeFixture(t){this.fixtures.delete(t)}getFixture(t){return this.fixtures.get(t)}getAllFixtures(){return Array.from(this.fixtures.values())}getProfile(t){return this.profiles.get(t)}registerProfile(t){this.profiles.set(t.id,t)}setChannel(t,n,a){const s=this.universes.get(t);s&&n>=1&&n<=512&&(s.channels[n-1]=Math.max(0,Math.min(255,a)))}getChannel(t,n){const a=this.universes.get(t);return a&&n>=1&&n<=512?a.channels[n-1]:0}setFixtureValues(t,n){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);if(s)for(let i=0;i<Math.min(n.length,s.channelCount);i++)a.values[i]=n[i],this.setChannel(a.universe,a.startChannel+i,n[i])}setFixtureColor(t,n,a,s,i=0){const o=this.fixtures.get(t);if(!o)return;const l=this.profiles.get(o.profileId);if(!l)return;const c=[...o.values];l.channels.forEach((u,h)=>{u.name.toLowerCase().includes("red")?c[h]=n:u.name.toLowerCase().includes("green")?c[h]=a:u.name.toLowerCase().includes("blue")?c[h]=s:u.name.toLowerCase().includes("white")&&(c[h]=i)}),this.setFixtureValues(t,c)}setFixtureDimmer(t,n){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);s&&s.channels.forEach((i,o)=>{i.type==="dimmer"&&(a.values[o]=Math.max(0,Math.min(255,Math.round(n*255))),this.setChannel(a.universe,a.startChannel+o,a.values[o]))})}fadeFixture(t,n,a,s="linear"){return new Promise(i=>{const o=this.fixtures.get(t);if(!o){i();return}const l=[...o.values],c=performance.now(),u=()=>{const h=performance.now()-c,p=Math.min(1,h/a);let 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 b=n[x]??m;return Math.round(m+(b-m)*g)});this.setFixtureValues(t,y),p<1?requestAnimationFrame(u):i()};u()})}setOutputCallback(t){this.outputCallback=t}start(){this.running||(this.running=!0,this.intervalId=window.setInterval(()=>{this.sendOutput()},1e3/this.frameRate))}stop(){this.running=!1,this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null)}sendOutput(){this.outputCallback&&this.universes.forEach((t,n)=>{this.outputCallback(n,t.channels)})}blackout(){this.universes.forEach(t=>{t.channels.fill(0)}),this.fixtures.forEach(t=>{t.values.fill(0)})}fullOn(){this.fixtures.forEach(t=>{this.setFixtureDimmer(t.id,1)})}}const Ug=6454,Vg=new Uint8Array([65,114,116,45,78,101,116,0]);function qg(e,t){const n=new Uint8Array(18+t.length);return n.set(Vg,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 Hg=5568;function Kg(e,t,n,a=100,s="Nice2Dev DMX"){const i=Math.min(t.length,512),o=126+i,l=new Uint8Array(o),c=new DataView(l.buffer);c.setUint16(0,16,!1),c.setUint16(2,0,!1);const u=[65,83,67,45,69,49,46,49,55,0,0,0];for(let m=0;m<u.length;m++)l[4+m]=u[m];const h=o-16;c.setUint16(16,28672|h&4095,!1),c.setUint32(18,4,!1);for(let m=0;m<16;m++)l[22+m]=m+1;const p=o-38;c.setUint16(38,28672|p&4095,!1),c.setUint32(40,2,!1);const 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 Yg(e){const t=e>>8&255,n=e&255;return`239.255.${t}.${n}`}class Zg{constructor(t,n){this.config=t,this.scenes=n,this.currentStep=0,this.direction=1,this.isRunning=!1,this.timer=null,this.fadeStartTime=0,this.fadeFromValues=new Uint8Array(512),this.fadeToValues=new Uint8Array(512),this.onOutput=null}setOutputCallback(t){this.onOutput=t}start(){this.isRunning||(this.isRunning=!0,this.currentStep=this.config.direction==="backward"?this.config.steps.length-1:0,this.direction=this.config.direction==="backward"?-1:1,this.executeStep())}stop(){this.isRunning=!1,this.timer&&(clearTimeout(this.timer),this.timer=null)}executeStep(){var o;if(!this.isRunning)return;const t=this.config.steps[this.currentStep];if(!t)return;const n=this.scenes.get(t.sceneId);if(!n){this.advanceStep();return}const a=new Uint8Array(512);if(n.channels)for(const l of n.channels)l.channel>=1&&l.channel<=512&&(a[l.channel-1]=l.value);this.fadeFromValues.set(this.fadeToValues),this.fadeToValues.set(a),this.fadeStartTime=performance.now();const s=t.fadeTime/this.config.speed,i=t.holdTime/this.config.speed;s>0?this.runFade(s,()=>{var l;(l=this.onOutput)==null||l.call(this,this.fadeToValues),this.timer=setTimeout(()=>this.advanceStep(),i)}):((o=this.onOutput)==null||o.call(this,a),this.timer=setTimeout(()=>this.advanceStep(),i))}runFade(t,n){const a=performance.now(),s=new Uint8Array(512),i=()=>{var c;if(!this.isRunning)return;const o=performance.now()-a,l=Math.min(o/t,1);for(let u=0;u<512;u++)s[u]=Math.round(this.fadeFromValues[u]+(this.fadeToValues[u]-this.fadeFromValues[u])*l);(c=this.onOutput)==null||c.call(this,s),l<1?requestAnimationFrame(i):n()};requestAnimationFrame(i)}advanceStep(){if(!this.isRunning)return;const{steps:t,loop:n,direction:a}=this.config;if(this.currentStep+=this.direction,a==="bounce"){if(this.currentStep>=t.length?(this.direction=-1,this.currentStep=t.length-2):this.currentStep<0&&(this.direction=1,this.currentStep=1),this.currentStep<0||this.currentStep>=t.length){if(!n){this.stop();return}this.currentStep=0,this.direction=1}}else if(this.currentStep>=t.length||this.currentStep<0){if(!n){this.stop();return}this.currentStep=a==="backward"?t.length-1:0}this.executeStep()}}const Xg=({engine:e,tracks:t=[],scenes:n=[],duration:a=3e5,currentTime:s=0,bpm:i=120,onTimeChange:o,onCueAdd:l,onCueUpdate:c,onCueDelete:u,onTrackAdd:h,onTrackUpdate:p,onPlay:g,onPause:y,onStop:m,className:x=""})=>{const{t:b}=xe(),[f,j]=d.useState(1),[v,C]=d.useState(0),[T,M]=d.useState(!1),[k,R]=d.useState(null),[P,I]=d.useState(null),[A,L]=d.useState(!0),[E,D]=d.useState(1e3),Z=d.useRef(null),G=d.useRef(null),F=d.useRef(0),q=d.useMemo(()=>.1*f,[f]),V=d.useCallback($=>$*q,[q]),K=d.useCallback($=>$/q,[q]),W=d.useCallback($=>{if(!A)return $;const H=6e4/i;return Math.round($/H)*H},[A,i]),Q=d.useRef(()=>{});d.useEffect(()=>{if(!T)return;const $=performance.now(),H=s,X=()=>{const re=performance.now()-$,oe=H+re;if(oe>=a){M(!1),o==null||o(0),m==null||m();return}Q.current(oe),o==null||o(oe),G.current=requestAnimationFrame(X)};return G.current=requestAnimationFrame(X),()=>{G.current!==null&&(cancelAnimationFrame(G.current),G.current=null)}},[T,s,a,o,m]);const w=d.useRef(!1);d.useEffect(()=>{T!==w.current&&(w.current=T,T?g==null||g():y==null||y())},[T,g,y]);const N=d.useCallback($=>{t.forEach(H=>{H.muted||H.cues.forEach(X=>{const re=X.startTime,oe=re+X.duration;if($>=re&&$<oe&&F.current<re){const se=n.find(z=>z.id===X.sceneId);se&&se.fixtures.forEach(z=>{X.fadeIn&&X.fadeIn>0?e.fadeFixture(z.fixtureId,z.values,X.fadeIn):e.setFixtureValues(z.fixtureId,z.values)})}if(F.current<oe&&$>=oe){const se=n.find(z=>z.id===X.sceneId);se&&se.fixtures.forEach(z=>{if(e.getFixture(z.fixtureId)&&X.fadeOut&&X.fadeOut>0){const ae=new Array(z.values.length).fill(0);e.fadeFixture(z.fixtureId,ae,X.fadeOut)}})}})}),F.current=$},[t,n,e]);Q.current=N;const S=$=>{const H=Math.floor($/1e3),X=Math.floor(H/60),re=H%60,oe=Math.floor($%1e3/(1e3/30));return`${X}:${re.toString().padStart(2,"0")}:${oe.toString().padStart(2,"0")}`},O=d.useCallback($=>{if(!Z.current)return;const H=Z.current.getBoundingClientRect(),X=$.clientX-H.left+v,re=W(K(X));o==null||o(Math.max(0,Math.min(a,re)))},[v,K,W,a,o]),Y=d.useCallback(($,H,X)=>{const re=t.find(z=>z.id===H),oe=re==null?void 0:re.cues.find(z=>z.id===$);if(!oe)return;const se=W(Math.max(0,oe.startTime+K(X)));c==null||c({...oe,startTime:se})},[t,K,W,c]),_=()=>{const $=6e4/i,H=Math.ceil(a/$),X=[];for(let re=0;re<=H;re++){const oe=re*$,se=V(oe),z=re%4===0;X.push(r.jsx("div",{className:`nice-dmx-timeline__beat ${z?"nice-dmx-timeline__beat--measure":""}`,style:{left:se},children:z&&r.jsx("span",{className:"nice-dmx-timeline__beat-label",children:re/4+1})},re))}return X},U=($,H)=>{const X=V($.startTime),re=V($.duration),oe=n.find(se=>se.id===$.sceneId);return r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,className:`nice-dmx-timeline__cue ${k===$.id?"nice-dmx-timeline__cue--selected":""}`,style:{left:X,width:re,backgroundColor:(oe==null?void 0:oe.color)||H.color||"var(--nice-accent, #8b5cf6)"},onClick:se=>{se.stopPropagation(),R($.id)},draggable:!H.locked,onDragEnd:se=>{var ee;const z=(ee=se.target.parentElement)==null?void 0:ee.getBoundingClientRect();z&&Y($.id,H.id,se.clientX-z.left-X)},children:[r.jsx("span",{className:"nice-dmx-timeline__cue-name",children:$.name||(oe==null?void 0:oe.name)}),$.fadeIn&&$.fadeIn>0&&r.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--in",style:{width:V($.fadeIn)}}),$.fadeOut&&$.fadeOut>0&&r.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--out",style:{width:V($.fadeOut)}})]},$.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:b("dmxTimeline.goToStart","Go to start"),"aria-label":b("dmxTimeline.goToStart","Go to start"),children:r.jsx(B.NtdSkipBack,{size:14})}),r.jsx("button",{type:"button",onClick:()=>M(!T),title:T?b("dmxTimeline.pause","Pause"):b("dmxTimeline.play","Play"),"aria-label":T?b("dmxTimeline.pause","Pause"):b("dmxTimeline.play","Play"),children:T?r.jsx(B.NtdPause,{size:14}):r.jsx(B.NtdPlay,{size:14})}),r.jsx("button",{type:"button",onClick:()=>{M(!1),o==null||o(0),e.blackout(),m==null||m()},title:b("dmxTimeline.stop","Stop"),"aria-label":b("dmxTimeline.stop","Stop"),children:r.jsx(B.NtdStop,{size:14})})]}),r.jsx("div",{className:"nice-dmx-timeline__time",children:S(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:()=>L(!A),title:b("dmxTimeline.snapToGrid","Snap to grid"),"aria-label":b("dmxTimeline.snapToGrid","Snap to grid"),children:r.jsx(B.NtdGrid,{size:14})}),r.jsx("button",{type:"button",onClick:()=>j(Math.max(.25,f-.25)),title:b("dmxTimeline.zoomOut","Zoom out"),"aria-label":b("dmxTimeline.zoomOut","Zoom out"),children:r.jsx(B.NtdZoomOut,{size:14})}),r.jsxs("span",{className:"nice-dmx-timeline__zoom",children:[Math.round(f*100),"%"]}),r.jsx("button",{type:"button",onClick:()=>j(Math.min(4,f+.25)),title:b("dmxTimeline.zoomIn","Zoom in"),"aria-label":b("dmxTimeline.zoomIn","Zoom in"),children:r.jsx(B.NtdZoomIn,{size:14})})]}),r.jsxs("div",{className:"nice-dmx-timeline__bpm",children:[r.jsx("label",{children:b("dmxTimeline.bpm","BPM:")}),r.jsx("span",{children:i})]}),r.jsx("button",{type:"button",className:"nice-dmx-timeline__blackout",onClick:()=>e.blackout(),title:b("dmxTimeline.blackout","Blackout"),"aria-label":b("dmxTimeline.blackout","Blackout"),children:r.jsx(B.NtdMoon,{size:14})})]}),r.jsxs("div",{className:"nice-dmx-timeline__content",children:[r.jsxs("div",{className:"nice-dmx-timeline__headers",children:[t.map($=>r.jsxs("div",{role:"button",tabIndex:0,onKeyDown:ve.clickOnActivationKey,className:`nice-dmx-timeline__header ${P===$.id?"nice-dmx-timeline__header--selected":""}`,onClick:()=>I($.id),children:[r.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:$.color||"var(--nice-accent, #8b5cf6)"}}),r.jsx("span",{className:"nice-dmx-timeline__track-name",children:$.name}),r.jsxs("div",{className:"nice-dmx-timeline__track-controls",children:[r.jsx("button",{type:"button",className:`nice-dmx-timeline__track-toggle ${$.muted?"nice-dmx-timeline__track-toggle--active":""}`,onClick:H=>{H.stopPropagation(),p==null||p({...$,muted:!$.muted})},title:b("dmxTimeline.mute","Mute"),children:"M"}),r.jsx("button",{type:"button",className:`nice-dmx-timeline__track-toggle ${$.locked?"nice-dmx-timeline__track-toggle--active":""}`,onClick:H=>{H.stopPropagation(),p==null||p({...$,locked:!$.locked})},title:b("dmxTimeline.lock","Lock"),"aria-label":b("dmxTimeline.lock","Lock"),children:r.jsx(B.NtdLock,{size:14})})]})]},$.id)),r.jsxs("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:[r.jsx(B.NtdPlus,{size:14})," ",b("dmxTimeline.addTrack","Add Track")]})]}),r.jsxs("div",{role:"presentation",className:"nice-dmx-timeline__tracks",ref:Z,onClick:O,onScroll:$=>C($.currentTarget.scrollLeft),children:[r.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:V(a)},children:_()}),t.map($=>r.jsx("div",{className:`nice-dmx-timeline__track ${$.muted?"nice-dmx-timeline__track--muted":""}`,style:{width:V(a)},children:$.cues.map(H=>U(H,$))},$.id)),r.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:V(s)}})]})]})]})};function Qg(){const[e]=d.useState(()=>new Rc);return d.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function Jg(e,t,n=120){const[a,s]=d.useState(0),i=d.useRef(0);return d.useEffect(()=>{if(!t)return;const o=60/n,l=()=>{const c=t.currentTime,u=Math.floor(c/o);u!==i.current&&(i.current=u,s(u))};return t.addEventListener("timeupdate",l),()=>t.removeEventListener("timeupdate",l)},[t,n]),{currentBeat:a}}const ey=[],ty=[],ny=[{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 Nc(){const{t:e}=xe(),[t,n]=d.useState(!1),[a,s]=d.useState(.8),[i,o]=d.useState(!1),[l,c]=d.useState(null),[u,h]=d.useState(null),[p,g]=d.useState(null),y=d.useRef(null),m=d.useRef(null),x=d.useRef(null),b=d.useRef(null),f=d.useRef([]),j=d.useRef(null),v=d.useRef(null),C=d.useRef(a),T=d.useCallback(()=>{if(m.current)return;const G=new AudioContext;m.current=G;const F=G.createGain();F.gain.value=C.current,b.current=F;const q=G.createAnalyser();q.fftSize=256,j.current=q,F.connect(q).connect(G.destination)},[]),M=d.useCallback(()=>{const G=y.current,F=m.current,q=b.current;if(!G||!F||!q||x.current)return;const V=F.createMediaElementSource(G);x.current=V,f.current.length>0?(V.connect(f.current[0]),f.current[f.current.length-1].connect(q)):V.connect(q)},[]),k=d.useCallback(()=>{var F;const G=y.current;!G||!v.current||(Xt(),T(),M(),((F=m.current)==null?void 0:F.state)==="suspended"&&m.current.resume(),G.play().catch(q=>h(String(q))))},[T,M]),R=d.useCallback(()=>{var G;(G=y.current)==null||G.pause()},[]),P=d.useCallback(()=>{t?R():k()},[t,k,R]),I=d.useCallback(G=>{const F=Math.max(0,Math.min(1,G));s(F),C.current=F,b.current&&(b.current.gain.value=F),y.current&&(y.current.volume=F)},[]),A=d.useCallback(G=>{v.current=G,h(null),c(null),o(!0),x.current&&(x.current.disconnect(),x.current=null),y.current||(y.current=new Audio,y.current.crossOrigin="anonymous",y.current.addEventListener("playing",()=>{n(!0),o(!1)}),y.current.addEventListener("pause",()=>n(!1)),y.current.addEventListener("waiting",()=>o(!0)),y.current.addEventListener("canplay",()=>o(!1)),y.current.addEventListener("error",()=>h(e("radioPlayer.failedToLoadStream","Failed to load stream")))),y.current.src=G.streamUrl,y.current.load(),c({genre:G.genre,bitrate:G.bitrate})},[e]),L=d.useCallback(G=>{m.current||T();const q=m.current;f.current.forEach(K=>K.disconnect());const V=G.bands.map(K=>{const W=q.createBiquadFilter();return W.type="peaking",W.frequency.value=K.frequency,W.gain.value=K.gain,W.Q.value=K.Q??1.4,W});for(let K=0;K<V.length-1;K++)V[K].connect(V[K+1]);f.current=V,x.current&&b.current&&(x.current.disconnect(),x.current.connect(V[0]),V[V.length-1].connect(b.current)),g(G.name)},[T]),E=d.useCallback(()=>{f.current.forEach(G=>G.disconnect()),f.current=[],x.current&&b.current&&(x.current.disconnect(),x.current.connect(b.current)),g(null)},[]);return d.useEffect(()=>()=>{var G,F,q;(G=y.current)==null||G.pause(),y.current=null,f.current.forEach(V=>V.disconnect()),(F=x.current)==null||F.disconnect(),(q=m.current)==null||q.close()},[]),[{isPlaying:t,volume:a,isBuffering:i,metadata:l,error:u,activePreset:p},{play:k,pause:R,toggle:P,setVolume:I,setStation:A,applyEQPreset:L,clearEQ:E}]}function Tc({stations:e=ey,activeStationId:t,onSelect:n,onToggleFavorite:a,className:s}){const{t:i}=xe(),[o,l]=d.useState(""),[c,u]=d.useState(null),[h,p]=d.useState(!1),g=d.useMemo(()=>[...new Set(e.map(m=>m.genre).filter(Boolean))],[e]),y=d.useMemo(()=>e.filter(m=>{var x,b;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)||(((b=m.country)==null?void 0:b.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=>u(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(B.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.jsx("span",{className:"nice-station-browser__bitrate",children:i("radioPlayer.kbps","{bitrate}kbps").replace("{bitrate}",String(m.bitrate))}),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(B.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 ry({stations:e=ty,initialStationId:t,autoPlay:n=!1,eqPresets:a=ny,onStationChange:s,onPlayingChange:i,onMetadata:o,onToggleFavorite:l,onRecordingStart:c,onRecordingStop:u,showBrowser:h=!0,showEqualizer:p=!1,showVisualizer:g=!1,showMetadataHistory:y=!1,showRecording:m=!1,showSleepTimer:x=!1,className:b,style:f}){var O,Y;const{t:j}=xe(),[v,C]=Nc(),[T,M]=d.useState(()=>t?e.find(_=>_.id===t)??null:null),[k,R]=d.useState(p),P=d.useRef(null),I=d.useRef(0),[A,L]=d.useState([]),[E,D]=d.useState(!1),Z=d.useRef(null),G=d.useRef([]),[F,q]=d.useState(0),V=d.useRef(null),[K,W]=d.useState(0),[Q,w]=d.useState(null),N=d.useRef(null);d.useEffect(()=>{i==null||i(v.isPlaying)},[v.isPlaying,i]),d.useEffect(()=>{v.metadata&&(o==null||o(v.metadata),(v.metadata.title||v.metadata.artist)&&L(_=>[{time:new Date,meta:v.metadata},..._.slice(0,49)]))},[v.metadata,o]);const S=d.useCallback(_=>{M(_),C.setStation(_),s==null||s(_),n&&setTimeout(()=>C.play(),100)},[C,s,n]);return d.useEffect(()=>{if(t&&!T){const _=e.find(U=>U.id===t);_&&S(_)}},[t,e,T,S]),d.useEffect(()=>{if(!g||!P.current)return;const _=P.current,U=_.getContext("2d");if(!U)return;const $=()=>{I.current=requestAnimationFrame($),U.clearRect(0,0,_.width,_.height);const H=U.createLinearGradient(0,_.height,0,0);if(H.addColorStop(0,ve.resolveCssColor("var(--nice-accent-tint-80, rgba(99, 102, 241, 0.8))",U.canvas)),H.addColorStop(.5,ve.resolveCssColor("var(--nice-accent-tint-50, rgba(168,85,247,0.6))",U.canvas)),H.addColorStop(1,"rgba(236,72,153,0.4)"),!v.isPlaying){const se=_.width/32;for(let z=0;z<32;z++){const ee=4+Math.sin(Date.now()/1e3+z*.3)*3;U.fillStyle=H,U.fillRect(z*se+1,_.height-ee,se-2,ee)}return}const X=32,re=_.width/X;for(let oe=0;oe<X;oe++){const se=oe/X,ee=(Math.sin(Date.now()/200+oe*.5)*.3+.5)*_.height*(1-se*.5)*(.5+Math.random()*.5);U.fillStyle=H,U.fillRect(oe*re+1,_.height-ee,re-2,ee)}};return $(),()=>cancelAnimationFrame(I.current)},[g,v.isPlaying]),d.useCallback(()=>{if(v.isPlaying)try{const U=new AudioContext().createMediaStreamDestination();G.current=[];const $=new MediaRecorder(U.stream,{mimeType:"audio/webm"});$.ondataavailable=H=>{H.data.size>0&&G.current.push(H.data)},$.onstop=()=>{const H=new Blob(G.current,{type:"audio/webm"});u==null||u(H),q(0),V.current&&window.clearInterval(V.current)},$.start(1e3),Z.current=$,D(!0),q(0),V.current=window.setInterval(()=>{q(H=>H+1)},1e3),c==null||c()}catch{}},[v.isPlaying,c,u]),d.useCallback(()=>{Z.current&&E&&(Z.current.stop(),D(!1),V.current&&window.clearInterval(V.current))},[E]),d.useCallback(_=>{N.current&&window.clearInterval(N.current),W(_),w(_*60),N.current=window.setInterval(()=>{w(U=>!U||U<=1?(N.current&&window.clearInterval(N.current),N.current=null,C.pause(),null):U-1)},1e3)},[C]),d.useCallback(()=>{N.current&&window.clearInterval(N.current),N.current=null,w(null),W(0)},[]),d.useEffect(()=>()=>{V.current&&window.clearInterval(V.current),N.current&&window.clearInterval(N.current),cancelAnimationFrame(I.current)},[]),r.jsxs("div",{className:`nice-radio-player${b?` ${b}`:""}`,style:f,children:[r.jsx("div",{className:"nice-radio-player__now-playing",children:T?r.jsxs(r.Fragment,{children:[T.logoUrl&&r.jsx("img",{className:"nice-radio-player__cover",src:T.logoUrl,alt:T.name}),r.jsxs("div",{className:"nice-radio-player__info",children:[r.jsx("span",{className:"nice-radio-player__station-name",children:T.name}),((O=v.metadata)==null?void 0:O.title)&&r.jsx("span",{className:"nice-radio-player__track",children:v.metadata.artist?`${v.metadata.artist} — ${v.metadata.title}`:v.metadata.title}),((Y=v.metadata)==null?void 0:Y.genre)&&r.jsx("span",{className:"nice-radio-player__genre",children:v.metadata.genre}),v.isBuffering&&r.jsx("span",{className:"nice-radio-player__buffering",children:j("radioPlayer.buffering","Buffering…")})]})]}):r.jsx("div",{className:"nice-radio-player__placeholder",children:j("radioPlayer.selectStation","Select a station")})}),r.jsxs("div",{className:"nice-radio-player__controls",children:[r.jsx("button",{className:"nice-radio-player__play-btn",onClick:C.toggle,disabled:!T,"aria-label":v.isPlaying?j("radioPlayer.pause","Pause"):j("radioPlayer.play","Play"),children:v.isPlaying?r.jsx(B.NtdPause,{size:16}):r.jsx(B.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(B.NtdVolume,{size:16})}),r.jsx("input",{type:"range",min:0,max:1,step:.01,value:v.volume,onChange:_=>C.setVolume(parseFloat(_.target.value)),className:"nice-radio-player__volume-slider","aria-label":j("radioPlayer.volume","Volume")})]}),r.jsx("button",{className:`nice-radio-player__eq-btn${k?" nice-radio-player__eq-btn--active":""}`,onClick:()=>R(!k),title:j("radioPlayer.equalizer","Equalizer"),children:"EQ"})]}),v.error&&r.jsx("div",{className:"nice-radio-player__error",children:v.error}),k&&r.jsx("div",{className:"nice-radio-player__equalizer",children:r.jsxs("div",{className:"nice-radio-player__eq-presets",children:[a.map(_=>r.jsx("button",{className:`nice-radio-player__eq-preset${v.activePreset===_.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>C.applyEQPreset(_),children:_.name},_.name)),v.activePreset&&r.jsx("button",{className:"nice-radio-player__eq-preset",onClick:C.clearEQ,children:j("clear","Clear")})]})}),h&&r.jsx(Tc,{stations:e,activeStationId:T==null?void 0:T.id,onSelect:S})]})}const ay=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],sy={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class Pc{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??ay,audioConstraints:{...sy,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 iy(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function oy(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function ly(){return new AudioContext({sampleRate:48e3,latencyHint:"interactive"})}const gs=d.forwardRef(function(t,n){const{t:a}=xe(),{mode:s="bars",width:i=300,height:o=100,barCount:l=32,barColor:c="var(--nice-primary, #3b82f6)",backgroundColor:u="transparent",fftSize:h=256,smoothing:p=.8,minDecibels:g=-90,maxDecibels:y=-10,deviceId:m,autoStart:x=!1,onStart:b,onStop:f,onAudioLevel:j,onError:v,className:C,style:T,barBorderRadius:M=2,barGap:k=2,lineWidth:R=2}=t,P=d.useRef(null),I=d.useRef(null),A=d.useRef(null),L=d.useRef(null),E=d.useRef(0),D=d.useRef(null),Z=d.useRef(0),[G,F]=d.useState(!1),q=Array.isArray(c)?c.join("|"):c,V=d.useMemo(()=>q.split("|").map(_=>ve.resolveCssColor(_,P.current)),[q]),K=d.useCallback((_,U,$=!0)=>{const H=$?_.createLinearGradient(0,o,0,0):_.createLinearGradient(0,0,i,0);return U.forEach((X,re)=>{H.addColorStop(re/(U.length-1),X)}),H},[i,o]),W=d.useCallback((_,U)=>{const H=(i-(l-1)*k)/l,X=Math.floor(U.length/l),re=V,oe=re.length>1?K(_,re):re[0];_.fillStyle=oe;for(let se=0;se<l;se++){const ee=U[se*X]/255*o,ae=se*(H+k),ce=o-ee;M>0?(_.beginPath(),_.roundRect(ae,ce,H,ee,M),_.fill()):_.fillRect(ae,ce,H,ee)}},[l,V,k,M,i,o,K]),Q=d.useCallback((_,U)=>{const $=o/2,X=(i-(l-1)*k)/l,re=Math.floor(U.length/l),oe=V,se=oe.length>1?K(_,oe):oe[0];_.fillStyle=se;for(let z=0;z<l;z++){const ae=U[z*re]/255*$,ce=z*(X+k);M>0?(_.beginPath(),_.roundRect(ce,$-ae,X,ae,M),_.fill(),_.beginPath(),_.roundRect(ce,$,X,ae,M),_.fill()):(_.fillRect(ce,$-ae,X,ae),_.fillRect(ce,$,X,ae))}},[l,V,k,M,i,o,K]),w=d.useCallback((_,U)=>{const $=V;_.strokeStyle=$.length>1?K(_,$,!1):$[0],_.lineWidth=R,_.lineCap="round",_.lineJoin="round",_.beginPath();const H=i/U.length;let X=0;for(let re=0;re<U.length;re++){const se=U[re]/128*o/2;re===0?_.moveTo(X,se):_.lineTo(X,se),X+=H}_.stroke()},[V,R,i,o,K]),N=d.useCallback((_,U)=>{const $=i/2,H=o/2,X=Math.min(i,o)/3,re=V;_.strokeStyle=re.length>1?K(_,re):re[0],_.lineWidth=R;const oe=Math.floor(U.length/64),se=Math.PI*2/64;_.beginPath();for(let z=0;z<64;z++){const ee=U[z*oe]/255,ae=X+ee*X*.5,ce=z*se-Math.PI/2,le=$+Math.cos(ce)*ae,ne=H+Math.sin(ce)*ae;z===0?_.moveTo(le,ne):_.lineTo(le,ne)}_.closePath(),_.stroke()},[V,R,i,o,K]),S=d.useCallback(()=>{const _=P.current,U=A.current,$=D.current;if(!_||!U||!$)return;const H=_.getContext("2d");if(!H)return;s==="waveform"?U.getByteTimeDomainData($):U.getByteFrequencyData($);let X=0;for(let re=0;re<$.length;re++)X+=$[re];switch(Z.current=X/($.length*255),j==null||j(Z.current),H.clearRect(0,0,i,o),u!=="transparent"&&(H.fillStyle=ve.resolveCssColor(u,H.canvas),H.fillRect(0,0,i,o)),s){case"bars":W(H,$);break;case"mirror-bars":Q(H,$);break;case"waveform":w(H,$);break;case"circle":N(H,$);break}E.current=requestAnimationFrame(S)},[s,i,o,u,W,Q,w,N,j]),O=d.useCallback(async()=>{try{if(G)return;const _=await navigator.mediaDevices.getUserMedia({audio:m?{deviceId:{exact:m}}:!0,video:!1});L.current=_;const U=new AudioContext;I.current=U;const $=U.createMediaStreamSource(_),H=U.createAnalyser();H.fftSize=h,H.smoothingTimeConstant=p,H.minDecibels=g,H.maxDecibels=y,$.connect(H),A.current=H,D.current=new Uint8Array(H.frequencyBinCount),F(!0),b==null||b(),S()}catch(_){v==null||v(_ instanceof Error?_:new Error(String(_)))}},[G,m,h,p,g,y,b,v,S]),Y=d.useCallback(()=>{cancelAnimationFrame(E.current),L.current&&(L.current.getTracks().forEach(U=>U.stop()),L.current=null),I.current&&(I.current.close(),I.current=null),A.current=null,D.current=null,Z.current=0,F(!1),f==null||f();const _=P.current;if(_){const U=_.getContext("2d");U&&(U.clearRect(0,0,i,o),u!=="transparent"&&(U.fillStyle=ve.resolveCssColor(u,U.canvas),U.fillRect(0,0,i,o)))}},[i,o,u,f]);return d.useImperativeHandle(n,()=>({start:O,stop:Y,isCapturing:()=>G,getAudioLevel:()=>Z.current}),[O,Y,G]),d.useEffect(()=>(x&&O(),()=>{Y()}),[x]),r.jsx("canvas",{ref:P,width:i,height:o,className:C,style:{display:"block",...T},"aria-label":a("streamingVisualizer.audioVisualizer","Audio visualizer")})}),Ei=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}}},cy={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"},dy={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))"},uy={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))"},Ec=d.forwardRef(function(t,n){const{t:a}=xe(),{userId:s,userName:i,userAvatarUrl:o,participants:l=[],rtcConfig:c,position:u="bottom-right",expanded:h=!0,onSignalingMessage:p,onMuteToggle:g,onLeave:y,onSpeakingChange:m,speakingThreshold:x=.1,theme:b="auto",className:f,style:j,zIndex:v=1e3}=t,C=d.useRef(null),T=d.useRef(null),M=d.useRef(new Map);d.useRef(new Map);const[k,R]=d.useState(!1),[P,I]=d.useState(!1),[A,L]=d.useState(!1),[E,D]=d.useState(h),G=d.useMemo(()=>b==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":b,[b])==="dark"?uy:dy;d.useEffect(()=>{const w=new Pc(s,c);w.onRemoteStream=(S,O)=>{let Y=M.current.get(S);Y||(Y=new Audio,Y.autoplay=!0,M.current.set(S,Y)),Y.srcObject=O},w.onSignalingMessage=S=>{p==null||p(S)},w.onPeerStateChange=(S,O)=>{O==="connected"&&I(!0)},C.current=w,w.initialize().then(()=>{var S;(S=T.current)==null||S.start()});const N=M.current;return()=>{w.disconnect(),N.forEach(S=>{S.srcObject=null}),N.clear()}},[s,c,p]);const F=d.useCallback(()=>{var N;const w=!k;R(w),(N=C.current)==null||N.setMuted(w),g==null||g(w)},[k,g]),q=d.useCallback(()=>{var w,N;(w=C.current)==null||w.disconnect(),(N=T.current)==null||N.stop(),I(!1),y==null||y()},[y]),V=d.useCallback(w=>{const N=w>x;N!==A&&(L(N),m==null||m(s,N))},[x,A,s,m]),K=d.useCallback(async w=>{var N;await((N=C.current)==null?void 0:N.createOffer(w))},[]),W=d.useCallback(async w=>{var N;await((N=C.current)==null?void 0:N.handleSignalingMessage(w))},[]);d.useImperativeHandle(n,()=>({connectToPeer:K,handleSignalingMessage:W,toggleMute:F,isMuted:()=>k,leave:q,getManager:()=>C.current}),[K,W,F,k,q]);const Q=({participant:w,isLocal:N,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:G.hoverBg,border:`2px solid ${S?G.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:G.text,transition:"border-color 0.15s ease"},children:w.avatarUrl?r.jsx("img",{src:w.avatarUrl,alt:w.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):w.name.charAt(0).toUpperCase()}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsxs("div",{style:{color:G.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[w.name,N&&r.jsxs("span",{style:{color:G.textSecondary,fontWeight:400},children:[" ",a("voiceChatOverlay.you","(You)")]})]})}),w.isMuted&&r.jsx(B.NtdMicrophoneOff,{size:16,variant:"outline",primaryColor:G.mutedIcon})]});return E?r.jsxs("div",{className:f,style:{...cy,...Ei(u),backgroundColor:G.background,border:`1px solid ${G.border}`,zIndex:v,...j},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${G.border}`},children:[r.jsx("span",{style:{color:G.text,fontWeight:600},children:a("voiceChatOverlay.voiceChat","Voice Chat")}),r.jsx("button",{onClick:()=>D(!1),style:{background:"none",border:"none",cursor:"pointer",padding:4,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:4},"aria-label":a("voiceChatOverlay.collapse","Collapse"),children:r.jsx(B.NtdMinimize,{size:16,variant:"outline",primaryColor:G.textSecondary})})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[r.jsx(Q,{participant:{id:s,name:i,avatarUrl:o,isMuted:k},isLocal:!0,isSpeaking:A&&!k}),l.map(w=>r.jsx(Q,{participant:w,isSpeaking:w.isSpeaking},w.id))]}),r.jsx(gs,{ref:T,mode:"bars",width:256,height:32,barCount:24,barColor:k?"var(--nice-text-muted, #9ca3af)":["var(--nice-primary, #3b82f6)","var(--nice-accent, #8b5cf6)"],barGap:3,barBorderRadius:2,autoStart:!1,onAudioLevel:V,style:{borderRadius:4,opacity:k?.5:1}}),r.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[r.jsx("button",{onClick:F,style:{flex:1,padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:k?G.mutedBg:G.activeBg,color:k?G.mutedIcon:G.activeIcon,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":k?a("voiceChatOverlay.unmute","Unmute"):a("voiceChatOverlay.mute","Mute"),children:k?r.jsxs(r.Fragment,{children:[r.jsx(B.NtdMicrophoneOff,{size:16,variant:"outline"}),a("voiceChatOverlay.muted","Muted")]}):r.jsxs(r.Fragment,{children:[r.jsx(B.NtdMicrophone,{size:16,variant:"outline"}),a("voiceChatOverlay.micOn","Mic On")]})}),r.jsx("button",{onClick:q,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(B.NtdLogOut,{size:16,variant:"outline"})})]})]}):r.jsx("div",{className:f,style:{position:"fixed",...Ei(u),zIndex:v,...j},children:r.jsxs("button",{onClick:()=>D(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:G.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(B.NtdMicrophone,{size:24,variant:"outline",primaryColor:G.text}),l.length>0&&r.jsx("span",{style:{position:"absolute",top:-4,right:-4,width:20,height:20,borderRadius:"50%",backgroundColor:G.speakingRing,color:"var(--nice-color-white, #fff)",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:l.length+1})]})})});function hy(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 py(e){return e.undoIndex<0?e:{...e,undoIndex:e.undoIndex-1}}function fy(e){return e.undoIndex>=e.operations.length-1?e:{...e,undoIndex:e.undoIndex+1}}function my(e,t,n){const s=({"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":.6666666666666666,"1/8T":.3333333333333333,"1/16T":.16666666666666666,"1/4D":1.5,"1/8D":.75}[t.grid]??1)*n,i=t.strength/100;return e.map(o=>{const l=Math.round(o.startTick/s)*s,c=o.startTick+(l-o.startTick)*i,u=(Math.random()-.5)*2*t.humanize;return{...o,startTick:Math.max(0,Math.round(c+u))}})}function gy(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 $c={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 yy(e,t,n){const a=$c[n],s=(e-t+120)%12;let i=a[0],o=999;for(const c of a){const u=Math.min(Math.abs(s-c),12-Math.abs(s-c));u<o&&(o=u,i=c)}const l=Math.floor((e-t)/12);return t+l*12+i}function vy(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 by(e){return e>=95?"S":e>=85?"A":e>=70?"B":e>=55?"C":e>=40?"D":"F"}const xy={"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]}},Sy={"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=qn;exports.ALL_EFFECTS=zl;exports.ALL_TEXTURES=Io;exports.ARTNET_PORT=Ug;exports.ASYMMETRIC_CAPS=jo;exports.AudioEffectType=kc;exports.AudioPlaybackEngine=x0;exports.AudioRecorder=za;exports.AutoSavePanel=zi;exports.CONTROLLER_PROFILES=Zl;exports.ChaseRunner=Zg;exports.CollaboratorPermission=wc;exports.DEFAULT_ARP_CONFIG=fa;exports.DEFAULT_AUDIO_INPUT_SETTINGS=Ol;exports.DEFAULT_BAR_FILL=Ut;exports.DEFAULT_CAP_STYLE=Ro;exports.DEFAULT_EMPTY_BAR_FILL=Br;exports.DEFAULT_FONT_SETTINGS=Ur;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=Gr;exports.DEFAULT_GOLD_FILLED_BAR_FILL=Wr;exports.DEFAULT_KARAOKE_SETTINGS=No;exports.DEFAULT_SEED_CONFIG=Gl;exports.DMXEngine=Rc;exports.DRUM_PATTERN_NAMES=I0;exports.DefaultScoringPresets=Ba;exports.DmxChannelControl=ms;exports.DmxChannelType=Bt;exports.DmxEditor=jc;exports.DmxOptionsControl=fs;exports.DmxSliderControl=Hn;exports.DynamicRuleField=ot;exports.DynamicRuleOperator=lt;exports.EditorTrackProvider=Fa;exports.EditorUndoManager=ju;exports.FIXTURE_PROFILES=Mc;exports.GENERIC_PROFILE=os;exports.GM_DRUM_MAP=Sy;exports.GRADIENT_PRESETS=fl;exports.GROOVE_TEMPLATES=us;exports.GenericPlaylistItem=ts;exports.KARAOKE_FONT_OPTIONS=kp;exports.KEY_MAPS=Yo;exports.KaraokeFormat=Qa;exports.LANE_COLORS=_n;exports.LAUNCH_CONTROL_PROFILE=Yl;exports.LAYER_COLORS=Dg;exports.MINILAB_PROFILE=Kl;exports.MPK_MINI_PROFILE=Hl;exports.MasterFXPanel=Oi;exports.MidiCCMapper=_0;exports.NOTE_NAMES=N0;exports.NiceArpeggiatorPanel=uu;exports.NiceAudioEffectsRack=m0;exports.NiceAudioErrorBoundary=Gc;exports.NiceAudioInputPicker=b0;exports.NiceAudioPitchAnalyzer=xh;exports.NiceAudioStudio=Ud;exports.NiceAudioTimeline=Di;exports.NiceAutoSavePanel=zi;exports.NiceBarFillEditor=bh;exports.NiceCCAutomationLaneEditor=lu;exports.NiceCCLane=ed;exports.NiceDMXTimeline=Xg;exports.NiceDmxChannelControl=ms;exports.NiceDmxEditor=jc;exports.NiceDmxOptionsControl=fs;exports.NiceDmxSliderControl=Hn;exports.NiceDynamicRuleEditor=Kf;exports.NiceEditorTrackProvider=Fa;exports.NiceGenericPlayer=Do;exports.NiceGenericPlayerControls=Ip;exports.NiceGenericPlayerStage=pf;exports.NiceGenericPlaylist=Mf;exports.NiceGenericPlaylistItem=ts;exports.NiceI18nProvider=Oc;exports.NiceKaraokeEditorManager=Np;exports.NiceKaraokeLyrics=go;exports.NiceKaraokeManager=tp;exports.NiceKaraokePhaserRenderer=Ep;exports.NiceKaraokeSelectionMode=pl;exports.NiceKaraokeSessionJoin=xp;exports.NiceKaraokeSetupPanel=hl;exports.NiceKaraokeSongBrowser=up;exports.NiceKaraokeSummaryOverlay=Lo;exports.NiceKaraokeTimeline=$o;exports.NiceKaraokeUploader=Ho;exports.NiceLFOPanel=fu;exports.NiceLatencyCalibrator=pp;exports.NiceMasterFXPanel=Oi;exports.NiceModeSwitcher=yl;exports.NiceMusicLibraryExplorer=bf;exports.NiceNoteParticles=Xm;exports.NiceNoteRiver=Um;exports.NicePadKaraokeOverlay=Ko;exports.NicePianoRoll=Ia;exports.NicePitchMeter=Ou;exports.NicePlaylistBrowser=sm;exports.NicePlaylistDualPane=Xf;exports.NicePlaylistGridView=cm;exports.NicePlaylistImportWizard=bm;exports.NicePlaylistList=as;exports.NicePlaylistOverview=um;exports.NicePlaylistSearchBar=hm;exports.NicePlaylistSidebar=om;exports.NicePlaylistTagEditor=Nf;exports.NicePlaylistTrackList=Ml;exports.NiceRadioPlayer=ry;exports.NiceRecordingOptionsPanel=Bi;exports.NiceSampleBrowser=qd;exports.NiceStageVisualizer=vl;exports.NiceStationBrowser=Tc;exports.NiceStepSequencerPanel=vu;exports.NiceStreamingVisualizer=gs;exports.NiceUndoRedoPanel=Fi;exports.NiceVocalEffectsRack=y0;exports.NiceVocalPerformanceReport=ip;exports.NiceVoiceChatOverlay=Ec;exports.NiceWaveform=Ai;exports.NiceYouTubePlayer=ff;exports.NiceZoomSnapControls=La;exports.OVERLAY_PATTERNS=Ar;exports.OXYGEN25_PROFILE=ql;exports.PLAYER_COLORS=Xe;exports.PLAYER_COLOR_VARS=fr;exports.PROGRESSION_NAMES=A0;exports.PadNotePlayer=Jo;exports.PaneSide=kl;exports.PianoRoll=Ia;exports.PlaylistList=as;exports.PlaylistType=ns;exports.RecordingOptionsPanel=Bi;exports.SACN_PORT=Hg;exports.SCALE_INTERVALS=$c;exports.SCALE_NAMES=$0;exports.SKEW_CAPS=Mo;exports.STANDARD_TUNINGS=xy;exports.SYMMETRIC_CAPS=Ha;exports.ShortcutManager=xc;exports.SimpleSynth=Bl;exports.SortDirection=un;exports.SortField=wl;exports.StreamingVisualizer=gs;exports.TEXTURE_CATEGORIES=Za;exports.TrackSource=bt;exports.UndoRedoPanel=Fi;exports.ViewMode=Sl;exports.VocalEffectsEngine=Fl;exports.VoiceChatOverlay=Ec;exports.WebRTCAudioManager=Pc;exports.ZoomSnapControls=La;exports.addEffectToLayer=Y0;exports.addMidiNote=J0;exports.analyzeAudioFileWithAlgorithm=lg;exports.applyGroove=mg;exports.applyGrooveTemplate=vc;exports.applyHumanize=yc;exports.applyKaraokeDisplayVars=es;exports.applyMidiTransform=vy;exports.applySwing=gc;exports.arrow_L=Gt;exports.arrow_R=Rt;exports.autoCorrelate=Oo;exports.bracket_L=Wa;exports.bracket_R=wo;exports.buildArpSequence=lo;exports.buildLanes=Zo;exports.buildNoteDescriptors=Xa;exports.buildPadNoteEvents=Qo;exports.buildSegmentScores=Bo;exports.canRedo=Ki;exports.canUndo=Hi;exports.chamfer_L=Tr;exports.chamfer_R=mn;exports.clearMidiNotes=tg;exports.clearPattern=oc;exports.computeGrade=by;exports.computeTheoreticalMax=sl;exports.computeVocalPerformanceReport=cl;exports.convertBrowserSongToKaraokeSongFile=Fh;exports.copyCCEvents=pa;exports.createAnalyserNode=hc;exports.createArpPattern=O0;exports.createArtNetPacket=qg;exports.createBasslinePattern=B0;exports.createCCHistory=Wi;exports.createCompressorNode=fc;exports.createDefaultLFO=Fr;exports.createDefaultShortcuts=Rg;exports.createDropZoneHandlers=Lg;exports.createEmptyPattern=Qt;exports.createEmptyStep=ls;exports.createGainNode=pc;exports.createHiHatPattern=F0;exports.createKickPattern=D0;exports.createLoopRegion=Sg;exports.createSACNPacket=Kg;exports.createSnarePattern=z0;exports.createVocoderNode=mc;exports.createVoiceChatAudioContext=ly;exports.cutCCEvents=Zi;exports.deleteCCEventsInRange=Xi;exports.deserializeLFO=au;exports.deserializePattern=W0;exports.detectChord=gy;exports.downsampleAndQuantizePitchPoints=Go;exports.drawGlossyBarOnCanvas=En;exports.drawTimeline=va;exports.estimateLatencyMs=Wo;exports.estimateLatencyMsFromRecording=ul;exports.evaluateLFO=_a;exports.evaluateLFOAsCC=Da;exports.exportCCLane=eo;exports.extractBpmFromNotes=yo;exports.findTextureByUrl=gh;exports.formatShortcut=Ng;exports.generateArpEvents=du;exports.generatePlaceholderWaveform=pg;exports.generateSeed=Vl;exports.generateUltrastarText=cg;exports.getActiveGradient=gl;exports.getActiveLyrics=Eu;exports.getActiveWords=$u;exports.getAlgorithmColor=Dh;exports.getAlgorithmCssVar=zh;exports.getAlgorithmLabel=_h;exports.getArpModes=co;exports.getArpRates=uo;exports.getAudioContext=Yn;exports.getAudioInputDevices=oy;exports.getAudioWorkletProcessorCode=dc;exports.getBackgroundUrl=Lh;exports.getCachedImage=ph;exports.getCapStyleByName=Tn;exports.getComboMultiplier=rl;exports.getCoverUrl=Ih;exports.getGrooveTemplate=gg;exports.getGrooveTemplateNames=yg;exports.getLaneForPitch=Xo;exports.getNextPlayerColor=od;exports.getNextPlayerColorCss=ld;exports.getOverlayCanvasPattern=Ln;exports.getPatternByName=Pn;exports.getSACNMulticastAddress=Yg;exports.getScoringPreset=Or;exports.getTexturePattern=An;exports.getVerseRatingLabel=nl;exports.handleAddCCEvent=rg;exports.handleRedo=Cu;exports.handleRemoveCCEvent=sg;exports.handleSelectCCLane=ng;exports.handleUndo=wu;exports.handleUpdateCCEvent=ag;exports.hexToHsl=Ir;exports.humanizeMidiNotes=xg;exports.hydrateKaraokeDisplayFromBackend=wp;exports.hydratePlayerKaraokeSettingsFromBackend=Hu;exports.hzToMidi=It;exports.hzToUltrastarPitch=vo;exports.importCCLane=to;exports.initKaraokeDisplaySettings=jp;exports.instrumentPresets=S0;exports.isAudioContextRunning=Ii;exports.isInLoopRegion=Cg;exports.isWebRTCSupported=iy;exports.loadAllKaraokeSettings=Ku;exports.loadAudioWorkletModule=uc;exports.loadKaraokeDisplaySettings=ml;exports.loadKaraokeSettings=Ka;exports.loadRemoteScoringPresets=Uu;exports.makeClickReference=dl;exports.makeClipSelectionId=dg;exports.mergeWaveforms=hg;exports.midiSeedGenerator=L0;exports.midiToHz=ba;exports.midiToNoteName=Lt;exports.normalizeHex=Lr;exports.openAudioFilePicker=_g;exports.ornate_L=Va;exports.ornate_R=$r;exports.parseLyrics=Tu;exports.parseNotes=Zn;exports.parseUltraStarText=qo;exports.parseVersesWithSyllables=mo;exports.parseVersesWithWords=Pu;exports.parseVideoMetadata=Fo;exports.pasteCCEvents=Yi;exports.pill_L=Kt;exports.pill_R=Ot;exports.preloadTexture=Ya;exports.preloadTextures=fh;exports.probeAudioFile=Sc;exports.pushCCState=Ui;exports.pushOperation=hy;exports.quantizeMidiNotes=vg;exports.quantizeNotes=my;exports.quantizeStepInBeats=bc;exports.quantizeStepInSeconds=hs;exports.randomizeVelocity=ic;exports.recordCCEvent=Qi;exports.redoCC=qi;exports.redoOperation=fy;exports.removeEffectFromLayer=Z0;exports.removeMidiNote=eg;exports.renderGlossyBarSvg=To;exports.resumeAudioContext=Xt;exports.reversePattern=ac;exports.sampleLFOForDisplay=io;exports.sampleLFOToCCEvents=so;exports.saveKaraokeDisplaySettings=Cp;exports.saveKaraokeSettings=qu;exports.scaleResult=ol;exports.scaleTo10k=il;exports.scoreNotesWithPitchPoints=al;exports.selectCCEventsInRange=Hd;exports.semitoneOffset=Vn;exports.serializeLFO=ru;exports.serializePattern=G0;exports.setLoopFromSelection=kg;exports.setProjectWithUndo=po;exports.setStepGate=ec;exports.setStepNote=Ql;exports.setStepProbability=tc;exports.setStepVelocity=Jl;exports.sharp_L=pn;exports.sharp_R=fn;exports.shield_L=Pr;exports.shield_R=ko;exports.shiftPattern=sc;exports.shouldTrigger=cc;exports.skewTL_L=mr;exports.skewTL_R=ya;exports.skewTR_L=ga;exports.skewTR_R=gr;exports.snapLoopToGrid=wg;exports.snapTimeToQuantize=Ea;exports.snapToGrid=ug;exports.snapToScale=yy;exports.soft_L=Ga;exports.soft_R=So;exports.stepDuration=cs;exports.stepTimeOffset=lc;exports.syncDivisionToHz=ro;exports.tab_L=Ua;exports.tab_R=Co;exports.thinCCEvents=Ji;exports.toTrack=Vo;exports.toggleEffectBypass=X0;exports.toggleStep=Xl;exports.toggleStepSlide=nc;exports.transposePattern=rc;exports.undoCC=Vi;exports.undoOperation=py;exports.updateEffectParams=Q0;exports.useAudioWorklet=K0;exports.useAutoSave=bu;exports.useCCAutomation=no;exports.useCanPickSong=bp;exports.useDMXAudioSync=Jg;exports.useDMXEngine=Qg;exports.useEditorTrack=Nu;exports.useKaraokePitch=tl;exports.useKaraokeScoring=ll;exports.useLocalPlaylists=rs;exports.useMPE=j0;exports.useMidiLearn=w0;exports.useNiceTranslation=xe;exports.useOxygen25=R0;exports.usePitchWorker=V0;exports.usePlaybackEngine=xu;exports.useProjectCRUD=Ru;exports.useRadioStream=Nc;exports.useRecording=Su;exports.useScoringWorker=q0;exports.useStepSequencer=U0;exports.useWebMidi=Hr;exports.useWorker=ds;exports.validateAudioFiles=ps;exports.wave_L=Er;exports.wave_R=qa;exports.waveformValue=ao;exports.wrapTimeInLoop=jg;
|