@nice2dev/ui-audio 1.2.0 → 1.2.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 +142 -0
- package/dist/core/audioIcons.d.ts +1 -1
- package/dist/index.cjs +40 -40
- package/dist/index.d.ts +2 -0
- package/dist/index.mjs +10787 -10375
- package/dist/karaoke/KaraokeManager.d.ts +1 -1
- package/dist/karaoke/KaraokeSelectionMode.d.ts +1 -1
- package/dist/karaoke/PadKaraokeOverlay.d.ts +4 -4
- package/dist/karaoke/karaokeTimelineTypes.d.ts +1 -1
- package/dist/radio/NiceRadioPlayer.d.ts +1 -1
- package/dist/ui-audio.css +1 -1
- package/package.json +6 -6
package/dist/index.cjs
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
"use strict";var Pc=Object.create;var gs=Object.defineProperty;var Ac=Object.getOwnPropertyDescriptor;var Ec=Object.getOwnPropertyNames;var Ic=Object.getPrototypeOf,Lc=Object.prototype.hasOwnProperty;var zc=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ec(t))!Lc.call(e,s)&&s!==n&&gs(e,s,{get:()=>t[s],enumerable:!(a=Ac(t,s))||a.enumerable});return e};var Hr=(e,t,n)=>(n=e!=null?Pc(Ic(e)):{},zc(t||!e||!e.__esModule?gs(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),we=require("@nice2dev/ui-core"),u=require("react"),se=require("@nice2dev/ui"),B=require("@nice2dev/icons"),la=require("pitchy"),$a=require("react-youtube");var bt=typeof document<"u"?document.currentScript:null;const Ti=u.createContext(null),Dc=({t:e,children:t})=>r.jsx(Ti.Provider,{value:e,children:t});function Te(){const e=u.useContext(Ti),{t}=we.useNiceTranslation();return{t:u.useMemo(()=>e??((a,s)=>t(a,s??a)),[e,t])}}class _c extends u.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){var s,i;const a=this.props.componentName?`[${this.props.componentName}]`:"[AudioErrorBoundary]";console.error(`${a} Caught error:`,t,n),(i=(s=this.props).onError)==null||i.call(s,t,n)}render(){return this.state.hasError&&this.state.error?typeof this.props.fallback=="function"?this.props.fallback(this.state.error,this.reset):this.props.fallback?this.props.fallback:r.jsx("div",{className:"nice-audio-error-boundary",role:"alert",children:r.jsxs("div",{className:"nice-audio-error-boundary__content",children:[r.jsx("h3",{className:"nice-audio-error-boundary__title",children:this.props.componentName?`${this.props.componentName} encountered an error`:"Something went wrong"}),r.jsx("p",{className:"nice-audio-error-boundary__message",children:this.state.error.message}),r.jsx("button",{className:"nice-audio-error-boundary__retry",onClick:this.reset,children:"Try Again"})]})}):this.props.children}}function Fc(e){if(!e)return[128,128,128];const t=e.match(/^#([0-9a-f]{3,8})$/i);if(t){let a=t[1];if(a.length===3&&(a=a[0]+a[0]+a[1]+a[1]+a[2]+a[2]),a.length>=6)return[parseInt(a.slice(0,2),16),parseInt(a.slice(2,4),16),parseInt(a.slice(4,6),16)]}const n=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);return n?[+n[1],+n[2],+n[3]]:[128,128,128]}const Kr={},ca={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function Oc(){const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:bt&&bt.tagName.toUpperCase()==="SCRIPT"&&bt.src||new URL("index.cjs",document.baseURI).href}<"u"?Kr==null?void 0:Kr.VITE_LOG_LEVEL:void 0;return e&&e in ca?e:"WARN"}const Bc=Oc();function Kn(e){return ca[e]>=ca[Bc]}function Yn(e){return`[${e}]`}const ot={debug(e,t,...n){Kn("DEBUG")&&console.debug(Yn(e),t,...n)},info(e,t,...n){Kn("INFO")&&console.info(Yn(e),t,...n)},warn(e,t,...n){Kn("WARN")&&console.warn(Yn(e),t,...n)},error(e,t,...n){Kn("ERROR")&&console.error(Yn(e),t,...n)},scoped(e){return{debug:(t,...n)=>ot.debug(e,t,...n),info:(t,...n)=>ot.info(e,t,...n),warn:(t,...n)=>ot.warn(e,t,...n),error:(t,...n)=>ot.error(e,t,...n)}}},ys=ot.scoped("Waveform"),Gc=["audio/","video/"],$i=({audioBlob:e,currentTime:t,duration:n,width:a=600,height:s=200,zoom:i=1,onSeek:l,onRegionSelect:o,markers:c=[],regions:d=[],displayMode:h="waveform",multiChannel:f=!1,waveColor:p="#007bff",progressColor:y="rgba(255,0,0,0.8)",backgroundColor:g="transparent",showRuler:x=!1,showChannelLabels:v=!0,showPeakMeter:m=!1,className:S})=>{const b=u.useRef(null),w=u.useRef(null),[N,R]=u.useState(null),[P,j]=u.useState(0),[M,I]=u.useState(!1),[T,E]=u.useState(null),[_,D]=u.useState(null),[q,te]=u.useState(0),z=Math.max(a,a*i),U=x?24:0;u.useEffect(()=>{if(!e||e.size===0){R(null);return}e.type&&!Gc.some(C=>e.type.startsWith(C))&&ys.warn("Unexpected blob MIME type:",e.type);let O=!1;return(async()=>{let C=null;try{const $=await e.arrayBuffer();if($.byteLength===0||O)return;C=new AudioContext;const k=await C.decodeAudioData($);O||R(k)}catch($){ys.error("Failed to decode audio:",$)}finally{C==null||C.close().catch(()=>{})}})(),()=>{O=!0}},[e]),u.useEffect(()=>{if(i>1&&n>0){const O=t/n*z;(O<P||O>P+a)&&j(Math.max(0,O-a/2))}},[t,n,i,a,z,P]),u.useEffect(()=>{const O=b.current,C=N;if(!O||!n||n===1/0)return;const $=O.getContext("2d");if(!$)return;const k=z,W=s;if(O.width=k,O.height=W+U,$.clearRect(0,0,k,W+U),g!=="transparent"&&($.fillStyle=we.resolveCssColor(g),$.fillRect(0,0,k,W+U)),x){const A=we.resolveCssColor("var(--nice-text-secondary, #888)");$.fillStyle="rgba(128,128,128,0.15)",$.fillRect(0,0,k,U),$.fillStyle=A,$.font="10px monospace",$.textAlign="center";const L=Math.max(1,Math.floor(n/(z/80)));for(let G=0;G<=n;G+=L){const F=G/n*k;$.fillText(qc(G),F,U-4),$.fillStyle="rgba(128,128,128,0.3)",$.fillRect(F,U,1,W),$.fillStyle=A}}for(const A of d){const L=A.start/n*k,G=A.end/n*k;$.fillStyle=we.resolveCssColor(A.color??"var(--nice-accent-tint-15, rgba(99, 102, 241, 0.15))"),$.fillRect(L,U,G-L,W),A.label&&($.fillStyle=we.resolveCssColor(A.color??"var(--nice-info, #6366f1)"),$.font="10px sans-serif",$.textAlign="left",$.fillText(A.label,L+2,U+12))}if(T!==null&&_!==null){const A=Math.min(T,_),L=Math.max(T,_);$.fillStyle="rgba(255,200,0,0.2)",$.fillRect(A,U,L-A,W)}if(C){const A=f?C.numberOfChannels:1,L=W/A,G=we.resolveCssColor(p);let F=0;for(let V=0;V<A;V++){const Q=C.getChannelData(V),le=U+V*L;if(h==="waveform"?Wc($,Q,k,L,le,G):h==="bars"?Uc($,Q,k,L,le,G):h==="spectrogram"&&Vc($,Q,k,L,le,C.sampleRate),m&&n>0){const oe=Math.floor(t/n*Q.length),ne=Math.floor(C.sampleRate*.05);let K=0;for(let ie=Math.max(0,oe-ne);ie<Math.min(Q.length,oe+ne);ie++)K+=Q[ie]*Q[ie];const H=Math.sqrt(K/(ne*2));F=Math.max(F,H)}f&&v&&A>1&&($.fillStyle=we.resolveCssColor("var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"),$.font="bold 11px sans-serif",$.textAlign="left",$.fillText(V===0?"L":V===1?"R":`Ch${V+1}`,4,le+14))}te(F)}if(n>0){const A=Math.max(0,Math.min(t/n*k,k));$.beginPath(),$.strokeStyle=we.resolveCssColor(y),$.lineWidth=2,$.moveTo(A,U),$.lineTo(A,W+U),$.stroke()}for(const A of c){const L=A.time/n*k,G=we.resolveCssColor(A.color??"var(--nice-warning, #f59e0b)");$.beginPath(),$.strokeStyle=G,$.lineWidth=2,$.setLineDash([4,4]),$.moveTo(L,U),$.lineTo(L,W+U),$.stroke(),$.setLineDash([]),A.label&&($.fillStyle=G,$.font="bold 10px sans-serif",$.textAlign="center",$.fillText(A.label,L,U+W-4))}},[N,t,n,z,s,i,h,f,p,y,g,x,c,d,T,_,m,v,U]);const Z=u.useCallback(O=>{var k;if(!n)return;const C=(k=b.current)==null?void 0:k.getBoundingClientRect();if(!C)return;const $=O.clientX-C.left+P;I(!0),E($),D($)},[n,P]),ae=u.useCallback(O=>{if(!M||!b.current)return;const C=b.current.getBoundingClientRect(),$=O.clientX-C.left+P;D($)},[M,P]),Y=u.useCallback(()=>{if(!M||T===null||_===null||!n){I(!1),E(null),D(null);return}const O=Math.min(T,_),C=Math.max(T,_),$=(C-O)/z*n;if(I(!1),E(null),D(null),$<.2){const k=O/z*n;l==null||l(k)}else{const k=O/z*n,W=C/z*n;o==null||o({start:k,end:W})}},[M,T,_,n,z,l,o]);return r.jsxs("div",{ref:w,className:`nice-waveform${S?` ${S}`:""}`,style:{position:"relative",width:a,overflow:i>1?"auto":"hidden",cursor:l?"crosshair":"default"},onScroll:O=>j(O.target.scrollLeft),children:[r.jsx("canvas",{ref:b,width:z,height:s+U,style:{display:"block"},role:"img","aria-label":"Waveform canvas",onMouseDown:Z,onMouseMove:ae,onMouseUp:Y,onMouseLeave:Y}),m&&r.jsx("div",{style:{position:"absolute",right:4,top:U+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,q*300)}%`,background:q>.8?"var(--nice-danger, #ef4444)":q>.5?"var(--nice-warning, #f59e0b)":"var(--nice-success, #22c55e)",borderRadius:4,transition:"height 50ms"}})})]})};function Wc(e,t,n,a,s,i){const l=Math.floor(t.length/n),o=s+a/2;e.beginPath(),e.strokeStyle=i,e.lineWidth=1;for(let c=0;c<n;c++){const d=c*l,h=t.subarray(d,d+l);let f=0,p=0;for(let x=0;x<h.length;x++)h[x]<f&&(f=h[x]),h[x]>p&&(p=h[x]);const y=o-p*(a/2),g=o-f*(a/2);e.moveTo(c,y),e.lineTo(c,g)}e.stroke()}function Uc(e,t,n,a,s,i){const l=Math.max(2,Math.floor(n/128)),o=Math.floor(n/l),c=Math.floor(t.length/o);for(let d=0;d<o;d++){const h=d*c,f=t.subarray(h,h+c);let p=0;for(let v=0;v<f.length;v++)p+=Math.abs(f[v]);const g=p/f.length*a*.9,x=d*l;e.fillStyle=i,e.fillRect(x+1,s+a-g,l-2,g)}}function Vc(e,t,n,a,s,i){const o=Math.min(n,512),c=Math.floor(t.length/o),d=n/o;for(let h=0;h<o;h++){const f=h*c,p=new Float32Array(256/2);for(let g=0;g<256/2;g++){let x=0,v=0;for(let m=0;m<256&&f+m<t.length;m++){const S=2*Math.PI*g*m/256;x+=t[f+m]*Math.cos(S),v-=t[f+m]*Math.sin(S)}p[g]=Math.sqrt(x*x+v*v)/256}const y=a/p.length;for(let g=0;g<p.length;g++){const x=Math.min(1,p[g]*10),v=Math.floor(x*255),m=Math.floor(x*100),S=Math.floor((1-x)*200);e.fillStyle=`rgb(${v},${m},${S})`,e.fillRect(h*d,s+a-(g+1)*y,d+1,y+1)}}}function qc(e){const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const vs=88,Jt=16,Zn=16,Hc=320;function Kc(e){return e-21}function Yc(e){return e+21}const Pa=({notes:e,onAddNote:t,onRemoveNote:n,selectedNoteId:a,setSelectedNoteId:s,duration:i=4,zoom:l=1})=>{const o=u.useRef(null),c=Hc*l,d=vs*Jt,h=u.useRef(null);u.useEffect(()=>{},[e,l,i]);const f=y=>{const g=o.current;if(!g)return;const x=g.getBoundingClientRect(),v=y.clientX-x.left,m=y.clientY-x.top,S=Math.floor(m/Jt),b=Yc(S),w=v/c*i;h.current={drawing:!0,startX:v,key:S},t(b,w,i/Zn)},p=(y,g)=>{g.stopPropagation(),s==null||s(y)};return r.jsxs("svg",{ref:o,width:c,height:d,style:{background:"var(--nice-bg-secondary, #f8fafc)",border:"1px solid var(--nice-border-color, #cbd5e1)",userSelect:"none",display:"block"},onMouseDown:f,children:[[...Array(vs)].map((y,g)=>r.jsx("rect",{x:0,y:g*Jt,width:c,height:Jt,fill:g%2===0?"var(--nice-bg-secondary, #f8fafc)":"var(--nice-bg-tertiary, #f1f5f9)"},g)),[...Array(Zn+1)].map((y,g)=>r.jsx("line",{x1:g*c/Zn,y1:0,x2:g*c/Zn,y2:d,stroke:"var(--nice-border-muted, #ccc)",strokeWidth:g%4===0?2:1},g)),e.map(y=>{const g=Kc(y.pitch),x=y.start/i*c,v=y.duration/i*c;return r.jsx("rect",{x,y:g*Jt,width:Math.max(6,v),height:Jt-2,fill:y.id===a?"var(--nice-color-primary, #6366f1)":"color-mix(in srgb, var(--nice-color-primary, #6366f1) 55%, var(--nice-bg-primary, #ffffff))",stroke:"var(--nice-color-primary, #6366f1)",strokeWidth:y.id===a?2:1,rx:3,onClick:m=>p(y.id,m),onDoubleClick:()=>n(y.id),style:{cursor:"pointer"}},y.id)})]})},Zc=({ccEvents:e,onAddEvent:t,onUpdateEvent:n,onRemoveEvent:a,ccType:s,duration:i,width:l,height:o=60,curveType:c})=>{const d=u.useRef(null),{t:h}=Te(),[f,p]=u.useState(null),[y,g]=u.useState(null),[x,v]=u.useState(null),m=[...e].sort((_,D)=>_.time-D.time),S=_=>[_.time/i*l,(127-_.value)/127*o],b=(_,D,q)=>Math.max(D,Math.min(q,_)),w=_=>{var Z;if(_.target instanceof SVGCircleElement)return;const D=(Z=d.current)==null?void 0:Z.getBoundingClientRect();if(!D)return;const q=_.clientX-D.left,te=_.clientY-D.top,z=b(q/l*i,0,i),U=b(127-Math.round(te/o*127),0,127);t(s,U,z)},N=(_,D)=>{var U;D.stopPropagation(),p(_.id),v(_.id);const[q,te]=S(_),z=(U=d.current)==null?void 0:U.getBoundingClientRect();z&&g({dx:D.clientX-z.left-q,dy:D.clientY-z.top-te})},R=_=>{var Z;if(f==null||!y)return;const D=(Z=d.current)==null?void 0:Z.getBoundingClientRect();if(!D)return;const q=b(_.clientX-D.left-y.dx,0,l),te=b(_.clientY-D.top-y.dy,0,o),z=b(q/l*i,0,i),U=b(127-Math.round(te/o*127),0,127);n(f,U,z)},P=()=>{p(null),g(null)};u.useEffect(()=>{const _=D=>{(D.key==="Delete"||D.key==="Backspace")&&x!=null&&(a(x),v(null))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[x,a]),u.useEffect(()=>{if(f!=null)return window.addEventListener("mousemove",R),window.addEventListener("mouseup",P),()=>{window.removeEventListener("mousemove",R),window.removeEventListener("mouseup",P)}});const[j,M]=u.useState(null),I=(_,D)=>{const[q,te]=S(_);M({x:q+10,y:te-10,text:`Val: ${_.value}, Time: ${_.time.toFixed(2)}s`})},T=()=>M(null),E=_=>{var Z;const D=(Z=d.current)==null?void 0:Z.getBoundingClientRect();if(!D)return;const q=_.clientX-D.left,te=_.clientY-D.top,z=b(q/l*i,0,i),U=b(127-Math.round(te/o*127),0,127);t(s,U,z)};return r.jsxs("svg",{ref:d,width:l,height:o,style:{background:"var(--nice-bg-tertiary, #f3f3f3)",border:"1px solid var(--nice-border, #bbb)",cursor:f?"grabbing":"crosshair",display:"block"},onClick:w,onDoubleClick:E,tabIndex:0,children:[[...Array(9)].map((_,D)=>r.jsx("line",{x1:0,y1:D*o/8,x2:l,y2:D*o/8,stroke:"var(--nice-border-muted, #ddd)",strokeWidth:D===0||D===8?2:1},D)),m.length>1&&r.jsx("polyline",{fill:"none",stroke:"var(--nice-color-accent, #1976d2)",strokeWidth:2,points:m.map(_=>S(_).join(",")).join(" ")}),m.map(_=>{const[D,q]=S(_);return r.jsxs("g",{children:[r.jsx("circle",{cx:D,cy:q,r:x===_.id?8:6,fill:x===_.id?"var(--nice-color-accent, #1976d2)":"var(--nice-color-accent-light, #90caf9)",stroke:"var(--nice-color-accent, #1976d2)",strokeWidth:x===_.id?3:2,style:{cursor:"pointer"},onMouseDown:te=>N(_,te),onContextMenu:te=>{te.preventDefault(),a(_.id)},onClick:te=>{te.stopPropagation(),v(_.id)},onMouseOver:te=>I(_),onMouseOut:T}),x===_.id&&r.jsx("foreignObject",{x:D+10,y:q-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:_.handleType||c||"linear",onChange:te=>{n(_.id,_.value,_.time,te.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")})]})]})})]},_.id)}),j&&r.jsxs("g",{pointerEvents:"none",children:[r.jsx("rect",{x:j.x,y:j.y-18,width:90,height:20,fill:"var(--nice-color-surface, #fff)",stroke:"var(--nice-color-accent, #1976d2)",rx:4}),r.jsx("text",{x:j.x+6,y:j.y-4,fontSize:13,fill:"var(--nice-color-accent, #1976d2)",children:j.text})]}),r.jsxs("text",{x:6,y:16,fontSize:14,fill:"var(--nice-color-accent, #1976d2)",children:["CC",s]})]})},Xc=ot.scoped("audioContext");let Gn=null;function qn(){if(!Gn)try{Gn=new(window.AudioContext||window.webkitAudioContext)}catch(e){Xc.error("Error initializing AudioContext:",e)}return Gn}async function Zt(){const e=qn();e&&e.state==="suspended"&&await e.resume()}function Pi(){return!!Gn&&Gn.state==="running"}function Ai(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 Qc(e,t){if(!t.snapEnabled)return e;const n=Ai(t);return Math.round(e/n)*n}function Jc(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 ed(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 Ei(e,t,n=!0){const a=e.getContext("2d");if(!a)return;const s=30*t.zoom*t.duration,i=Math.max(80,30*t.zoom);e.width=s,e.height=i,a.clearRect(0,0,s,i),a.fillStyle=we.resolveCssColor("var(--nice-color-surface, #f5f5f5)",a.canvas),a.fillRect(0,0,s,i);const l=s/t.duration;let o=1;l<30?o=5:l<60?o=2:l>150&&(o=.5),a.strokeStyle=we.resolveCssColor("var(--nice-border-secondary, #ddd)",a.canvas),a.lineWidth=1;for(let c=0;c<=t.duration;c+=o){const d=c/t.duration*s,h=c%1===0;if(a.strokeStyle=we.resolveCssColor(h?"var(--nice-border-secondary, #ccc)":"var(--nice-border-muted, #eee)",a.canvas),a.lineWidth=h?1.5:.5,a.beginPath(),a.moveTo(d,0),a.lineTo(d,i),a.stroke(),h&&l>40){a.fillStyle=we.resolveCssColor("var(--nice-text-muted, #666)",a.canvas),a.font="10px monospace",a.textAlign="center";const f=n?ed(c,t.bpm):Jc(c);a.fillText(f,d,12)}}if(t.snapEnabled){const c=Ai(t);a.strokeStyle=we.resolveCssColor("var(--nice-color-accent, #ffeb3b)",a.canvas),a.lineWidth=.5;for(let d=0;d<=t.duration;d+=c){const h=d/t.duration*s;a.beginPath(),a.moveTo(h,i-5),a.lineTo(h,i),a.stroke()}}}function td(e,t,n,a){const s=e.getContext("2d");if(!s)return;const i=30*t.zoom*t.duration,l=Math.max(80,30*t.zoom),o=n/t.duration*i;Ei(e,t),s.strokeStyle=we.resolveCssColor(a?"var(--nice-color-danger, #f44336)":"var(--nice-color-accent, #2196f3)",s.canvas),s.lineWidth=2,s.beginPath(),s.moveTo(o,0),s.lineTo(o,l),s.stroke(),s.fillStyle=we.resolveCssColor(a?"var(--nice-color-danger, #f44336)":"var(--nice-color-accent, #2196f3)",s.canvas),s.beginPath(),s.moveTo(o,0),s.lineTo(o-5,-8),s.lineTo(o+5,-8),s.closePath(),s.fill()}function nd(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,o=e.height/2,c=Math.max(10,o-6);s.save(),s.strokeStyle=we.resolveCssColor(a,s.canvas),s.lineWidth=1,s.beginPath(),n.forEach((d,h)=>{const f=h/(n.length-1)*i,p=o-d*c;h===0?s.moveTo(f,p):s.lineTo(f,p)}),s.stroke(),s.restore()}const Ii=({zoom:e=1,duration:t=4,isPlaying:n,isRecording:a,currentTime:s,bpm:i=120,snapEnabled:l=!1,snapMode:o="beat",waveform:c,waveformColor:d,onCurrentTimeChange:h,onZoomChange:f})=>{const p=u.useRef(null),[y,g]=u.useState(!1),x=u.useRef(s);x.current=s;const v=u.useRef(t);v.current=t;const m=u.useRef(h);m.current=h;const S={zoom:e,duration:t,bpm:i,snapEnabled:l,snapMode:o};u.useEffect(()=>{Zt(),b()},[e,t,s,a,i,l,o,c]),u.useEffect(()=>{if(!n)return;let M=performance.now(),I=0;const T=E=>{const _=Math.max(0,E-M)/1e3;M=E;const D=Math.min(x.current+_,v.current);x.current=D,m.current(D),D<v.current&&(I=requestAnimationFrame(T))};return I=requestAnimationFrame(T),()=>cancelAnimationFrame(I)},[n]);const b=()=>{p.current&&(Ei(p.current,S),c!=null&&c.length&&nd(p.current,S,c,d),td(p.current,S,s,a))},w=M=>{g(!0),P(M)},N=M=>{y&&P(M)},R=()=>{g(!1)},P=M=>{if(!p.current)return;const I=p.current.getBoundingClientRect();let E=(M.clientX-I.left)/I.width*t;E=Qc(E,S),h(Math.min(Math.max(E,0),t))},j=M=>{if(!f)return;M.preventDefault();const I=M.deltaY>0?-.1:.1,T=Math.max(.5,Math.min(5,e+I));f(T)};return r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:r.jsx("canvas",{ref:p,style:{border:"1px solid black",backgroundColor:"white",width:`${30*e*t}px`,height:`${Math.max(80,30*e)}px`,cursor:y?"grabbing":"pointer"},onMouseDown:w,onMouseMove:N,onMouseUp:R,onMouseLeave:R,onWheel:j,role:"img","aria-label":"Audio timeline canvas"})})},et=["var(--nice-primary, #2196f3)","var(--nice-danger, #e53935)","var(--nice-warning, #ffeb3b)","var(--nice-success, #43a047)","var(--nice-warning, #ff9800)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-warning, #ffc107)","var(--nice-success, #8bc34a)","var(--nice-danger, #f44336)","var(--nice-accent, #3f51b5)","var(--nice-text-secondary, #607d8b)","var(--nice-warning-dark, #795548)","var(--nice-warning, #cddc39)","var(--nice-accent, #673ab7)","var(--nice-success, #009688)"];function rd(e){for(const t of et)if(!e.includes(t))return t;return et[Math.floor(Math.random()*et.length)]}const ur=et.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function ad(e){for(let t=0;t<et.length;t++){const n=et[t],a=ur[t];if(!e.includes(n)&&!e.includes(a))return a}return ur[Math.floor(Math.random()*ur.length)]}const sd="_panel_3bj7x_3",id="_panelCompact_3bj7x_19",od="_panelNarrow_3bj7x_25",ld="_panelWide_3bj7x_31",cd="_heading_3bj7x_37",dd="_row_3bj7x_53",ud="_field_3bj7x_65",hd="_buttonRow_3bj7x_71",pd="_sliderW200_3bj7x_83",fd="_sliderW240_3bj7x_89",md="_selectW160_3bj7x_95",gd="_inputW120_3bj7x_101",yd="_inputW160_3bj7x_107",vd="_inputW200_3bj7x_113",bd="_noteText_3bj7x_123",xd="_noteTextMargin_3bj7x_131",Sd="_presetDivider_3bj7x_145",wd="_presetLabel_3bj7x_159",kd="_countInAlert_3bj7x_173",Cd="_levelLabel_3bj7x_181",jd="_levelMeter_3bj7x_189",Md="_levelBar_3bj7x_205",Rd="_panelInactive_3bj7x_225",Nd="_header_3bj7x_231",Td="_title_3bj7x_245",$d="_grid2_3bj7x_257",Pd="_full_3bj7x_267",Ad="_label_3bj7x_275",Ed="_grow_3bj7x_291",Id="_pushRight_3bj7x_299",Ld="_alignStart_3bj7x_305",zd="_toolbar_3bj7x_311",Dd="_subPanel_3bj7x_325",ye={panel:sd,panelCompact:id,panelNarrow:od,panelWide:ld,heading:cd,row:dd,field:ud,buttonRow:hd,sliderW200:pd,sliderW240:fd,selectW160:md,inputW120:gd,inputW160:yd,inputW200:vd,noteText:bd,noteTextMargin:xd,presetDivider:Sd,presetLabel:wd,countInAlert:kd,levelLabel:Cd,levelMeter:jd,levelBar:Md,panelInactive:Rd,header:Nd,title:Td,grid2:$d,full:Pd,label:Ad,grow:Ed,pushRight:Id,alignStart:Ld,toolbar:zd,subPanel:Dd},$t=e=>Array.isArray(e)?e[0]??"":e,Li=({autoSaveMode:e,setAutoSaveMode:t,autoSaveInterval:n,setAutoSaveInterval:a})=>{const{t:s}=Te();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(se.NiceSelect,{label:s("editorPanels.autoSaveMode","Auto-save mode"),size:"sm",value:e,onChange:i=>t($t(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(se.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}=Te();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(se.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(se.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.")})]})},bs=e=>`${e.toFixed(1)}x`,Aa=({zoom:e,setZoom:t,uiZoom:n,setUiZoom:a,snapEnabled:s,onToggleSnap:i,snapMode:l,onSnapModeChange:o,bpm:c,setBpm:d})=>{const{t:h}=Te();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(se.NiceSlider,{label:h("editorPanels.zoom","Zoom"),size:"sm",min:.5,max:5,step:.1,value:e,onChange:t,showValue:!0,formatValue:bs})}),r.jsx("div",{className:ye.sliderW200,children:r.jsx(se.NiceSlider,{label:h("editorPanels.uiZoom","Zoom UI"),size:"sm",min:1,max:4,step:.1,value:n,onChange:a,showValue:!0,formatValue:bs})}),r.jsx(se.NiceCheckbox,{label:h("editorPanels.snap","Snap"),size:"sm",checked:s,onChange:()=>i()}),s&&r.jsx("div",{className:ye.selectW160,children:r.jsx(se.NiceSelect,{size:"sm","aria-label":h("editorPanels.snapTo","Snap to"),value:l,onChange:f=>o($t(f)),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(se.NiceNumberInput,{label:"BPM",size:"sm",min:20,max:300,value:c,onChange:f=>d(f??c)})})]})})},_d=[["peaking","Peaking"],["lowpass","Low-pass"],["highpass","High-pass"],["lowshelf","Low shelf"],["highshelf","High shelf"],["notch","Notch"],["bandpass","Band-pass"]],Di=({masterVolume:e,onMasterVolumeChange:t,filterType:n,filterFreq:a,filterQ:s,filterGain:i,onFilterChange:l,masterEQPresets:o,customPresets:c,onLoadPreset:d,onSavePreset:h,onDeletePreset:f})=>{const{t:p}=Te(),[y,g]=u.useState(""),x=()=>{y.trim()&&(h(y.trim()),g(""))};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(se.NiceSlider,{label:p("editorPanels.masterVolume","Master Vol"),size:"sm",min:0,max:1,step:.01,value:e,onChange:t,showValue:!0,formatValue:v=>`${Math.round(v*100)}%`})}),r.jsx("div",{className:ye.selectW160,children:r.jsx(se.NiceSelect,{label:p("editorPanels.filter","Filter"),size:"sm",value:n,onChange:v=>l({type:$t(v)}),options:_d.map(([v,m])=>({value:v,label:p(`editorPanels.filter.${v}`,m)}))})}),r.jsx("div",{className:ye.sliderW240,children:r.jsx(se.NiceSlider,{label:p("editorPanels.frequency","Freq"),size:"sm",min:40,max:12e3,step:10,value:a,onChange:v=>l({frequency:v}),showValue:!0,formatValue:v=>`${Math.round(v)} Hz`})}),r.jsx("div",{className:ye.sliderW200,children:r.jsx(se.NiceSlider,{label:"Q",size:"sm",min:.1,max:12,step:.1,value:s,onChange:v=>l({q:v}),showValue:!0,formatValue:v=>v.toFixed(1)})}),(n==="peaking"||n==="lowshelf"||n==="highshelf")&&r.jsx("div",{className:ye.sliderW200,children:r.jsx(se.NiceSlider,{label:p("editorPanels.gain","Gain"),size:"sm",min:-18,max:18,step:.5,value:i,onChange:v=>l({gain:v}),showValue:!0,formatValue:v=>`${v.toFixed(1)} dB`})})]}),r.jsxs("div",{className:ye.presetDivider,children:[r.jsxs("div",{className:ye.row,children:[r.jsxs("span",{className:ye.presetLabel,children:[p("editorPanels.eqPresets","EQ Presets"),":"]}),[...o,...c].map(v=>r.jsx(se.NiceButton,{variant:"outline",size:"xs",onClick:()=>d(v),children:v.name},v.name)),c.length>0&&r.jsx("div",{className:ye.selectW160,children:r.jsx(se.NiceSelect,{size:"sm","aria-label":p("editorPanels.deletePreset","Delete preset..."),placeholder:p("editorPanels.deletePreset","Delete preset..."),value:"",onChange:v=>{const m=$t(v);m&&f(m)},options:c.map(v=>({value:v.name,label:v.name}))})})]}),r.jsxs("div",{className:ye.row,children:[r.jsx("div",{className:ye.inputW200,children:r.jsx(se.NiceTextInput,{size:"sm",controlWidth:"100%","aria-label":p("editorPanels.presetName","Preset name..."),placeholder:p("editorPanels.presetName","Preset name..."),value:y,onChange:g,onKeyDown:v=>v.key==="Enter"&&x()})}),r.jsx(se.NiceButton,{variant:"success",size:"xs",onClick:x,disabled:!y.trim(),children:p("editorPanels.saveCurrent","Save Current")})]})]})]})},_i=({countInBars:e,setCountInBars:t,isCountIn:n,countInRemaining:a,overdubEnabled:s,setOverdubEnabled:i,punchIn:l,setPunchIn:o,punchOut:c,setPunchOut:d,monitorLevel:h})=>{const{t:f}=Te();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(se.NiceNumberInput,{label:f("editorPanels.countIn","Count-in (bars)"),size:"sm",min:0,max:8,step:1,value:e,onChange:p=>t(p??0)})}),n&&r.jsx("span",{className:ye.countInAlert,children:f("editorPanels.countInRemaining","Count-in: {seconds}s").replace("{seconds}",a.toFixed(1))}),r.jsx(se.NiceCheckbox,{label:f("editorPanels.overdub","Overdub (play background)"),size:"sm",checked:s,onChange:i}),r.jsx("div",{className:ye.inputW160,children:r.jsx(se.NiceNumberInput,{label:f("editorPanels.punchIn","Punch In (s)"),size:"sm",min:0,step:.1,value:l,onChange:o})}),r.jsx("div",{className:ye.inputW160,children:r.jsx(se.NiceNumberInput,{label:f("editorPanels.punchOut","Punch Out (s)"),size:"sm",min:0,step:.1,value:c,onChange:d})}),r.jsx(se.NiceButton,{variant:"outline",size:"xs",onClick:()=>{o(null),d(null)},children:f("editorPanels.clearPunch","Clear punch")}),r.jsx("div",{className:ye.levelLabel,children:f("editorPanels.level","Level")}),r.jsx("div",{className:ye.levelMeter,role:"meter","aria-label":f("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)"}})})]})})},Fd=[{id:1,name:"Audio 1",type:"audio",color:et[0],volume:.8,audioBlob:null},{id:2,name:"MIDI 1",type:"midi",color:et[1],volume:.8,notes:[]}],Od=({initialTracks:e,tracks:t,onTracksChange:n,initialBpm:a=120,duration:s=30,height:i=480,title:l="Untitled project",displayMode:o="standard",onNew:c,onOpen:d,onSave:h,onExport:f,t:p})=>{var H,ie;const{t:y}=Te(),g=p??y,[x,v]=u.useState(o),m=x==="advanced",S=x!=="basic",[b,w]=u.useState(e??Fd),N=t??b,R=u.useCallback(re=>{t===void 0&&w(re),n==null||n(re)},[t,n]),[P,j]=u.useState(!1),[M,I]=u.useState(0),[T,E]=u.useState(1),[_,D]=u.useState(2),[q,te]=u.useState(!0),[z,U]=u.useState("beat"),[Z,ae]=u.useState(a),[Y,O]=u.useState(80),[C,$]=u.useState(((H=N[0])==null?void 0:H.id)??null),k=u.useRef(0),W=u.useRef(0);u.useEffect(()=>{if(!P)return;W.current=performance.now();const re=he=>{const J=(he-W.current)/1e3;W.current=he,I(ue=>{const me=ue+J;return me>=s?(j(!1),s):me}),k.current=requestAnimationFrame(re)};return k.current=requestAnimationFrame(re),()=>cancelAnimationFrame(k.current)},[P,s]);const A=u.useCallback((re,he)=>R(N.map(J=>J.id===re?{...J,...he}:J)),[N,R]),L=u.useCallback(re=>{const he=N.reduce((ue,me)=>Math.max(ue,me.id),0)+1,J=N.filter(ue=>ue.type===re).length+1;R([...N,{id:he,name:`${re==="audio"?"Audio":"MIDI"} ${J}`,type:re,color:et[N.length%et.length],volume:.8,...re==="audio"?{audioBlob:null}:{notes:[]}}]),$(he)},[N,R]),G=u.useCallback(re=>R(N.filter(he=>he.id!==re)),[N,R]),F=u.useCallback(()=>{if(c){c();return}R([]),I(0),j(!1)},[c,R]),V=u.useCallback((re,he,J,ue)=>{const me=N.find(xe=>xe.id===re),Se=(me==null?void 0:me.notes)??[],de=Se.reduce((xe,Me)=>Math.max(xe,Me.id),0)+1;A(re,{notes:[...Se,{id:de,pitch:he,start:J,duration:ue,velocity:100}]})},[N,A]),Q=u.useCallback((re,he)=>{const J=N.find(ue=>ue.id===re);A(re,{notes:((J==null?void 0:J.notes)??[]).filter(ue=>ue.id!==he)})},[N,A]),le=u.useMemo(()=>{const re=Math.floor(M/60),he=Math.floor(M%60),J=Math.floor(M%1*100);return`${re}:${he.toString().padStart(2,"0")}.${J.toString().padStart(2,"0")}`},[M]),oe=u.useMemo(()=>{const re=(J,ue)=>({id:`mode-${J}`,label:`${x===J?"• ":" "}${ue}`,onClick:()=>v(J)}),he=[{id:"file",label:g("studio.menu.file","File"),children:[{id:"new",label:g("studio.menu.new","New"),onClick:F},...d?[{id:"open",label:g("studio.menu.open","Open…"),onClick:d}]:[],{id:"save",label:g("studio.menu.save","Save"),onClick:()=>h==null?void 0:h(N)},{id:"export",label:g("studio.menu.export","Export…"),onClick:()=>f==null?void 0:f(N)}]}];return S&&he.push({id:"edit",label:g("studio.menu.edit","Edit"),children:[{id:"add-audio",label:g("studio.addAudio","Add audio track"),onClick:()=>L("audio")},{id:"add-midi",label:g("studio.addMidi","Add MIDI track"),onClick:()=>L("midi")}]}),he.push({id:"view",label:g("studio.menu.view","View"),children:[{id:"modes",label:g("studio.menu.modes","Display mode"),divider:!1,disabled:!0},re("basic",g("studio.mode.basic","Basic")),re("standard",g("studio.mode.standard","Standard")),re("advanced",g("studio.mode.advanced","Advanced")),{id:"d1",divider:!0},{id:"snap",label:`${q?"• ":" "}${g("studio.snap","Snap to grid")}`,onClick:()=>te(J=>!J)}]}),he.push({id:"help",label:g("studio.menu.help","Help"),children:[{id:"about",label:g("studio.menu.about","About NiceAudioStudio"),disabled:!0}]}),he},[g,x,S,q,F,d,h,f,N,L]),ne=r.jsxs(r.Fragment,{children:[r.jsxs(se.NiceButton,{variant:"primary",size:"sm",onClick:()=>j(re=>!re),children:[P?r.jsx(B.NtdPause,{size:14}):r.jsx(B.NtdPlay,{size:14})," ",P?g("studio.pause","Pause"):g("studio.play","Play")]}),r.jsxs(se.NiceButton,{variant:"secondary",size:"sm",onClick:()=>{j(!1),I(0)},children:[r.jsx(B.NtdStop,{size:14})," ",g("studio.stop","Stop")]}),r.jsx("span",{style:{fontVariantNumeric:"tabular-nums",fontWeight:700,minWidth:80},children:le}),r.jsx("span",{style:{flex:1}}),r.jsxs(se.NiceButton,{variant:"outline",size:"sm",onClick:()=>L("audio"),children:[r.jsx(B.NtdPlus,{size:14})," ",g("studio.addAudio","Audio")]}),S&&r.jsxs(se.NiceButton,{variant:"outline",size:"sm",onClick:()=>L("midi"),children:[r.jsx(B.NtdPlus,{size:14})," ",g("studio.addMidi","MIDI")]}),r.jsx("span",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:g("studio.master","Master")}),r.jsx("div",{style:{width:90},children:r.jsx(se.NiceSlider,{value:Y,onChange:O,min:0,max:100})})]}),K=r.jsxs(r.Fragment,{children:[r.jsxs("span",{children:[Z," BPM"]}),r.jsx("span",{children:"·"}),r.jsx("span",{style:{fontVariantNumeric:"tabular-nums"},children:le}),r.jsx("span",{children:"·"}),r.jsxs("span",{children:[N.length," ",g("studio.tracks","tracks")]}),m&&C!=null&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"·"}),r.jsxs("span",{children:[g("studio.active","Active"),": ",((ie=N.find(re=>re.id===C))==null?void 0:ie.name)??"—"]})]}),r.jsx("span",{style:{flex:1}}),r.jsx("span",{style:{textTransform:"capitalize"},children:x})]});return r.jsxs(se.NiceAppShell,{className:"nice-audio-studio",height:i,menubar:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[r.jsx(se.NiceMenu,{items:oe,orientation:"horizontal"}),r.jsx("span",{style:{color:"var(--nice-text-secondary)",fontSize:13},children:l})]}),toolbar:ne,statusBar:K,children:[S&&r.jsx("div",{style:{padding:"6px 12px",borderBottom:"1px solid var(--nice-border-color)"},children:r.jsx(Aa,{zoom:T,setZoom:E,uiZoom:_,setUiZoom:D,snapEnabled:q,onToggleSnap:()=>te(re=>!re),snapMode:z,onSnapModeChange:U,bpm:Z,setBpm:ae})}),r.jsx("div",{style:{padding:8},children:r.jsx(Ii,{zoom:T,duration:s,isPlaying:P,isRecording:!1,currentTime:M,bpm:Z,snapEnabled:q,snapMode:z,onCurrentTimeChange:I,onZoomChange:E})}),N.length===0?r.jsx("div",{style:{padding:32,textAlign:"center",color:"var(--nice-text-muted, #94a3b8)"},children:g("studio.empty","No tracks — add an audio or MIDI track to start.")}):N.map(re=>r.jsxs("div",{style:{display:"flex",gap:8,padding:8,borderTop:"1px solid var(--nice-border-color)",background:C===re.id?"color-mix(in srgb, var(--nice-color-primary) 8%, transparent)":"transparent"},onClick:()=>$(re.id),children:[r.jsxs("div",{style:{flex:"0 0 180px",display:"flex",flexDirection:"column",gap:6},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:re.color||et[0],flex:"0 0 auto"}}),r.jsx("div",{style:{flex:1},children:r.jsx(se.NiceTextInput,{value:re.name,onChange:he=>A(re.id,{name:he}),size:"sm"})})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[r.jsx(se.NiceButton,{variant:re.muted?"danger":"ghost",size:"sm",onClick:()=>A(re.id,{muted:!re.muted}),children:"M"}),S&&r.jsx(se.NiceButton,{variant:re.solo?"warning":"ghost",size:"sm",onClick:()=>A(re.id,{solo:!re.solo}),children:"S"}),r.jsx("div",{style:{flex:1},children:r.jsx(se.NiceSlider,{value:Math.round((re.volume??.8)*100),onChange:he=>A(re.id,{volume:he/100}),min:0,max:100})}),r.jsx(se.NiceButton,{variant:"ghost",size:"sm",onClick:()=>G(re.id),children:r.jsx(B.NtdClose,{size:14})})]})]}),r.jsx("div",{style:{flex:1,minWidth:0,opacity:re.muted?.5:1},children:re.type==="audio"?r.jsx($i,{audioBlob:re.audioBlob??null,currentTime:M,duration:s,zoom:T,height:80,waveColor:re.color,onSeek:I}):r.jsx(Pa,{notes:re.notes??[],onAddNote:(he,J,ue)=>V(re.id,he,J,ue),onRemoveNote:he=>Q(re.id,he),duration:s,zoom:T})})]},re.id))]})};function Fi(e){return{past:[],present:e,future:[]}}function Oi(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function Bi(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 Gi(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 Wi(e){return e.past.length>0}function Ui(e){return e.future.length>0}function da(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>({...n}))}function Vi(e,t,n){if(t.length===0)return e;const a=Math.min(...t.map(l=>l.time)),s=n-a,i=t.map(l=>({...l,id:Date.now()+Math.floor(Math.random()*1e4)+l.id,time:l.time+s}));return[...e,...i]}function qi(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 Hi(e,t){return e.filter(n=>n.time<t.start||n.time>t.end)}function Bd(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>n.id)}function Ki(e,t,n,a){const s={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:a};return[...e,s]}function Yi(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 Zi(e){return JSON.stringify(e,null,2)}function Xi(e){try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&"id"in n&&"cc"in n&&"value"in n&&"time"in n):[]}catch{return[]}}function yt(e,t){var n;return((n=e.find(a=>a.layerId===t))==null?void 0:n.events)??[]}function Mt(e,t,n){return e.find(s=>s.layerId===t)?e.map(s=>s.layerId===t?{...s,events:n}:s):[...e,{layerId:t,events:n}]}function Gd(e,t){switch(t.type){case"UNDO":return Bi(e);case"REDO":return Gi(e);default:{let n=e.present;switch(t.type){case"ADD_EVENT":{const a=[...yt(n,t.layerId),t.event];n=Mt(n,t.layerId,a);break}case"UPDATE_EVENT":{const a=yt(n,t.layerId).map(s=>s.id===t.id?{...s,value:t.value,time:t.time,handleType:t.handleType??s.handleType}:s);n=Mt(n,t.layerId,a);break}case"REMOVE_EVENT":{const a=yt(n,t.layerId).filter(s=>s.id!==t.id);n=Mt(n,t.layerId,a);break}case"SET_EVENTS":n=Mt(n,t.layerId,t.events);break;case"PASTE":{const a=yt(n,t.layerId),s=Vi(a,t.clipboard,t.targetTime);n=Mt(n,t.layerId,s);break}case"CUT":{const a=yt(n,t.layerId),{remaining:s}=qi(a,t.range);n=Mt(n,t.layerId,s);break}case"DELETE_RANGE":{const a=yt(n,t.layerId),s=Hi(a,t.range);n=Mt(n,t.layerId,s);break}case"RECORD":{const a=yt(n,t.layerId),s=Ki(a,t.cc,t.value,t.time);n=Mt(n,t.layerId,s);break}case"THIN":{const a=yt(n,t.layerId),s=Yi(a,t.keepEveryN);n=Mt(n,t.layerId,s);break}case"IMPORT":{const a=Xi(t.json);a.length>0&&(n=Mt(n,t.layerId,a));break}}return Oi(e,n)}}}function Qi(e=[]){const[t,n]=u.useReducer(Gd,Fi(e)),a=u.useRef([]),s=u.useCallback(b=>yt(t.present,b),[t.present]),i=u.useCallback((b,w)=>n({type:"ADD_EVENT",layerId:b,event:w}),[]),l=u.useCallback((b,w,N,R,P)=>n({type:"UPDATE_EVENT",layerId:b,id:w,value:N,time:R,handleType:P}),[]),o=u.useCallback((b,w)=>n({type:"REMOVE_EVENT",layerId:b,id:w}),[]),c=u.useCallback((b,w)=>n({type:"SET_EVENTS",layerId:b,events:w}),[]),d=u.useCallback(()=>n({type:"UNDO"}),[]),h=u.useCallback(()=>n({type:"REDO"}),[]),f=u.useCallback((b,w)=>{a.current=da(yt(t.present,b),w)},[t.present]),p=u.useCallback((b,w)=>{a.current=da(yt(t.present,b),w),n({type:"CUT",layerId:b,range:w})},[t.present]),y=u.useCallback((b,w)=>{a.current.length>0&&n({type:"PASTE",layerId:b,clipboard:a.current,targetTime:w})},[]),g=u.useCallback((b,w)=>n({type:"DELETE_RANGE",layerId:b,range:w}),[]),x=u.useCallback((b,w,N,R)=>n({type:"RECORD",layerId:b,cc:w,value:N,time:R}),[]),v=u.useCallback((b,w)=>n({type:"THIN",layerId:b,keepEveryN:w}),[]),m=u.useCallback(b=>Zi(yt(t.present,b)),[t.present]),S=u.useCallback((b,w)=>n({type:"IMPORT",layerId:b,json:w}),[]);return{snapshots:t.present,getEvents:s,addEvent:i,updateEvent:l,removeEvent:o,setEvents:c,undo:d,redo:h,canUndo:Wi(t),canRedo:Ui(t),copy:f,cut:p,paste:y,clipboard:a.current,deleteRange:g,record:x,thin:v,exportLane:m,importLane:S}}let Wd=Date.now();function yn(){return Wd++}function Ud(e,t,n=.01){if(e.length===0)return[];const a=[];let s=-1/0;for(const i of e)i.time-s>=n&&(a.push({id:yn(),cc:t,value:vn(i.value),time:i.time}),s=i.time);return a}function xs(e,t,n,a=32){const s=[];for(let i=0;i<=a;i++){const l=i/a;s.push({id:yn(),cc:n,value:vn(jr(e.value,t.value,l)),time:jr(e.time,t.time,l)})}return s}function Vd(e,t,n,a,s=48){const i=[];for(let l=0;l<=s;l++){const o=l/s,c=Ss(e.time,t.time,n.time,o),d=Ss(e.value,t.value,n.value,o);i.push({id:yn(),cc:a,value:vn(d),time:c})}return i}function qd(e,t,n,a=8){const s=[],i=(t.time-e.time)/a,l=(t.value-e.value)/a;for(let o=0;o<a;o++){const c=e.time+o*i,d=vn(e.value+o*l);s.push({id:yn(),cc:n,value:d,time:c}),s.push({id:yn(),cc:n,value:d,time:c+i-.001})}return s}function Hd(e,t,n,a=2,s=32){const i=[];for(let l=0;l<=s;l++){const o=l/s,c=Math.pow(o,a);i.push({id:yn(),cc:n,value:vn(jr(e.value,t.value,c)),time:jr(e.time,t.time,o)})}return i}function Kd(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)),l=Math.min(n.length,i+t),o=n.slice(i,l),c=o.reduce((d,h)=>d+h.value,0)/o.length;return{...a,value:vn(Math.round(c))}})}function Yd(e,t){let n;switch(e.mode){case"pencil":n=Ud(t,e.cc,e.resolution);break;case"line":n=t.length>=2?xs(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?n=Vd(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?n=xs(t[0],t[t.length-1],e.cc):n=[];break;case"step":n=t.length>=2?qd(t[0],t[t.length-1],e.cc):[];break;case"ramp":n=t.length>=2?Hd(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=Kd(n,a)}return n}function vn(e){return Math.max(0,Math.min(127,Math.round(e)))}function jr(e,t,n){return e+(t-e)*n}function Ss(e,t,n,a){const s=1-a;return s*s*e+2*s*a*t+a*a*n}function zr(){return{waveform:"sine",rate:1,depth:.5,phase:0,center:.5,syncToBpm:!1,syncDivision:"1/4",enabled:!0}}const Zd={"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 Ji(e,t){return e/60*Zd[t]/4}function eo(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 Ea(e,t,n){if(!e.enabled)return e.center;const a=e.syncToBpm&&n?Ji(n,e.syncDivision):e.rate,s=t*a+e.phase/(2*Math.PI),i=eo(e.waveform,s),l=e.center+i*e.depth*.5;return Math.max(0,Math.min(1,l))}function Ia(e,t,n){return Math.round(Ea(e,t,n)*127)}function to(e,t,n,a,s=30,i){const l=n-t,o=Math.max(2,Math.ceil(l*s)),c=[];for(let d=0;d<=o;d++){const h=t+d/o*l,f=Ia(e,h,i);c.push({time:h,value:f,cc:a})}return c}function no(e,t,n,a=2,s,i=200){const l=[];for(let o=0;o<=i;o++){const c=o/i*a,d=Ea(e,c,s);l.push({x:o/i*t,y:(1-d)*n})}return l}function Xd(e){return JSON.stringify(e,null,2)}function Qd(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const Yr=140,bn=24,Jd=[{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"}],eu=[{mode:"pencil",label:"Pencil"},{mode:"line",label:"Line"},{mode:"curve",label:"Curve"},{mode:"step",label:"Step"},{mode:"ramp",label:"Ramp"}],tu=["sine","triangle","sawtooth","square","random","sample-hold"],nu=({layerId:e=0,ccNumber:t,duration:n=8,zoom:a=1,automation:s,onChangeCCNumber:i})=>{const l=Qi(),o=s??l,[c,d]=we.useControllableState({value:t,fallbackValue:1,onChange:i,componentName:"NiceCCAutomationLaneEditor"}),{t:h}=Te(),f=u.useRef(null),[p,y]=u.useState("pencil"),[g,x]=u.useState(!1),v=u.useRef([]),[m,S]=u.useState(null),[b,w]=u.useState(!1),[N,R]=u.useState(zr()),P=u.useRef(null),j=o.getEvents(e),M=j.filter(C=>C.cc===c),I=Math.max(400,n*30*a),T=u.useCallback(C=>C/I*n,[I,n]),E=u.useCallback(C=>Math.round(Math.max(0,Math.min(127,127-(C-bn)/Yr*127))),[]),_=u.useCallback(C=>C/n*I,[I,n]),D=u.useCallback(C=>bn+(127-C)/127*Yr,[]),q=u.useCallback(()=>{const C=f.current;if(!C)return;const $=C.getContext("2d");if(!$)return;const k=C.width,W=C.height;$.clearRect(0,0,k,W),$.fillStyle=we.resolveCssColor("var(--nice-bg, #1a1a2e)",$.canvas),$.fillRect(0,0,k,W);const A=we.resolveCssColor("var(--nice-border-color, #cbd5e1)",$.canvas);$.strokeStyle=A,$.lineWidth=1,$.globalAlpha=.5;for(let F=0;F<=127;F+=16){const V=D(F);$.beginPath(),$.moveTo(0,V),$.lineTo(k,V),$.stroke()}$.globalAlpha=1,$.fillStyle=we.resolveCssColor("var(--nice-text-muted, #64748b)",$.canvas),$.font="10px monospace",$.textBaseline="middle";for(const F of[0,32,64,96,127])$.fillText(String(F),2,D(F));$.strokeStyle=A,$.globalAlpha=.3;for(let F=0;F<=n;F++){const V=_(F);$.beginPath(),$.moveTo(V,0),$.lineTo(V,W),$.stroke()}$.globalAlpha=1;const L=[...M].sort((F,V)=>F.time-V.time);if(L.length>0){$.beginPath(),$.moveTo(_(L[0].time),W-bn);for(const F of L)$.lineTo(_(F.time),D(F.value));$.lineTo(_(L[L.length-1].time),W-bn),$.closePath(),$.fillStyle=we.resolveCssColor("var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",$.canvas),$.fill(),$.beginPath(),$.strokeStyle=we.resolveCssColor("var(--nice-primary, #3b82f6)",$.canvas),$.lineWidth=2;for(let F=0;F<L.length;F++){const V=_(L[F].time),Q=D(L[F].value);F===0?$.moveTo(V,Q):((L[F].handleType??"linear")==="step"&&$.lineTo(V,D(L[F-1].value)),$.lineTo(V,Q))}$.stroke();for(const F of L){const V=_(F.time),Q=D(F.value),le=m===F.id;$.beginPath(),$.arc(V,Q,le?6:4,0,Math.PI*2),$.fillStyle=we.resolveCssColor(le?"var(--nice-primary-light, #60a5fa)":"var(--nice-primary, #3b82f6)",$.canvas),$.fill(),$.strokeStyle=we.resolveCssColor("var(--nice-bg, #fff)",$.canvas),$.lineWidth=1.5,$.stroke()}}$.strokeStyle=A,$.lineWidth=1,$.setLineDash([4,4]);const G=D(0);$.beginPath(),$.moveTo(0,G),$.lineTo(k,G),$.stroke(),$.setLineDash([])},[M,n,I,_,D,m]);u.useEffect(()=>{q()},[q]);const te=C=>{var A;const $=(A=f.current)==null?void 0:A.getBoundingClientRect();if(!$)return;const k=C.clientX-$.left,W=C.clientY-$.top;p==="pencil"?(x(!0),v.current=[{time:T(k),value:E(W)}]):(x(!0),v.current=[{time:T(k),value:E(W)}])},z=C=>{var G;const $=(G=f.current)==null?void 0:G.getBoundingClientRect();if(!$)return;const k=C.clientX-$.left,W=C.clientY-$.top;g&&v.current.push({time:T(k),value:E(W)});const A=[...M].sort((F,V)=>F.time-V.time);let L=null;for(const F of A){const V=_(F.time),Q=D(F.value);if(Math.abs(k-V)<8&&Math.abs(W-Q)<8){L=F.id;break}}S(L)},U=()=>{if(!g)return;x(!1);const C=v.current;if(C.length===0)return;const $=Yd({mode:p,cc:c,resolution:.02,smoothing:p==="pencil"?.3:0},C);$.length>0&&o.setEvents(e,[...j,...$]),v.current=[]},Z=C=>{var A;const $=(A=f.current)==null?void 0:A.getBoundingClientRect();if(!$)return;const k=C.clientX-$.left,W=C.clientY-$.top;for(const L of M){const G=_(L.time),F=D(L.value);if(Math.abs(k-G)<8&&Math.abs(W-F)<8){o.removeEvent(e,L.id);return}}o.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:c,value:E(W),time:T(k)})},ae=()=>{const $=to(N,0,n,c,Math.ceil(n*20),120).map((k,W)=>({...k,id:Date.now()+W}));o.setEvents(e,[...j,...$]),w(!1)},Y=()=>{const C=o.exportLane(e),$=new Blob([C],{type:"application/json"}),k=URL.createObjectURL($),W=document.createElement("a");W.href=k,W.download=`cc-lane-${c}-layer-${e}.json`,document.body.appendChild(W),W.click(),W.remove(),URL.revokeObjectURL(k)},O=C=>{var k;const $=(k=C.target.files)==null?void 0:k[0];$&&($.text().then(W=>{o.importLane(e,W)}),P.current&&(P.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(se.NiceSelect,{size:"sm",controlWidth:180,"aria-label":h("ccLane.controller","Controller"),value:String(c),onChange:C=>d(Number($t(C))),options:Jd.map(C=>({value:String(C.cc),label:`${h(`ccLane.preset.${C.key}`,C.label)} (CC${C.cc})`}))}),r.jsx(se.NiceSegmentedControl,{size:"sm",value:p,onChange:y,options:eu.map(C=>({value:C.mode,label:h(`ccLane.mode.${C.mode}`,C.label)}))}),r.jsx(se.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(B.NtdUndo,{size:14}),ariaLabel:h("ccLane.undo","Undo"),title:h("ccLane.undo","Undo"),onClick:o.undo,disabled:!o.canUndo,children:null}),r.jsx(se.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(B.NtdRedo,{size:14}),ariaLabel:h("ccLane.redo","Redo"),title:h("ccLane.redo","Redo"),onClick:o.redo,disabled:!o.canRedo,children:null})]}),r.jsxs("div",{className:ye.toolbar,children:[r.jsx(se.NiceButton,{size:"sm",variant:b?"primary":"outline","aria-pressed":b,onClick:()=>w(!b),title:h("ccLane.lfoHint","Apply LFO modulation"),children:h("ccLane.lfo","LFO")}),r.jsx(se.NiceButton,{size:"sm",variant:"outline",onClick:Y,title:h("ccLane.exportHint","Export CC lane as JSON"),children:h("ccLane.export","Export")}),r.jsx(se.NiceButton,{size:"sm",variant:"outline",onClick:()=>{var C;return(C=P.current)==null?void 0:C.click()},title:h("ccLane.importHint","Import CC lane from JSON"),children:h("ccLane.import","Import")}),r.jsx("input",{ref:P,type:"file",accept:".json",hidden:!0,onChange:O}),r.jsx(se.NiceButton,{size:"sm",variant:"danger",onClick:()=>o.setEvents(e,j.filter(C=>C.cc!==c)),title:h("ccLane.clearHint","Clear all CC events for this lane"),children:h("ccLane.clear","Clear")}),r.jsxs("span",{className:`${ye.noteText} ${ye.pushRight}`,children:[M.length," ",h("ccLane.events","events")]})]}),b&&r.jsxs("div",{className:ye.subPanel,children:[r.jsxs("div",{className:`${ye.row} ${ye.alignStart} ${ye.field}`,children:[r.jsx(se.NiceSelect,{size:"sm",controlWidth:130,label:h("ccLane.lfoWave","Wave"),value:N.waveform,onChange:C=>R($=>({...$,waveform:$t(C)})),options:tu.map(C=>({value:C,label:C}))}),r.jsx(se.NiceNumberInput,{size:"sm",className:ye.inputW120,label:h("ccLane.lfoRate","Rate (Hz)"),min:.01,max:20,step:.1,precision:2,value:N.rate,onChange:C=>{C!==null&&R($=>({...$,rate:C}))}}),r.jsx("div",{className:ye.sliderW200,children:r.jsx(se.NiceSlider,{size:"sm",label:h("ccLane.lfoDepth","Depth"),min:0,max:1,step:.01,value:N.depth,onChange:C=>R($=>({...$,depth:C})),showValue:!0,formatValue:C=>C.toFixed(2)})}),r.jsx("div",{className:ye.sliderW200,children:r.jsx(se.NiceSlider,{size:"sm",label:h("ccLane.lfoCenter","Center"),min:0,max:1,step:.01,value:N.center,onChange:C=>R($=>({...$,center:C})),showValue:!0,formatValue:C=>C.toFixed(2)})})]}),r.jsxs("div",{className:ye.buttonRow,children:[r.jsx(se.NiceButton,{size:"sm",variant:"primary",onClick:ae,children:h("ccLane.applyLfo","Apply LFO")}),r.jsx(se.NiceButton,{size:"sm",variant:"outline",onClick:()=>w(!1),children:h("ccLane.cancel","Cancel")})]})]}),r.jsx("div",{style:{overflowX:"auto",borderRadius:6},children:r.jsx("canvas",{ref:f,width:I,height:Yr+bn*2,style:{cursor:g?"crosshair":m?"pointer":"crosshair",display:"block",borderRadius:6},onMouseDown:te,onMouseMove:z,onMouseUp:U,onMouseLeave:()=>{g&&U()},onDoubleClick:Z,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.")})]})},ro={"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":1/1.5,"1/8T":.5/1.5,"1/16T":.25/1.5},ua={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function ru(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 ao(e,t){if(e.length===0)return[];const n=ru(e,t.octaves),a=[...n].sort((l,o)=>l.pitch-o.pitch),s=[...n].sort((l,o)=>o.pitch-l.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((l,o)=>l.originalOrder-o.originalOrder);break;case"chord":i=n;break;default:i=a}if(t.repeats>1){const l=[];for(const o of i)for(let c=0;c<t.repeats;c++)l.push(o);i=l}return i}function au(e,t,n,a=0,s=1){const i=ao(e,t);if(i.length===0)return[];const l=60/n,o=ro[t.rate]*l,c=o*t.gate,d=[],h=t.mode==="chord",f=h?s:i.length*s;for(let p=0;p<f;p++){const y=p%2===1?o*t.swing*.5:0,g=a+p*o+y;if(h)for(const x of i){const v=t.velocityPattern?t.velocityPattern[p%t.velocityPattern.length]:x.velocity;d.push({pitch:x.pitch,velocity:v,startTime:g,duration:c,step:p})}else{const x=p%i.length,v=i[x],m=t.velocityPattern?t.velocityPattern[p%t.velocityPattern.length]:v.velocity;d.push({pitch:v.pitch,velocity:m,startTime:g,duration:c,step:p})}}return d}function so(){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 io(){return Object.keys(ro)}const ws=e=>`${Math.round(e*100)}%`,su=({config:e=ua,onChange:t=()=>{},active:n=!1,onToggleActive:a=()=>{}})=>{const{t:s}=Te(),i=so(),l=io(),o=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(se.NiceButton,{size:"sm",variant:n?"success":"outline","aria-pressed":n,onClick:a,children:n?s("arp.on","ON"):s("arp.off","OFF")}),r.jsx(se.NiceButton,{size:"sm",variant:e.latch?"warning":"outline","aria-pressed":!!e.latch,onClick:()=>o({latch:!e.latch}),title:s("arp.latchHint","Latch — keep arp running after releasing keys"),children:s("arp.latch","Latch")}),r.jsx(se.NiceButton,{size:"sm",variant:"outline",onClick:()=>t(ua),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(se.NiceSegmentedControl,{size:"sm",block:!0,value:e.mode,onChange:c=>o({mode:c}),options:i.map(c=>({value:c.mode,label:r.jsx("span",{title:c.description,children:c.label})}))})]}),r.jsx(se.NiceSelect,{size:"sm",label:s("arp.rate","Rate"),value:e.rate,onChange:c=>o({rate:$t(c)}),options:l.map(c=>({value:c,label:c}))}),r.jsx(se.NiceSlider,{size:"sm",label:s("arp.octaves","Octaves"),min:1,max:4,step:1,value:e.octaves,onChange:c=>o({octaves:c}),showValue:!0}),r.jsx(se.NiceSlider,{size:"sm",label:s("arp.gate","Gate"),min:.05,max:1,step:.05,value:e.gate,onChange:c=>o({gate:c}),showValue:!0,formatValue:ws}),r.jsx(se.NiceSlider,{size:"sm",label:s("arp.swing","Swing"),min:0,max:1,step:.01,value:e.swing,onChange:c=>o({swing:c}),showValue:!0,formatValue:ws}),r.jsx(se.NiceSlider,{size:"sm",label:s("arp.repeats","Repeats"),min:1,max:4,step:1,value:e.repeats,onChange:c=>o({repeats:c}),showValue:!0})]})]})},ks=e=>`${Math.round(e*100)}%`,iu=["sine","triangle","sawtooth","square","random","sample-hold"],ou=["1/1","1/2","1/4","1/8","1/16","1/32"],xn=200,en=48,lu=({config:e,onChange:t,index:n,onRemove:a})=>{const{t:s}=Te(),i=u.useRef(null),l=c=>t({...e,...c}),o=u.useCallback(()=>{const c=i.current;if(!c)return;const d=c.getContext("2d");if(!d)return;d.clearRect(0,0,xn,en),d.fillStyle=we.resolveCssColor("var(--nice-bg-secondary, #161b22)",d.canvas),d.fillRect(0,0,xn,en),d.strokeStyle=we.resolveCssColor("var(--nice-border-color, #cbd5e1)",d.canvas),d.lineWidth=1,d.setLineDash([3,3]),d.beginPath(),d.moveTo(0,en/2),d.lineTo(xn,en/2),d.stroke(),d.setLineDash([]);const h=no(e,xn,en);if(h.length>0){d.beginPath(),d.strokeStyle=we.resolveCssColor(e.enabled?"var(--nice-primary, #3b82f6)":"var(--nice-text-secondary, #484f58)",d.canvas),d.lineWidth=1.5;for(let f=0;f<h.length;f++){const p=h[f].x,y=h[f].y;f===0?d.moveTo(p,y):d.lineTo(p,y)}d.stroke()}},[e]);return u.useEffect(()=>{o()},[o]),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(se.NiceButton,{size:"xs",variant:e.enabled?"success":"outline","aria-pressed":e.enabled,onClick:()=>l({enabled:!e.enabled}),children:e.enabled?s("lfo.on","ON"):s("lfo.off","OFF")}),r.jsx(se.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(se.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:xn,height:en,style:{borderRadius:4,border:"1px solid var(--nice-border-color, #30363d)",flexShrink:0},role:"img","aria-label":s("lfo.preview","LFO waveform preview")}),r.jsxs("div",{className:ye.grow,children:[r.jsx("div",{className:ye.field,children:r.jsx(se.NiceSegmentedControl,{size:"xs",block:!0,value:e.waveform,onChange:c=>l({waveform:c}),options:iu.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(se.NiceSlider,{size:"xs",label:s("lfo.rate","Rate"),min:.01,max:20,step:.1,value:e.rate,onChange:c=>l({rate:c}),showValue:!0,formatValue:c=>`${c.toFixed(1)} Hz`}),r.jsx(se.NiceSlider,{size:"xs",label:s("lfo.depth","Depth"),min:0,max:1,step:.01,value:e.depth,onChange:c=>l({depth:c}),showValue:!0,formatValue:ks}),r.jsx(se.NiceSlider,{size:"xs",label:s("lfo.center","Center"),min:0,max:1,step:.01,value:e.center,onChange:c=>l({center:c}),showValue:!0,formatValue:ks}),r.jsx(se.NiceSlider,{size:"xs",label:s("lfo.phase","Phase"),min:0,max:360,step:1,value:e.phase,onChange:c=>l({phase:c}),showValue:!0,formatValue:c=>`${Math.round(c)}°`})]}),r.jsxs("div",{className:ye.row,children:[r.jsx(se.NiceCheckbox,{size:"xs",label:s("lfo.bpmSync","BPM Sync"),checked:e.syncToBpm,onChange:c=>l({syncToBpm:c})}),e.syncToBpm&&r.jsx(se.NiceSelect,{size:"xs","aria-label":s("lfo.syncDivision","Sync division"),value:e.syncDivision??"1/4",onChange:c=>l({syncDivision:$t(c)}),options:ou.map(c=>({value:c,label:c}))}),r.jsx(se.NiceNumberInput,{size:"xs",label:"CC",min:0,max:127,value:e.targetCC??1,onChange:c=>l({targetCC:c??1})})]})]})]})]})},cu=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],du=[16,32,64],uu=e=>`${Math.round(e*100)}%`;function Cs(e){const t=Math.floor(e/12)-1;return`${cu[e%12]}${t}`}const hu=({seq:e})=>{const{t}=Te(),n=e==null?void 0:e.pattern,a=u.useMemo(()=>n?n.steps.slice(0,n.length):[],[n]);if(!e||!n)return r.jsxs("div",{className: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,l=o=>c=>{var g;c.preventDefault();const d=c.currentTarget,h=d.getBoundingClientRect(),f=x=>e.setVelocity(o,Math.round(Math.max(1,Math.min(127,(1-(x-h.top)/h.height)*127)))),p=x=>f(x.clientY),y=()=>{d.removeEventListener("pointermove",p),d.removeEventListener("pointerup",y),d.removeEventListener("pointercancel",y)};(g=d.setPointerCapture)==null||g.call(d,c.pointerId),d.addEventListener("pointermove",p),d.addEventListener("pointerup",y),d.addEventListener("pointercancel",y),f(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(se.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(se.NiceNumberInput,{size:"sm",className:ye.inputW120,label:t("stepSeq.bpm","BPM"),min:20,max:300,value:n.bpm,onChange:o=>{o!==null&&e.setBpm(o)}}),r.jsx("div",{className:ye.sliderW200,children:r.jsx(se.NiceSlider,{size:"sm",label:t("stepSeq.swing","Swing"),min:0,max:1,step:.01,value:n.swing,onChange:e.setSwing,showValue:!0,formatValue:uu})}),r.jsxs("div",{children:[r.jsx("span",{className:ye.label,children:t("stepSeq.length","Steps")}),r.jsx(se.NiceSegmentedControl,{size:"sm",value:n.length,onChange:e.setLength,options:du.map(o=>({value:o,label:String(o)}))})]})]}),r.jsxs("div",{className:ye.toolbar,children:[r.jsx(se.NiceButton,{size:"sm",variant:"outline",onClick:()=>e.transpose(1),title:t("stepSeq.transposeUp","Transpose up one semitone"),children:"+1"}),r.jsx(se.NiceButton,{size:"sm",variant:"outline",onClick:()=>e.transpose(-1),title:t("stepSeq.transposeDown","Transpose down one semitone"),children:"-1"}),r.jsx(se.NiceButton,{size:"sm",variant:"outline",onClick:()=>e.transpose(12),title:t("stepSeq.octaveUpHint","Transpose up one octave"),children:t("stepSeq.octaveUp","+Oct")}),r.jsx(se.NiceButton,{size:"sm",variant:"outline",onClick:()=>e.transpose(-12),title:t("stepSeq.octaveDownHint","Transpose down one octave"),children:t("stepSeq.octaveDown","-Oct")}),r.jsx(se.NiceButton,{size:"sm",variant:"outline",onClick:e.reverse,children:t("stepSeq.reverse","Reverse")}),r.jsx(se.NiceButton,{size:"sm",variant:"outline",rightIcon:r.jsx(B.NtdArrowRight,{size:12}),onClick:()=>e.shift(1),children:t("stepSeq.shift","Shift")}),r.jsx(se.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(B.NtdArrowLeft,{size:12}),onClick:()=>e.shift(-1),children:t("stepSeq.shift","Shift")}),r.jsx(se.NiceButton,{size:"sm",variant:"outline",onClick:()=>e.randomizeVel(),title:t("stepSeq.randomVelocityHint","Randomize velocities"),children:t("stepSeq.randomVelocity","Rnd Vel")}),r.jsx(se.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((o,c)=>{const d=o.active,h=s===c,f=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:f?"var(--nice-text-muted, #8b949e)":"var(--nice-text-secondary, #30363d)"},children:c+1}),r.jsx("button",{type:"button","aria-pressed":d,"aria-label":`${t("stepSeq.step","Step")} ${c+1}${d?`, ${Cs(o.note)}`:""}`,onClick:()=>e.toggle(c),style:{width:32,height:32,borderRadius:4,border:h?"2px solid var(--nice-warning, #f0c040)":"1px solid var(--nice-border, #30363d)",background:d?`hsl(${210+o.velocity/127*40}, 80%, ${35+o.velocity/127*20}%)`:f?"var(--nice-bg-secondary, #21262d)":"var(--nice-bg-secondary, #161b22)",cursor:"pointer",padding:0,color:d?"var(--nice-color-white, #ffffff)":"var(--nice-text-secondary, #484f58)",fontSize:8,fontWeight:600,transition:"background 0.1s"},children:d?Cs(o.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")}: ${o.velocity}`,onPointerDown:l(c),children:r.jsx("div",{style:{position:"absolute",bottom:0,left:0,width:"100%",height:`${o.velocity/127*100}%`,background:d?"var(--nice-primary-tint-60, rgba(59, 130, 246, 0.6))":"var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",borderRadius:2,pointerEvents:"none"}})}),d&&o.probability<1&&r.jsxs("span",{style:{fontSize:8,color:"var(--nice-warning, #f0c040)"},children:[Math.round(o.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 pu(e,t,n){const[a,s]=u.useState("interval"),[i,l]=u.useState(30),o=u.useRef(null),c=u.useCallback(()=>{if(e)try{localStorage.setItem("audioEditor.autoSave",JSON.stringify(e)),t("Project auto-saved locally"),n("success"),setTimeout(()=>t(""),2e3)}catch(d){t("Auto-save error: "+d.message),n("error")}},[e,t,n]);return u.useEffect(()=>{(a==="onChange"||a==="both")&&c()},[e,a,c]),u.useEffect(()=>(o.current&&(clearInterval(o.current),o.current=null),(a==="interval"||a==="both")&&i>0&&(o.current=window.setInterval(c,i*1e3)),()=>{o.current&&(clearInterval(o.current),o.current=null)}),[a,i,c]),{autoSaveMode:a,setAutoSaveMode:s,autoSaveInterval:i,setAutoSaveInterval:l}}function fu(e,t,n){const a=u.useRef(null),[s,i]=u.useState(!1),[l,o]=u.useState(0),[c,d]=u.useState(10),[h,f]=u.useState(!1),[p,y]=u.useState(120),g=u.useCallback((P,j)=>`L${P}-C${j}`,[]),x=u.useCallback((P,j)=>{if(!a.current||!j.audioBuffer)return;const M=g(P,j.id),I=e[P];a.current.addClip({id:M,buffer:j.audioBuffer,startTime:j.start,offset:0,duration:j.duration,layerId:P,volume:(I==null?void 0:I.volume)??1,pan:(I==null?void 0:I.pan)??0,stretchFactor:j.stretchFactor||1,effectChain:(I==null?void 0:I.effectChain)||[]})},[e,g]),v=u.useCallback((P,j)=>{var M;(M=a.current)==null||M.removeClip(g(P,j))},[g]);u.useEffect(()=>{Object.entries(t).forEach(([P,j])=>{const M=Number(P);j==null||j.forEach(I=>x(M,I))})},[t,e,x]),u.useEffect(()=>{a.current&&Object.entries(n).forEach(([P,j])=>{const M=Number(P);a.current.setMidiCCEvents(M,j)})},[n]);const m=u.useCallback(()=>{a.current&&(s?a.current.pause():a.current.play())},[s]),S=u.useCallback(()=>{var P;(P=a.current)==null||P.stop()},[]),b=u.useCallback(P=>{var j;(j=a.current)==null||j.seek(P)},[]),w=u.useCallback(()=>{if(!a.current)return;const P=!h;f(P),a.current.setLoopRegion(0,c,P)},[h,c]),N=u.useCallback(P=>{var M;const j=Math.max(1,c+P);d(j),(M=a.current)==null||M.setLoopRegion(0,j,h)},[c,h]),R=u.useCallback(async(P,j=1024)=>{const M=await P.arrayBuffer(),I=new(window.AudioContext||window.webkitAudioContext),T=await I.decodeAudioData(M.slice(0)),E=T.getChannelData(0),_=E.length,D=Math.max(1,Math.floor(_/j)),q=[];for(let te=0;te<j;te++){const z=te*D;if(z>=_)break;q.push(E[z])}return I.close(),{waveform:q.map(te=>Math.max(-1,Math.min(1,te))),duration:T.duration,buffer:T}},[]);return{engineRef:a,isPlaying:s,setIsPlaying:i,currentTime:l,setCurrentTime:o,duration:c,setDuration:d,isLooping:h,setIsLooping:f,bpm:p,setBpm:y,handlePlayPause:m,handleStop:S,handleSeek:b,handleToggleLoop:w,handleAdjustDuration:N,upsertEngineClip:x,removeEngineClip:v,makeEngineClipId:g,blobToWaveform:R}}class La{constructor(){this.stream=null,this.mediaRecorder=null,this.audioChunks=[],this.isRecording=!1,this.audioContext=null,this.analyser=null,this.gainNode=null,this.monitorGain=null,this.levelRaf=null}async startRecording(t={}){if(this.isRecording)return;this.levelCallback=t.onLevel,this.stream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t.deviceId||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}});const n=t.mimeType||"audio/webm";this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:n}),this.audioChunks=[],this.audioContext=new(window.AudioContext||window.webkitAudioContext);let s=this.audioContext.createMediaStreamSource(this.stream);t.gain!==void 0&&t.gain>0&&(this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=t.gain,s.connect(this.gainNode),s=this.gainNode),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,s.connect(this.analyser),t.monitorEnabled&&(this.monitorGain=this.audioContext.createGain(),this.monitorGain.gain.value=(t.monitorVolume??100)/100,s.connect(this.monitorGain),this.monitorGain.connect(this.audioContext.destination));const i=()=>{if(!this.analyser)return;const l=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(l);let o=0;for(let d=0;d<l.length;d++){const h=(l[d]-128)/128;o+=h*h}const c=Math.sqrt(o/l.length);this.levelCallback&&this.levelCallback(c),this.isRecording&&(this.levelRaf=requestAnimationFrame(i))};this.mediaRecorder.ondataavailable=l=>{l.data&&l.data.size>0&&this.audioChunks.push(l.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 mu(e){const[t,n]=u.useState(!1),[a,s]=u.useState(!1),[i,l]=u.useState(0),[o,c]=u.useState(0),[d,h]=u.useState(null),f=u.useRef(null),p=u.useRef(null),y=u.useRef(0),g=u.useRef(null),x=u.useRef(null),v=u.useCallback(()=>{g.current&&(clearInterval(g.current),g.current=null),x.current&&(clearTimeout(x.current),x.current=null)},[]),m=u.useCallback(async()=>{if(!e.activeLayer){e.showToast("Select a layer to record.","error");return}t||(f.current||(f.current=new La),y.current=p.current??e.currentTime,n(!0),l(0),await f.current.startRecording({onLevel:l}))},[e,t]),S=u.useCallback(async()=>{var E;if(v(),s(!1),c(0),p.current=null,!f.current){n(!1),l(0);return}const N=await f.current.stopRecording();if(n(!1),l(0),!N||!e.activeLayer)return;const{waveform:R,duration:P,buffer:j}=await e.blobToWaveform(N),M=e.activeLayer.id;e.setWaveforms(_=>({..._,[M]:R}));const I=Math.max(0,y.current||0),T={id:Date.now(),label:"Recording",start:I,duration:P,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:(E=e.layerSettings[M])==null?void 0:E.color,blob:N,blobUrl:URL.createObjectURL(N),audioBuffer:j};e.setLayerClips(_=>({..._,[M]:[..._[M]||[],T]})),e.upsertEngineClip(M,T),e.setSelectedClip({layerId:M,clipId:T.id})},[e,v]),b=u.useCallback(N=>{if(N<=0){m();return}s(!0),c(N);const R=performance.now();g.current=window.setInterval(()=>{const P=(performance.now()-R)/1e3;c(Math.max(0,N-P))},100),x.current=window.setTimeout(()=>{v(),s(!1),c(0),p.current||m()},N*1e3)},[m,v]),w=u.useCallback(async()=>{if(t||a){await S();return}if(!e.activeLayer){e.showToast("Select a layer before recording","error");return}const N=Math.max(0,e.countInBars)*4*(60/e.bpm),R=e.punchIn!=null&&e.punchIn>e.currentTime?e.punchIn:null;R&&(p.current=R),e.overdubEnabled&&!e.isPlaying&&e.playEngine(),R?N>0&&b(N):b(N)},[t,a,e,S,b]);return{isRecording:t,isCountIn:a,monitorLevel:i,countInRemaining:o,punchOut:d,setPunchOut:h,armedPunchInRef:p,recorderRef:f,clearCountInTimers:v,startRecordingNow:m,stopRecordingFlow:S,handleRecord:w}}var oo=(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))(oo||{});const gu={};class Xn{constructor(t,n,a,s={}){this.type=t,this.name=n,this.component=gu[t]??(()=>null),this.audioType=a,this.parameters=s}}new Xn("Recorder","Recorder","vocal",{deviceId:"",gain:1,sensitivity:"high"}),new Xn("Audio Clip","Audio Clip","instrumental",{clipId:null,octave:"4"}),new Xn("Speech Synth","Speech Synth","vocal",{text:"",voice:"default"}),new Xn("Keyboard/Pads","Keyboard","instrumental",{instrument:"piano",preset:"default",velocity:100});function lo(e,t,n,a,s){n(i=>t?[...i,t]:i),a([]),s(e)}function yu(e,t,n,a){t(s=>{if(s.length===0)return s;const i=s[s.length-1];return n(l=>e?[e,...l]:l),a(i),s.slice(0,-1)})}function vu(e,t,n,a){n(s=>{if(s.length===0)return s;const i=s[0];return t(l=>e?[...l,e]:l),a(i),s.slice(1)})}class bu{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 xu=ot.scoped("useProjectCRUD");function Su(e){const{project:t,activeSection:n,setProject:a,setActiveSection:s,setLayers:i,setActiveLayer:l,setUndoStack:o,setRedoStack:c}=e,d=u.useCallback(v=>lo(v,t,o,c,a),[t,o,c,a]),h=u.useCallback(async()=>{var b;if(!t)return;const v=(((b=t.sections)==null?void 0:b.length)??0)+1,S={id:await e.addSection(t.id,"Section",v),projectId:t.id,name:"Section",orderNumber:v,layers:[]};d({...t,sections:[...t.sections||[],S]}),s(S)},[t,d,s]),f=u.useCallback(async v=>{var b,w,N;if(!t||!await e.confirm("Delete this section?"))return;await e.deleteSection(v);const S=(t.sections??[]).filter(R=>R.id!==v);d({...t,sections:S}),s(S[0]??null),i(((b=S[0])==null?void 0:b.layers)??[]),l(((N=(w=S[0])==null?void 0:w.layers)==null?void 0:N[0])??null)},[t,d,s,i,l,e]),p=u.useCallback(async()=>{var m;if(!n)return;const v={id:-Date.now(),name:"New Layer",sectionId:n.id,audioSource:oo.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};i(S=>[...S,v]),l(v);try{const S=await e.addLayer(n.id,v.name,v.audioSource,v.audioSourceParameters);i(b=>b.map(w=>w.id===v.id?{...v,id:S}:w)),t&&d({...t,sections:((m=t.sections)==null?void 0:m.map(b=>b.id===n.id?{...b,layers:[...(b.layers??[]).filter(w=>w.id!==S),{...v,id:S}]}:b))??[]})}catch(S){i(b=>b.filter(w=>w.id!==v.id)),xu.error("Failed to add layer:",S)}},[n,t,d,i,l]),y=u.useCallback(async v=>{var S,b;if((S=e.layerSettings[v])!=null&&S.locked){e.showToast("Layer is locked. Unlock to delete.","error");return}await e.confirm("Delete this layer?")&&((e.layerClips[v]||[]).forEach(w=>e.removeEngineClip(v,w.id)),e.setLayerMidiNotes(w=>{const N={...w};return delete N[v],N}),await e.deleteLayer(v),i(w=>w.filter(N=>N.id!==v)),l(w=>(w==null?void 0:w.id)===v?null:w),t&&d({...t,sections:((b=t.sections)==null?void 0:b.map(w=>w.id===(n==null?void 0:n.id)?{...w,layers:(w.layers??[]).filter(N=>N.id!==v)}:w))??[]}))},[t,n,d,i,l,e]),g=u.useCallback(async()=>{if(!t)return;const v=e.projectVolume===""?void 0:Number(e.projectVolume);if(Number.isNaN(v)){e.setStatusType("error"),e.setStatusMessage("Volume musi byc liczba");return}if(!e.projectName.trim()){e.setStatusType("error"),e.setStatusMessage("Nazwa projektu nie moze byc pusta");return}await e.updateProject(t.id,{name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:v}),d({...t,name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:v}),e.setStatusType("success"),e.setStatusMessage("Project saved")},[t,e,d]),x=u.useCallback(async()=>{var S;if(!n)return;const v=e.sectionName||n.name,m=e.sectionOrder===""?n.orderNumber:Number(e.sectionOrder);if(!v.trim()){e.setStatusType("error"),e.setStatusMessage("Section name cannot be empty");return}if(Number.isNaN(m)){e.setStatusType("error"),e.setStatusMessage("Order musi byc liczba");return}await e.updateSection(n.id,{name:v,orderNumber:m}),s({...n,name:v,orderNumber:m}),t&&d({...t,sections:((S=t.sections)==null?void 0:S.map(b=>b.id===n.id?{...b,name:v,orderNumber:m}:b))??[]}),e.setStatusType("success"),e.setStatusMessage("Section saved")},[n,t,e,d,s]);return{handleAddSection:h,handleDeleteSection:f,handleAddLayer:p,handleDeleteLayer:y,handleSaveProject:g,handleSaveSection:x}}const co=u.createContext(null);function wu(){const e=u.useContext(co);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const za=({value:e,children:t})=>r.jsx(co.Provider,{value:e,children:t});za.displayName="EditorTrackProvider";const un=(e,t)=>t&&t>0?e*15/t:e/10,Da=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},ku=(e,t)=>{const n=t??Da(e),a=[];let s="",i=0,l="",o=!0;function c(){l.trim()!==""&&(s.length>0&&(s+=" "),s+=l.trim()),l=""}return e.forEach(d=>{if(!(d.startsWith("#")||d.startsWith("E"))){if(d.startsWith("-"))c(),s.trim().length>0&&(a.push({text:s.trim(),timestamp:i}),s=""),o=!0;else if(d.startsWith(":")||d.startsWith("*")){const h=d.indexOf(" "),f=d.indexOf(" ",h+1),p=d.indexOf(" ",f+1),y=d.indexOf(" ",p+1);if(y===-1)return;const g=un(parseFloat(d.substring(h+1,f)),n);s===""&&(i=g);const x=d.substring(y+1);if(x.trim()==="~")return;let v=x;v.startsWith("~")&&(v=v.substring(1)),o?(c(),l=v.trimEnd()):l+=v.trimEnd(),o=x.endsWith(" ")}}}),c(),s.trim().length>0&&a.push({text:s.trim(),timestamp:i}),a},Cu=(e,t)=>{const n=t??Da(e),a=[];let s=[],i="",l=0,o=!0,c=null,d="";function h(){c&&d.trim()!==""&&(c.text=d.trim(),s.push({...c}),i.length>0&&(i+=" "),i+=c.text),c=null,d=""}return e.forEach(f=>{if(!(f.startsWith("#")||f.startsWith("E"))){if(f.startsWith("-"))h(),i.trim().length>0&&(a.push({text:i.trim(),timestamp:l,words:s}),i="",s=[]),o=!0;else if(f.startsWith(":")||f.startsWith("*")){const p=f.startsWith("*"),y=f.indexOf(" "),g=f.indexOf(" ",y+1),x=f.indexOf(" ",g+1),v=f.indexOf(" ",x+1);if(v===-1)return;const m=un(parseFloat(f.substring(y+1,g)),n),S=un(parseFloat(f.substring(g+1,x)),n),b=m+S;i===""&&(l=m);const w=f.substring(v+1);if(w.trim()==="~"){c&&(c.endTime=b);return}let N=w;N.startsWith("~")&&(N=N.substring(1)),o?(h(),d=N.trimEnd(),c={text:"",startTime:m,endTime:b,isGolden:p}):c?(d+=N.trimEnd(),c.endTime=b,p&&(c.isGolden=!0)):(d=N.trimEnd(),c={text:"",startTime:m,endTime:b,isGolden:p}),o=w.endsWith(" ")}}}),h(),i.trim().length>0&&a.push({text:i.trim(),timestamp:l,words:s}),a},uo=(e,t)=>{const n=t??Da(e),a=[];let s=[],i=0;function l(){s.length>0&&(a.push({timestamp:i,syllables:[...s]}),s=[])}return e.forEach(o=>{if(!(o.startsWith("#")||o.startsWith("E"))){if(o.startsWith("-")){l();const c=o.trim().split(/\s+/);if(c.length>=2){const d=parseFloat(c[1]);isFinite(d)&&(i=un(d,n))}}else if(o.startsWith(":")||o.startsWith("*")){const c=o.startsWith("*"),d=o.indexOf(" "),h=o.indexOf(" ",d+1),f=o.indexOf(" ",h+1),p=o.indexOf(" ",f+1);if(p===-1)return;const y=parseFloat(o.substring(d+1,h)),g=parseFloat(o.substring(h+1,f)),x=un(y,n),v=x+un(g,n);s.length===0&&(i=x);const m=o.substring(p+1);if(m.trim()==="~"){s.length>0&&(s[s.length-1].endTime=v);return}let S=m;S.startsWith("~")&&(S=S.substring(1));const b=m.endsWith(" "),w=b?S.slice(0,-1):S;s.push({text:w,startTime:x,endTime:v,isGolden:c,hasTrailingSpace:b})}}}),l(),a},ju=(e,t,n=3)=>{const a=[];let s=-1;for(let i=0;i<e.length;i++){const l=e[i].timestamp,o=e[i+1]?e[i+1].timestamp:l+5;if(t>=l&&t<o){s=i;break}}if(s>=0){const i=Math.max(0,s-(n-1));for(let l=i;l<=s;l++)a.push(e[l].text)}return a},Mu=(e,t)=>{const n=[];for(const a of e)for(const s of a.words)t>=s.startTime&&t<=s.endTime&&n.push(s);return n},js="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",Ms="var(--karaoke-gold-glow-first, 0 0 12px #FFD700)",Ru="var(--karaoke-active-glow, 0 0 10px rgba(0,229,255,0.6), 0 0 4px rgba(255,230,0,0.4))",Nu="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",Tu=({song:e,currentTime:t=0})=>{const n=u.useMemo(()=>!e||!e.notes.length?[]:uo(e.notes.map(o=>o.noteLine),e.bpm??void 0),[e]),a=t-((e==null?void 0:e.gap)??0)/1e3;let s=-1;for(let o=0;o<n.length;o++){const c=n[o].timestamp,d=o+1<n.length?n[o+1].timestamp:c+30;if(a>=c&&a<d){s=o;break}}const i=s>=0?n[s]:null,l=s>=0&&s+1<n.length?n[s+1]:null;return r.jsx("div",{className:"karaoke-lyrics",style:{textAlign:"center",fontSize:"28px",marginTop:"20px",minHeight:"80px",textShadow:"var(--karaoke-outline, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000)",fontWeight:700,fontStyle:"italic",fontFamily:"var(--karaoke-font-family, Arial)"},children:i?r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"var(--karaoke-primary-text, #fff)",margin:"5px 0",lineHeight:1.4,textShadow:Ru,background:"var(--karaoke-active-bg, linear-gradient(90deg, transparent 0%, rgba(0,229,255,0.08) 20%, rgba(255,230,0,0.06) 80%, transparent 100%))",borderRadius:8,padding:"2px 10px",transition:"text-shadow 0.3s ease, background 0.3s ease"},children:i.syllables.map((o,c)=>{let d=0;a>=o.endTime?d=1:a>o.startTime&&(d=(a-o.startTime)/(o.endTime-o.startTime));const h=Math.round(d*100),f=o.text+(o.hasTrailingSpace?" ":""),p=d>0&&d<1,y=o.isGolden;return d<=0?r.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",transition:"color 0.15s ease"},children:f},c):d>=1?r.jsx("span",{style:{background:y?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":js,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:y?`drop-shadow(${Ms})`:"none",transition:"filter 0.2s ease"},children:f},c):r.jsxs("span",{style:{position:"relative",display:"inline",filter:p?y?`drop-shadow(${Ms})`:`drop-shadow(${Nu})`:"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:f}),r.jsx("span",{style:{position:"absolute",left:0,top:0,background:y?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":js,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",clipPath:`inset(0 ${100-h}% 0 0)`,pointerEvents:"none"},children:f})]},c)})}),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((o,c)=>r.jsx("span",{style:{color:o.isGolden?"var(--karaoke-golden-next, rgba(255,215,0,0.5))":"var(--karaoke-next-dim, #777)"},children:o.text+(o.hasTrailingSpace?" ":"")},c))})]}):n.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})," Waiting for lyrics..."]})})},ho=u.memo(Tu),Zr={},$u=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:bt&&bt.tagName.toUpperCase()==="SCRIPT"&&bt.src||new URL("index.cjs",document.baseURI).href}<"u"&&(Zr==null?void 0:Zr.VITE_DEBUG_KARAOKE)==="true";function ha(e,t,...n){($u||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 po=e=>{for(const t of e){const n=t.trim();if(n.toUpperCase().startsWith("#BPM:")){const a=parseFloat(n.substring(5).replace(",","."));if(isFinite(a)&&a>0)return a}}return null},Rs=(e,t)=>t&&t>0?e*15/t:e/10,Hn=(e,t)=>{const n=t??po(e),a=[];let s=[];return e.forEach(i=>{const l=i.split(" ");if(!(l.length<4))if(i.startsWith("-"))s.length>0&&(a.push(s),s=[]);else{const o=(l[0]||"").charAt(0),c=o==="*"||o==="G";s.push({startTime:Rs(parseFloat(l[1]),n),duration:Rs(parseFloat(l[2]),n),pitch:parseInt(l[3],10),isGold:c})}}),s.length>0&&a.push(s),a},fo=(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},Pu=ot.scoped("karaokeScoringConfig"),_a={easy:{semitoneTolerance:2,preWindow:.25,postExtra:.3,difficultyMult:.9},normal:{semitoneTolerance:1,preWindow:.15,postExtra:.2,difficultyMult:1},hard:{semitoneTolerance:0,preWindow:.08,postExtra:.12,difficultyMult:1.05}},Au="karaoke.scoringPresets";function Eu(){try{const e=localStorage.getItem(Au);return e?JSON.parse(e):null}catch(e){return Pu.warn("Failed to parse scoring presets overrides",e),null}}function mo(e){const t={..._a},n=Eu();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=mo();const Iu=async e=>{try{let t=null;if(e?t=await e.getKaraokeScoringConfig():(console.debug("[karaokeScoringConfig] No fetcher provided, using defaults"),t=null),t&&t.presets)return exports.ScoringPresets=mo(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},Dr=(e="normal")=>exports.ScoringPresets[e]||_a.normal,Lu=3,ee=Lu;function Ht(e){const t=e/2|0;return{w:t,out:`M${t} 0H${t}V${e}H${t}A${t} ${t} 0 0 1 0 ${t}A${t} ${t} 0 0 1 ${t} 0Z`,inn:`M${t} ${ee}V${e-ee}A${t-ee} ${t-ee} 0 0 1 ${ee} ${t}A${t-ee} ${t-ee} 0 0 1 ${t} ${ee}Z`}}function hn(e){return{w:ee+1,out:`M0 0H${ee+1}V${e}H0Z`,inn:`M${ee} ${ee}H${ee+1}V${e-ee}H${ee}Z`}}function Fa(e){const t=Math.min(14,e*.22)|0,n=t+2,a=Math.max(t-ee,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}V${t}Q0 0 ${t} 0Z`,inn:`M${ee+a} ${ee}H${n}V${e-ee}H${ee+a}Q${ee} ${e-ee} ${ee} ${e-ee-a}V${ee+a}Q${ee} ${ee} ${ee+a} ${ee}Z`}}function Mr(e){const t=e*.3|0,n=t+2,a=Math.max(t-ee,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e-t}V${t}Z`,inn:`M${ee+a} ${ee}H${n}V${e-ee}H${ee+a}L${ee} ${e-ee-a}V${ee+a}Z`}}function Bt(e){const t=e*.42|0,n=t+2,a=Math.max(t-(ee*1.4|0),2);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e/2}Z`,inn:`M${ee+a} ${ee}H${n}V${e-ee}H${ee+a}L${ee} ${e/2}Z`}}function Rr(e){const t=e*.3|0,n=t+4,a=Math.max(t-ee,1);return{w:n,out:`M${t} 0H${n}V${e}H${t*.6|0}L0 ${e-t}V${t}Q0 0 ${t} 0Z`,inn:`M${ee+a} ${ee}H${n}V${e-ee}H${ee+(a*.6|0)}L${ee} ${e-ee-a}V${ee+a}Q${ee} ${ee} ${ee+a} ${ee}Z`}}function Oa(e){const t=e*.16|0,n=t*2+4;return{w:n,out:`M${t*1.5|0} 0H${n}V${e}H${t*1.5|0}C${t*2.5|0} ${e*.35|0} ${t*2.5|0} ${e*.65|0} ${t*1.5|0} ${e}Z`,inn:`M${ee+(t*1.2|0)} ${ee}H${n}V${e-ee}H${ee+(t*1.2|0)}C${ee+(t*2.2|0)} ${e*.37|0} ${ee+(t*2.2|0)} ${e*.63|0} ${ee+(t*1.2|0)} ${e-ee}Z`}}function Ba(e){const t=e*.32|0,n=t+3,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}Z`,inn:`M${ee} ${ee}H${n}V${e-ee}H${ee+a}Q${ee} ${e-ee} ${ee} ${e-ee-a}Z`}}function Nr(e){const t=e*.14|0,n=t*3+2;return{w:n,out:`M${t*2} 0H${n}V${e}H${t*2}C${t*.5|0} ${e*.8|0} ${t*3} ${e*.55|0} ${t*.5|0} ${e*.35|0}S${t} 0 ${t*2} 0Z`,inn:`M${ee+(t*1.8|0)} ${ee}H${n}V${e-ee}H${ee+(t*1.8|0)}C${ee+(t*.4|0)} ${e*.78|0} ${ee+(t*2.8|0)} ${e*.55|0} ${ee+(t*.4|0)} ${e*.37|0}S${ee+(t*.9|0)} ${ee} ${ee+(t*1.8|0)} ${ee}Z`}}function Ga(e){const t=e*.09|0,n=e*.35|0;return{w:n,out:`M${t*3} 0H${n}V${e}H${t*3}L${t} ${e-t*2}L${t*2} ${e*.65|0}L0 ${e/2|0}L${t*2} ${e*.35|0}L${t} ${t*2}Z`,inn:`M${ee+(t*2.5|0)} ${ee}H${n}V${e-ee}H${ee+(t*2.5|0)}L${ee+(t*.7|0)} ${e-ee-(t*1.6|0)}L${ee+(t*1.7|0)} ${e*.64|0}L${ee} ${e/2|0}L${ee+(t*1.7|0)} ${e*.36|0}L${ee+(t*.7|0)} ${ee+(t*1.6|0)}Z`}}function hr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M${t} 0H${n}V${e}H0Z`,inn:`M${ee+t-(ee*1.3|0)} ${ee}H${n}V${e-ee}H${ee+1}Z`}}function pa(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}V${e}H${t}Z`,inn:`M${ee} ${ee}H${n}V${e-ee}H${ee+t-(ee*1.3|0)+1}Z`}}function Ft(e){const t=e/2|0;return{w:t,out:`M0 0A${t} ${t} 0 0 1 ${t} ${t}A${t} ${t} 0 0 1 0 ${e}Z`,inn:`M0 ${ee}A${t-ee} ${t-ee} 0 0 1 ${t-ee} ${t}A${t-ee} ${t-ee} 0 0 1 0 ${e-ee}Z`}}function pn(e){return{w:ee+1,out:`M0 0H${ee+1}V${e}H0Z`,inn:`M0 ${ee}H1V${e-ee}H0Z`}}function go(e){const t=Math.min(14,e*.22)|0,n=t+2,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n-t}Q${n} 0 ${n} ${t}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-a}Q${n-ee} ${ee} ${n-ee} ${ee+a}V${e-ee-a}Q${n-ee} ${e-ee} ${n-ee-a} ${e-ee}H0Z`}}function fn(e){const t=e*.3|0,n=t+2,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n-t}L${n} ${t}V${e-t}L${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-a}L${n-ee} ${ee+a}V${e-ee-a}L${n-ee-a} ${e-ee}H0Z`}}function Tt(e){const t=e*.42|0,n=t+2,a=Math.max(t-(ee*1.4|0),2);return{w:n,out:`M0 0H${n-t}L${n} ${e/2}L${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-a}L${n-ee} ${e/2}L${n-ee-a} ${e-ee}H0Z`}}function yo(e){const t=e*.3|0,n=t+4,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n-t}Q${n} 0 ${n} ${t}V${e-t}L${n-(t*.6|0)} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-a}Q${n-ee} ${ee} ${n-ee} ${ee+a}V${e-ee-a}L${n-ee-(a*.6|0)} ${e-ee}H0Z`}}function vo(e){const t=e*.16|0,n=t*2+4;return{w:n,out:`M0 0H${n-(t*1.5|0)}C${n-(t*2.5|0)} ${e*.35|0} ${n-(t*2.5|0)} ${e*.65|0} ${n-(t*1.5|0)} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-(t*1.2|0)}C${n-ee-(t*2.2|0)} ${e*.37|0} ${n-ee-(t*2.2|0)} ${e*.63|0} ${n-ee-(t*1.2|0)} ${e-ee}H0Z`}}function bo(e){const t=e*.32|0,n=t+3,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee}V${e-ee-a}Q${n-ee} ${e-ee} ${n-ee-a} ${e-ee}H0Z`}}function Wa(e){const t=e*.14|0,n=t*3+2;return{w:n,out:`M0 0H${n-t*2}C${n-t} 0 ${n+(t*.3|0)} ${e*.2|0} ${n-(t*.5|0)} ${e*.35|0}S${n-(t*.5|0)} ${e*.8|0} ${n-t*2} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-(t*1.8|0)}C${n-ee-(t*.9|0)} ${ee} ${n-ee+(t*.1|0)} ${e*.22|0} ${n-ee-(t*.4|0)} ${e*.37|0}S${n-ee-(t*.4|0)} ${e*.78|0} ${n-ee-(t*1.8|0)} ${e-ee}H0Z`}}function Tr(e){const t=e*.09|0,n=e*.35|0;return{w:n,out:`M0 0H${n-t*3}L${n-t} ${t*2}L${n-t*2} ${e*.35|0}L${n} ${e/2|0}L${n-t*2} ${e*.65|0}L${n-t} ${e-t*2}L${n-t*3} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-(t*2.5|0)}L${n-ee-(t*.7|0)} ${ee+(t*1.6|0)}L${n-ee-(t*1.7|0)} ${e*.36|0}L${n-ee} ${e/2|0}L${n-ee-(t*1.7|0)} ${e*.64|0}L${n-ee-(t*.7|0)} ${e-ee-(t*1.6|0)}L${n-ee-(t*2.5|0)} ${e-ee}H0Z`}}function fa(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}L${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee}L${n-ee-t+(ee*1.3|0)} ${e-ee}H0Z`}}function pr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n-t}L${n} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-t+(ee*1.3|0)}L${n-ee} ${e-ee}H0Z`}}const Ua=[{name:"Pill",L:Ht,R:Ft},{name:"Sharp",L:hn,R:pn},{name:"Soft",L:Fa,R:go},{name:"Chamfer",L:Mr,R:fn},{name:"Arrow",L:Bt,R:Tt},{name:"Shield",L:Rr,R:yo},{name:"Bracket",L:Oa,R:vo},{name:"Tab",L:Ba,R:bo},{name:"Wave",L:Nr,R:Wa},{name:"Ornate",L:Ga,R:Tr}],xo=[{name:"Pill→Arrow",L:Ht,R:Tt},{name:"Arrow→Pill",L:Bt,R:Ft},{name:"Pill→Sharp",L:Ht,R:pn},{name:"Sharp→Pill",L:hn,R:Ft},{name:"Pill→Chamfer",L:Ht,R:fn},{name:"Chamfer→Pill",L:Mr,R:Ft},{name:"Arrow→Sharp",L:Bt,R:pn},{name:"Sharp→Arrow",L:hn,R:Tt},{name:"Arrow→Chamfer",L:Bt,R:fn},{name:"Chamfer→Arrow",L:Mr,R:Tt},{name:"Soft→Arrow",L:Fa,R:Tt},{name:"Shield→Chamfer",L:Rr,R:fn},{name:"Pill→Wave",L:Ht,R:Wa},{name:"Wave→Arrow",L:Nr,R:Tt},{name:"Tab→Pill",L:Ba,R:Ft},{name:"Ornate→Sharp",L:Ga,R:pn},{name:"Sharp→Ornate",L:hn,R:Tr},{name:"Bracket→Arrow",L:Oa,R:Tt},{name:"Shield→Pill",L:Rr,R:Ft},{name:"Wave→Ornate",L:Nr,R:Tr}],So=[{name:"Skew ╲",L:hr,R:fa},{name:"Skew ╱",L:pa,R:pr},{name:"◇ Romb",L:Bt,R:Tt},{name:"╲→Pill",L:hr,R:Ft},{name:"Pill→╲",L:Ht,R:fa},{name:"╱→Sharp",L:pa,R:pn},{name:"Sharp→╱",L:hn,R:pr},{name:"╲→Arrow",L:hr,R:Tt},{name:"Arrow→╱",L:Bt,R:pr},{name:"◇→Chamfer",L:Bt,R:fn}],Wn=[...Ua,...xo,...So],wo=Ua[0];function Rn(e){return Wn.find(t=>t.name===e)||wo}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 Nn(e){return $r.find(t=>t.name===e)||null}const Wt={color:null,capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,glass:0,textureUrl:null,textureScale:1},_r={...Wt,glass:85},Fr={...Wt,patternName:"Stars"},Or={...Wt,patternName:"Stars"},Br={fontFamily:null,fontSize:18,fontColor:null,outlineColor:null,outlineWidth:0,shadow:null},ko={filledBar:{...Wt},emptyBar:{..._r},goldFilledBar:{...Or},goldEmptyBar:{...Fr},font:{...Br},disableGoldNotes:!1},Ns={capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,emptyGlass:85,filledTextureUrl:null,emptyTextureUrl:null,textureScale:1,emptyPreset:"custom",goldPatternName:"Stars",goldPatternColor:null,goldHitPatternName:"Stars",goldHitPatternColor:null,goldEmptyTextureUrl:null,goldFilledTextureUrl:null,fontFamily:null,fontSize:18,fontColor:null,fontOutlineColor:null,fontOutlineWidth:0,fontShadow:null},Ts="nice2dev-player-bar-style",$s="nice2dev-player-karaoke-settings";function mn(e){return e!=null?`${$s}-${e}`:$s}function Ps(e){return e!=null?`${Ts}-${e}`:Ts}function As(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 Es(e){const t=ko,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 Va(e){try{const t=localStorage.getItem(mn(e));if(t){const a=JSON.parse(t);return Es(a)}const n=localStorage.getItem(Ps(e));if(n){const a=JSON.parse(n),s=As({...Ns,...a});return localStorage.setItem(mn(e),JSON.stringify(s)),s}if(e!=null){const a=localStorage.getItem(mn());if(a)return Es(JSON.parse(a));const s=localStorage.getItem(Ps());if(s)return As({...Ns,...JSON.parse(s)})}}catch{}return{filledBar:{...Wt},emptyBar:{..._r},goldFilledBar:{...Or},goldEmptyBar:{...Fr},font:{...Br}}}function zu(e,t){const n=JSON.stringify(e);localStorage.setItem(mn(t),n)}let Is=!1;async function Du(e){if(Is||(Is=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(mn())||localStorage.setItem(mn(),t)}catch{}}function _u(e){const t=new Map;for(const n of e)t.set(n,Va(n));return t}const Fu={"&":"&","<":"<",">":">",'"':""","'":"'"},Ou=/[&<>"']/g;function Bu(e){return e.replace(Ou,t=>Fu[t])}function Gu(e){const t=e.trim().toLowerCase();return!!(t.startsWith("http://")||t.startsWith("https://")||t.startsWith("blob:")||t.startsWith("data:image/")||t.startsWith("/")||t.startsWith("./")||t.startsWith("../"))}const Wu=3,Qe=Wu;function Pr(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 l=0,o=0;const c=(s+i)/2;if(s!==i){const d=s-i;switch(o=c>.5?d/(2-s-i):d/(s+i),s){case t:l=((n-a)/d+(n<a?6:0))/6;break;case n:l=((a-t)/d+2)/6;break;case a:l=((t-n)/d+4)/6;break}}return[Math.round(l*360),Math.round(o*100),Math.round(c*100)]}function Ar(e){let t=e.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),"#"+t.toLowerCase()}function ut(e,t){return e.replace(/([MLHVCSQTAZ])/gi,`
|
|
1
|
+
"use strict";var $c=Object.create;var gs=Object.defineProperty;var Ac=Object.getOwnPropertyDescriptor;var Ic=Object.getOwnPropertyNames;var Lc=Object.getPrototypeOf,_c=Object.prototype.hasOwnProperty;var zc=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ic(t))!_c.call(e,s)&&s!==n&&gs(e,s,{get:()=>t[s],enumerable:!(a=Ac(t,s))||a.enumerable});return e};var Hr=(e,t,n)=>(n=e!=null?$c(Lc(e)):{},zc(t||!e||!e.__esModule?gs(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),ke=require("@nice2dev/ui-core"),d=require("react"),ie=require("@nice2dev/ui"),F=require("@nice2dev/icons"),la=require("pitchy"),Pa=require("react-youtube");var vt=typeof document<"u"?document.currentScript:null;const Ti=d.createContext(null),Dc=({t:e,children:t})=>r.jsx(Ti.Provider,{value:e,children:t});function xe(){const e=d.useContext(Ti),{t}=ke.useNiceTranslation();return{t:d.useMemo(()=>e??((a,s)=>t(a,s??a)),[e,t])}}function Fc({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 Oc 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(Fc,{componentName:this.props.componentName,error:this.state.error,onReset:this.reset}):this.props.children}}function Bc(e){if(!e)return[128,128,128];const t=e.match(/^#([0-9a-f]{3,8})$/i);if(t){let a=t[1];if(a.length===3&&(a=a[0]+a[0]+a[1]+a[1]+a[2]+a[2]),a.length>=6)return[parseInt(a.slice(0,2),16),parseInt(a.slice(2,4),16),parseInt(a.slice(4,6),16)]}const n=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);return n?[+n[1],+n[2],+n[3]]:[128,128,128]}const Kr={},ca={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function Gc(){const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:vt&&vt.tagName.toUpperCase()==="SCRIPT"&&vt.src||new URL("index.cjs",document.baseURI).href}<"u"?Kr==null?void 0:Kr.VITE_LOG_LEVEL:void 0;return e&&e in ca?e:"WARN"}const Wc=Gc();function Kn(e){return ca[e]>=ca[Wc]}function Yn(e){return`[${e}]`}const st=(function(){return{debug(e,t,...n){Kn("DEBUG")&&console.debug(Yn(e),t,...n)},info(e,t,...n){Kn("INFO")&&console.info(Yn(e),t,...n)},warn(e,t,...n){Kn("WARN")&&console.warn(Yn(e),t,...n)},error(e,t,...n){Kn("ERROR")&&console.error(Yn(e),t,...n)},scoped(e){return{debug:(t,...n)=>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)}}}})(),ys=st.scoped("Waveform"),Vc=["audio/","video/"],Pi=({audioBlob:e,currentTime:t,duration:n,width:a=600,height:s=200,zoom:i=1,onSeek:o,onRegionSelect:l,markers:c=[],regions: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:k})=>{const{t:v}=xe(),w=d.useRef(null),R=d.useRef(null),[M,j]=d.useState(null),[T,P]=d.useState(0),[A,I]=d.useState(!1),[L,N]=d.useState(null),[_,ee]=d.useState(null),[Y,O]=d.useState(0),U=Math.max(a,a*i),V=x?24:0;d.useEffect(()=>{if(!e||e.size===0){j(null);return}e.type&&!Vc.some($=>e.type.startsWith($))&&ys.warn("Unexpected blob MIME type:",e.type);let C=!1;return(async()=>{let $=null;try{const S=await e.arrayBuffer();if(S.byteLength===0||C)return;$=new AudioContext;const B=await $.decodeAudioData(S);C||j(B)}catch(S){ys.error("Failed to decode audio:",S)}finally{$==null||$.close().catch(()=>{})}})(),()=>{C=!0}},[e]),d.useEffect(()=>{if(i>1&&n>0){const C=t/n*U;(C<T||C>T+a)&&P(Math.max(0,C-a/2))}},[t,n,i,a,U,T]),d.useEffect(()=>{const C=w.current,$=M;if(!C||!n||n===1/0)return;const S=C.getContext("2d");if(!S)return;const B=U,H=s;if(C.width=B,C.height=H+V,S.clearRect(0,0,B,H+V),m!=="transparent"&&(S.fillStyle=ke.resolveCssColor(m),S.fillRect(0,0,B,H+V)),x){const z=ke.resolveCssColor("var(--nice-text-secondary, #888)");S.fillStyle=ke.resolveCssColor("var(--nice-bg-secondary, rgba(128,128,128,0.15))"),S.fillRect(0,0,B,V),S.fillStyle=z,S.font="10px monospace",S.textAlign="center";const Z=Math.max(1,Math.floor(n/(U/80)));for(let E=0;E<=n;E+=Z){const q=E/n*B;S.fillText(Kc(E),q,V-4),S.fillStyle=ke.resolveCssColor("var(--nice-border-color, rgba(128,128,128,0.3))"),S.fillRect(q,V,1,H),S.fillStyle=z}}for(const z of u){const Z=z.start/n*B,E=z.end/n*B;S.fillStyle=ke.resolveCssColor(z.color??"var(--nice-accent-tint-15, rgba(99, 102, 241, 0.15))"),S.fillRect(Z,V,E-Z,H),z.label&&(S.fillStyle=ke.resolveCssColor(z.color??"var(--nice-info, #6366f1)"),S.font="10px sans-serif",S.textAlign="left",S.fillText(z.label,Z+2,V+12))}if(L!==null&&_!==null){const z=Math.min(L,_),Z=Math.max(L,_);S.fillStyle=ke.resolveCssColor("var(--nice-warning-tint-20, rgba(255,200,0,0.2))"),S.fillRect(z,V,Z-z,H)}if($){const z=p?$.numberOfChannels:1,Z=H/z,E=ke.resolveCssColor(g);let q=0;for(let X=0;X<z;X++){const re=$.getChannelData(X),oe=V+X*Z;if(h==="waveform"?Uc(S,re,B,Z,oe,E):h==="bars"?qc(S,re,B,Z,oe,E):h==="spectrogram"&&Hc(S,re,B,Z,oe,$.sampleRate),f&&n>0){const se=Math.floor(t/n*re.length),D=Math.floor($.sampleRate*.05);let J=0;for(let ce=Math.max(0,se-D);ce<Math.min(re.length,se+D);ce++)J+=re[ce]*re[ce];const ae=Math.sqrt(J/(D*2));q=Math.max(q,ae)}p&&b&&z>1&&(S.fillStyle=ke.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))}O(q)}if(n>0){const z=Math.max(0,Math.min(t/n*B,B));S.beginPath(),S.strokeStyle=ke.resolveCssColor(y),S.lineWidth=2,S.moveTo(z,V),S.lineTo(z,H+V),S.stroke()}for(const z of c){const Z=z.time/n*B,E=ke.resolveCssColor(z.color??"var(--nice-warning, #f59e0b)");S.beginPath(),S.strokeStyle=E,S.lineWidth=2,S.setLineDash([4,4]),S.moveTo(Z,V),S.lineTo(Z,H+V),S.stroke(),S.setLineDash([]),z.label&&(S.fillStyle=E,S.font="bold 10px sans-serif",S.textAlign="center",S.fillText(z.label,Z,V+H-4))}},[M,t,n,U,s,i,h,p,g,y,m,x,c,u,L,_,f,b,V]);const K=d.useCallback(C=>{var B;if(!n)return;const $=(B=w.current)==null?void 0:B.getBoundingClientRect();if(!$)return;const S=C.clientX-$.left+T;I(!0),N(S),ee(S)},[n,T]),G=d.useCallback(C=>{if(!A||!w.current)return;const $=w.current.getBoundingClientRect(),S=C.clientX-$.left+T;ee(S)},[A,T]),W=d.useCallback(()=>{if(!A||L===null||_===null||!n){I(!1),N(null),ee(null);return}const C=Math.min(L,_),$=Math.max(L,_),S=($-C)/U*n;if(I(!1),N(null),ee(null),S<.2){const B=C/U*n;o==null||o(B)}else{const B=C/U*n,H=$/U*n;l==null||l({start:B,end:H})}},[A,L,_,n,U,o,l]);return r.jsxs("div",{ref:R,className:`nice-waveform${k?` ${k}`:""}`,style:{position:"relative",width:a,overflow:i>1?"auto":"hidden",cursor:o?"crosshair":"default"},onScroll:C=>P(C.target.scrollLeft),children:[r.jsx("canvas",{ref:w,width:U,height:s+V,style:{display:"block"},role:"img","aria-label":v("waveform.waveformCanvas","Waveform canvas"),onMouseDown:K,onMouseMove:G,onMouseUp:W,onMouseLeave:W}),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,Y*300)}%`,background:Y>.8?"var(--nice-danger, #ef4444)":Y>.5?"var(--nice-warning, #f59e0b)":"var(--nice-success, #22c55e)",borderRadius:4,transition:"height 50ms"}})})]})};function Uc(e,t,n,a,s,i){const o=Math.floor(t.length/n),l=s+a/2;e.beginPath(),e.strokeStyle=i,e.lineWidth=1;for(let c=0;c<n;c++){const 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 qc(e,t,n,a,s,i){const o=Math.max(2,Math.floor(n/128)),l=Math.floor(n/o),c=Math.floor(t.length/l);for(let 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 Hc(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 k=2*Math.PI*m*f/256;x+=t[p+f]*Math.cos(k),b-=t[p+f]*Math.sin(k)}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),k=Math.floor((1-x)*200);e.fillStyle=`rgb(${b},${f},${k})`,e.fillRect(h*u,s+a-(m+1)*y,u+1,y+1)}}}function Kc(e){const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const vs=88,Jt=16,Zn=16,Yc=320;function Zc(e){return e-21}function Xc(e){return e+21}const Ea=({notes:e,onAddNote:t,onRemoveNote:n,selectedNoteId:a,setSelectedNoteId:s,duration:i=4,zoom:o=1})=>{const l=d.useRef(null),c=Yc*o,u=vs*Jt,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,k=Math.floor(f/Jt),v=Xc(k),w=b/c*i;h.current={drawing:!0,startX:b,key:k},t(v,w,i/Zn)},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(vs)].map((y,m)=>r.jsx("rect",{x:0,y:m*Jt,width:c,height:Jt,fill:m%2===0?"var(--nice-bg-secondary, #f8fafc)":"var(--nice-bg-tertiary, #f1f5f9)"},m)),[...Array(Zn+1)].map((y,m)=>r.jsx("line",{x1:m*c/Zn,y1:0,x2:m*c/Zn,y2:u,stroke:"var(--nice-border-muted, #ccc)",strokeWidth:m%4===0?2:1},m)),e.map(y=>{const m=Zc(y.pitch),x=y.start/i*c,b=y.duration/i*c;return r.jsx("rect",{x,y:m*Jt,width:Math.max(6,b),height:Jt-2,fill:y.id===a?"var(--nice-color-primary, #6366f1)":"color-mix(in srgb, var(--nice-color-primary, #6366f1) 55%, var(--nice-bg-primary, #ffffff))",stroke:"var(--nice-color-primary, #6366f1)",strokeWidth:y.id===a?2:1,rx:3,onClick:f=>g(y.id,f),onDoubleClick:()=>n(y.id),style:{cursor:"pointer"}},y.id)})]})},Qc=({ccEvents:e,onAddEvent:t,onUpdateEvent:n,onRemoveEvent:a,ccType:s,duration:i,width:o,height:l=60,curveType:c})=>{const 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((N,_)=>N.time-_.time),k=N=>[N.time/i*o,(127-N.value)/127*l],v=(N,_,ee)=>Math.max(_,Math.min(ee,N)),w=N=>{var V;if(N.target instanceof SVGCircleElement)return;const _=(V=u.current)==null?void 0:V.getBoundingClientRect();if(!_)return;const ee=N.clientX-_.left,Y=N.clientY-_.top,O=v(ee/o*i,0,i),U=v(127-Math.round(Y/l*127),0,127);t(s,U,O)},R=(N,_)=>{var U;_.stopPropagation(),g(N.id),b(N.id);const[ee,Y]=k(N),O=(U=u.current)==null?void 0:U.getBoundingClientRect();O&&m({dx:_.clientX-O.left-ee,dy:_.clientY-O.top-Y})},M=N=>{var V;if(p==null||!y)return;const _=(V=u.current)==null?void 0:V.getBoundingClientRect();if(!_)return;const ee=v(N.clientX-_.left-y.dx,0,o),Y=v(N.clientY-_.top-y.dy,0,l),O=v(ee/o*i,0,i),U=v(127-Math.round(Y/l*127),0,127);n(p,U,O)},j=()=>{g(null),m(null)};d.useEffect(()=>{const N=_=>{(_.key==="Delete"||_.key==="Backspace")&&x!=null&&(a(x),b(null))};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[x,a]),d.useEffect(()=>{if(p!=null)return window.addEventListener("mousemove",M),window.addEventListener("mouseup",j),()=>{window.removeEventListener("mousemove",M),window.removeEventListener("mouseup",j)}});const[T,P]=d.useState(null),A=(N,_)=>{const[ee,Y]=k(N);P({x:ee+10,y:Y-10,text:h("ccLane.valTimeS","Val: {value}, Time: {time}s").replace("{value}",String(N.value)).replace("{time}",String(N.time.toFixed(2)))})},I=()=>P(null),L=N=>{var V;const _=(V=u.current)==null?void 0:V.getBoundingClientRect();if(!_)return;const ee=N.clientX-_.left,Y=N.clientY-_.top,O=v(ee/o*i,0,i),U=v(127-Math.round(Y/l*127),0,127);t(s,U,O)};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:w,onDoubleClick:L,tabIndex:0,children:[[...Array(9)].map((N,_)=>r.jsx("line",{x1:0,y1:_*l/8,x2:o,y2:_*l/8,stroke:"var(--nice-border-muted, #ddd)",strokeWidth:_===0||_===8?2:1},_)),f.length>1&&r.jsx("polyline",{fill:"none",stroke:"var(--nice-color-accent, #1976d2)",strokeWidth:2,points:f.map(N=>k(N).join(",")).join(" ")}),f.map(N=>{const[_,ee]=k(N);return r.jsxs("g",{children:[r.jsx("circle",{cx:_,cy:ee,r:x===N.id?8:6,fill:x===N.id?"var(--nice-color-accent, #1976d2)":"var(--nice-color-accent-light, #90caf9)",stroke:"var(--nice-color-accent, #1976d2)",strokeWidth:x===N.id?3:2,style:{cursor:"pointer"},onMouseDown:Y=>R(N,Y),onContextMenu:Y=>{Y.preventDefault(),a(N.id)},onClick:Y=>{Y.stopPropagation(),b(N.id)},onMouseOver:Y=>A(N),onMouseOut:I}),x===N.id&&r.jsx("foreignObject",{x:_+10,y:ee-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:N.handleType||c||"linear",onChange:Y=>{n(N.id,N.value,N.time,Y.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")})]})]})})]},N.id)}),T&&r.jsxs("g",{pointerEvents:"none",children:[r.jsx("rect",{x:T.x,y:T.y-18,width:90,height:20,fill:"var(--nice-color-surface, #fff)",stroke:"var(--nice-color-accent, #1976d2)",rx:4}),r.jsx("text",{x:T.x+6,y:T.y-4,fontSize:13,fill:"var(--nice-color-accent, #1976d2)",children:T.text})]}),r.jsxs("text",{x:6,y:16,fontSize:14,fill:"var(--nice-color-accent, #1976d2)",children:["CC",s]})]})},Jc=st.scoped("audioContext");let Gn=null;function qn(){if(!Gn)try{Gn=new(window.AudioContext||window.webkitAudioContext)}catch(e){Jc.error("Error initializing AudioContext:",e)}return Gn}async function Yt(){const e=qn();e&&e.state==="suspended"&&await e.resume()}function Ei(){return!!Gn&&Gn.state==="running"}function $i(e){const t=e.bpm/60;switch(e.snapMode){case"bar":return 4/t;case"beat":return 1/t;case"sub-beat":return 1/(t*4);case"second":default:return 1}}function ed(e,t){if(!t.snapEnabled)return e;const n=$i(t);return Math.round(e/n)*n}function td(e,t=!1){const n=Math.floor(e/60),a=Math.floor(e%60),s=Math.floor(e%1*1e3);return t?`${n}:${a.toString().padStart(2,"0")}.${s.toString().padStart(3,"0")}`:`${n}:${a.toString().padStart(2,"0")}`}function nd(e,t){const n=t/60,a=e*n,s=Math.floor(a/4),i=Math.floor(a%4);return`${s+1}:${i+1}`}function Ai(e,t,n=!0){const a=e.getContext("2d");if(!a)return;const s=30*t.zoom*t.duration,i=Math.max(80,30*t.zoom);e.width=s,e.height=i,a.clearRect(0,0,s,i),a.fillStyle=ke.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=ke.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=ke.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=ke.resolveCssColor("var(--nice-text-muted, #666)",a.canvas),a.font="10px monospace",a.textAlign="center";const p=n?nd(c,t.bpm):td(c);a.fillText(p,u,12)}}if(t.snapEnabled){const c=$i(t);a.strokeStyle=ke.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 rd(e,t,n,a){const s=e.getContext("2d");if(!s)return;const i=30*t.zoom*t.duration,o=Math.max(80,30*t.zoom),l=n/t.duration*i;Ai(e,t),s.strokeStyle=ke.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=ke.resolveCssColor(a?"var(--nice-color-danger, #f44336)":"var(--nice-color-accent, #2196f3)",s.canvas),s.beginPath(),s.moveTo(l,0),s.lineTo(l-5,-8),s.lineTo(l+5,-8),s.closePath(),s.fill()}function ad(e,t,n,a="var(--nice-color-success, #4caf50)"){const s=e.getContext("2d");if(!s||!(n!=null&&n.length))return;const i=30*t.zoom*t.duration,l=e.height/2,c=Math.max(10,l-6);s.save(),s.strokeStyle=ke.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 Ii=({zoom:e=1,duration:t=4,isPlaying:n,isRecording:a,currentTime:s,bpm:i=120,snapEnabled:o=!1,snapMode:l="beat",waveform:c,waveformColor: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 k=d.useRef(h);k.current=h;const v={bpm:i,snapEnabled:o,snapMode:l};d.useEffect(()=>{Yt();const P=y.current;if(!P)return;const A={zoom:e,duration:t,bpm:i,snapEnabled:o,snapMode:l};Ai(P,A),c!=null&&c.length&&ad(P,A,c,u),rd(P,A,s,a)},[e,t,s,a,i,o,l,c,u]),d.useEffect(()=>{if(!n)return;let P=performance.now(),A=0;const I=L=>{const N=Math.max(0,L-P)/1e3;P=L;const _=Math.min(b.current+N,f.current);b.current=_,k.current(_),_<f.current&&(A=requestAnimationFrame(I))};return A=requestAnimationFrame(I),()=>cancelAnimationFrame(A)},[n]);const w=P=>{x(!0),j(P)},R=P=>{m&&j(P)},M=()=>{x(!1)},j=P=>{if(!y.current)return;const A=y.current.getBoundingClientRect();let L=(P.clientX-A.left)/A.width*t;L=ed(L,v),h(Math.min(Math.max(L,0),t))},T=P=>{if(!p)return;P.preventDefault();const A=P.deltaY>0?-.1:.1,I=Math.max(.5,Math.min(5,e+A));p(I)};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:w,onMouseMove:R,onMouseUp:M,onMouseLeave:M,onWheel:T,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 sd(e){for(const t of Xe)if(!e.includes(t))return t;return Xe[Math.floor(Math.random()*Xe.length)]}const ur=Xe.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function id(e){for(let t=0;t<Xe.length;t++){const n=Xe[t],a=ur[t];if(!e.includes(n)&&!e.includes(a))return a}return ur[Math.floor(Math.random()*ur.length)]}const od="_panel_3bj7x_3",ld="_panelCompact_3bj7x_19",cd="_panelNarrow_3bj7x_25",dd="_panelWide_3bj7x_31",ud="_heading_3bj7x_37",hd="_row_3bj7x_53",pd="_field_3bj7x_65",fd="_buttonRow_3bj7x_71",md="_sliderW200_3bj7x_83",gd="_sliderW240_3bj7x_89",yd="_selectW160_3bj7x_95",vd="_inputW120_3bj7x_101",bd="_inputW160_3bj7x_107",xd="_inputW200_3bj7x_113",Sd="_noteText_3bj7x_123",kd="_noteTextMargin_3bj7x_131",wd="_presetDivider_3bj7x_145",Cd="_presetLabel_3bj7x_159",jd="_countInAlert_3bj7x_173",Md="_levelLabel_3bj7x_181",Rd="_levelMeter_3bj7x_189",Nd="_levelBar_3bj7x_205",Td="_panelInactive_3bj7x_225",Pd="_header_3bj7x_231",Ed="_title_3bj7x_245",$d="_grid2_3bj7x_257",Ad="_full_3bj7x_267",Id="_label_3bj7x_275",Ld="_grow_3bj7x_291",_d="_pushRight_3bj7x_299",zd="_alignStart_3bj7x_305",Dd="_toolbar_3bj7x_311",Fd="_subPanel_3bj7x_325",ye={panel:od,panelCompact:ld,panelNarrow:cd,panelWide:dd,heading:ud,row:hd,field:pd,buttonRow:fd,sliderW200:md,sliderW240:gd,selectW160:yd,inputW120:vd,inputW160:bd,inputW200:xd,noteText:Sd,noteTextMargin:kd,presetDivider:wd,presetLabel:Cd,countInAlert:jd,levelLabel:Md,levelMeter:Rd,levelBar:Nd,panelInactive:Td,header:Pd,title:Ed,grid2:$d,full:Ad,label:Id,grow:Ld,pushRight:_d,alignStart:zd,toolbar:Dd,subPanel:Fd},Tt=e=>Array.isArray(e)?e[0]??"":e,Li=({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.")]})]})},_i=({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(F.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(F.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.")})]})},bs=e=>`${e.toFixed(1)}x`,$a=({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:bs})}),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:bs})}),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)})})]})})},Od=[["peaking","Peaking"],["lowpass","Low-pass"],["highpass","High-pass"],["lowshelf","Low shelf"],["highshelf","High shelf"],["notch","Notch"],["bandpass","Band-pass"]],zi=({masterVolume:e,onMasterVolumeChange:t,filterType:n,filterFreq:a,filterQ:s,filterGain:i,onFilterChange:o,masterEQPresets:l,customPresets:c,onLoadPreset: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:Od.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")})]})]})]})},Di=({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)"}})})]})})},Bd=[{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:[]}],Gd=({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),k=b==="advanced",v=b!=="basic",[w,R]=d.useState(e??Bd),M=t??w,j=d.useCallback(le=>{t===void 0&&R(le),n==null||n(le)},[t,n]),[T,P]=d.useState(!1),[A,I]=d.useState(0),[L,N]=d.useState(1),[_,ee]=d.useState(2),[Y,O]=d.useState(!0),[U,V]=d.useState("beat"),[K,G]=d.useState(a),[W,C]=d.useState(80),[$,S]=d.useState(((ae=M[0])==null?void 0:ae.id)??null),B=d.useRef(0),H=d.useRef(0);d.useEffect(()=>{if(!T)return;H.current=performance.now();const le=ne=>{const pe=(ne-H.current)/1e3;H.current=ne,I(fe=>{const me=fe+pe;return me>=s?(P(!1),s):me}),B.current=requestAnimationFrame(le)};return B.current=requestAnimationFrame(le),()=>cancelAnimationFrame(B.current)},[T,s]);const z=d.useCallback((le,ne)=>j(M.map(pe=>pe.id===le?{...pe,...ne}:pe)),[M,j]),Z=d.useCallback(le=>{const ne=M.reduce((fe,me)=>Math.max(fe,me.id),0)+1,pe=M.filter(fe=>fe.type===le).length+1;j([...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,j]),E=d.useCallback(le=>j(M.filter(ne=>ne.id!==le)),[M,j]),q=d.useCallback(()=>{if(c){c();return}j([]),I(0),P(!1)},[c,j]),X=d.useCallback((le,ne,pe,fe)=>{const me=M.find(je=>je.id===le),he=(me==null?void 0:me.notes)??[],we=he.reduce((je,Ne)=>Math.max(je,Ne.id),0)+1;z(le,{notes:[...he,{id:we,pitch:ne,start:pe,duration:fe,velocity:100}]})},[M,z]),re=d.useCallback((le,ne)=>{const pe=M.find(fe=>fe.id===le);z(le,{notes:((pe==null?void 0:pe.notes)??[]).filter(fe=>fe.id!==ne)})},[M,z]),oe=d.useMemo(()=>{const le=Math.floor(A/60),ne=Math.floor(A%60),pe=Math.floor(A%1*100);return`${le}:${ne.toString().padStart(2,"0")}.${pe.toString().padStart(2,"0")}`},[A]),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:q},...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:()=>Z("audio")},{id:"add-midi",label:m("studio.addMidi","Add MIDI track"),onClick:()=>Z("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:`${Y?"• ":" "}${m("studio.snap","Snap to grid")}`,onClick:()=>O(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,Y,q,u,h,p,M,Z]),D=r.jsxs(r.Fragment,{children:[r.jsxs(ie.NiceButton,{variant:"primary",size:"sm",onClick:()=>P(le=>!le),children:[T?r.jsx(F.NtdPause,{size:14}):r.jsx(F.NtdPlay,{size:14})," ",T?m("studio.pause","Pause"):m("studio.play","Play")]}),r.jsxs(ie.NiceButton,{variant:"secondary",size:"sm",onClick:()=>{P(!1),I(0)},children:[r.jsx(F.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:()=>Z("audio"),children:[r.jsx(F.NtdPlus,{size:14})," ",m("studio.addAudioShort","Audio")]}),v&&r.jsxs(ie.NiceButton,{variant:"outline",size:"sm",onClick:()=>Z("midi"),children:[r.jsx(F.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:W,onChange:C,min:0,max:100})})]}),J=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")]}),k&&$!=null&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"·"}),r.jsxs("span",{children:[m("studio.active","Active"),": ",((ce=M.find(le=>le.id===$))==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:D,statusBar:J,children:[v&&r.jsx("div",{style:{padding:"6px 12px",borderBottom:"1px solid var(--nice-border-color)"},children:r.jsx($a,{zoom:L,setZoom:N,uiZoom:_,setUiZoom:ee,snapEnabled:Y,onToggleSnap:()=>O(le=>!le),snapMode:U,onSnapModeChange:V,bpm:K,setBpm:G})}),r.jsx("div",{style:{padding:8},children:r.jsx(Ii,{zoom:L,duration:s,isPlaying:T,isRecording:!1,currentTime:A,bpm:K,snapEnabled:Y,snapMode:U,onCurrentTimeChange:I,onZoomChange:N})}),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",{onFocus:()=>S(le.id),style:{display:"flex",gap:8,padding:8,borderTop:"1px solid var(--nice-border-color)",background:$===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=>z(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:()=>z(le.id,{muted:!le.muted}),children:"M"}),v&&r.jsx(ie.NiceButton,{variant:le.solo?"warning":"ghost",size:"sm",onClick:()=>z(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=>z(le.id,{volume:ne/100}),min:0,max:100})}),r.jsx(ie.NiceButton,{variant:"ghost",size:"sm",onClick:()=>E(le.id),children:r.jsx(F.NtdClose,{size:14})})]})]}),r.jsx("div",{style:{flex:1,minWidth:0,opacity:le.muted?.5:1},children:le.type==="audio"?r.jsx(Pi,{audioBlob:le.audioBlob??null,currentTime:A,duration:s,zoom:L,height:80,waveColor:le.color,onSeek:I}):r.jsx(Ea,{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))]})},Fi=({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=ke.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})},Wd=({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",{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(F.NtdStop,{size:14}):r.jsx(F.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(F.NtdStar,{size:14,style:{color:e.favorite?"var(--nice-warning, #facc15)":"var(--nice-text-muted)"}})}),r.jsx("div",{className:"nice-sample-row__name",title:e.name,children:e.name}),s&&r.jsx("div",{className:"nice-sample-row__waveform",children:r.jsx(Fi,{data:e.waveformData,progress:a})}),r.jsx("div",{className:"nice-sample-row__duration",children:g(e.duration)}),i&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"nice-sample-row__bpm",children:e.bpm?`${e.bpm} BPM`:"—"}),r.jsx("div",{className:"nice-sample-row__key",children:e.key||"—"})]}),r.jsx("div",{className:"nice-sample-row__size",children:y(e.fileSize)}),e.tags&&e.tags.length>0&&r.jsx("div",{className:"nice-sample-row__tags",children:e.tags.slice(0,2).map(m=>r.jsx("span",{className:"nice-sample-row__tag",children:m},m))})]})},Vd=({folders:e=[],samples:t=[],onSampleSelect:n,onSampleDragStart:a,onFolderSelect:s,onAnalyze:i,audioContext:o,showWaveform:l=!0,showAnalysis:c=!0,sortBy:u="name",sortDirection:h="asc",filterTags:p,searchQuery:g="",className:y=""})=>{const{t:m}=xe(),[x,b]=d.useState(null),[f,k]=d.useState(null),[v,w]=d.useState(null),[R,M]=d.useState(0),[j,T]=d.useState(new Map),[P,A]=d.useState(t),I=d.useRef(null),L=d.useRef(null);d.useEffect(()=>(I.current=new Audio,I.current.addEventListener("ended",()=>{w(null),M(0)}),()=>{I.current&&(I.current.pause(),I.current=null),L.current&&clearInterval(L.current)}),[]);const N=d.useMemo(()=>{let K=[...P];if(g){const G=g.toLowerCase();K=K.filter(W=>{var C;return W.name.toLowerCase().includes(G)||((C=W.tags)==null?void 0:C.some($=>$.toLowerCase().includes(G)))})}return p&&p.length>0&&(K=K.filter(G=>{var W;return(W=G.tags)==null?void 0:W.some(C=>p.includes(C))})),f&&(K=f.samples||[]),K.sort((G,W)=>{var $,S;let C=0;switch(u){case"name":C=G.name.localeCompare(W.name);break;case"duration":C=G.duration-W.duration;break;case"bpm":C=(G.bpm||0)-(W.bpm||0);break;case"key":C=(G.key||"").localeCompare(W.key||"");break;case"date":C=((($=G.dateAdded)==null?void 0:$.getTime())||0)-(((S=W.dateAdded)==null?void 0:S.getTime())||0);break}return h==="asc"?C:-C}),K},[P,g,p,f,u,h]),_=d.useCallback(K=>{b(K),n==null||n(K)},[n]),ee=d.useCallback(async K=>{if(I.current&&(I.current.pause(),L.current&&clearInterval(L.current),I.current.src=K.url||K.path,I.current.play(),w(K.id),M(0),L.current=window.setInterval(()=>{I.current&&M(I.current.currentTime/I.current.duration)},50),c&&!j.has(K.id)&&i))try{const G=await i(K);T(W=>new Map(W).set(K.id,G)),A(W=>W.map(C=>C.id===K.id?{...C,bpm:G.bpm,key:G.key,waveformData:G.waveformData}:C))}catch(G){console.error("Failed to analyze sample:",G)}},[c,j,i]),Y=d.useCallback(()=>{I.current&&(I.current.pause(),I.current.currentTime=0),L.current&&clearInterval(L.current),w(null),M(0)},[]),O=d.useCallback(K=>{A(G=>G.map(W=>W.id===K?{...W,favorite:!W.favorite}:W))},[]),U=d.useCallback((K,G)=>{G.dataTransfer.setData("application/json",JSON.stringify(K)),G.dataTransfer.effectAllowed="copy",a==null||a(K,G)},[a]),V=(K,G=0)=>{var W;return r.jsxs("div",{className:"nice-sample-folder",style:{paddingLeft:G*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:()=>{k(K),s==null||s(K)},children:[r.jsx("span",{className:"nice-sample-folder__icon","aria-hidden":"true",children:r.jsx(F.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})]}),(W=K.children)==null?void 0:W.map(C=>V(C,G+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:()=>k(null),children:[r.jsx("span",{className:"nice-sample-folder__icon","aria-hidden":"true",children:r.jsx(F.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:N.length===0?r.jsx("div",{className:"nice-sample-browser__empty",children:m("sampleBrowser.noSamplesFound","No samples found")}):N.map(K=>r.jsx(Wd,{sample:K,isSelected:(x==null?void 0:x.id)===K.id,isPlaying:v===K.id,playProgress:v===K.id?R:0,showWaveform:l,showAnalysis:c,onSelect:()=>_(K),onPlay:()=>ee(K),onStop:Y,onDragStart:G=>U(K,G),onFavorite:()=>O(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(Fi,{data:x.waveformData,width:300,height:80,progress:v===x.id?R: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 Oi(e){return{past:[],present:e,future:[]}}function Bi(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function Gi(e){if(e.past.length===0)return e;const t=e.past[e.past.length-1];return{past:e.past.slice(0,-1),present:t,future:[e.present,...e.future]}}function Wi(e){if(e.future.length===0)return e;const t=e.future[0];return{past:[...e.past,e.present],present:t,future:e.future.slice(1)}}function Vi(e){return e.past.length>0}function Ui(e){return e.future.length>0}function da(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>({...n}))}function qi(e,t,n){if(t.length===0)return e;const a=Math.min(...t.map(o=>o.time)),s=n-a,i=t.map(o=>({...o,id:Date.now()+Math.floor(Math.random()*1e4)+o.id,time:o.time+s}));return[...e,...i]}function Hi(e,t){const n=[],a=[];for(const s of e)s.time>=t.start&&s.time<=t.end?n.push({...s}):a.push(s);return{remaining:a,cut:n}}function Ki(e,t){return e.filter(n=>n.time<t.start||n.time>t.end)}function Ud(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>n.id)}function Yi(e,t,n,a){const s={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:a};return[...e,s]}function Zi(e,t=3){if(e.length<=2)return e;const n=[...e].sort((s,i)=>s.time-i.time),a=[n[0]];for(let s=1;s<n.length-1;s++)s%t===0&&a.push(n[s]);return a.push(n[n.length-1]),a}function Xi(e){return JSON.stringify(e,null,2)}function Qi(e){try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&"id"in n&&"cc"in n&&"value"in n&&"time"in n):[]}catch{return[]}}function 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 qd(e,t){switch(t.type){case"UNDO":return Gi(e);case"REDO":return Wi(e);default:{let n=e.present;switch(t.type){case"ADD_EVENT":{const a=[...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=qi(a,t.clipboard,t.targetTime);n=jt(n,t.layerId,s);break}case"CUT":{const a=gt(n,t.layerId),{remaining:s}=Hi(a,t.range);n=jt(n,t.layerId,s);break}case"DELETE_RANGE":{const a=gt(n,t.layerId),s=Ki(a,t.range);n=jt(n,t.layerId,s);break}case"RECORD":{const a=gt(n,t.layerId),s=Yi(a,t.cc,t.value,t.time);n=jt(n,t.layerId,s);break}case"THIN":{const a=gt(n,t.layerId),s=Zi(a,t.keepEveryN);n=jt(n,t.layerId,s);break}case"IMPORT":{const a=Qi(t.json);a.length>0&&(n=jt(n,t.layerId,a));break}}return Bi(e,n)}}}function Ji(e=[]){const[t,n]=d.useReducer(qd,Oi(e)),a=d.useRef([]),s=d.useCallback(v=>gt(t.present,v),[t.present]),i=d.useCallback((v,w)=>n({type:"ADD_EVENT",layerId:v,event:w}),[]),o=d.useCallback((v,w,R,M,j)=>n({type:"UPDATE_EVENT",layerId:v,id:w,value:R,time:M,handleType:j}),[]),l=d.useCallback((v,w)=>n({type:"REMOVE_EVENT",layerId:v,id:w}),[]),c=d.useCallback((v,w)=>n({type:"SET_EVENTS",layerId:v,events:w}),[]),u=d.useCallback(()=>n({type:"UNDO"}),[]),h=d.useCallback(()=>n({type:"REDO"}),[]),p=d.useCallback((v,w)=>{a.current=da(gt(t.present,v),w)},[t.present]),g=d.useCallback((v,w)=>{a.current=da(gt(t.present,v),w),n({type:"CUT",layerId:v,range:w})},[t.present]),y=d.useCallback((v,w)=>{a.current.length>0&&n({type:"PASTE",layerId:v,clipboard:a.current,targetTime:w})},[]),m=d.useCallback((v,w)=>n({type:"DELETE_RANGE",layerId:v,range:w}),[]),x=d.useCallback((v,w,R,M)=>n({type:"RECORD",layerId:v,cc:w,value:R,time:M}),[]),b=d.useCallback((v,w)=>n({type:"THIN",layerId:v,keepEveryN:w}),[]),f=d.useCallback(v=>Xi(gt(t.present,v)),[t.present]),k=d.useCallback((v,w)=>n({type:"IMPORT",layerId:v,json:w}),[]);return{snapshots:t.present,getEvents:s,addEvent:i,updateEvent:o,removeEvent:l,setEvents:c,undo:u,redo:h,canUndo:Vi(t),canRedo:Ui(t),copy:p,cut:g,paste:y,clipboard:a.current,deleteRange:m,record:x,thin:b,exportLane:f,importLane:k}}let Hd=Date.now();function yn(){return Hd++}function Kd(e,t,n=.01){if(e.length===0)return[];const a=[];let s=-1/0;for(const i of e)i.time-s>=n&&(a.push({id:yn(),cc:t,value:vn(i.value),time:i.time}),s=i.time);return a}function xs(e,t,n,a=32){const s=[];for(let i=0;i<=a;i++){const o=i/a;s.push({id:yn(),cc:n,value:vn(jr(e.value,t.value,o)),time:jr(e.time,t.time,o)})}return s}function Yd(e,t,n,a,s=48){const i=[];for(let o=0;o<=s;o++){const l=o/s,c=Ss(e.time,t.time,n.time,l),u=Ss(e.value,t.value,n.value,l);i.push({id:yn(),cc:a,value:vn(u),time:c})}return i}function Zd(e,t,n,a=8){const s=[],i=(t.time-e.time)/a,o=(t.value-e.value)/a;for(let l=0;l<a;l++){const c=e.time+l*i,u=vn(e.value+l*o);s.push({id:yn(),cc:n,value:u,time:c}),s.push({id:yn(),cc:n,value:u,time:c+i-.001})}return s}function Xd(e,t,n,a=2,s=32){const i=[];for(let o=0;o<=s;o++){const l=o/s,c=Math.pow(l,a);i.push({id:yn(),cc:n,value:vn(jr(e.value,t.value,c)),time:jr(e.time,t.time,l)})}return i}function Qd(e,t=3){if(e.length<t)return e;const n=[...e].sort((a,s)=>a.time-s.time);return n.map((a,s)=>{const i=Math.max(0,s-Math.floor(t/2)),o=Math.min(n.length,i+t),l=n.slice(i,o),c=l.reduce((u,h)=>u+h.value,0)/l.length;return{...a,value:vn(Math.round(c))}})}function Jd(e,t){let n;switch(e.mode){case"pencil":n=Kd(t,e.cc,e.resolution);break;case"line":n=t.length>=2?xs(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?n=Yd(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?n=xs(t[0],t[t.length-1],e.cc):n=[];break;case"step":n=t.length>=2?Zd(t[0],t[t.length-1],e.cc):[];break;case"ramp":n=t.length>=2?Xd(t[0],t[t.length-1],e.cc):[];break;default:n=[]}if(e.smoothing>0){const a=Math.max(2,Math.round(e.smoothing*8));n=Qd(n,a)}return n}function vn(e){return Math.max(0,Math.min(127,Math.round(e)))}function jr(e,t,n){return e+(t-e)*n}function Ss(e,t,n,a){const s=1-a;return s*s*e+2*s*a*t+a*a*n}function _r(){return{waveform:"sine",rate:1,depth:.5,phase:0,center:.5,syncToBpm:!1,syncDivision:"1/4",enabled:!0}}const eu={"4/1":.25,"2/1":.5,"1/1":1,"1/2":2,"1/4":4,"1/8":8,"1/16":16,"1/32":32,"1/2t":3,"1/4t":6,"1/8t":12,"1/16t":24};function eo(e,t){return e/60*eu[t]/4}function to(e,t){const n=(t%1+1)%1;switch(e){case"sine":return Math.sin(n*2*Math.PI);case"triangle":return n<.5?4*n-1:3-4*n;case"sawtooth":return 2*n-1;case"square":return n<.5?1:-1;case"random":return Math.sin(n*127.1)*Math.cos(n*311.7)*2;case"sample-hold":return Math.sin(Math.floor(n*4)*2.399+.5)*2-1;default:return 0}}function Aa(e,t,n){if(!e.enabled)return e.center;const a=e.syncToBpm&&n?eo(n,e.syncDivision):e.rate,s=t*a+e.phase/(2*Math.PI),i=to(e.waveform,s),o=e.center+i*e.depth*.5;return Math.max(0,Math.min(1,o))}function Ia(e,t,n){return Math.round(Aa(e,t,n)*127)}function no(e,t,n,a,s=30,i){const o=n-t,l=Math.max(2,Math.ceil(o*s)),c=[];for(let u=0;u<=l;u++){const h=t+u/l*o,p=Ia(e,h,i);c.push({time:h,value:p,cc:a})}return c}function ro(e,t,n,a=2,s,i=200){const o=[];for(let l=0;l<=i;l++){const c=l/i*a,u=Aa(e,c,s);o.push({x:l/i*t,y:(1-u)*n})}return o}function tu(e){return JSON.stringify(e,null,2)}function nu(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const Yr=140,bn=24,ru=[{cc:1,key:"modWheel",label:"Mod Wheel"},{cc:7,key:"volume",label:"Volume"},{cc:10,key:"pan",label:"Pan"},{cc:11,key:"expression",label:"Expression"},{cc:64,key:"sustain",label:"Sustain"},{cc:74,key:"brightness",label:"Brightness"}],au=[{mode:"pencil",label:"Pencil"},{mode:"line",label:"Line"},{mode:"curve",label:"Curve"},{mode:"step",label:"Step"},{mode:"ramp",label:"Ramp"}],su=["sine","triangle","sawtooth","square","random","sample-hold"],iu=({layerId:e=0,ccNumber:t,duration:n=8,zoom:a=1,automation:s,onChangeCCNumber:i})=>{const o=Ji(),l=s??o,[c,u]=ke.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,k]=d.useState(null),[v,w]=d.useState(!1),[R,M]=d.useState(_r()),j=d.useRef(null),T=l.getEvents(e),P=T.filter(C=>C.cc===c),A=Math.max(400,n*30*a),I=d.useCallback(C=>C/A*n,[A,n]),L=d.useCallback(C=>Math.round(Math.max(0,Math.min(127,127-(C-bn)/Yr*127))),[]),N=d.useCallback(C=>C/n*A,[A,n]),_=d.useCallback(C=>bn+(127-C)/127*Yr,[]),ee=d.useCallback(()=>{const C=p.current;if(!C)return;const $=C.getContext("2d");if(!$)return;const S=C.width,B=C.height;$.clearRect(0,0,S,B),$.fillStyle=ke.resolveCssColor("var(--nice-bg, #1a1a2e)",$.canvas),$.fillRect(0,0,S,B);const H=ke.resolveCssColor("var(--nice-border-color, #cbd5e1)",$.canvas);$.strokeStyle=H,$.lineWidth=1,$.globalAlpha=.5;for(let E=0;E<=127;E+=16){const q=_(E);$.beginPath(),$.moveTo(0,q),$.lineTo(S,q),$.stroke()}$.globalAlpha=1,$.fillStyle=ke.resolveCssColor("var(--nice-text-muted, #64748b)",$.canvas),$.font="10px monospace",$.textBaseline="middle";for(const E of[0,32,64,96,127])$.fillText(String(E),2,_(E));$.strokeStyle=H,$.globalAlpha=.3;for(let E=0;E<=n;E++){const q=N(E);$.beginPath(),$.moveTo(q,0),$.lineTo(q,B),$.stroke()}$.globalAlpha=1;const z=[...P].sort((E,q)=>E.time-q.time);if(z.length>0){$.beginPath(),$.moveTo(N(z[0].time),B-bn);for(const E of z)$.lineTo(N(E.time),_(E.value));$.lineTo(N(z[z.length-1].time),B-bn),$.closePath(),$.fillStyle=ke.resolveCssColor("var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",$.canvas),$.fill(),$.beginPath(),$.strokeStyle=ke.resolveCssColor("var(--nice-primary, #3b82f6)",$.canvas),$.lineWidth=2;for(let E=0;E<z.length;E++){const q=N(z[E].time),X=_(z[E].value);E===0?$.moveTo(q,X):((z[E].handleType??"linear")==="step"&&$.lineTo(q,_(z[E-1].value)),$.lineTo(q,X))}$.stroke();for(const E of z){const q=N(E.time),X=_(E.value),re=f===E.id;$.beginPath(),$.arc(q,X,re?6:4,0,Math.PI*2),$.fillStyle=ke.resolveCssColor(re?"var(--nice-primary-light, #60a5fa)":"var(--nice-primary, #3b82f6)",$.canvas),$.fill(),$.strokeStyle=ke.resolveCssColor("var(--nice-bg, #fff)",$.canvas),$.lineWidth=1.5,$.stroke()}}$.strokeStyle=H,$.lineWidth=1,$.setLineDash([4,4]);const Z=_(0);$.beginPath(),$.moveTo(0,Z),$.lineTo(S,Z),$.stroke(),$.setLineDash([])},[P,n,N,_,f]);d.useEffect(()=>{ee()},[ee]);const Y=C=>{var H;const $=(H=p.current)==null?void 0:H.getBoundingClientRect();if(!$)return;const S=C.clientX-$.left,B=C.clientY-$.top;g==="pencil"?(x(!0),b.current=[{time:I(S),value:L(B)}]):(x(!0),b.current=[{time:I(S),value:L(B)}])},O=C=>{var Z;const $=(Z=p.current)==null?void 0:Z.getBoundingClientRect();if(!$)return;const S=C.clientX-$.left,B=C.clientY-$.top;m&&b.current.push({time:I(S),value:L(B)});const H=[...P].sort((E,q)=>E.time-q.time);let z=null;for(const E of H){const q=N(E.time),X=_(E.value);if(Math.abs(S-q)<8&&Math.abs(B-X)<8){z=E.id;break}}k(z)},U=()=>{if(!m)return;x(!1);const C=b.current;if(C.length===0)return;const $=Jd({mode:g,cc:c,resolution:.02,smoothing:g==="pencil"?.3:0},C);$.length>0&&l.setEvents(e,[...T,...$]),b.current=[]},V=C=>{var H;const $=(H=p.current)==null?void 0:H.getBoundingClientRect();if(!$)return;const S=C.clientX-$.left,B=C.clientY-$.top;for(const z of P){const Z=N(z.time),E=_(z.value);if(Math.abs(S-Z)<8&&Math.abs(B-E)<8){l.removeEvent(e,z.id);return}}l.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:c,value:L(B),time:I(S)})},K=()=>{const $=no(R,0,n,c,Math.ceil(n*20),120).map((S,B)=>({...S,id:Date.now()+B}));l.setEvents(e,[...T,...$]),w(!1)},G=()=>{const C=l.exportLane(e),$=new Blob([C],{type:"application/json"}),S=URL.createObjectURL($),B=document.createElement("a");B.href=S,B.download=`cc-lane-${c}-layer-${e}.json`,document.body.appendChild(B),B.click(),B.remove(),URL.revokeObjectURL(S)},W=C=>{var S;const $=(S=C.target.files)==null?void 0:S[0];$&&($.text().then(B=>{l.importLane(e,B)}),j.current&&(j.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:C=>u(Number(Tt(C))),options:ru.map(C=>({value:String(C.cc),label:h("ccLane.cc2","{label} (CC{cc})").replace("{label}",String(h(`ccLane.preset.${C.key}`,C.label))).replace("{cc}",String(C.cc))}))}),r.jsx(ie.NiceSegmentedControl,{size:"sm",value:g,onChange:y,options:au.map(C=>({value:C.mode,label:h(`ccLane.mode.${C.mode}`,C.label)}))}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(F.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(F.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:()=>w(!v),title:h("ccLane.lfoHint","Apply LFO modulation"),children:h("ccLane.lfo","LFO")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:G,title:h("ccLane.exportHint","Export CC lane as JSON"),children:h("ccLane.export","Export")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",onClick:()=>{var C;return(C=j.current)==null?void 0:C.click()},title:h("ccLane.importHint","Import CC lane from JSON"),children:h("ccLane.import","Import")}),r.jsx("input",{ref:j,type:"file",accept:".json",hidden:!0,onChange:W}),r.jsx(ie.NiceButton,{size:"sm",variant:"danger",onClick:()=>l.setEvents(e,T.filter(C=>C.cc!==c)),title:h("ccLane.clearHint","Clear all CC events for this lane"),children:h("ccLane.clear","Clear")}),r.jsxs("span",{className:`${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:R.waveform,onChange:C=>M($=>({...$,waveform:Tt(C)})),options:su.map(C=>({value:C,label:C}))}),r.jsx(ie.NiceNumberInput,{size:"sm",className:ye.inputW120,label:h("ccLane.lfoRate","Rate (Hz)"),min:.01,max:20,step:.1,precision:2,value:R.rate,onChange:C=>{C!==null&&M($=>({...$,rate:C}))}}),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:R.depth,onChange:C=>M($=>({...$,depth:C})),showValue:!0,formatValue:C=>C.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:R.center,onChange:C=>M($=>({...$,center:C})),showValue:!0,formatValue:C=>C.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:()=>w(!1),children:h("ccLane.cancel","Cancel")})]})]}),r.jsx("div",{style:{overflowX:"auto",borderRadius:6},children:r.jsx("canvas",{ref:p,width:A,height:Yr+bn*2,style:{cursor:m?"crosshair":f?"pointer":"crosshair",display:"block",borderRadius:6},onMouseDown:Y,onMouseMove:O,onMouseUp:U,onMouseLeave:()=>{m&&U()},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.")})]})},ao={"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":1/1.5,"1/8T":.5/1.5,"1/16T":.25/1.5},ua={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function ou(e,t){const n=[];for(let a=0;a<t;a++)for(const s of e)n.push({...s,pitch:s.pitch+a*12});return n}function so(e,t){if(e.length===0)return[];const n=ou(e,t.octaves),a=[...n].sort((o,l)=>o.pitch-l.pitch),s=[...n].sort((o,l)=>l.pitch-o.pitch);let i;switch(t.mode){case"up":i=a;break;case"down":i=s;break;case"updown":i=[...a,...s.slice(1,-1)];break;case"downup":i=[...s,...a.slice(1,-1)];break;case"random":i=[...n].sort(()=>Math.random()-.5);break;case"as-played":i=[...n].sort((o,l)=>o.originalOrder-l.originalOrder);break;case"chord":i=n;break;default:i=a}if(t.repeats>1){const o=[];for(const l of i)for(let c=0;c<t.repeats;c++)o.push(l);i=o}return i}function lu(e,t,n,a=0,s=1){const i=so(e,t);if(i.length===0)return[];const o=60/n,l=ao[t.rate]*o,c=l*t.gate,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 io(){return[{mode:"up",label:"Up",description:"Notes played low to high"},{mode:"down",label:"Down",description:"Notes played high to low"},{mode:"updown",label:"Up/Down",description:"Alternates up then down"},{mode:"downup",label:"Down/Up",description:"Alternates down then up"},{mode:"random",label:"Random",description:"Random note order"},{mode:"as-played",label:"As Played",description:"Order in which notes were pressed"},{mode:"chord",label:"Chord",description:"All notes played simultaneously"}]}function oo(){return Object.keys(ao)}const ks=e=>`${Math.round(e*100)}%`,cu=({config:e=ua,onChange:t=()=>{},active:n=!1,onToggleActive:a=()=>{}})=>{const{t:s}=xe(),i=io(),o=oo(),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(ua),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:ks}),r.jsx(ie.NiceSlider,{size:"sm",label:s("arp.swing","Swing"),min:0,max:1,step:.01,value:e.swing,onChange:c=>l({swing:c}),showValue:!0,formatValue:ks}),r.jsx(ie.NiceSlider,{size:"sm",label:s("arp.repeats","Repeats"),min:1,max:4,step:1,value:e.repeats,onChange:c=>l({repeats:c}),showValue:!0})]})]})},ws=e=>`${Math.round(e*100)}%`,du=["sine","triangle","sawtooth","square","random","sample-hold"],uu=["1/1","1/2","1/4","1/8","1/16","1/32"],xn=200,en=48,hu=({config:e,onChange:t,index:n,onRemove:a})=>{const{t:s}=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,xn,en),u.fillStyle=ke.resolveCssColor("var(--nice-bg-secondary, #161b22)",u.canvas),u.fillRect(0,0,xn,en),u.strokeStyle=ke.resolveCssColor("var(--nice-border-color, #cbd5e1)",u.canvas),u.lineWidth=1,u.setLineDash([3,3]),u.beginPath(),u.moveTo(0,en/2),u.lineTo(xn,en/2),u.stroke(),u.setLineDash([]);const h=ro(e,xn,en);if(h.length>0){u.beginPath(),u.strokeStyle=ke.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(_r()),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(F.NtdClose,{size:12})})})]}),r.jsxs("div",{className:`${ye.row} ${ye.alignStart}`,children:[r.jsx("canvas",{ref:i,width:xn,height:en,style:{borderRadius:4,border:"1px solid var(--nice-border-color, #30363d)",flexShrink:0},role:"img","aria-label":s("lfo.preview","LFO waveform preview")}),r.jsxs("div",{className: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:du.map(c=>({value:c,label:r.jsx("span",{title:c,children:c==="sample-hold"?"S&H":c.slice(0,3)})}))})}),r.jsxs("div",{className: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:ws}),r.jsx(ie.NiceSlider,{size:"xs",label:s("lfo.center","Center"),min:0,max:1,step:.01,value:e.center,onChange:c=>o({center:c}),showValue:!0,formatValue:ws}),r.jsx(ie.NiceSlider,{size:"xs",label:s("lfo.phase","Phase"),min:0,max:360,step:1,value:e.phase,onChange:c=>o({phase:c}),showValue:!0,formatValue:c=>`${Math.round(c)}°`})]}),r.jsxs("div",{className: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:uu.map(c=>({value:c,label:c}))}),r.jsx(ie.NiceNumberInput,{size:"xs",label:s("lfo.cc","CC"),min:0,max:127,value:e.targetCC??1,onChange:c=>o({targetCC:c??1})})]})]})]})]})},pu=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],fu=[16,32,64],mu=e=>`${Math.round(e*100)}%`;function Cs(e){const t=Math.floor(e/12)-1;return`${pu[e%12]}${t}`}const gu=({seq:e})=>{const{t}=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(F.NtdStop,{size:12}):r.jsx(F.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:mu})}),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:fu.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(F.NtdArrowRight,{size:12}),onClick:()=>e.shift(1),children:t("stepSeq.shift","Shift")}),r.jsx(ie.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(F.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?`, ${Cs(l.note)}`:""}`,onClick:()=>e.toggle(c),style:{width:32,height:32,borderRadius:4,border:h?"2px solid var(--nice-warning, #f0c040)":"1px solid var(--nice-border, #30363d)",background: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?Cs(l.note):""}),r.jsx("div",{style:{width:32,height:20,background:"var(--nice-bg-secondary, #161b22)",borderRadius:2,position:"relative",overflow:"hidden",cursor:"ns-resize",touchAction:"none"},title:`${t("stepSeq.velocity","Velocity")}: ${l.velocity}`,onPointerDown:o(c),children:r.jsx("div",{style:{position:"absolute",bottom:0,left:0,width:"100%",height:`${l.velocity/127*100}%`,background: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 yu(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("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 vu(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((j,T)=>`L${j}-C${T}`,[]),x=d.useCallback((j,T)=>{if(!a.current||!T.audioBuffer)return;const P=m(j,T.id),A=e[j];a.current.addClip({id:P,buffer:T.audioBuffer,startTime:T.start,offset:0,duration:T.duration,layerId:j,volume:(A==null?void 0:A.volume)??1,pan:(A==null?void 0:A.pan)??0,stretchFactor:T.stretchFactor||1,effectChain:(A==null?void 0:A.effectChain)||[]})},[e,m]),b=d.useCallback((j,T)=>{var P;(P=a.current)==null||P.removeClip(m(j,T))},[m]);d.useEffect(()=>{Object.entries(t).forEach(([j,T])=>{const P=Number(j);T==null||T.forEach(A=>x(P,A))})},[t,e,x]),d.useEffect(()=>{a.current&&Object.entries(n).forEach(([j,T])=>{const P=Number(j);a.current.setMidiCCEvents(P,T)})},[n]);const f=d.useCallback(()=>{a.current&&(s?a.current.pause():a.current.play())},[s]),k=d.useCallback(()=>{var j;(j=a.current)==null||j.stop()},[]),v=d.useCallback(j=>{var T;(T=a.current)==null||T.seek(j)},[]),w=d.useCallback(()=>{if(!a.current)return;const j=!h;p(j),a.current.setLoopRegion(0,c,j)},[h,c]),R=d.useCallback(j=>{var P;const T=Math.max(1,c+j);u(T),(P=a.current)==null||P.setLoopRegion(0,T,h)},[c,h]),M=d.useCallback(async(j,T=1024)=>{const P=await j.arrayBuffer(),A=new(window.AudioContext||window.webkitAudioContext),I=await A.decodeAudioData(P.slice(0)),L=I.getChannelData(0),N=L.length,_=Math.max(1,Math.floor(N/T)),ee=[];for(let Y=0;Y<T;Y++){const O=Y*_;if(O>=N)break;ee.push(L[O])}return A.close(),{waveform:ee.map(Y=>Math.max(-1,Math.min(1,Y))),duration:I.duration,buffer:I}},[]);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:k,handleSeek:v,handleToggleLoop:w,handleAdjustDuration:R,upsertEngineClip:x,removeEngineClip:b,makeEngineClipId:m,blobToWaveform:M}}class La{constructor(){this.stream=null,this.mediaRecorder=null,this.audioChunks=[],this.isRecording=!1,this.audioContext=null,this.analyser=null,this.gainNode=null,this.monitorGain=null,this.levelRaf=null}async startRecording(t={}){if(this.isRecording)return;this.levelCallback=t.onLevel,this.stream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t.deviceId||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}});const n=t.mimeType||"audio/webm";this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:n}),this.audioChunks=[],this.audioContext=new(window.AudioContext||window.webkitAudioContext);let s=this.audioContext.createMediaStreamSource(this.stream);t.gain!==void 0&&t.gain>0&&(this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=t.gain,s.connect(this.gainNode),s=this.gainNode),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,s.connect(this.analyser),t.monitorEnabled&&(this.monitorGain=this.audioContext.createGain(),this.monitorGain.gain.value=(t.monitorVolume??100)/100,s.connect(this.monitorGain),this.monitorGain.connect(this.audioContext.destination));const i=()=>{if(!this.analyser)return;const o=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(o);let l=0;for(let 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 bu(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)},[]),k=d.useCallback(async()=>{if(!e.activeLayer){e.showToast("Select a layer to record.","error");return}n||(g.current||(g.current=new La),m.current=y.current??e.currentTime,a(!0),l(0),await g.current.startRecording({onLevel:l}))},[e,n]),v=d.useCallback(async()=>{var N;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:j,duration:T,buffer:P}=await e.blobToWaveform(M),A=e.activeLayer.id;e.setWaveforms(_=>({..._,[A]:j}));const I=Math.max(0,m.current||0),L={id:Date.now(),label:t("useRecording.recording","Recording"),start:I,duration:T,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:(N=e.layerSettings[A])==null?void 0:N.color,blob:M,blobUrl:URL.createObjectURL(M),audioBuffer:P};e.setLayerClips(_=>({..._,[A]:[..._[A]||[],L]})),e.upsertEngineClip(A,L),e.setSelectedClip({layerId:A,clipId:L.id})},[e,f,t]),w=d.useCallback(M=>{if(M<=0){k();return}i(!0),u(M);const j=performance.now();x.current=window.setInterval(()=>{const T=(performance.now()-j)/1e3;u(Math.max(0,M-T))},100),b.current=window.setTimeout(()=>{f(),i(!1),u(0),y.current||k()},M*1e3)},[k,f]),R=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),j=e.punchIn!=null&&e.punchIn>e.currentTime?e.punchIn:null;j&&(y.current=j),e.overdubEnabled&&!e.isPlaying&&e.playEngine(),j?M>0&&w(M):w(M)},[n,s,e,v,w]);return{isRecording:n,isCountIn:s,monitorLevel:o,countInRemaining:c,punchOut:h,setPunchOut:p,armedPunchInRef:y,recorderRef:g,clearCountInTimers:f,startRecordingNow:k,stopRecordingFlow:v,handleRecord:R}}var lo=(e=>(e.Recorder="Recorder",e.AudioClip="Audio Clip",e.SpeechSynth="Speech Synth",e.Stream="Stream",e.KeyboardPad="Keyboard/Pads",e.Keyboard="Keyboard",e.AudioClipCompact="AudioClip",e))(lo||{});const xu={};class Xn{constructor(t,n,a,s={}){this.type=t,this.name=n,this.component=xu[t]??(()=>null),this.audioType=a,this.parameters=s}}new Xn("Recorder","Recorder","vocal",{deviceId:"",gain:1,sensitivity:"high"}),new Xn("Audio Clip","Audio Clip","instrumental",{clipId:null,octave:"4"}),new Xn("Speech Synth","Speech Synth","vocal",{text:"",voice:"default"}),new Xn("Keyboard/Pads","Keyboard","instrumental",{instrument:"piano",preset:"default",velocity:100});function co(e,t,n,a,s){n(i=>t?[...i,t]:i),a([]),s(e)}function Su(e,t,n,a){t(s=>{if(s.length===0)return s;const i=s[s.length-1];return n(o=>e?[e,...o]:o),a(i),s.slice(0,-1)})}function ku(e,t,n,a){n(s=>{if(s.length===0)return s;const i=s[0];return t(o=>e?[...o,e]:o),a(i),s.slice(1)})}class wu{constructor(t={}){this.undoStack=[],this.redoStack=[],this.maxSize=t.maxSize??100,this.onChange=t.onChange}push(t,n,a,s){this.undoStack.push({label:t,category:n,timestamp:Date.now(),oldState:a,newState:s}),this.undoStack.length>this.maxSize&&this.undoStack.shift(),this.redoStack.length=0}undo(){var n;const t=this.undoStack.pop();return t?(this.redoStack.push(t),(n=this.onChange)==null||n.call(this,t,"undo"),t.oldState):null}redo(){var n;const t=this.redoStack.pop();return t?(this.undoStack.push(t),(n=this.onChange)==null||n.call(this,t,"redo"),t.newState):null}get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}get undoLabel(){return this.undoStack.length>0?this.undoStack[this.undoStack.length-1].label:null}get redoLabel(){return this.redoStack.length>0?this.redoStack[this.redoStack.length-1].label:null}get undoCount(){return this.undoStack.length}get redoCount(){return this.redoStack.length}getHistory(){return[...this.undoStack].reverse()}clear(){this.undoStack.length=0,this.redoStack.length=0}undoTo(t){const n=Math.min(t+1,this.undoStack.length);let a=null;for(let s=0;s<n;s++)a=this.undo();return a}}const Cu=st.scoped("useProjectCRUD");function ju(e){const{project:t,activeSection:n,setProject:a,setActiveSection:s,setLayers:i,setActiveLayer:o,setUndoStack:l,setRedoStack:c,addSection:u,addLayer:h}=e,p=d.useCallback(k=>co(k,t,l,c,a),[t,l,c,a]),g=d.useCallback(async()=>{var R;if(!t)return;const k=(((R=t.sections)==null?void 0:R.length)??0)+1,w={id:await u(t.id,"Section",k),projectId:t.id,name:"Section",orderNumber:k,layers:[]};p({...t,sections:[...t.sections||[],w]}),s(w)},[t,p,s,u]),y=d.useCallback(async k=>{var R,M,j;if(!t||!await e.confirm("Delete this section?"))return;await e.deleteSection(k);const w=(t.sections??[]).filter(T=>T.id!==k);p({...t,sections:w}),s(w[0]??null),i(((R=w[0])==null?void 0:R.layers)??[]),o(((j=(M=w[0])==null?void 0:M.layers)==null?void 0:j[0])??null)},[t,p,s,i,o,e]),m=d.useCallback(async()=>{var v;if(!n)return;const k={id:-Date.now(),name:"New Layer",sectionId:n.id,audioSource:lo.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};i(w=>[...w,k]),o(k);try{const w=await h(n.id,k.name,k.audioSource,k.audioSourceParameters);i(R=>R.map(M=>M.id===k.id?{...k,id:w}:M)),t&&p({...t,sections:((v=t.sections)==null?void 0:v.map(R=>R.id===n.id?{...R,layers:[...(R.layers??[]).filter(M=>M.id!==w),{...k,id:w}]}:R))??[]})}catch(w){i(R=>R.filter(M=>M.id!==k.id)),Cu.error("Failed to add layer:",w)}},[n,t,p,i,o,h]),x=d.useCallback(async k=>{var w,R;if((w=e.layerSettings[k])!=null&&w.locked){e.showToast("Layer is locked. Unlock to delete.","error");return}await e.confirm("Delete this layer?")&&((e.layerClips[k]||[]).forEach(M=>e.removeEngineClip(k,M.id)),e.setLayerMidiNotes(M=>{const j={...M};return delete j[k],j}),await e.deleteLayer(k),i(M=>M.filter(j=>j.id!==k)),o(M=>(M==null?void 0:M.id)===k?null:M),t&&p({...t,sections:((R=t.sections)==null?void 0:R.map(M=>M.id===(n==null?void 0:n.id)?{...M,layers:(M.layers??[]).filter(j=>j.id!==k)}:M))??[]}))},[t,n,p,i,o,e]),b=d.useCallback(async()=>{if(!t)return;const k=e.projectVolume===""?void 0:Number(e.projectVolume);if(Number.isNaN(k)){e.setStatusType("error"),e.setStatusMessage("Volume musi byc liczba");return}if(!e.projectName.trim()){e.setStatusType("error"),e.setStatusMessage("Nazwa projektu nie moze byc pusta");return}await e.updateProject(t.id,{name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:k}),p({...t,name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:k}),e.setStatusType("success"),e.setStatusMessage("Project saved")},[t,e,p]),f=d.useCallback(async()=>{var w;if(!n)return;const k=e.sectionName||n.name,v=e.sectionOrder===""?n.orderNumber:Number(e.sectionOrder);if(!k.trim()){e.setStatusType("error"),e.setStatusMessage("Section name cannot be empty");return}if(Number.isNaN(v)){e.setStatusType("error"),e.setStatusMessage("Order musi byc liczba");return}await e.updateSection(n.id,{name:k,orderNumber:v}),s({...n,name:k,orderNumber:v}),t&&p({...t,sections:((w=t.sections)==null?void 0:w.map(R=>R.id===n.id?{...R,name:k,orderNumber:v}:R))??[]}),e.setStatusType("success"),e.setStatusMessage("Section saved")},[n,t,e,p,s]);return{handleAddSection:g,handleDeleteSection:y,handleAddLayer:m,handleDeleteLayer:x,handleSaveProject:b,handleSaveSection:f}}const uo=d.createContext(null);function Mu(){const e=d.useContext(uo);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const _a=({value:e,children:t})=>r.jsx(uo.Provider,{value:e,children:t});process.env.NODE_ENV!=="production"&&(_a.displayName="EditorTrackProvider");const un=(e,t)=>t&&t>0?e*15/t:e/10,za=e=>{for(const t of e){const n=t.trim();if(n.toUpperCase().startsWith("#BPM:")){const a=parseFloat(n.substring(5).replace(",","."));if(isFinite(a)&&a>0)return a}}return null},Ru=(e,t)=>{const n=t??za(e),a=[];let s="",i=0,o="",l=!0;function c(){o.trim()!==""&&(s.length>0&&(s+=" "),s+=o.trim()),o=""}return e.forEach(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=un(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},Nu=(e,t)=>{const n=t??za(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=un(parseFloat(p.substring(y+1,m)),n),k=un(parseFloat(p.substring(m+1,x)),n),v=f+k;i===""&&(o=f);const w=p.substring(b+1);if(w.trim()==="~"){c&&(c.endTime=v);return}let R=w;R.startsWith("~")&&(R=R.substring(1)),l?(h(),u=R.trimEnd(),c={text:"",startTime:f,endTime:v,isGolden:g}):c?(u+=R.trimEnd(),c.endTime=v,g&&(c.isGolden=!0)):(u=R.trimEnd(),c={text:"",startTime:f,endTime:v,isGolden:g}),l=w.endsWith(" ")}}}),h(),i.trim().length>0&&a.push({text:i.trim(),timestamp:o,words:s}),a},ho=(e,t)=>{const n=t??za(e),a=[];let s=[],i=0;function o(){s.length>0&&(a.push({timestamp:i,syllables:[...s]}),s=[])}return e.forEach(l=>{if(!(l.startsWith("#")||l.startsWith("E"))){if(l.startsWith("-")){o();const c=l.trim().split(/\s+/);if(c.length>=2){const u=parseFloat(c[1]);isFinite(u)&&(i=un(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=un(y,n),b=x+un(m,n);s.length===0&&(i=x);const f=l.substring(g+1);if(f.trim()==="~"){s.length>0&&(s[s.length-1].endTime=b);return}let k=f;k.startsWith("~")&&(k=k.substring(1));const v=f.endsWith(" "),w=v?k.slice(0,-1):k;s.push({text:w,startTime:x,endTime:b,isGolden:c,hasTrailingSpace:v})}}}),o(),a},Tu=(e,t,n=3)=>{const a=[];let s=-1;for(let i=0;i<e.length;i++){const o=e[i].timestamp,l=e[i+1]?e[i+1].timestamp:o+5;if(t>=o&&t<l){s=i;break}}if(s>=0){const i=Math.max(0,s-(n-1));for(let o=i;o<=s;o++)a.push(e[o].text)}return a},Pu=(e,t)=>{const n=[];for(const a of e)for(const s of a.words)t>=s.startTime&&t<=s.endTime&&n.push(s);return n},js="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",Ms="var(--karaoke-gold-glow-first, 0 0 12px #FFD700)",Eu="var(--karaoke-active-glow, 0 0 10px rgba(0,229,255,0.6), 0 0 4px rgba(255,230,0,0.4))",$u="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",Au=({song:e,currentTime:t=0})=>{const{t:n}=xe(),a=d.useMemo(()=>!e||!e.notes.length?[]:ho(e.notes.map(c=>c.noteLine),e.bpm??void 0),[e]),s=t-((e==null?void 0:e.gap)??0)/1e3;let i=-1;for(let c=0;c<a.length;c++){const 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:Eu,background:"var(--karaoke-active-bg, linear-gradient(90deg, transparent 0%, rgba(0,229,255,0.08) 20%, rgba(255,230,0,0.06) 80%, transparent 100%))",borderRadius:8,padding:"2px 10px",transition:"text-shadow 0.3s ease, background 0.3s ease"},children: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))":js,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:m?`drop-shadow(${Ms})`:"none",transition:"filter 0.2s ease"},children:g},u):r.jsxs("span",{style:{position:"relative",display:"inline",filter:y?m?`drop-shadow(${Ms})`:`drop-shadow(${$u})`:"none",transition:"filter 0.15s ease"},children:[r.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",visibility:"visible"},children:g}),r.jsx("span",{style:{position:"absolute",left:0,top:0,background:m?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":js,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",clipPath:`inset(0 ${100-p}% 0 0)`,pointerEvents:"none"},children:g})]},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(F.NtdMusic,{size:20})}):r.jsxs("p",{style:{color:"var(--karaoke-waiting-text, #999)",display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(F.NtdMicrophone,{size:18})," ",n("karaokeLyrics.waitingForLyrics","Waiting for lyrics...")]})})},po=d.memo(Au),Zr={},Iu=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_DEBUG_KARAOKE)==="true";function ha(e,t,...n){(Iu||typeof window<"u"&&window.DEBUG_KARAOKE)&&console.log(`%c[KARAOKE-DEBUG]%c [${e}] ${t}`,"background:var(--nice-color-accent-hover, #6c3483);color:var(--nice-text-on-primary, #FFF);padding: var(--nice-space-px, 1px) var(--nice-space-1, 4px);border-radius:var(--nice-radius-sm, 3px);font-weight:bold","color:var(--nice-color-accent-hover, #6c3483);font-weight:bold",...n)}const fo=e=>{for(const t of e){const n=t.trim();if(n.toUpperCase().startsWith("#BPM:")){const a=parseFloat(n.substring(5).replace(",","."));if(isFinite(a)&&a>0)return a}}return null},Rs=(e,t)=>t&&t>0?e*15/t:e/10,Hn=(e,t)=>{const n=t??fo(e),a=[];let s=[];return e.forEach(i=>{const o=i.split(" ");if(!(o.length<4))if(i.startsWith("-"))s.length>0&&(a.push(s),s=[]);else{const l=(o[0]||"").charAt(0),c=l==="*"||l==="G";s.push({startTime:Rs(parseFloat(o[1]),n),duration:Rs(parseFloat(o[2]),n),pitch:parseInt(o[3],10),isGold:c})}}),s.length>0&&a.push(s),a},mo=(e,t)=>{let a=(Math.round(12*Math.log2(e/440)+69)%12+12)%12;if(t!==null){for(;a-t>6;)a-=12;for(;a-t<-6;)a+=12}return a},go=st.scoped("karaokeScoringConfig"),Da={easy:{semitoneTolerance:2,preWindow:.25,postExtra:.3,difficultyMult:.9},normal:{semitoneTolerance:1,preWindow:.15,postExtra:.2,difficultyMult:1},hard:{semitoneTolerance:0,preWindow:.08,postExtra:.12,difficultyMult:1.05}},Lu="karaoke.scoringPresets";function _u(){try{const e=localStorage.getItem(Lu);return e?JSON.parse(e):null}catch(e){return go.warn("Failed to parse scoring presets overrides",e),null}}function yo(e){const t={...Da},n=_u();return n&&Object.keys(n).forEach(a=>{const s=n[a];s&&(t[a]={...t[a],...s})}),e&&Object.keys(e).forEach(a=>{const s=e[a];s&&(t[a]={...t[a],...s})}),t}exports.ScoringPresets=yo();const zu=async e=>{try{let t=null;if(e?t=await e.getKaraokeScoringConfig():(go.debug("No fetcher provided, using defaults"),t=null),t&&t.presets)return exports.ScoringPresets=yo(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},zr=(e="normal")=>exports.ScoringPresets[e]||Da.normal,Du=3,te=Du;function qt(e){const t=e/2|0;return{w:t,out:`M${t} 0H${t}V${e}H${t}A${t} ${t} 0 0 1 0 ${t}A${t} ${t} 0 0 1 ${t} 0Z`,inn:`M${t} ${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 hn(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 Fa(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 Mr(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 Ot(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 Rr(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 Oa(e){const t=e*.16|0,n=t*2+4;return{w:n,out:`M${t*1.5|0} 0H${n}V${e}H${t*1.5|0}C${t*2.5|0} ${e*.35|0} ${t*2.5|0} ${e*.65|0} ${t*1.5|0} ${e}Z`,inn:`M${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 Ba(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 Nr(e){const t=e*.14|0,n=t*3+2;return{w:n,out:`M${t*2} 0H${n}V${e}H${t*2}C${t*.5|0} ${e*.8|0} ${t*3} ${e*.55|0} ${t*.5|0} ${e*.35|0}S${t} 0 ${t*2} 0Z`,inn:`M${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 Ga(e){const t=e*.09|0,n=e*.35|0;return{w:n,out:`M${t*3} 0H${n}V${e}H${t*3}L${t} ${e-t*2}L${t*2} ${e*.65|0}L0 ${e/2|0}L${t*2} ${e*.35|0}L${t} ${t*2}Z`,inn:`M${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 hr(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 pa(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 Dt(e){const t=e/2|0;return{w:t,out:`M0 0A${t} ${t} 0 0 1 ${t} ${t}A${t} ${t} 0 0 1 0 ${e}Z`,inn:`M0 ${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 pn(e){return{w:te+1,out:`M0 0H${te+1}V${e}H0Z`,inn:`M0 ${te}H1V${e-te}H0Z`}}function vo(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 fn(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 bo(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 xo(e){const t=e*.16|0,n=t*2+4;return{w:n,out:`M0 0H${n-(t*1.5|0)}C${n-(t*2.5|0)} ${e*.35|0} ${n-(t*2.5|0)} ${e*.65|0} ${n-(t*1.5|0)} ${e}H0Z`,inn:`M0 ${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 So(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 Wa(e){const t=e*.14|0,n=t*3+2;return{w:n,out:`M0 0H${n-t*2}C${n-t} 0 ${n+(t*.3|0)} ${e*.2|0} ${n-(t*.5|0)} ${e*.35|0}S${n-(t*.5|0)} ${e*.8|0} ${n-t*2} ${e}H0Z`,inn:`M0 ${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 Tr(e){const t=e*.09|0,n=e*.35|0;return{w:n,out:`M0 0H${n-t*3}L${n-t} ${t*2}L${n-t*2} ${e*.35|0}L${n} ${e/2|0}L${n-t*2} ${e*.65|0}L${n-t} ${e-t*2}L${n-t*3} ${e}H0Z`,inn:`M0 ${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 fa(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 pr(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 Va=[{name:"Pill",L:qt,R:Dt},{name:"Sharp",L:hn,R:pn},{name:"Soft",L:Fa,R:vo},{name:"Chamfer",L:Mr,R:fn},{name:"Arrow",L:Ot,R:Nt},{name:"Shield",L:Rr,R:bo},{name:"Bracket",L:Oa,R:xo},{name:"Tab",L:Ba,R:So},{name:"Wave",L:Nr,R:Wa},{name:"Ornate",L:Ga,R:Tr}],ko=[{name:"Pill→Arrow",L:qt,R:Nt},{name:"Arrow→Pill",L:Ot,R:Dt},{name:"Pill→Sharp",L:qt,R:pn},{name:"Sharp→Pill",L:hn,R:Dt},{name:"Pill→Chamfer",L:qt,R:fn},{name:"Chamfer→Pill",L:Mr,R:Dt},{name:"Arrow→Sharp",L:Ot,R:pn},{name:"Sharp→Arrow",L:hn,R:Nt},{name:"Arrow→Chamfer",L:Ot,R:fn},{name:"Chamfer→Arrow",L:Mr,R:Nt},{name:"Soft→Arrow",L:Fa,R:Nt},{name:"Shield→Chamfer",L:Rr,R:fn},{name:"Pill→Wave",L:qt,R:Wa},{name:"Wave→Arrow",L:Nr,R:Nt},{name:"Tab→Pill",L:Ba,R:Dt},{name:"Ornate→Sharp",L:Ga,R:pn},{name:"Sharp→Ornate",L:hn,R:Tr},{name:"Bracket→Arrow",L:Oa,R:Nt},{name:"Shield→Pill",L:Rr,R:Dt},{name:"Wave→Ornate",L:Nr,R:Tr}],wo=[{name:"Skew ╲",L:hr,R:fa},{name:"Skew ╱",L:pa,R:pr},{name:"◇ Romb",L:Ot,R:Nt},{name:"╲→Pill",L:hr,R:Dt},{name:"Pill→╲",L:qt,R:fa},{name:"╱→Sharp",L:pa,R:pn},{name:"Sharp→╱",L:hn,R:pr},{name:"╲→Arrow",L:hr,R:Nt},{name:"Arrow→╱",L:Ot,R:pr},{name:"◇→Chamfer",L:Ot,R:fn}],Wn=(function(){return[...Va,...ko,...wo]})(),Co=Va[0];function Rn(e){return Wn.find(t=>t.name===e)||Co}const Pr=[{name:"Flames",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="12" height="16" patternUnits="userSpaceOnUse"><path d="M6 0C8 3 10 5 9 9C8 12 6 14 6 16C6 14 4 12 3 9C2 5 4 3 6 0Z" fill="${t}" opacity=".5"/><path d="M3 6C4 8 5 10 3 14C1 10 2 8 3 6Z" fill="${a}" opacity=".3"/><path d="M9 6C10 8 11 10 9 14C7 10 8 8 9 6Z" fill="${a}" opacity=".3"/></pattern>`}},{name:"Zigzag",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M0 5L5 0L10 5L5 10Z" fill="${n||t}" fill-opacity=".15" stroke="${t}" stroke-width="1.2" opacity=".55"/></pattern>`},{name:"Scales",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="12" height="8" patternUnits="userSpaceOnUse"><ellipse cx="6" cy="8" rx="6" ry="4.5" fill="none" stroke="${t}" stroke-width="1" opacity=".5"/><ellipse cx="0" cy="4" rx="6" ry="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".3"/><ellipse cx="12" cy="4" rx="6" ry="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".3"/></pattern>`}},{name:"Hex",mk:(e,t,n)=>`<pattern id="${e}" width="18" height="20" patternUnits="userSpaceOnUse"><path d="M9 2L16 6V14L9 18L2 14V6Z" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M9 12L13.5 14.5V19L9 21.5L4.5 19V14.5Z" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Dots",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="8" height="8" patternUnits="userSpaceOnUse"><circle cx="4" cy="4" r="2" fill="${t}" opacity=".5"/><circle cx="0" cy="0" r="1" fill="${a}" opacity=".3"/><circle cx="8" cy="8" r="1" fill="${a}" opacity=".3"/></pattern>`}},{name:"Stars",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M7 1L8.8 5.2L13.2 5.2L9.7 7.8L11 12.2L7 9.4L3 12.2L4.3 7.8L.8 5.2L5.2 5.2Z" fill="${t}" opacity=".45" stroke="${n||t}" stroke-width=".4" stroke-opacity=".3"/></pattern>`},{name:"Diamonds",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M5 .5L9.5 5L5 9.5L.5 5Z" fill="${n||"none"}" fill-opacity=".15" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Waves",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="8" patternUnits="userSpaceOnUse"><path d="M0 4Q4 0 8 4Q12 8 16 4" fill="none" stroke="${t}" stroke-width="1.3" opacity=".5"/><path d="M0 6Q4 2 8 6Q12 10 16 6" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Crosses",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M5 2V8" stroke="${t}" stroke-width="1.3" stroke-linecap="round" opacity=".5"/><path d="M2 5H8" stroke="${n||t}" stroke-width="1.3" stroke-linecap="round" opacity=".5"/></pattern>`},{name:"Triangles",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M6 1L11 9H1Z" fill="${n||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Chevrons",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M0 7L6 1.5L12 7" fill="none" stroke="${t}" stroke-width="1.2" opacity=".55"/><path d="M0 10L6 4.5L12 10" fill="none" stroke="${n||t}" stroke-width=".7" opacity=".25"/></pattern>`},{name:"Hatch ╲",mk:(e,t,n)=>`<pattern id="${e}" width="6" height="6" patternUnits="userSpaceOnUse"><path d="M0 6L6 0" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M-1 1L1 -1M5 7L7 5" stroke="${n||t}" stroke-width=".8" opacity=".3"/></pattern>`},{name:"Hatch ╳",mk:(e,t,n)=>`<pattern id="${e}" width="7" height="7" patternUnits="userSpaceOnUse"><path d="M0 7L7 0" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M0 0L7 7" stroke="${n||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Grid",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M10 0V10" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M0 10H10" fill="none" stroke="${n||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Bricks",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="8" patternUnits="userSpaceOnUse"><rect width="14" height="8" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><line x1="7" y1="0" x2="7" y2="4" stroke="${n||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Hearts",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="12" patternUnits="userSpaceOnUse"><path d="M6 10C4 8 1 6.5 1 4C1 2.3 2.8 1 4.5 2.2L6 4L7.5 2.2C9.2 1 11 2.3 11 4C11 6.5 8 8 6 10Z" fill="${t}" opacity=".4" stroke="${n||t}" stroke-width=".5" stroke-opacity=".3"/></pattern>`},{name:"Arrows",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M3 2L9 5L3 8" fill="${n||"none"}" fill-opacity=".15" stroke="${t}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity=".5"/></pattern>`},{name:"Bolts",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="16" patternUnits="userSpaceOnUse"><path d="M7 1L4 7H8L3 15" fill="none" stroke="${t}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity=".5"/><circle cx="5" cy="11" r="1" fill="${n||t}" opacity=".3"/></pattern>`},{name:"Leaves",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M7 2C10 4 12 7 10 11C8 13 5 12 4 10C3 7 4 4 7 2Z" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M7 3L6 10" stroke="${a}" stroke-width=".6" opacity=".3"/><path d="M5 5L7 6M5 8L7 7.5" stroke="${a}" stroke-width=".4" opacity=".25"/></pattern>`}},{name:"Spirals",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="16" patternUnits="userSpaceOnUse"><path d="M8 4A4 4 0 0 1 12 8A3.5 3.5 0 0 1 8.5 11.5A2.5 2.5 0 0 1 6 9A1.5 1.5 0 0 1 7.5 7.5" fill="none" stroke="${t}" stroke-width="1.2" stroke-linecap="round" opacity=".45"/><circle cx="8" cy="8" r="1" fill="${n||t}" opacity=".25"/></pattern>`},{name:"Moons",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M9 2A5 5 0 1 0 9 12" fill="none" stroke="${t}" stroke-width="1" opacity=".4"/><path d="M9 2A3.5 3.5 0 0 1 9 12" fill="none" stroke="${n||t}" stroke-width="1" opacity=".3"/></pattern>`},{name:"Rings",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="12" patternUnits="userSpaceOnUse"><circle cx="6" cy="6" r="4" fill="none" stroke="${t}" stroke-width="1.2" opacity=".5"/><circle cx="6" cy="6" r="2" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Teeth",mk:(e,t,n)=>`<pattern id="${e}" width="8" height="10" patternUnits="userSpaceOnUse"><path d="M0 10V4L4 0L8 4V10" fill="${n||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Swirl",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="10" patternUnits="userSpaceOnUse"><path d="M0 5C3 0 6 0 8 5C10 10 13 10 16 5" fill="none" stroke="${t}" stroke-width="1.3" opacity=".5"/><path d="M0 7C3 2 6 2 8 7C10 12 13 12 16 7" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".2"/></pattern>`},{name:"Chain",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="16" patternUnits="userSpaceOnUse"><ellipse cx="5" cy="4" rx="3.5" ry="4" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><ellipse cx="5" cy="12" rx="3.5" ry="4" fill="none" stroke="${n||t}" stroke-width="1" opacity=".45"/></pattern>`},{name:"Feathers",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="18" patternUnits="userSpaceOnUse"><path d="M6 1C9 5 10 9 6 17" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M6 1C3 5 2 9 6 17" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M4 5L6 4L8 5M4 9L6 8L8 9M4 13L6 12L8 13" stroke="${n||t}" stroke-width=".5" opacity=".3"/></pattern>`},{name:"DNA",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="18" patternUnits="userSpaceOnUse"><path d="M3 0C3 4.5 11 4.5 11 9S3 13.5 3 18" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M11 0C11 4.5 3 4.5 3 9S11 13.5 11 18" fill="none" stroke="${n||t}" stroke-width="1" opacity=".45"/></pattern>`},{name:"Bubbles",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="18" height="18" patternUnits="userSpaceOnUse"><circle cx="5" cy="5" r="3.5" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><circle cx="14" cy="12" r="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".35"/><circle cx="11" cy="3" r="1.8" fill="${a}" opacity=".25"/></pattern>`}},{name:"Celtic",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="16" patternUnits="userSpaceOnUse"><path d="M8 2C12 2 14 4 14 8C14 12 12 14 8 14C4 14 2 12 2 8C2 4 4 2 8 2Z" fill="none" stroke="${t}" stroke-width=".8" opacity=".35"/><path d="M4 4L12 12M12 4L4 12" stroke="${n||t}" stroke-width=".6" opacity=".2"/></pattern>`},{name:"Squares",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><rect x="1.5" y="1.5" width="7" height="7" rx="1" fill="${n||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`}];function Nn(e){return Pr.find(t=>t.name===e)||null}const Gt={color:null,capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,glass:0,textureUrl:null,textureScale:1},Dr=(function(){return{...Gt,glass:85}})(),Fr=(function(){return{...Gt,patternName:"Stars"}})(),Or=(function(){return{...Gt,patternName:"Stars"}})(),Br={fontFamily:null,fontSize:18,fontColor:null,outlineColor:null,outlineWidth:0,shadow:null},jo=(function(){return{filledBar:{...Gt},emptyBar:{...Dr},goldFilledBar:{...Or},goldEmptyBar:{...Fr},font:{...Br},disableGoldNotes:!1}})(),Ns={capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,emptyGlass:85,filledTextureUrl:null,emptyTextureUrl:null,textureScale:1,emptyPreset:"custom",goldPatternName:"Stars",goldPatternColor:null,goldHitPatternName:"Stars",goldHitPatternColor:null,goldEmptyTextureUrl:null,goldFilledTextureUrl:null,fontFamily:null,fontSize:18,fontColor:null,fontOutlineColor:null,fontOutlineWidth:0,fontShadow:null},Ts="nice2dev-player-bar-style",Ps="nice2dev-player-karaoke-settings";function mn(e){return e!=null?`${Ps}-${e}`:Ps}function Es(e){return e!=null?`${Ts}-${e}`:Ts}function $s(e){return{filledBar:{color:null,capStyleName:e.capStyleName,patternName:e.patternName,patternColor:e.patternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.filledTextureUrl,textureScale:e.textureScale},emptyBar:{color:null,capStyleName:e.capStyleName,patternName:e.patternName,patternColor:e.patternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:e.emptyGlass,textureUrl:e.emptyTextureUrl,textureScale:e.textureScale},goldFilledBar:{color:null,capStyleName:e.capStyleName,patternName:e.goldHitPatternName,patternColor:e.goldHitPatternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.goldFilledTextureUrl,textureScale:e.textureScale},goldEmptyBar:{color:null,capStyleName:e.capStyleName,patternName:e.goldPatternName,patternColor:e.goldPatternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.goldEmptyTextureUrl,textureScale:e.textureScale},font:{fontFamily:e.fontFamily,fontSize:e.fontSize,fontColor:e.fontColor,outlineColor:e.fontOutlineColor,outlineWidth:e.fontOutlineWidth,shadow:e.fontShadow}}}function As(e){const t=jo,n=(s,i)=>!i||typeof i!="object"?{...s}:{...s,...i},a=(s,i)=>!i||typeof i!="object"?{...s}:{...s,...i};return{filledBar:n(t.filledBar,e.filledBar),emptyBar:n(t.emptyBar,e.emptyBar),goldFilledBar:n(t.goldFilledBar,e.goldFilledBar),goldEmptyBar:n(t.goldEmptyBar,e.goldEmptyBar),font:a(t.font,e.font),disableGoldNotes:typeof e.disableGoldNotes=="boolean"?e.disableGoldNotes:t.disableGoldNotes}}function Ua(e){try{const t=localStorage.getItem(mn(e));if(t){const a=JSON.parse(t);return As(a)}const n=localStorage.getItem(Es(e));if(n){const a=JSON.parse(n),s=$s({...Ns,...a});return localStorage.setItem(mn(e),JSON.stringify(s)),s}if(e!=null){const a=localStorage.getItem(mn());if(a)return As(JSON.parse(a));const s=localStorage.getItem(Es());if(s)return $s({...Ns,...JSON.parse(s)})}}catch{}return{filledBar:{...Gt},emptyBar:{...Dr},goldFilledBar:{...Or},goldEmptyBar:{...Fr},font:{...Br}}}function Fu(e,t){const n=JSON.stringify(e);localStorage.setItem(mn(t),n)}let Is=!1;async function Ou(e){if(Is||(Is=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(mn())||localStorage.setItem(mn(),t)}catch{}}function Bu(e){const t=new Map;for(const n of e)t.set(n,Ua(n));return t}const Gu={"&":"&","<":"<",">":">",'"':""","'":"'"},Wu=/[&<>"']/g;function Vu(e){return e.replace(Wu,t=>Gu[t])}function Uu(e){const t=e.trim().toLowerCase();return!!(t.startsWith("http://")||t.startsWith("https://")||t.startsWith("blob:")||t.startsWith("data:image/")||t.startsWith("/")||t.startsWith("./")||t.startsWith("../"))}const qu=3,Ze=qu;function Er(e){const t=parseInt(e.slice(1,3),16)/255,n=parseInt(e.slice(3,5),16)/255,a=parseInt(e.slice(5,7),16)/255,s=Math.max(t,n,a),i=Math.min(t,n,a);let o=0,l=0;const c=(s+i)/2;if(s!==i){const u=s-i;switch(l=c>.5?u/(2-s-i):u/(s+i),s){case t:o=((n-a)/u+(n<a?6:0))/6;break;case n:o=((a-t)/u+2)/6;break;case a:o=((t-n)/u+4)/6;break}}return[Math.round(o*360),Math.round(l*100),Math.round(c*100)]}function $r(e){let t=e.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),"#"+t.toLowerCase()}function dt(e,t){return e.replace(/([MLHVCSQTAZ])/gi,`
|
|
2
2
|
$1`).split(`
|
|
3
|
-
`).filter(Boolean).map(n=>{const 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
|
|
4
|
-
${
|
|
5
|
-
${
|
|
6
|
-
<clipPath id="${
|
|
3
|
+
`).filter(Boolean).map(n=>{const a=n[0],s=n.slice(1).trim().split(/[\s,]+/).map(Number);if(a==="H")return`H${s[0]+t}`;if(a==="V"||a==="Z")return n;if("MLCSQT".includes(a.toUpperCase())){for(let i=0;i<s.length;i+=2)s[i]+=t;return a+s.join(" ")}return a==="A"&&s.length>=7?(s[5]+=t,a+s.join(" ")):n}).join("")}function Mo(e){const{width:t,height:n,capStyle:a,color:s,highlight:i=70,glow:o=55,glass:l=0,pattern:c=null,patternColor:u=null,patternOnly:h=!1,textureUrl:p=null,textureScale:g=1}=e,y=p&&Uu(p)?Vu(p):null,[m,x,b]=Er($r(s)),f="c"+Math.random().toString(36).slice(2,7),k=a.L(n),v=a.R(n),w=t-k.w-v.w;if(w<4)return"";if(h&&c){const X=`hsl(${m},${x}%,${b}%)`,re=`hsl(${m},${Math.max(x-20,0)}%,${Math.min(b+30,95)}%)`,oe=u||re,se=k.w,D=k.w+w,J=k.inn,ae=`M${se} ${Ze}H${D}V${n-Ze}H${se}Z`,ce=dt(v.inn,D),le=k.out,ne=`M${se} 0H${D}V${n}H${se}Z`,pe=dt(v.out,D),fe=c.mk(f+"pat",oe,u||void 0),me=Math.round(256*g),he=Math.round(256*g),we=y?`<pattern id="${f}tex" patternUnits="userSpaceOnUse" width="${me}" height="${he}"><image href="${y}" width="${me}" 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
|
+
${fe}
|
|
5
|
+
${we}
|
|
6
|
+
<clipPath id="${f}c"><path d="${J}"/><path d="${ae}"/><path d="${ce}"/></clipPath>
|
|
7
7
|
</defs>
|
|
8
|
-
<path d="${
|
|
9
|
-
<path d="${
|
|
10
|
-
${
|
|
11
|
-
<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${
|
|
12
|
-
</svg>`}const
|
|
13
|
-
${
|
|
14
|
-
${
|
|
15
|
-
<linearGradient id="${
|
|
16
|
-
<linearGradient id="${
|
|
17
|
-
<linearGradient id="${
|
|
18
|
-
<linearGradient id="${
|
|
19
|
-
<clipPath id="${
|
|
8
|
+
<path d="${le}" fill="rgba(255,255,255,.18)"/><path d="${ne}" fill="rgba(255,255,255,.18)"/><path d="${pe}" fill="rgba(255,255,255,.18)"/>
|
|
9
|
+
<path d="${J}" fill="${X}" opacity=".22"/><path d="${ae}" fill="${X}" opacity=".22"/><path d="${ce}" fill="${X}" opacity=".22"/>
|
|
10
|
+
${je}
|
|
11
|
+
<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${f}pat)" clip-path="url(#${f}c)"/>
|
|
12
|
+
</svg>`}const R=`hsl(${m},${Math.min(x+10,100)}%,${Math.max(b-22,4)}%)`,M=`hsl(${m},${x}%,${b}%)`,j=`hsl(${m},${Math.max(x-12,0)}%,${Math.min(b+18,88)}%)`,T=`hsl(${m},${Math.min(x+20,100)}%,${Math.min(b+30,93)}%)`,P=`hsl(${m},${Math.max(x-20,0)}%,${Math.min(b+30,95)}%)`,A=u||P,I=i/100*.78,L=o/100*.65,N=1-l/100*.87,_=Ze,ee=n-Ze,Y=_+(ee-_)*.44,O=_+(ee-_)*.58,U=k.w,V=k.w+w,K=k.out,G=`M${U} 0H${V}V${n}H${U}Z`,W=dt(v.out,V),C=k.inn,$=`M${U} ${Ze}H${V}V${n-Ze}H${U}Z`,S=dt(v.inn,V),B=c?c.mk(f+"pat",A,u||void 0):"",H=c?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${f}pat)" clip-path="url(#${f}c)"/>`:"",z=Math.round(256*g),Z=Math.round(256*g),E=y?`<pattern id="${f}tex" patternUnits="userSpaceOnUse" width="${z}" height="${Z}"><image href="${y}" width="${z}" height="${Z}" preserveAspectRatio="none"/></pattern>`:"",q=y?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${f}tex)" opacity="${N*.9}" clip-path="url(#${f}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
|
|
13
|
+
${B}
|
|
14
|
+
${E}
|
|
15
|
+
<linearGradient id="${f}b" x1="0" y1="0" x2="0" y2="${n}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="rgba(255,255,255,.55)"/><stop offset=".3" stop-color="rgba(255,255,255,.35)"/><stop offset="1" stop-color="rgba(255,255,255,.08)"/></linearGradient>
|
|
16
|
+
<linearGradient id="${f}f" x1="0" y1="${_}" x2="0" y2="${ee}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${j}"/><stop offset=".5" stop-color="${M}"/><stop offset="1" stop-color="${R}"/></linearGradient>
|
|
17
|
+
<linearGradient id="${f}h" x1="0" y1="${_}" x2="0" y2="${Y}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fff" stop-opacity="${I}"/><stop offset=".5" stop-color="#fff" stop-opacity="${I*.25}"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient>
|
|
18
|
+
<linearGradient id="${f}g" x1="0" y1="${O}" x2="0" y2="${ee}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${T}" stop-opacity="0"/><stop offset=".6" stop-color="${T}" stop-opacity="${L*.6}"/><stop offset="1" stop-color="${T}" stop-opacity="${L}"/></linearGradient>
|
|
19
|
+
<clipPath id="${f}c"><path d="${C}"/><path d="${$}"/><path d="${S}"/></clipPath>
|
|
20
20
|
</defs>
|
|
21
|
-
<path d="${
|
|
22
|
-
<path d="${C}" fill="url(#${
|
|
23
|
-
${
|
|
24
|
-
${
|
|
25
|
-
<rect x="0" y="${
|
|
26
|
-
<rect x="0" y="${
|
|
27
|
-
</svg>`}function
|
|
21
|
+
<path d="${K}" fill="url(#${f}b)"/><path d="${G}" fill="url(#${f}b)"/><path d="${W}" fill="url(#${f}b)"/>
|
|
22
|
+
<path d="${C}" fill="url(#${f}f)" opacity="${N}"/><path d="${$}" fill="url(#${f}f)" opacity="${N}"/><path d="${S}" fill="url(#${f}f)" opacity="${N}"/>
|
|
23
|
+
${q}
|
|
24
|
+
${H}
|
|
25
|
+
<rect x="0" y="${O}" width="${t}" height="${ee-O}" fill="url(#${f}g)" clip-path="url(#${f}c)"/>
|
|
26
|
+
<rect x="0" y="${_}" width="${t}" height="${Y-_}" 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,k=(x-y)/2,v=f*f+k*k,w=v>b*b?Math.sqrt(v):b,R=w*w,M=Math.sqrt(Math.max(0,(R-v)/v)),j=h!==p?1:-1,T=(m+g)/2+j*M*k,P=(x+y)/2-j*M*f,A=Math.atan2(x-P,m-T),I=Math.atan2(y-P,g-T);e.arc(T,P,w,A,I,!p),a=g,s=y;break}case"Z":e.closePath();break}}}function Tn(e,t,n,a,s,i,o,l=70,c=55,u=0,h,p,g=!1,y,m){const[x,b,f]=Er($r(o)),k=i.L(s),v=i.R(s),w=a-k.w-v.w;if(w<0){const[C,,$]=Er($r(o));e.save(),e.translate(t,n),e.globalAlpha=1-u/100*.87,e.fillStyle=`hsl(${C},50%,${Math.min($+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 R=k.w,M=k.w+w;if(g){const C=`hsla(${x},${b}%,${f}%,0.22)`;e.save(),e.translate(t,n),e.fillStyle="rgba(255,255,255,0.18)",e.beginPath(),et(e,k.out),e.fill(),e.fillRect(R,0,w,s),e.beginPath(),et(e,dt(v.out,M)),e.fill(),e.fillStyle=C,e.beginPath(),et(e,k.inn),e.fill(),e.fillRect(R,Ze,w,s-2*Ze),e.beginPath(),et(e,dt(v.inn,M)),e.fill(),y&&(e.save(),e.beginPath(),et(e,k.inn),e.rect(R,Ze,w,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,k.inn),e.rect(R,Ze,w,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 j=`hsl(${x},${Math.min(b+10,100)}%,${Math.max(f-22,4)}%)`,T=`hsl(${x},${b}%,${f}%)`,P=`hsl(${x},${Math.max(b-12,0)}%,${Math.min(f+18,88)}%)`,A=`hsl(${x},${Math.min(b+20,100)}%,${Math.min(f+30,93)}%)`,I=l/100*.78,L=c/100*.65,N=1-u/100*.87,_=Ze,ee=s-Ze,Y=ee-_,O=_+Y*.44,U=_+Y*.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,k.out),e.fill(),e.fillRect(R,0,w,s),e.beginPath(),et(e,dt(v.out,M)),e.fill();const K=e.createLinearGradient(0,_,0,ee);K.addColorStop(0,P),K.addColorStop(.5,T),K.addColorStop(1,j),e.globalAlpha=N,e.fillStyle=K,e.beginPath(),et(e,k.inn),e.fill(),e.fillRect(R,Ze,w,s-2*Ze),e.beginPath(),et(e,dt(v.inn,M)),e.fill(),e.globalAlpha=1,y&&(e.save(),e.beginPath(),et(e,k.inn),e.rect(R,Ze,w,s-2*Ze),et(e,dt(v.inn,M)),e.clip(),e.globalAlpha=N*.9,e.fillStyle=y,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),m&&(e.save(),e.beginPath(),et(e,k.inn),e.rect(R,Ze,w,s-2*Ze),et(e,dt(v.inn,M)),e.clip(),e.globalAlpha=N*.85,e.fillStyle=m,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),e.save(),e.beginPath(),et(e,k.inn),e.rect(R,Ze,w,s-2*Ze),et(e,dt(v.inn,M)),e.clip();const G=e.createLinearGradient(0,U,0,ee);G.addColorStop(0,"transparent"),G.addColorStop(.6,A.replace(")",`, ${L*.6})`).replace("hsl","hsla")),G.addColorStop(1,A.replace(")",`, ${L})`).replace("hsl","hsla")),e.fillStyle=G,e.fillRect(0,U,a,ee-U);const W=e.createLinearGradient(0,_,0,O);W.addColorStop(0,`rgba(255,255,255,${I})`),W.addColorStop(.5,`rgba(255,255,255,${I*.25})`),W.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=W,e.fillRect(0,_,a,O-_),e.restore(),e.restore()}const Ht="var(--nice-warning, #FFD700)",Ro="var(--nice-warning-bg, #fff0a8)";function Hu(e){const{ctx:t,ballX:n,height:a,playerColor:s,currentTime:i}=e;t.save(),t.globalCompositeOperation="source-over";const o=t.createLinearGradient(Math.max(0,n-60),0,n,0);o.addColorStop(0,"transparent"),o.addColorStop(1,s),t.globalAlpha=.18,t.fillStyle=o,t.fillRect(Math.max(0,n-60),0,60,a),t.globalAlpha=.9,t.strokeStyle=s,t.lineWidth=3,t.shadowColor=s,t.shadowBlur=12,t.beginPath(),t.moveTo(n,0),t.lineTo(n,a),t.stroke();const l=6+Math.sin(i*6)*2;t.fillStyle=e.ballIsGold?ke.resolveCssColor(Ht,t.canvas):s,t.beginPath(),t.moveTo(n,e.ballY-l),t.lineTo(n+l*.7,e.ballY),t.lineTo(n,e.ballY+l),t.lineTo(n-l*.7,e.ballY),t.closePath(),t.fill(),t.restore(),t.save(),t.globalCompositeOperation="source-atop",t.globalAlpha=.35;for(const c of e.visibleNotes)c.isSung&&(t.fillStyle=c.isGold?ke.resolveCssColor(Ht,t.canvas):s,t.fillRect(c.x,c.y,c.w,c.h));t.restore()}function Ku(e){const{ctx:t,ballX:n,ballY:a,ballRadius:s,playerColor:i,ballIsGold:o,currentTime:l}=e,c=3,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?ke.resolveCssColor(Ht,t.canvas):i,t.lineWidth=2-m,t.beginPath(),t.arc(n,a,x,0,Math.PI*2),t.stroke()}t.globalAlpha=.8,t.shadowColor=o?ke.resolveCssColor(Ht,t.canvas):i,t.shadowBlur=16+Math.sin(l*8)*4,t.fillStyle=o?ke.resolveCssColor(Ro,t.canvas):i;const p=s*(.8+Math.sin(l*10)*.2);t.beginPath(),t.arc(n,a,p,0,Math.PI*2),t.fill();for(const g of e.visibleNotes){if(!g.isSung)continue;const y=(l*6+g.x*.01)%(Math.PI*2),m=.15+Math.sin(y)*.1;t.globalAlpha=m,t.fillStyle=g.isGold?ke.resolveCssColor(Ht,t.canvas):i,t.fillRect(g.x,g.y,g.w,g.h)}t.restore()}function Yu(e){const{ctx:t,ballX:n,ballY:a,ballRadius:s,playerColor:i,ballIsGold:o,currentTime:l}=e,c=20+Math.abs(Math.sin(l*3))*15,u=l*5%(Math.PI*2),h=-Math.abs(Math.sin(u))*c,p=a+h;t.save(),t.globalAlpha=.3,t.fillStyle=ke.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,k=(l-f)*5%(Math.PI*2),v=a+-Math.abs(Math.sin(k))*c,w=.15*(1-b/y),R=s*(.6-b*.08);t.globalAlpha=w,t.fillStyle=i,t.beginPath(),t.arc(n-b*3,v,Math.max(2,R),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?ke.resolveCssColor(Ht,t.canvas):i,t.shadowBlur=12,t.fillStyle=o?ke.resolveCssColor(Ro,t.canvas):i,t.beginPath(),t.arc(0,0,s,0,Math.PI*2),t.fill(),t.lineWidth=1.5,t.strokeStyle=ke.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?ke.resolveCssColor(Ht,t.canvas):i;for(let b=0;b<4;b++){const f=b/4*Math.PI*2+l,k=n+Math.cos(f)*(s+4),v=a+Math.sin(f)*2;t.beginPath(),t.arc(k,v,2,0,Math.PI*2),t.fill()}t.restore()}}function Zu(e,t){switch(e){case"wipe":return Hu(t),!0;case"pulse":return Ku(t),!0;case"bounce":return Yu(t),!0;case"ball":default:return!1}}const Xu=1e3,Qu=20,Ju=70,eh=5,Ls=26,_s="rgba(255,215,70,0.98)",zs=new Map,th=(e,t,n,a,s)=>{const i=`g${s}`,o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
28
28
|
<svg xmlns='http://www.w3.org/2000/svg' width='${a}' height='${a}' viewBox='0 0 ${a} ${a}'>
|
|
29
29
|
<defs>
|
|
30
30
|
<radialGradient id='g${i}' cx='50%' cy='40%' r='60%'>
|
|
@@ -36,17 +36,17 @@ ${A}
|
|
|
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(l)}`},Ju=(e,t,n,a,s)=>{const i=`${e}-${t}-${n}-${Math.round(a)}-${s}`;let l=Ds.get(i);return l||(l=new Image,l.src=Qu(e,t,n,a,s),Ds.set(i,l),l)},eh=e=>{const t=e.replace("#",""),n=parseInt(t.length===3?t[0]+t[0]:t.substring(0,2),16)/255,a=parseInt(t.length===3?t[1]+t[1]:t.substring(2,4),16)/255,s=parseInt(t.length===3?t[2]+t[2]:t.substring(4,6),16)/255,i=Math.max(n,a,s),l=Math.min(n,a,s);let o=0,c=0;const d=(i+l)/2;if(i!==l){const h=i-l;switch(c=d>.5?h/(2-i-l):h/(i+l),i){case n:o=(a-s)/h+(a<s?6:0);break;case a:o=(s-n)/h+2;break;case s:o=(n-a)/h+4;break}o/=6}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(d*100)}},th=(e,t,n,a=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(n)}%, ${a})`;function Qn(e){try{const t=we.resolveCssColor(e),[n,a,s]=Fc(t),i=l=>l.toString(16).padStart(2,"0");return`#${i(n)}${i(a)}${i(s)}`.toLowerCase()}catch{return"var(--nice-warning, #ffcc00)"}}function nh(e,t,n,a,s,i){const l=Math.min(i,a/2,s/2);e.beginPath(),e.moveTo(t+l,n),e.lineTo(t+a-l,n),e.quadraticCurveTo(t+a,n,t+a,n+l),e.lineTo(t+a,n+s-l),e.quadraticCurveTo(t+a,n+s,t+a-l,n+s),e.lineTo(t+l,n+s),e.quadraticCurveTo(t,n+s,t,n+s-l),e.lineTo(t,n+l),e.quadraticCurveTo(t,n,t+l,n),e.closePath()}const cn=new Map,$n=new Set,fr=new Set;function qa(e){const t=cn.get(e);return t?Promise.resolve(t):fr.has(e)?Promise.reject(new Error(`Texture failed: ${e}`)):$n.has(e)?new Promise((n,a)=>{const s=()=>{cn.has(e)?n(cn.get(e)):fr.has(e)?a(new Error(`Texture failed: ${e}`)):requestAnimationFrame(s)};s()}):($n.add(e),new Promise((n,a)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{cn.set(e,s),$n.delete(e),n(s)},s.onerror=()=>{$n.delete(e),fr.add(e),a(new Error(`Failed to load texture: ${e}`))},s.src=e}))}function rh(e){return cn.get(e)??null}function Pn(e,t,n=1){const a=cn.get(t);if(!a)return!$n.has(t)&&!fr.has(t)&&qa(t).catch(()=>{}),null;const s=e.createPattern(a,"repeat");if(!s)return null;if(n!==1){const i=new DOMMatrix;i.scaleSelf(n,n),s.setTransform(i)}return s}function ah(e){for(const t of e)t&&qa(t).catch(()=>{})}const An=new Map,sn=new Set;function Mo(e,t,n){return`${e}|${t}|${n??""}`}function sh(e,t,n){const a=Mo(e.name,t,n),s=An.get(a);if(s)return Promise.resolve(s);if(sn.has(a))return new Promise((g,x)=>{const v=()=>{An.has(a)?g(An.get(a)):sn.has(a)?requestAnimationFrame(v):x(new Error(`Pattern render failed: ${a}`))};v()});sn.add(a);const i="p",l=e.mk(i,t,n??void 0),o=l.match(/width="(\d+)"/),c=l.match(/height="(\d+)"/),d=o?parseInt(o[1],10):16,h=c?parseInt(c[1],10):16,f=`<svg xmlns="http://www.w3.org/2000/svg" width="${d}" height="${h}"><defs>${l}</defs><rect width="${d}" height="${h}" fill="url(#${i})"/></svg>`,p=new Blob([f],{type:"image/svg+xml;charset=utf-8"}),y=URL.createObjectURL(p);return new Promise((g,x)=>{const v=new Image;v.onload=()=>{An.set(a,v),sn.delete(a),URL.revokeObjectURL(y),g(v)},v.onerror=()=>{sn.delete(a),URL.revokeObjectURL(y),x(new Error(`Failed to render pattern tile: ${e.name}`))},v.src=y})}function En(e,t,n,a){const s=Mo(t.name,n,a),i=An.get(s);return i?e.createPattern(i,"repeat"):(sn.has(s)||sh(t,n,a).catch(()=>{}),null)}let Rt=null,at=null,ft=null,Pt=null,St=null,qe=null,_s="",Fs=0,Os="";const ma=(e,t,n,a,s,i,l,o,c,d,h,f,p,y,g,x,v,m,S,b,w,N,R,P)=>{e.clearRect(0,0,t,n);const j=P??null,M=(j==null?void 0:j.filledBar)??Wt,I=(j==null?void 0:j.emptyBar)??_r,T=(j==null?void 0:j.goldFilledBar)??Or,E=(j==null?void 0:j.goldEmptyBar)??Fr,_=(j==null?void 0:j.font)??Br,D=Rn(M.capStyleName),q=Rn(I.capStyleName),te=Rn(T.capStyleName),z=Rn(E.capStyleName),U=M.patternName?Nn(M.patternName):null,Z=I.patternName?Nn(I.patternName):null,ae=T.patternName?Nn(T.patternName):null,Y=E.patternName?Nn(E.patternName):null,O=U?En(e,U,M.patternColor??M.color??"var(--nice-bg, #fff)",M.patternColor):null,C=Z?En(e,Z,I.patternColor??I.color??"var(--nice-border, #d1d5db)",I.patternColor):null,$=ae?En(e,ae,T.patternColor??"var(--nice-warning, #FFD700)",T.patternColor):null,k=Y?En(e,Y,E.patternColor??"var(--nice-warning, #FFD700)",E.patternColor):null;Os!==i&&(Os=i,ha("RENDER",`Renderer using settings for "${i}" — filled: cap=${M.capStyleName}, glass=${M.glass} | empty: cap=${I.capStyleName}, glass=${I.glass} | goldFilled: cap=${T.capStyleName}, pattern=${T.patternName??"none"} | goldEmpty: cap=${E.capStyleName}, pattern=${E.patternName??"none"} | hasSettings=${!!j}`,{filledBar:M,emptyBar:I,goldFilledBar:T,goldEmptyBar:E,filledOverlay:!!O,emptyOverlay:!!C,goldFilledOverlay:!!$,goldEmptyOverlay:!!k}));const W=M.textureUrl?Pn(e,M.textureUrl,M.textureScale):null,A=I.textureUrl?Pn(e,I.textureUrl,I.textureScale):null,L=T.textureUrl?Pn(e,T.textureUrl,T.textureScale):null,G=E.textureUrl?Pn(e,E.textureUrl,E.textureScale):null,F=typeof document<"u"?we.resolveCssColor(o||"var(--nice-color-accent, #ffcc00)"):o||"var(--nice-color-accent, #ffcc00)",V=Qn(F||"var(--nice-warning, #ffcc00)"),Q=pe=>we.resolveCssColor(pe),le=_.fontFamily||"Arial",oe=_.fontSize||18,ne=Q(_.fontColor||"var(--btn-text, #fff)"),K=_.outlineColor?Q(_.outlineColor):null,H=typeof _.outlineWidth=="number"?_.outlineWidth:0,ie=_.shadow||null;typeof document<"u"&&((!Rt||Rt.width!==t||Rt.height!==n)&&(Rt=document.createElement("canvas"),Rt.width=t,Rt.height=n,at=Rt.getContext("2d")),at&&at.clearRect(0,0,t,n),(!ft||ft.width!==t||ft.height!==n)&&(ft=document.createElement("canvas"),ft.width=t,ft.height=n,Pt=ft.getContext("2d")),Pt&&Pt.clearRect(0,0,t,n),(!St||St.width!==t||St.height!==n)&&(St=document.createElement("canvas"),St.width=t,St.height=n,qe=St.getContext("2d")),qe&&qe.clearRect(0,0,t,n));const re=S?-S:0,he=b||t;e.fillStyle=F,e.font=`bold ${oe}px ${le}`;const ue=e.measureText(i).width+20;if(e.fillRect(re+10,5,ue,25),e.save(),e.fillStyle=ne,ie){const pe=ie.match(/(-?\d+)px\s+(-?\d+)px\s+(\d+)px\s+(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\)|[a-zA-Z]+)/);pe&&(e.shadowOffsetX=parseInt(pe[1],10),e.shadowOffsetY=parseInt(pe[2],10),e.shadowBlur=parseInt(pe[3],10),e.shadowColor=pe[4])}if(e.fillText(i,re+20,22),K&&H>0&&(e.lineWidth=H,e.strokeStyle=K,e.strokeText(i,re+20,22)),e.restore(),v){const pe=Q(m||"var(--nice-text-secondary, #6b7280)");e.font=`bold 12px ${le}`;const ke=e.measureText(v).width,Ve=8,Ie=re+10+ue+6,Re=20,Pe=7,Be=ke+Ve*2,Ge=4;e.beginPath(),e.moveTo(Ie+Ge,Pe),e.lineTo(Ie+Be-Ge,Pe),e.quadraticCurveTo(Ie+Be,Pe,Ie+Be,Pe+Ge),e.lineTo(Ie+Be,Pe+Re-Ge),e.quadraticCurveTo(Ie+Be,Pe+Re,Ie+Be-Ge,Pe+Re),e.lineTo(Ie+Ge,Pe+Re),e.quadraticCurveTo(Ie,Pe+Re,Ie,Pe+Re-Ge),e.lineTo(Ie,Pe+Ge),e.quadraticCurveTo(Ie,Pe,Ie+Ge,Pe),e.closePath(),e.fillStyle=pe,e.fill(),e.fillStyle=ne,e.fillText(v,Ie+Ve,Pe+14),e.font=`bold ${oe}px ${le}`}const me=120;if(e.fillStyle=F,e.fillRect(re+he-me-10,5,me,25),e.fillStyle=ne,e.fillText(`${l} pts`,re+he-me+15,22),w&&w.currentCombo>=5){const pe=w.currentCombo>=50?"3x":w.currentCombo>=30?"2.5x":w.currentCombo>=20?"2x":w.currentCombo>=10?"1.5x":"",ke=`${w.currentCombo} combo${pe?" "+pe:""}`;e.font=`bold 12px ${le}`;const Ie=e.measureText(ke).width+16,Re=re+he-me-10-Ie-6;e.fillStyle=Q(w.currentCombo>=20?"var(--nice-color-success, #FFD700)":"var(--nice-color-warning, #ff9800)"),e.globalAlpha=.9,nh(e,Re,7,Ie,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=Q(w.currentCombo>=20?"var(--nice-text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(ke,Re+8,22),e.font=`bold 14px ${le}`}if(N&&N.length>0){const pe=N[N.length-1];if(pe.label){const ke=`${N.length}-${pe.label}`;ke!==_s&&(_s=ke,Fs=Date.now());const Ve=Date.now()-Fs;if(Ve<2500){const Ie=Ve<2e3?1:1-(Ve-2e3)/500,Re={Perfect:Q("var(--nice-color-success, #00e676)"),Great:Q("var(--nice-color-success, #66bb6a)"),Good:Q("var(--nice-color-accent, #ffeb3b)"),OK:Q("var(--nice-color-warning, #ff9800)"),Bad:Q("var(--nice-color-error, #ef5350)"),Awful:Q("var(--nice-color-error, #b71c1c)")};e.save(),e.globalAlpha=Ie,e.font=`bold ${Math.round(oe*1.2)}px ${le}`;const Pe=pe.label,Be=e.measureText(Pe).width,Ge=re+he/2-Be/2;e.fillStyle=Re[Pe]||ne,e.shadowColor=we.resolveCssColor("var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",e.canvas),e.shadowBlur=6,e.fillText(Pe,Ge,58),K&&H>0&&(e.lineWidth=H,e.strokeStyle=K,e.strokeText(Pe,Ge,58)),e.restore()}}}const Se=s-2,de=s+5,xe=40;let Me=1/0,$e=-1/0;if(a.forEach(pe=>{pe.forEach(ke=>{ke.pitch<Me&&(Me=ke.pitch),ke.pitch>$e&&($e=ke.pitch)})}),c&&Array.isArray(c)&&c.length>0){let pe=null;isFinite(Me)&&isFinite($e)&&(pe=Math.round((Me+$e)/2));let ke=1/0,Ve=-1/0;c.forEach(({t:Ie,hz:Re})=>{if(!Re||Re<=0)return;let Pe=pe;for(const Ge of a)for(const Je of Ge)Ie>=Je.startTime&&Ie<=Je.startTime+Je.duration&&(Pe=Je.pitch);const Be=fo(Re,Pe);Be<ke&&(ke=Be),Be>Ve&&(Ve=Be)}),ke!==1/0&&Ve!==-1/0&&(ke<Me&&(Me=Math.floor(ke-2)),Ve>$e&&($e=Math.ceil(Ve+2)))}(!isFinite(Me)||!isFinite($e))&&(Me=40,$e=80),Me===$e&&(Me=Math.max(0,Me-6),$e=$e+6);const je=pe=>{const ke=n-xe-10;return xe+ke-(pe-Me)/($e-Me)*ke},ce=Dr(p||"normal"),ze=(n-xe-10)/Math.max(1,$e-Me),Ce=Math.max(10,Math.round(ze*(1+2*ce.semitoneTolerance)*.3)),De=Math.max(5,Math.round(Ce*.45));((pe,ke,Ve,Ie,Re,Pe)=>{pe.lineWidth=1;for(let Be=Math.ceil(Re);Be<=Math.floor(Pe);Be++){const Ge=je(Be);pe.strokeStyle=Q(Be%2===0?"var(--guide-line-strong, rgba(255, 255, 255, 0.12))":"var(--guide-line-weak, rgba(255, 255, 255, 0.06))"),pe.beginPath(),pe.moveTo(0,Math.round(Ge)+.5),pe.lineTo(ke,Math.round(Ge)+.5),pe.stroke()}})(e,t,n-xe,xe,Me,$e),Pt&&Pt.clearRect(0,0,t,n);const Ye=(s-Se)/(de-Se)*t;let He=n*.5,Lt=!1,pt=!1;const zt=(pe,ke,Ve,Ie,Re,Pe,Be=0)=>{const Ge=(Ee,Oe,ve,Ne,Ae,We)=>{const _e=Math.min(We,Ne/2,Ae/2);Ee.beginPath(),Ee.moveTo(Oe+_e,ve),Ee.lineTo(Oe+Ne-_e,ve),Ee.quadraticCurveTo(Oe+Ne,ve,Oe+Ne,ve+_e),Ee.lineTo(Oe+Ne,ve+Ae-_e),Ee.quadraticCurveTo(Oe+Ne,ve+Ae,Oe+Ne-_e,ve+Ae),Ee.lineTo(Oe+_e,ve+Ae),Ee.quadraticCurveTo(Oe,ve+Ae,Oe,ve+Ae-_e),Ee.lineTo(Oe,ve+_e),Ee.quadraticCurveTo(Oe,ve,Oe+_e,ve),Ee.closePath()},Je=Math.max(2,Ce/2);Ie.forEach(Ee=>{if(Ee.startTime+Ee.duration<Re||Ee.startTime>Pe)return;const Oe=(Ee.startTime-Re)/(Pe-Re)*ke,ve=Ee.duration/(Pe-Re)*ke,Ne=je(Ee.pitch)-Ce/2,Ae=[];if(Array.isArray(f)){const We=Ee.startTime+Ee.duration;f.forEach(_e=>{if(_e.pitch!==Ee.pitch||_e.noteStart!=null&&_e.noteEnd!=null&&(Math.abs(_e.noteStart-Ee.startTime)>.01||Math.abs(_e.noteEnd-We)>.01))return;const rt=Math.max(_e.start,Ee.startTime),Ze=Math.min(_e.end,We);if(rt>=Ze)return;const Ut=(rt-Re)/(Pe-Re)*ke,Qt=(Ze-Re)/(Pe-Re)*ke;Ae.push({x1:Ut,x2:Qt,frac:_e.frac})})}if(Ee.isGold){pe.save();const We=g&&g.shadowColor?g.shadowColor:zs,_e=g&&typeof g.glowBlur=="number"?g.glowBlur:Ls;pe.shadowColor=We,pe.shadowBlur=Math.max(4,_e-12),pe.fillStyle=Q("var(--gold-overlay, rgba(255, 215, 0, 0.15))"),Ge(pe,Oe-1,Ne-1,ve+2,Ce+2,Je),pe.fill(),pe.restore();const rt=Qn("var(--gold-base, #b4af9f)");Tn(pe,Oe,Ne,ve,Ce,z,E.color??rt,E.highlight,E.glow,E.glass,Y,E.patternColor,E.patternOnly,G,k),pe.save(),Ge(pe,Oe,Ne,ve,Ce,Je),pe.clip(),pe.globalAlpha=.18,pe.fillStyle=Q("var(--nice-color-success, #FFD700)"),pe.fillRect(Oe,Ne,ve,Math.max(1,Ce*.25)),pe.globalAlpha=1,pe.restore(),Ae.length>0&&(pe.save(),Ge(pe,Oe,Ne,ve,Ce,Je),pe.clip(),Ae.forEach(Ze=>{const Ut=Math.max(1,Ze.x2-Ze.x1);Tn(pe,Ze.x1,Ne,Ut,Ce,te,T.color??"var(--nice-warning, #FFD700)",T.highlight,T.glow,T.glass,ae,T.patternColor,T.patternOnly,L,$)}),pe.restore()),Ae.length===0&&(pe.lineWidth=1,pe.strokeStyle=Q("var(--gold-outline, rgba(255, 215, 0, 0.35))"),Ge(pe,Oe+.5,Ne+.5,ve-1,Math.max(1,Ce-1),Je),pe.stroke())}else{const We=Qn("var(--note-base, #d1d5db)");Tn(pe,Oe,Ne,ve,Ce,q,I.color??We,I.highlight,I.glow,I.glass,Z,I.patternColor,I.patternOnly,A,C),Ae.length>0&&(pe.save(),Ge(pe,Oe,Ne,ve,Ce,Je),pe.clip(),Ae.forEach(_e=>{const rt=Math.max(1,_e.x2-_e.x1);Tn(pe,_e.x1,Ne,rt,Ce,D,M.color??V,M.highlight,M.glow,M.glass,U,M.patternColor,M.patternOnly,W,O)}),pe.restore())}Pt&&(Pt.fillStyle=we.resolveCssColor("var(--nice-bg, #fff)",Pt.canvas),Pt.fillRect(Oe,Ne,ve,Ce))})};if(a.forEach(pe=>{zt(e,t,n-xe,pe,Se,de,xe);for(const ke of pe)if(s>=ke.startTime&&s<=ke.startTime+ke.duration){He=je(ke.pitch),Lt=!0,pt=!!ke.isGold;break}}),!Lt){let pe=null,ke=null;for(const Ve of a)for(const Ie of Ve)Ie.startTime>s&&(!pe||Ie.startTime<pe.startTime)&&(pe=Ie),Ie.startTime<=s&&(!ke||Ie.startTime>ke.startTime)&&(ke=Ie);pe?(He=je(pe.pitch),pt=!!pe.isGold):ke?(He=je(ke.pitch),pt=!!ke.isGold):He=n*.5}const dt=F||Q("var(--nice-color-accent, #ffcc00)"),fe=1+Math.sin((s||0)*8)*.06,be=De*fe,Fe=[];for(const pe of a)for(const ke of pe){if(ke.startTime+ke.duration<Se||ke.startTime>de)continue;const Ve=(ke.startTime-Se)/(de-Se)*t,Ie=ke.duration/(de-Se)*t,Re=je(ke.pitch)-Ce/2,Pe=ke.startTime+ke.duration<=s;Fe.push({x:Ve,y:Re,w:Ie,h:Ce,isGold:ke.isGold,isSung:Pe})}if(!Hu(R||"ball",{ctx:e,ballX:Ye,ballY:He,ballRadius:be,playerColor:dt,ballIsGold:pt,currentTime:s,height:n,visibleNotes:Fe})){Rt&&e.drawImage(Rt,0,0),St&&e.drawImage(St,0,0),e.save(),e.globalCompositeOperation="source-over",e.globalAlpha=.28;const pe=Math.max(18,be*5),ke=e.createRadialGradient(Ye,He,0,Ye,He,pe);if(ke.addColorStop(0,dt),ke.addColorStop(1,"transparent"),e.fillStyle=ke,e.beginPath(),e.arc(Ye,He,pe,0,Math.PI*2),e.fill(),e.restore(),y&&at&&ft&&(at.save(),at.globalCompositeOperation="source-over",at.globalAlpha=.95,at.fillStyle=dt,at.beginPath(),at.arc(Ye,He,be+4,0,Math.PI*2),at.fill(),at.restore(),at.save(),at.globalCompositeOperation="destination-in",at.drawImage(ft,0,0),at.restore(),e.drawImage(Rt,0,0)),y&&qe&&ft)try{const Re=Qn(dt),{h:Pe,s:Be,l:Ge}=eh(Re),Ee=th(Pe,Math.max(10,Math.round(Be*(typeof h=="number"?h:.25))),Ge,.85);qe.save(),qe.globalCompositeOperation="multiply",qe.globalAlpha=.65,qe.fillStyle=Ee,qe.beginPath(),qe.arc(Ye,He,Math.max(8,be+6),0,Math.PI*2),qe.fill(),qe.restore(),qe.save(),qe.globalCompositeOperation="destination-out",qe.drawImage(ft,0,0),qe.restore(),e.drawImage(St,0,0)}catch{qe.save(),qe.globalCompositeOperation="source-over",qe.globalAlpha=.6,qe.fillStyle=dt,qe.beginPath(),qe.arc(Ye,He,Math.max(8,be+6),0,Math.PI*2),qe.fill(),qe.restore(),qe.save(),qe.globalCompositeOperation="destination-out",qe.drawImage(ft,0,0),qe.restore(),e.drawImage(St,0,0)}const Ve=g&&g.shadowColor?g.shadowColor:zs,Ie=g&&typeof g.glowBlur=="number"?g.glowBlur:Ls;e.save(),pt?(e.shadowColor=Ve,e.shadowBlur=Ie,e.fillStyle=Q("var(--gold-light, #FFF0A8)")):(e.shadowColor=dt,e.shadowBlur=10,e.fillStyle=dt),e.globalCompositeOperation="source-over",e.globalAlpha=1,e.beginPath(),e.arc(Ye,He,be,0,Math.PI*2),e.fill(),e.lineWidth=1.5,e.strokeStyle=Q("var(--nice-shadow-md, rgba(0,0,0,0.35))"),e.stroke(),e.restore()}try{if(Array.isArray(x)&&x.length>0){const pe=Date.now(),ke=g&&typeof g.lifeMs=="number"?g.lifeMs:Ku,Ve=(Re,Pe,Be,Ge=5)=>{const Je=Be,Ee=Be*.45;e.beginPath();let Oe=Math.PI/2*3,ve=Re,Ne=Pe;const Ae=Math.PI/Ge;e.moveTo(Re,Pe-Je);for(let We=0;We<Ge;We++)ve=Re+Math.cos(Oe)*Je,Ne=Pe+Math.sin(Oe)*Je,e.lineTo(ve,Ne),Oe+=Ae,ve=Re+Math.cos(Oe)*Ee,Ne=Pe+Math.sin(Oe)*Ee,e.lineTo(ve,Ne),Oe+=Ae;e.lineTo(Re,Pe-Je),e.closePath()},Ie=Re=>{let Pe=Re>>>0;return()=>(Pe=Pe*1664525+1013904223>>>0,(Pe&2147483647)/2147483647)};x.forEach(Re=>{const Pe=pe-Re.createdAt;if(Pe<0||Pe>ke)return;const Be=Pe/ke,Ge=(Re.noteStart-(s-2))/7*t,Je=je(Re.notePitch),Ee=Ie(Re.seed||Math.floor(Re.createdAt%1e5)),Oe=g&&typeof g.count=="number"?g.count:Yu,ve=g&&typeof g.baseSpeed=="number"?g.baseSpeed:Zu,Ne=g&&typeof g.baseSize=="number"?g.baseSize:Xu;for(let Ae=0;Ae<Oe;Ae++){const We=Ee(),_e=Ee(),rt=Ae/Oe*Math.PI*2+We*Math.PI*.6+Be*1.5,Ze=6+ve*(1-Be)*(.5+_e*.8),Ut=Ge+Math.cos(rt)*Ze,Qt=Je+Math.sin(rt)*Ze*(.8+We*.6),jt=Math.max(1,Ne*(1-Be)*(.5+_e)),fs=40+Math.round(20*Ee()),ms=70+Math.round(20*Ee()),Vr=Math.max(0,1-Be)*(.9-Ee()*.3),$c=Math.max(6,jt*2.6),qr=Ju(fs,ms,60,Math.round($c),(Re.seed||0)+Ae);qr&&qr.complete?(e.save(),e.translate(Ut,Qt+4),e.rotate(rt+Be*4+(Ee()-.5)*1.2),e.globalAlpha=Vr,e.drawImage(qr,-jt/2,-jt/2,jt,jt),e.restore()):(e.save(),e.translate(Ut,Qt+4),e.rotate(rt+Be*4),e.fillStyle=`hsla(${fs}, ${ms}%, 60%, ${Vr})`,e.fillRect(-jt/2,-jt/2,jt,jt),e.restore()),Ee()>.85&&(e.save(),e.globalAlpha=Math.max(.35,1-Be),e.fillStyle=`hsla(${30+Math.round(10*Ee())}, ${60+Math.round(30*Ee())}%, ${70+Math.round(10*Ee())}%, ${Vr})`,e.strokeStyle=`rgba(0,0,0,${.12*(1-Be)})`,e.lineWidth=.8,Ve(Ut,Qt+4,jt*(1.4+Ee())),e.fill(),e.stroke(),e.restore())}})}}catch{}return{ballX:Ye,ballY:He,ballIsGold:pt}},Ro=({song:e,currentTime:t,playerRef:n,config:a={},userPitch:s,segmentScores:i,goldBursts:l,combo:o,verseRatings:c})=>{const{isPlaying:d=!1,playerName:h="Ziom",score:f=1e4,playerBgColor:p="var(--karaoke-player-bg, #2196f3)",playerCount:y=2,gapDesaturation:g,goldSettings:x,difficultyLevel:v,algorithmLabel:m,algorithmColor:S,latencyMs:b=null,top:w,animationMode:N,karaokeSettings:R=null}=a,P=u.useRef(null),j=u.useRef(null),[M,I]=u.useState({width:600,height:150,top:250,visibleWidth:600}),[T,E]=u.useState(0),_=u.useRef(0),D=u.useRef(null),q=u.useRef(null),te=u.useRef(null),z=u.useRef(t),U=u.useRef(performance.now()),Z=u.useRef(e),ae=u.useRef(M),Y=u.useRef(s),O=u.useRef(d),C=u.useRef(0),$=u.useRef(!1),k=u.useRef(null),W=u.useRef(null),A=()=>{const L=(e==null?void 0:e.id)??null;if(L!==W.current||!k.current){W.current=L;const G=e.notes.map(ne=>ne.noteLine);k.current=Hn(G,e.bpm??void 0);const F=k.current.reduce((ne,K)=>ne+K.length,0),V=k.current.reduce((ne,K)=>ne+K.filter(H=>H.isGold).length,0),Q=k.current.flat().map(ne=>ne.pitch),le=Q.length?Math.min(...Q):0,oe=Q.length?Math.max(...Q):0;ha("BARS",`Parsed notes for "${e.title}" — ${k.current.length} verses, ${F} notes (including ${V} golden), pitch range: ${le}–${oe}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:G.length,verseCount:k.current.length,totalNotes:F,goldCount:V,minPitch:le,maxPitch:oe})}return k.current};return u.useEffect(()=>{const L=(F,V,Q)=>F+(V-F)*Q,G=F=>{q.current===null&&(q.current=F);const V=Math.min(.1,(F-(q.current||F))/1e3);q.current=F;const Q=C.current,le=_.current,oe=1-Math.exp(-12*V),ne=Math.abs(le-Q)<.25?le:L(Q,le,oe);Math.abs(ne-Q)>1e-4&&(E(ne),C.current=ne,P.current&&(P.current.style.transform=`translateX(${ne}px)`)),D.current=requestAnimationFrame(G)};return D.current=requestAnimationFrame(G),()=>{D.current&&cancelAnimationFrame(D.current),D.current=null,q.current=null}},[]),u.useEffect(()=>{const L=()=>{if(!n.current)return;const G=n.current.getBoundingClientRect(),F=2/Math.max(1,y),V=Math.round(G.width*F),Q=Math.round(G.width),le=V*(150/600);I({width:V,height:le,top:30,visibleWidth:Q})};return L(),window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[n,y]),u.useEffect(()=>{var Q;if(d||!P.current)return;const L=P.current.getContext("2d");if(!L)return;const G=A(),F=t-(e.gap??0)/1e3,V=ma(L,M.width,M.height,G,F,h,f,p,s,e.id,g??void 0,i,v??void 0,d,x??void 0,l,m,S,C.current,M.visibleWidth,o,c,N,R);if(V&&P.current){const le=M.visibleWidth||(((Q=j.current)==null?void 0:Q.getBoundingClientRect().width)??M.width),oe=M.width;let ne=Math.round(le/2-V.ballX);const K=le-oe;ne=Math.max(K,Math.min(0,ne)),_.current=ne}},[t,e,M,s,d,i,l,N,R]),u.useEffect(()=>{z.current=t,U.current=performance.now()},[t]),u.useEffect(()=>{Z.current=e},[e]),u.useEffect(()=>{ae.current=M},[M]),u.useEffect(()=>{Y.current=s},[s]),u.useEffect(()=>{O.current=d},[d]),u.useEffect(()=>{const L=()=>{var ie;const G=P.current,F=Z.current,V=ae.current;if(!G||!F||!V)return;const Q=G.getContext("2d");if(!Q)return;const le=A(),oe=Math.min(.5,(performance.now()-U.current)/1e3),K=(O.current?z.current+oe:z.current)-(F.gap??0)/1e3,H=ma(Q,V.width,V.height,le,K,h,f,p,Y.current,F.id,g??void 0,i,v??void 0,O.current,x??void 0,l,m,S,C.current,V.visibleWidth,o,c,N,R);if(H){const re=V.visibleWidth||(((ie=j.current)==null?void 0:ie.getBoundingClientRect().width)??V.width),he=V.width;let J=Math.round(re/2-H.ballX);const ue=re-he;J=Math.max(ue,Math.min(0,J)),_.current=J}};if(d){$.current||($.current=!0,ha("BARS",`Drawing bars in RAF loop — canvas: ${ae.current.width}×${ae.current.height}px, player: ${h}`,{canvasSize:ae.current}));const G=()=>{L(),te.current=requestAnimationFrame(G)};return te.current=requestAnimationFrame(G),()=>{te.current&&cancelAnimationFrame(te.current),te.current=null}}$.current=!1},[d,h,f,p,g,i,v,x,l,N,R]),r.jsxs("div",{ref:j,style:{position:"absolute",left:"50%",top:`${w??M.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:M.visibleWidth,height:M.height,overflow:"hidden"},children:[r.jsx("style",{children:"@keyframes av-latency-pulse {0% { transform: scale(1); box-shadow: 0 4px 10px var(--nice-overlay-20, rgba(0, 0, 0, 0.2));} 50% { transform: scale(1.08); box-shadow: 0 8px 18px var(--nice-overlay-30, rgba(0,0,0,0.32));} 100% { transform: scale(1); box-shadow: 0 4px 10px var(--nice-overlay-20, rgba(0, 0, 0, 0.2));} } .av-latency-pulse { animation: av-latency-pulse 1s ease-in-out infinite; }"}),r.jsx("div",{style:{position:"absolute",right:8,top:6,zIndex:40,pointerEvents:"none",display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--nice-text-inverse, #fff)"},children:typeof b<"u"&&b!==null?(()=>{const L=b,G=L<=120?"var(--latency-good, #10b981)":L<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",F=`${L}ms`;return r.jsxs("div",{className:L>250?"av-latency-pulse":"",style:{background:G,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:F})]})})():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:P,width:M.width,height:M.height,role:"img","aria-label":`Pitch timeline for ${h??"player"}. Score: ${f??0}`,style:{position:"absolute",left:0,top:0,transform:`translateX(${T}px)`,willChange:"transform"}})]})},No="/textures/seamless/256x256";function At(e,t,n){return{name:e,icon:n,entries:Array.from({length:t},(a,s)=>{const i=String(s+1).padStart(2,"0");return{label:`${e} ${i}`,url:`${No}/${e}/Photoreal_${e}_${i}-512x512.png`}})}}function Dt(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:`${No}/${e}/${e}_${i}-256x256.png`}})}}const Ha=[At("Fire",8,"fire"),At("Metal",8,"metal"),At("Ice",8,"ice"),At("Stone",8,"stone"),At("Wood",8,"wood"),At("Tile",8,"tile"),At("Concrete",8,"concrete"),At("Trees",8,"trees"),At("Grass",8,"grass"),Dt("Wall",24,"wall"),Dt("Rust",24,"rust"),Dt("Woven",24,"woven"),Dt("Ground",24,"ground"),Dt("Pebbles",24,"pebbles"),Dt("Plant",24,"plant"),Dt("Roof",24,"roof"),Dt("Misc",24,"misc")],To=Ha.flatMap(e=>e.entries);function ih(e){return To.find(t=>t.url===e)}const oh={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},lh=({icon:e})=>{const t=oh[e];return t?r.jsx(t,{size:14}):r.jsx(r.Fragment,{children:e})},Et=({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}),ch=({fill:e=Wt,onChange:t=()=>{},previewColor:n="var(--nice-primary, #2196f3)",accentColor:a="var(--nice-primary, #0d6efd)",width:s,height:i})=>{const{t:l}=Te(),[o,c]=u.useState(null),d=(m,S)=>{t({...e,[m]:S})},h=u.useMemo(()=>{const m=e.color||n||"var(--nice-primary, #2196f3)";return(S,b,w)=>{const N=Wn.find(P=>P.name===S)||Wn[0],R=b?$r.find(P=>P.name===b)??null:null;return Co({width:80,height:22,capStyle:N,color:m,highlight:e.highlight,glow:e.glow,glass:e.glass,pattern:R,patternColor:e.patternColor,patternOnly:e.patternOnly,textureUrl:w??null,textureScale:e.textureScale})}},[e,n]),f=`2px solid ${a}`,p=a==="var(--nice-warning-dark, #d4a017)"?"var(--nice-warning-bg, #fff8e1)":"var(--nice-info-bg, #e7f1ff)",y=u.useRef(null),g=u.useRef(null),x=u.useCallback((m,S)=>{m.current&&m.current.scrollBy({left:S*180,behavior:"smooth"})},[]),v={position:"absolute",top:0,width:28,height:"100%",border:"none",cursor:"pointer",zIndex:2,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,fontWeight:700,color:"var(--nice-color-white, #ccc)",background:"linear-gradient(90deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"};return r.jsxs("div",{style:{padding:"4px 0",width:"100%",minWidth:0},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[r.jsx(Et,{inline:!0,children:l("playerForm.barColor","Color")}),r.jsx(se.NiceCheckbox,{label:l("playerForm.auto","Auto"),checked:!e.color,onChange:m=>d("color",m?null:n||"var(--nice-primary, #2196f3)")}),e.color&&r.jsx("input",{type:"color",value:e.color,onChange:m=>d("color",m.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),r.jsx(Et,{children:l("playerForm.capShape","Cap shape")}),r.jsxs("div",{style:{position:"relative",marginBottom:10},children:[r.jsx("button",{type:"button",style:{...v,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>x(y,-1),"aria-label":l("playerForm.scrollLeft","Scroll left"),children:r.jsx(B.NtdChevronLeft,{size:16})}),r.jsx("button",{type:"button",style:{...v,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>x(y,1),"aria-label":l("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:Wn.map(m=>{const S=e.capStyleName===m.name;return r.jsx("div",{title:m.name,onClick:()=>d("capStyleName",m.name),style:{cursor:"pointer",flexShrink:0,border:S?f:"1px solid var(--nice-border-color, #555)",borderRadius:6,padding:3,background:S?p:"var(--nice-bg-secondary, #222)"},dangerouslySetInnerHTML:{__html:h(m.name,null)}},m.name)})})]}),r.jsx(Et,{children:l("playerForm.pattern","Pattern")}),r.jsxs("div",{style:{position:"relative",marginBottom:10},children:[r.jsx("button",{type:"button",style:{...v,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>x(g,-1),"aria-label":l("playerForm.scrollLeft","Scroll left"),children:r.jsx(B.NtdChevronLeft,{size:16})}),r.jsx("button",{type:"button",style:{...v,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>x(g,1),"aria-label":l("playerForm.scrollRight","Scroll right"),children:r.jsx(B.NtdChevronRight,{size:16})}),r.jsxs("div",{ref:g,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:[r.jsx("div",{title:"None",onClick:()=>d("patternName",null),style:{cursor:"pointer",flexShrink:0,border:e.patternName?"1px solid var(--nice-border-color, #555)":f,borderRadius:6,padding:"3px 8px",background:e.patternName?"var(--nice-text, #222)":p,fontSize:12,lineHeight:"22px",color:"var(--nice-text-inverse, #ccc)"},children:"—"}),$r.map(m=>{const S=e.patternName===m.name;return r.jsx("div",{title:m.name,onClick:()=>d("patternName",m.name),style:{cursor:"pointer",flexShrink:0,border:S?f:"1px solid var(--nice-border-color, #555)",borderRadius:6,padding:3,background:S?p:"var(--nice-bg-secondary, #222)"},dangerouslySetInnerHTML:{__html:h(e.capStyleName,m.name)}},m.name)})]})]}),r.jsx("div",{style:{marginBottom:8},children:r.jsx(se.NiceToggle,{label:l("playerForm.patternOnly","Pattern only (flat, no 3D)"),checked:e.patternOnly,onChange:m=>d("patternOnly",m)})}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[r.jsx(Et,{inline:!0,children:l("playerForm.patternColor","Pattern color")}),r.jsx(se.NiceCheckbox,{label:l("playerForm.auto","Auto"),checked:!e.patternColor,onChange:m=>d("patternColor",m?null:n||"var(--nice-bg, #fff)")}),e.patternColor&&r.jsx("input",{type:"color",value:e.patternColor,onChange:m=>d("patternColor",m.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),!e.patternOnly&&r.jsxs(r.Fragment,{children:[r.jsxs(Et,{children:[l("playerForm.highlight","Highlight"),": ",e.highlight,"%"]}),r.jsx("div",{style:{marginBottom:8},children:r.jsx(se.NiceSlider,{min:0,max:100,value:e.highlight,onChange:m=>d("highlight",m)})}),r.jsxs(Et,{children:[l("playerForm.glow","Glow"),": ",e.glow,"%"]}),r.jsx("div",{style:{marginBottom:8},children:r.jsx(se.NiceSlider,{min:0,max:100,value:e.glow,onChange:m=>d("glow",m)})})]}),r.jsxs(Et,{children:[l("playerForm.glass","Transparency (glass)"),": ",e.glass,"%"]}),r.jsx("div",{style:{marginBottom:8},children:r.jsx(se.NiceSlider,{min:0,max:100,value:e.glass,onChange:m=>d("glass",m)})}),r.jsx("div",{style:{marginTop:4},children:r.jsx(Et,{strong:!0,children:l("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(se.NiceButton,{size:"sm",variant:e.textureUrl?"outline":"primary",onClick:()=>{d("textureUrl",null),c(null)},children:l("playerForm.texNone","None")}),Ha.map(m=>r.jsx(se.NiceButton,{size:"sm",variant:(o==null?void 0:o.name)===m.name?"primary":"outline",onClick:()=>c(S=>(S==null?void 0:S.name)===m.name?null:m),title:m.name,ariaLabel:m.name,children:r.jsx(lh,{icon:m.icon})},m.name))]}),o&&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:o.entries.map(m=>{const S=e.textureUrl===m.url;return r.jsx("div",{title:m.label,onClick:()=>d("textureUrl",S?null:m.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:S?`3px solid ${a}`:"1px solid var(--nice-text-muted, #bbb)",backgroundImage:`url(${m.url})`,backgroundSize:"cover",boxShadow:S?`0 0 6px ${a}`:void 0}},m.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(Et,{children:[l("playerForm.textureScale","Texture scale"),": ",e.textureScale.toFixed(1),"×"]}),r.jsx("div",{style:{marginBottom:8},children:r.jsx(se.NiceSlider,{min:10,max:200,step:10,value:Math.round(e.textureScale*100),onChange:m=>d("textureScale",m/100)})})]})]})},st=ot.scoped("AudioPitchAnalyzer");function dh({onSegments:e,defaultCompareAll:t=!1,externalFile:n=null,postPitch:a,postLibrosaPitchTrack:s}){const{t:i}=Te(),[l,o]=u.useState("pitchy"),[c,d]=u.useState(null),[h,f]=u.useState(t),[p,y]=u.useState({}),[g,x]=u.useState({}),[v,m]=u.useState([]),[S,b]=u.useState([]),[w,N]=u.useState(!1),[R,P]=u.useState(null),[j]=u.useState(null),[M]=u.useState(null),[I,T]=u.useState(null),E=u.useRef(null);function _(Y){try{if(Y instanceof Error){let C=`${Y.message}
|
|
40
|
-
${
|
|
39
|
+
</svg>`;return`data:image/svg+xml;utf8,${encodeURIComponent(o)}`},nh=(e,t,n,a,s)=>{const i=`${e}-${t}-${n}-${Math.round(a)}-${s}`;let o=zs.get(i);return o||(o=new Image,o.src=th(e,t,n,a,s),zs.set(i,o),o)},rh=e=>{const t=e.replace("#",""),n=parseInt(t.length===3?t[0]+t[0]:t.substring(0,2),16)/255,a=parseInt(t.length===3?t[1]+t[1]:t.substring(2,4),16)/255,s=parseInt(t.length===3?t[2]+t[2]:t.substring(4,6),16)/255,i=Math.max(n,a,s),o=Math.min(n,a,s);let l=0,c=0;const 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)}},ah=(e,t,n,a=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(n)}%, ${a})`;function Qn(e){try{const t=ke.resolveCssColor(e),[n,a,s]=Bc(t),i=o=>o.toString(16).padStart(2,"0");return`#${i(n)}${i(a)}${i(s)}`.toLowerCase()}catch{return"var(--nice-warning, #ffcc00)"}}function sh(e,t,n,a,s,i){const o=Math.min(i,a/2,s/2);e.beginPath(),e.moveTo(t+o,n),e.lineTo(t+a-o,n),e.quadraticCurveTo(t+a,n,t+a,n+o),e.lineTo(t+a,n+s-o),e.quadraticCurveTo(t+a,n+s,t+a-o,n+s),e.lineTo(t+o,n+s),e.quadraticCurveTo(t,n+s,t,n+s-o),e.lineTo(t,n+o),e.quadraticCurveTo(t,n,t+o,n),e.closePath()}const cn=new Map,Pn=new Set,fr=new Set;function qa(e){const t=cn.get(e);return t?Promise.resolve(t):fr.has(e)?Promise.reject(new Error(`Texture failed: ${e}`)):Pn.has(e)?new Promise((n,a)=>{const s=()=>{cn.has(e)?n(cn.get(e)):fr.has(e)?a(new Error(`Texture failed: ${e}`)):requestAnimationFrame(s)};s()}):(Pn.add(e),new Promise((n,a)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{cn.set(e,s),Pn.delete(e),n(s)},s.onerror=()=>{Pn.delete(e),fr.add(e),a(new Error(`Failed to load texture: ${e}`))},s.src=e}))}function ih(e){return cn.get(e)??null}function En(e,t,n=1){const a=cn.get(t);if(!a)return!Pn.has(t)&&!fr.has(t)&&qa(t).catch(()=>{}),null;const s=e.createPattern(a,"repeat");if(!s)return null;if(n!==1){const i=new DOMMatrix;i.scaleSelf(n,n),s.setTransform(i)}return s}function oh(e){for(const t of e)t&&qa(t).catch(()=>{})}const $n=new Map,sn=new Set;function No(e,t,n){return`${e}|${t}|${n??""}`}function lh(e,t,n){const a=No(e.name,t,n),s=$n.get(a);if(s)return Promise.resolve(s);if(sn.has(a))return new Promise((m,x)=>{const b=()=>{$n.has(a)?m($n.get(a)):sn.has(a)?requestAnimationFrame(b):x(new Error(`Pattern render failed: ${a}`))};b()});sn.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=()=>{$n.set(a,b),sn.delete(a),URL.revokeObjectURL(y),m(b)},b.onerror=()=>{sn.delete(a),URL.revokeObjectURL(y),x(new Error(`Failed to render pattern tile: ${e.name}`))},b.src=y})}function An(e,t,n,a){const s=No(t.name,n,a),i=$n.get(s);return i?e.createPattern(i,"repeat"):(sn.has(s)||lh(t,n,a).catch(()=>{}),null)}let Mt=null,nt=null,pt=null,Et=null,bt=null,Ue=null,Ds="",Fs=0,Os="";const ma=(e,t,n,a,s,i,o,l,c,u,h,p,g,y,m,x,b,f,k,v,w,R,M,j)=>{e.clearRect(0,0,t,n);const T=j??null,P=(T==null?void 0:T.filledBar)??Gt,A=(T==null?void 0:T.emptyBar)??Dr,I=(T==null?void 0:T.goldFilledBar)??Or,L=(T==null?void 0:T.goldEmptyBar)??Fr,N=(T==null?void 0:T.font)??Br,_=Rn(P.capStyleName),ee=Rn(A.capStyleName),Y=Rn(I.capStyleName),O=Rn(L.capStyleName),U=P.patternName?Nn(P.patternName):null,V=A.patternName?Nn(A.patternName):null,K=I.patternName?Nn(I.patternName):null,G=L.patternName?Nn(L.patternName):null,W=U?An(e,U,P.patternColor??P.color??"var(--nice-bg, #fff)",P.patternColor):null,C=V?An(e,V,A.patternColor??A.color??"var(--nice-border, #d1d5db)",A.patternColor):null,$=K?An(e,K,I.patternColor??"var(--nice-warning, #FFD700)",I.patternColor):null,S=G?An(e,G,L.patternColor??"var(--nice-warning, #FFD700)",L.patternColor):null;Os!==i&&(Os=i,ha("RENDER",`Renderer using settings for "${i}" — filled: cap=${P.capStyleName}, glass=${P.glass} | empty: cap=${A.capStyleName}, glass=${A.glass} | goldFilled: cap=${I.capStyleName}, pattern=${I.patternName??"none"} | goldEmpty: cap=${L.capStyleName}, pattern=${L.patternName??"none"} | hasSettings=${!!T}`,{filledBar:P,emptyBar:A,goldFilledBar:I,goldEmptyBar:L,filledOverlay:!!W,emptyOverlay:!!C,goldFilledOverlay:!!$,goldEmptyOverlay:!!S}));const B=P.textureUrl?En(e,P.textureUrl,P.textureScale):null,H=A.textureUrl?En(e,A.textureUrl,A.textureScale):null,z=I.textureUrl?En(e,I.textureUrl,I.textureScale):null,Z=L.textureUrl?En(e,L.textureUrl,L.textureScale):null,E=typeof document<"u"?ke.resolveCssColor(l||"var(--nice-color-accent, #ffcc00)"):l||"var(--nice-color-accent, #ffcc00)",q=Qn(E||"var(--nice-warning, #ffcc00)"),X=Se=>ke.resolveCssColor(Se),re=N.fontFamily||"Arial",oe=N.fontSize||18,se=X(N.fontColor||"var(--btn-text, #fff)"),D=N.outlineColor?X(N.outlineColor):null,J=typeof N.outlineWidth=="number"?N.outlineWidth:0,ae=N.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,Ue=bt.getContext("2d")),Ue&&Ue.clearRect(0,0,t,n));const ce=k?-k:0,le=v||t;e.fillStyle=E,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 Se=ae.match(/(-?\d+)px\s+(-?\d+)px\s+(\d+)px\s+(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\)|[a-zA-Z]+)/);Se&&(e.shadowOffsetX=parseInt(Se[1],10),e.shadowOffsetY=parseInt(Se[2],10),e.shadowBlur=parseInt(Se[3],10),e.shadowColor=Se[4])}if(e.fillText(i,ce+20,22),D&&J>0&&(e.lineWidth=J,e.strokeStyle=D,e.strokeText(i,ce+20,22)),e.restore(),b){const Se=X(f||"var(--nice-text-secondary, #6b7280)");e.font=`bold 12px ${re}`;const Ce=e.measureText(b).width,We=8,ze=ce+10+pe+6,$e=20,Pe=7,de=Ce+We*2,ge=4;e.beginPath(),e.moveTo(ze+ge,Pe),e.lineTo(ze+de-ge,Pe),e.quadraticCurveTo(ze+de,Pe,ze+de,Pe+ge),e.lineTo(ze+de,Pe+$e-ge),e.quadraticCurveTo(ze+de,Pe+$e,ze+de-ge,Pe+$e),e.lineTo(ze+ge,Pe+$e),e.quadraticCurveTo(ze,Pe+$e,ze,Pe+$e-ge),e.lineTo(ze,Pe+ge),e.quadraticCurveTo(ze,Pe,ze+ge,Pe),e.closePath(),e.fillStyle=Se,e.fill(),e.fillStyle=se,e.fillText(b,ze+We,Pe+14),e.font=`bold ${oe}px ${re}`}const fe=120;if(e.fillStyle=E,e.fillRect(ce+le-fe-10,5,fe,25),e.fillStyle=se,e.fillText(`${o} pts`,ce+le-fe+15,22),w&&w.currentCombo>=5){const Se=w.currentCombo>=50?"3x":w.currentCombo>=30?"2.5x":w.currentCombo>=20?"2x":w.currentCombo>=10?"1.5x":"",Ce=`${w.currentCombo} combo${Se?" "+Se:""}`;e.font=`bold 12px ${re}`;const ze=e.measureText(Ce).width+16,$e=ce+le-fe-10-ze-6;e.fillStyle=X(w.currentCombo>=20?"var(--nice-color-success, #FFD700)":"var(--nice-color-warning, #ff9800)"),e.globalAlpha=.9,sh(e,$e,7,ze,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=X(w.currentCombo>=20?"var(--nice-text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(Ce,$e+8,22),e.font=`bold 14px ${re}`}if(R&&R.length>0){const Se=R[R.length-1];if(Se.label){const Ce=`${R.length}-${Se.label}`;Ce!==Ds&&(Ds=Ce,Fs=Date.now());const We=Date.now()-Fs;if(We<2500){const ze=We<2e3?1:1-(We-2e3)/500,$e={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=ze,e.font=`bold ${Math.round(oe*1.2)}px ${re}`;const Pe=Se.label,de=e.measureText(Pe).width,ge=ce+le/2-de/2;e.fillStyle=$e[Pe]||se,e.shadowColor=ke.resolveCssColor("var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",e.canvas),e.shadowBlur=6,e.fillText(Pe,ge,58),D&&J>0&&(e.lineWidth=J,e.strokeStyle=D,e.strokeText(Pe,ge,58)),e.restore()}}}const me=s-2,he=s+5,we=40;let je=1/0,Ne=-1/0;if(a.forEach(Se=>{Se.forEach(Ce=>{Ce.pitch<je&&(je=Ce.pitch),Ce.pitch>Ne&&(Ne=Ce.pitch)})}),c&&Array.isArray(c)&&c.length>0){let Se=null;isFinite(je)&&isFinite(Ne)&&(Se=Math.round((je+Ne)/2));let Ce=1/0,We=-1/0;c.forEach(({t:ze,hz:$e})=>{if(!$e||$e<=0)return;let Pe=Se;for(const ge of a)for(const Ae of ge)ze>=Ae.startTime&&ze<=Ae.startTime+Ae.duration&&(Pe=Ae.pitch);const de=mo($e,Pe);de<Ce&&(Ce=de),de>We&&(We=de)}),Ce!==1/0&&We!==-1/0&&(Ce<je&&(je=Math.floor(Ce-2)),We>Ne&&(Ne=Math.ceil(We+2)))}(!isFinite(je)||!isFinite(Ne))&&(je=40,Ne=80),je===Ne&&(je=Math.max(0,je-6),Ne=Ne+6);const Ee=Se=>{const Ce=n-we-10;return we+Ce-(Se-je)/(Ne-je)*Ce},ue=zr(g||"normal"),Oe=(n-we-10)/Math.max(1,Ne-je),Me=Math.max(10,Math.round(Oe*(1+2*ue.semitoneTolerance)*.3)),Ie=Math.max(5,Math.round(Me*.45));((Se,Ce,We,ze,$e,Pe)=>{Se.lineWidth=1;for(let de=Math.ceil($e);de<=Math.floor(Pe);de++){const ge=Ee(de);Se.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))"),Se.beginPath(),Se.moveTo(0,Math.round(ge)+.5),Se.lineTo(Ce,Math.round(ge)+.5),Se.stroke()}})(e,t,n-we,we,je,Ne),Et&&Et.clearRect(0,0,t,n);const Be=(s-me)/(he-me)*t;let He=n*.5,Lt=!1,ct=!1;const ht=(Se,Ce,We,ze,$e,Pe,de=0)=>{const ge=(Te,_e,ve,Re,Le,Ge)=>{const De=Math.min(Ge,Re/2,Le/2);Te.beginPath(),Te.moveTo(_e+De,ve),Te.lineTo(_e+Re-De,ve),Te.quadraticCurveTo(_e+Re,ve,_e+Re,ve+De),Te.lineTo(_e+Re,ve+Le-De),Te.quadraticCurveTo(_e+Re,ve+Le,_e+Re-De,ve+Le),Te.lineTo(_e+De,ve+Le),Te.quadraticCurveTo(_e,ve+Le,_e,ve+Le-De),Te.lineTo(_e,ve+De),Te.quadraticCurveTo(_e,ve,_e+De,ve),Te.closePath()},Ae=Math.max(2,Me/2);ze.forEach(Te=>{if(Te.startTime+Te.duration<$e||Te.startTime>Pe)return;const _e=(Te.startTime-$e)/(Pe-$e)*Ce,ve=Te.duration/(Pe-$e)*Ce,Re=Ee(Te.pitch)-Me/2,Le=[];if(Array.isArray(p)){const Ge=Te.startTime+Te.duration;p.forEach(De=>{if(De.pitch!==Te.pitch||De.noteStart!=null&&De.noteEnd!=null&&(Math.abs(De.noteStart-Te.startTime)>.01||Math.abs(De.noteEnd-Ge)>.01))return;const tt=Math.max(De.start,Te.startTime),Ke=Math.min(De.end,Ge);if(tt>=Ke)return;const Wt=(tt-$e)/(Pe-$e)*Ce,Qt=(Ke-$e)/(Pe-$e)*Ce;Le.push({x1:Wt,x2:Qt,frac:De.frac})})}if(Te.isGold){Se.save();const Ge=m&&m.shadowColor?m.shadowColor:_s,De=m&&typeof m.glowBlur=="number"?m.glowBlur:Ls;Se.shadowColor=Ge,Se.shadowBlur=Math.max(4,De-12),Se.fillStyle=X("var(--gold-overlay, rgba(255, 215, 0, 0.15))"),ge(Se,_e-1,Re-1,ve+2,Me+2,Ae),Se.fill(),Se.restore();const tt=Qn("var(--gold-base, #b4af9f)");Tn(Se,_e,Re,ve,Me,O,L.color??tt,L.highlight,L.glow,L.glass,G,L.patternColor,L.patternOnly,Z,S),Se.save(),ge(Se,_e,Re,ve,Me,Ae),Se.clip(),Se.globalAlpha=.18,Se.fillStyle=X("var(--nice-color-success, #FFD700)"),Se.fillRect(_e,Re,ve,Math.max(1,Me*.25)),Se.globalAlpha=1,Se.restore(),Le.length>0&&(Se.save(),ge(Se,_e,Re,ve,Me,Ae),Se.clip(),Le.forEach(Ke=>{const Wt=Math.max(1,Ke.x2-Ke.x1);Tn(Se,Ke.x1,Re,Wt,Me,Y,I.color??"var(--nice-warning, #FFD700)",I.highlight,I.glow,I.glass,K,I.patternColor,I.patternOnly,z,$)}),Se.restore()),Le.length===0&&(Se.lineWidth=1,Se.strokeStyle=X("var(--gold-outline, rgba(255, 215, 0, 0.35))"),ge(Se,_e+.5,Re+.5,ve-1,Math.max(1,Me-1),Ae),Se.stroke())}else{const Ge=Qn("var(--note-base, #d1d5db)");Tn(Se,_e,Re,ve,Me,ee,A.color??Ge,A.highlight,A.glow,A.glass,V,A.patternColor,A.patternOnly,H,C),Le.length>0&&(Se.save(),ge(Se,_e,Re,ve,Me,Ae),Se.clip(),Le.forEach(De=>{const tt=Math.max(1,De.x2-De.x1);Tn(Se,De.x1,Re,tt,Me,_,P.color??q,P.highlight,P.glow,P.glass,U,P.patternColor,P.patternOnly,B,W)}),Se.restore())}Et&&(Et.fillStyle=ke.resolveCssColor("var(--nice-bg, #fff)",Et.canvas),Et.fillRect(_e,Re,ve,Me))})};if(a.forEach(Se=>{ht(e,t,n-we,Se,me,he,we);for(const Ce of Se)if(s>=Ce.startTime&&s<=Ce.startTime+Ce.duration){He=Ee(Ce.pitch),Lt=!0,ct=!!Ce.isGold;break}}),!Lt){let Se=null,Ce=null;for(const We of a)for(const ze of We)ze.startTime>s&&(!Se||ze.startTime<Se.startTime)&&(Se=ze),ze.startTime<=s&&(!Ce||ze.startTime>Ce.startTime)&&(Ce=ze);Se?(He=Ee(Se.pitch),ct=!!Se.isGold):Ce?(He=Ee(Ce.pitch),ct=!!Ce.isGold):He=n*.5}const it=E||X("var(--nice-color-accent, #ffcc00)"),wt=1+Math.sin((s||0)*8)*.06,Je=Ie*wt,Pt=[];for(const Se of a)for(const Ce of Se){if(Ce.startTime+Ce.duration<me||Ce.startTime>he)continue;const We=(Ce.startTime-me)/(he-me)*t,ze=Ce.duration/(he-me)*t,$e=Ee(Ce.pitch)-Me/2,Pe=Ce.startTime+Ce.duration<=s;Pt.push({x:We,y:$e,w:ze,h:Me,isGold:Ce.isGold,isSung:Pe})}if(!Zu(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 Se=Math.max(18,Je*5),Ce=e.createRadialGradient(Be,He,0,Be,He,Se);if(Ce.addColorStop(0,it),Ce.addColorStop(1,"transparent"),e.fillStyle=Ce,e.beginPath(),e.arc(Be,He,Se,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&&Ue&&pt)try{const $e=Qn(it),{h:Pe,s:de,l:ge}=rh($e),Te=ah(Pe,Math.max(10,Math.round(de*(typeof h=="number"?h:.25))),ge,.85);Ue.save(),Ue.globalCompositeOperation="multiply",Ue.globalAlpha=.65,Ue.fillStyle=Te,Ue.beginPath(),Ue.arc(Be,He,Math.max(8,Je+6),0,Math.PI*2),Ue.fill(),Ue.restore(),Ue.save(),Ue.globalCompositeOperation="destination-out",Ue.drawImage(pt,0,0),Ue.restore(),e.drawImage(bt,0,0)}catch{Ue.save(),Ue.globalCompositeOperation="source-over",Ue.globalAlpha=.6,Ue.fillStyle=it,Ue.beginPath(),Ue.arc(Be,He,Math.max(8,Je+6),0,Math.PI*2),Ue.fill(),Ue.restore(),Ue.save(),Ue.globalCompositeOperation="destination-out",Ue.drawImage(pt,0,0),Ue.restore(),e.drawImage(bt,0,0)}const We=m&&m.shadowColor?m.shadowColor:_s,ze=m&&typeof m.glowBlur=="number"?m.glowBlur:Ls;e.save(),ct?(e.shadowColor=We,e.shadowBlur=ze,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 Se=Date.now(),Ce=m&&typeof m.lifeMs=="number"?m.lifeMs:Xu,We=($e,Pe,de,ge=5)=>{const Ae=de,Te=de*.45;e.beginPath();let _e=Math.PI/2*3,ve=$e,Re=Pe;const Le=Math.PI/ge;e.moveTo($e,Pe-Ae);for(let Ge=0;Ge<ge;Ge++)ve=$e+Math.cos(_e)*Ae,Re=Pe+Math.sin(_e)*Ae,e.lineTo(ve,Re),_e+=Le,ve=$e+Math.cos(_e)*Te,Re=Pe+Math.sin(_e)*Te,e.lineTo(ve,Re),_e+=Le;e.lineTo($e,Pe-Ae),e.closePath()},ze=$e=>{let Pe=$e>>>0;return()=>(Pe=Pe*1664525+1013904223>>>0,(Pe&2147483647)/2147483647)};x.forEach($e=>{const Pe=Se-$e.createdAt;if(Pe<0||Pe>Ce)return;const de=Pe/Ce,ge=($e.noteStart-(s-2))/7*t,Ae=Ee($e.notePitch),Te=ze($e.seed||Math.floor($e.createdAt%1e5)),_e=m&&typeof m.count=="number"?m.count:Qu,ve=m&&typeof m.baseSpeed=="number"?m.baseSpeed:Ju,Re=m&&typeof m.baseSize=="number"?m.baseSize:eh;for(let Le=0;Le<_e;Le++){const Ge=Te(),De=Te(),tt=Le/_e*Math.PI*2+Ge*Math.PI*.6+de*1.5,Ke=6+ve*(1-de)*(.5+De*.8),Wt=ge+Math.cos(tt)*Ke,Qt=Ae+Math.sin(tt)*Ke*(.8+Ge*.6),Ct=Math.max(1,Re*(1-de)*(.5+De)),fs=40+Math.round(20*Te()),ms=70+Math.round(20*Te()),Ur=Math.max(0,1-de)*(.9-Te()*.3),Ec=Math.max(6,Ct*2.6),qr=nh(fs,ms,60,Math.round(Ec),($e.seed||0)+Le);qr&&qr.complete?(e.save(),e.translate(Wt,Qt+4),e.rotate(tt+de*4+(Te()-.5)*1.2),e.globalAlpha=Ur,e.drawImage(qr,-Ct/2,-Ct/2,Ct,Ct),e.restore()):(e.save(),e.translate(Wt,Qt+4),e.rotate(tt+de*4),e.fillStyle=`hsla(${fs}, ${ms}%, 60%, ${Ur})`,e.fillRect(-Ct/2,-Ct/2,Ct,Ct),e.restore()),Te()>.85&&(e.save(),e.globalAlpha=Math.max(.35,1-de),e.fillStyle=`hsla(${30+Math.round(10*Te())}, ${60+Math.round(30*Te())}%, ${70+Math.round(10*Te())}%, ${Ur})`,e.strokeStyle=`rgba(0,0,0,${.12*(1-de)})`,e.lineWidth=.8,We(Wt,Qt+4,Ct*(1.4+Te())),e.fill(),e.stroke(),e.restore())}})}}catch{}return{ballX:Be,ballY:He,ballIsGold:ct}},To=({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:k,algorithmColor:v,latencyMs:w=null,top:R,animationMode:M,karaokeSettings:j=null}=a,T=d.useRef(null),P=d.useRef(null),[A,I]=d.useState({width:600,height:150,top:250,visibleWidth:600}),[L,N]=d.useState(0),_=d.useRef(0),ee=d.useRef(null),Y=d.useRef(null),O=d.useRef(null),U=d.useRef(t),V=d.useRef(performance.now()),K=d.useRef(e),G=d.useRef(A),W=d.useRef(s),C=d.useRef(h),$=d.useRef(0),S=d.useRef(!1),B=d.useRef(null),H=d.useRef(null),z=d.useCallback(()=>{const Z=(e==null?void 0:e.id)??null;if(Z!==H.current||!B.current){H.current=Z;const E=e.notes.map(D=>D.noteLine);B.current=Hn(E,e.bpm??void 0);const q=B.current.reduce((D,J)=>D+J.length,0),X=B.current.reduce((D,J)=>D+J.filter(ae=>ae.isGold).length,0),re=B.current.flat().map(D=>D.pitch),oe=re.length?Math.min(...re):0,se=re.length?Math.max(...re):0;ha("BARS",`Parsed notes for "${e.title}" — ${B.current.length} verses, ${q} notes (including ${X} golden), pitch range: ${oe}–${se}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:E.length,verseCount:B.current.length,totalNotes:q,goldCount:X,minPitch:oe,maxPitch:se})}return B.current},[e]);return d.useEffect(()=>{const Z=(q,X,re)=>q+(X-q)*re,E=q=>{Y.current===null&&(Y.current=q);const X=Math.min(.1,(q-(Y.current||q))/1e3);Y.current=q;const re=$.current,oe=_.current,se=1-Math.exp(-12*X),D=Math.abs(oe-re)<.25?oe:Z(re,oe,se);Math.abs(D-re)>1e-4&&(N(D),$.current=D,T.current&&(T.current.style.transform=`translateX(${D}px)`)),ee.current=requestAnimationFrame(E)};return ee.current=requestAnimationFrame(E),()=>{ee.current&&cancelAnimationFrame(ee.current),ee.current=null,Y.current=null}},[]),d.useEffect(()=>{const Z=()=>{if(!n.current)return;const E=n.current.getBoundingClientRect(),q=2/Math.max(1,m),X=Math.round(E.width*q),re=Math.round(E.width),oe=X*(150/600);I({width:X,height:oe,top:30,visibleWidth:re})};return Z(),window.addEventListener("resize",Z),()=>window.removeEventListener("resize",Z)},[n,m]),d.useEffect(()=>{var re;if(h||!T.current)return;const Z=T.current.getContext("2d");if(!Z)return;const E=z(),q=t-(e.gap??0)/1e3,X=ma(Z,A.width,A.height,E,q,p,g,y,s,e.id,x??void 0,i,f??void 0,h,b??void 0,o,k,v,$.current,A.visibleWidth,l,c,M,j);if(X&&T.current){const oe=A.visibleWidth||(((re=P.current)==null?void 0:re.getBoundingClientRect().width)??A.width),se=A.width;let D=Math.round(oe/2-X.ballX);const J=oe-se;D=Math.max(J,Math.min(0,D)),_.current=D}},[t,e,z,A,s,h,p,g,y,x,i,f,b,o,k,v,l,c,M,j]),d.useEffect(()=>{U.current=t,V.current=performance.now()},[t]),d.useEffect(()=>{K.current=e},[e]),d.useEffect(()=>{G.current=A},[A]),d.useEffect(()=>{W.current=s},[s]),d.useEffect(()=>{C.current=h},[h]),d.useEffect(()=>{const Z=()=>{var ce;const E=T.current,q=K.current,X=G.current;if(!E||!q||!X)return;const re=E.getContext("2d");if(!re)return;const oe=z(),se=Math.min(.5,(performance.now()-V.current)/1e3),J=(C.current?U.current+se:U.current)-(q.gap??0)/1e3,ae=ma(re,X.width,X.height,oe,J,p,g,y,W.current,q.id,x??void 0,i,f??void 0,C.current,b??void 0,o,k,v,$.current,X.visibleWidth,l,c,M,j);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)),_.current=pe}};if(h){S.current||(S.current=!0,ha("BARS",`Drawing bars in RAF loop — canvas: ${G.current.width}×${G.current.height}px, player: ${p}`,{canvasSize:G.current}));const E=()=>{Z(),O.current=requestAnimationFrame(E)};return O.current=requestAnimationFrame(E),()=>{O.current&&cancelAnimationFrame(O.current),O.current=null}}S.current=!1},[h,p,g,y,x,i,f,b,o,k,v,l,c,M,j,z]),r.jsxs("div",{ref:P,style:{position:"absolute",left:"50%",top:`${R??A.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:A.visibleWidth,height:A.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 w<"u"&&w!==null?(()=>{const Z=w,E=Z<=120?"var(--latency-good, #10b981)":Z<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",q=`${Z}ms`;return r.jsxs("div",{className:Z>250?"av-latency-pulse":"",style:{background:E,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(F.NtdStopwatch,{size:12}),r.jsx("span",{children:q})]})})():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:T,width:A.width,height:A.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"}})]})},Po="/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:`${Po}/${e}/Photoreal_${e}_${i}-512x512.png`}})}}function _t(e,t,n){return{name:e,icon:n,entries:Array.from({length:t},(a,s)=>{const i=String(s+1).padStart(2,"0");return{label:`${e} ${i}`,url:`${Po}/${e}/${e}_${i}-256x256.png`}})}}const Ha=[$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"),_t("Wall",24,"wall"),_t("Rust",24,"rust"),_t("Woven",24,"woven"),_t("Ground",24,"ground"),_t("Pebbles",24,"pebbles"),_t("Plant",24,"plant"),_t("Roof",24,"roof"),_t("Misc",24,"misc")],Eo=Ha.flatMap(e=>e.entries);function ch(e){return Eo.find(t=>t.url===e)}const dh={fire:F.NtdFire,metal:F.NtdSettings,ice:F.NtdSnowflake,stone:F.NtdMountain,wood:F.NtdTree,tile:F.NtdGrid,concrete:F.NtdLayers,trees:F.NtdTree,grass:F.NtdLeaf,wall:F.NtdHome,rust:F.NtdCircle,woven:F.NtdGrid,ground:F.NtdMountain,pebbles:F.NtdDroplet,plant:F.NtdLeaf,roof:F.NtdHome,misc:F.NtdPalette},uh=({icon:e})=>{const t=dh[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}),hh=({fill:e=Gt,onChange:t=()=>{},previewColor:n="var(--nice-primary, #2196f3)",accentColor:a="var(--nice-primary, #0d6efd)",width:s,height:i})=>{const{t:o}=xe(),[l,c]=d.useState(null),u=(f,k)=>{t({...e,[f]:k})},h=d.useMemo(()=>{const f=e.color||n||"var(--nice-primary, #2196f3)";return(k,v,w)=>{const R=Wn.find(j=>j.name===k)||Wn[0],M=v?Pr.find(j=>j.name===v)??null:null;return Mo({width:80,height:22,capStyle:R,color:f,highlight:e.highlight,glow:e.glow,glass:e.glass,pattern:M,patternColor:e.patternColor,patternOnly:e.patternOnly,textureUrl:w??null,textureScale:e.textureScale})}},[e,n]),p=`2px solid ${a}`,g=a==="var(--nice-warning-dark, #d4a017)"?"var(--nice-warning-bg, #fff8e1)":"var(--nice-info-bg, #e7f1ff)",y=d.useRef(null),m=d.useRef(null),x=d.useCallback((f,k)=>{f.current&&f.current.scrollBy({left:k*180,behavior:"smooth"})},[]),b={position:"absolute",top:0,width:28,height:"100%",border:"none",cursor:"pointer",zIndex:2,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,fontWeight:700,color:"var(--nice-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(F.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(F.NtdChevronRight,{size:16})}),r.jsx("div",{ref:y,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:Wn.map(f=>{const k=e.capStyleName===f.name;return r.jsx("div",{title:f.name,onClick:()=>u("capStyleName",f.name),style:{cursor:"pointer",flexShrink:0,border:k?p:"1px solid var(--nice-border-color, #555)",borderRadius:6,padding:3,background:k?g:"var(--nice-bg-secondary, #222)"},dangerouslySetInnerHTML:{__html:h(f.name,null)}},f.name)})})]}),r.jsx(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(F.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(F.NtdChevronRight,{size:16})}),r.jsxs("div",{ref:m,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:[r.jsx("div",{title:o("playerForm.none","None"),onClick:()=>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:"—"}),Pr.map(f=>{const k=e.patternName===f.name;return r.jsx("div",{title:f.name,onClick:()=>u("patternName",f.name),style:{cursor:"pointer",flexShrink:0,border:k?p:"1px solid var(--nice-border-color, #555)",borderRadius:6,padding:3,background:k?g:"var(--nice-bg-secondary, #222)"},dangerouslySetInnerHTML:{__html:h(e.capStyleName,f.name)}},f.name)})]})]}),r.jsx("div",{style:{marginBottom:8},children:r.jsx(ie.NiceToggle,{label:o("playerForm.patternOnly","Pattern only (flat, no 3D)"),checked:e.patternOnly,onChange:f=>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")}),Ha.map(f=>r.jsx(ie.NiceButton,{size:"sm",variant:(l==null?void 0:l.name)===f.name?"primary":"outline",onClick:()=>c(k=>(k==null?void 0:k.name)===f.name?null:f),title:f.name,ariaLabel:f.name,children:r.jsx(uh,{icon:f.icon})},f.name))]}),l&&r.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap",maxHeight:130,overflowY:"auto",padding:4,border:"1px solid var(--nice-border, #dee2e6)",borderRadius:6,background:"var(--nice-bg-secondary, #f8f9fa)"},children:l.entries.map(f=>{const k=e.textureUrl===f.url;return r.jsx("div",{title:f.label,onClick:()=>u("textureUrl",k?null:f.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:k?`3px solid ${a}`:"1px solid var(--nice-text-muted, #bbb)",backgroundImage:`url(${f.url})`,backgroundSize:"cover",boxShadow:k?`0 0 6px ${a}`:void 0}},f.url)})}),e.textureUrl&&r.jsxs("div",{style:{marginTop:4,display:"flex",alignItems:"center",gap:8},children:[r.jsx("div",{style:{width:80,height:22,borderRadius:6,backgroundImage:`url(${e.textureUrl})`,backgroundSize:`${Math.round(256*e.textureScale)}px`,border:"1px solid var(--nice-border-color, #aaa)"}}),r.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #666)"},children:e.textureUrl.split("/").pop()})]})]}),e.textureUrl&&r.jsxs(r.Fragment,{children:[r.jsxs(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 ph({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([]),[k,v]=d.useState([]),[w,R]=d.useState(!1),[M,j]=d.useState(null),[T]=d.useState(null),[P]=d.useState(null),[A,I]=d.useState(null),L=d.useRef(null);function N(G){try{if(G instanceof Error){let C=`${G.message}
|
|
40
|
+
${G.stack??""}`;const $=G;if($!=null&&$.attemptedUrls)try{C+=`
|
|
41
41
|
Attempted URLs: ${Array.isArray($.attemptedUrls)?$.attemptedUrls.join(", "):String($.attemptedUrls)}`}catch{C+=`
|
|
42
|
-
Attempted URLs: ${String($.attemptedUrls)}`}return C}const
|
|
43
|
-
Attempted URLs: ${Array.isArray(O.attemptedUrls)?O.attemptedUrls.join(", "):String(O.attemptedUrls)}`:String(Y)}catch{return"Unknown error"}}function D(Y){if(!Y||Y<=0)return null;const O=12*Math.log2(Y/440)+69;return Math.round(O-12)}async function q(Y){var C;const O=(C=Y.target.files)==null?void 0:C[0];O&&await te(O,h)}async function te(Y,O){P(null),b([]),N(!0);try{const C=await Y.arrayBuffer(),$=window.AudioContext??window.webkitAudioContext,W=await new $().decodeAudioData(C),A=W.getChannelData(0);d(A);const L=W.sampleRate,G=Math.floor(L*.1),F=G,V=()=>{const H=[],ie=la.PitchDetector.forFloat32Array(G);for(let re=0;re<A.length-G;re+=F){const he=A.slice(re,re+G),[J,ue]=ie.findPitch(he,L),me=D(J);me&&J>50&&J<2e3&&ue>.7&&H.push({start:re/L,duration:G/L,pitch:me,freq:J})}return H},Q=()=>{const H=[];for(let ie=0;ie<A.length-G;ie+=F){const re=A.slice(ie,ie+G),he=U(re,L),J=D(he);J&&he>50&&he<2e3&&H.push({start:ie/L,duration:G/L,pitch:J,freq:he})}return H};if(O){N(!0),P(null);const H={};try{const ie={};try{H.pitchy=V(),ie.pitchy=null}catch(re){H.pitchy=[],ie.pitchy=_(re),st.warn("pitchy failed",re)}try{H["ultrastar-wp"]=Q(),ie["ultrastar-wp"]=null}catch(re){H["ultrastar-wp"]=[],ie["ultrastar-wp"]=_(re),st.warn("ultrastar-wp failed",re)}H.aubio=[],ie.aubio="disabled";try{if(!a)throw new Error("CREPE backend not configured");const he=(await a(Y)).track??[];H.crepe=he.map((J,ue)=>{var me;return{start:J.t,duration:(me=he[ue+1])!=null&&me.t?he[ue+1].t-J.t:.1,pitch:D(J.hz)??0,freq:J.hz}}),ie.crepe=null}catch(re){H.crepe=[],ie.crepe=_(re),st.warn("crepe failed",re)}try{if(!s)throw new Error("Librosa backend not configured");const he=(await s(new File([Y],Y.name,{type:Y.type}))).track??[];H.librosa=he.map((J,ue)=>{var me;return{start:J.t,duration:(me=he[ue+1])!=null&&me.t?he[ue+1].t-J.t:.1,pitch:D(J.hz)??0,freq:J.hz}}),ie.librosa=null}catch(re){H.librosa=[],ie.librosa=_(re),st.warn("librosa failed",re)}x(ie),y(H),b(H[l]??[])}catch(ie){st.error("compareAll overall failed",ie);const re=ie instanceof Error?ie.message:String(ie);P(i("audioPitch.errorComparing","Error comparing algorithms: ")+re)}finally{N(!1)}return}const le=[],oe=[];let ne=0;if(l==="pitchy"){const H=la.PitchDetector.forFloat32Array(G);for(let ie=0;ie<A.length-G;ie+=F){const re=A.slice(ie,ie+G);let he=0;for(let Se=0;Se<re.length;Se++)he+=re[Se]*re[Se];he=Math.sqrt(he/re.length),oe.push(he);const[J,ue]=H.findPitch(re,L),me=D(J);me&&J>50&&J<2e3&&ue>.7&&(le.push({start:ie/L,duration:G/L,pitch:me,freq:J}),ne++)}}else if(l==="crepe")try{if(!a)throw new Error("CREPE backend not configured");const H=await a(Y);if(!H.track||H.track.length===0)P(i("audioPitch.crepeNoNotes","CREPE detected no notes")),st.warn("Crepe: No notes detected in audio file.");else{const ie=H.track.map((re,he)=>{const J=D(re.hz);return J&&re.hz>50&&re.hz<2e3?{start:re.t,duration:he<H.track.length-1?H.track[he+1].t-re.t:.1,pitch:J,freq:re.hz}:null}).filter(re=>re!==null);if(b(ie),e)try{e(ie)}catch(re){st.error("Error in onSegments:",re)}m([]),d(null);return}}catch(H){P(i("audioPitch.crepeBackendError","CREPE backend error")),T(_(H)),st.error("Crepe: Error calling backend:",H)}else if(l==="librosa")try{await z(Y),m([]),d(null);return}catch(H){P(i("audioPitch.librosaBackendError","Librosa backend error")),T(_(H)),st.error("Librosa: Error calling backend:",H)}else if(l==="ultrastar-wp")for(let H=0;H<A.length-G;H+=F){const ie=A.slice(H,H+G);let re=0;for(let ue=0;ue<ie.length;ue++)re+=ie[ue]*ie[ue];re=Math.sqrt(re/ie.length),oe.push(re);const he=U(ie,L),J=D(he);J&&he>50&&he<2e3&&(le.push({start:H/L,duration:G/L,pitch:J,freq:he}),ne++)}m(oe);const K=Z(le);if(b(K),e)try{e(K)}catch(H){st.error("Error in onSegments:",H)}K.length===0&&l!=="crepe"&&(P(i("audioPitch.noNotesDetected","No notes detected")),st.warn("No notes detected in audio file."))}catch(C){P(i("audioPitch.errorAnalyzing","Error analyzing the file: ")+(C instanceof Error?C.message:String(C))),T(_(C)),st.error("Error analyzing audio file:",C)}finally{N(!1)}}u.useEffect(()=>{n&&te(n,!0)},[n]);async function z(Y){try{if(!s)throw new Error("Librosa backend not configured");const O=new File([Y],"capture.wav",{type:"audio/wav"}),$=((await s(O)).track??[]).map(k=>({t:k.t,hz:k.hz}));if(e){const k=$.map((W,A)=>{var F;const L=((F=$[A+1])==null?void 0:F.t)??W.t+.1,G=D(W.hz)??0;return{start:W.t,duration:Math.max(.05,L-W.t),pitch:G,freq:W.hz}});e(k),b(k)}}catch(O){st.warn("Librosa analysis failed, falling back to local detectors",O);const $=(typeof O=="object"&&O!==null?O:{}).attemptedUrls;$&&st.error("Librosa attempted URLs:",$);const k=$?Array.isArray($)?$.join(", "):String($):null,W=O instanceof Error?O.message:String(O);P(i("audioPitch.librosaBackendError","Librosa backend error")+": "+W+(k?" (attempted: "+k+")":"")),T(_(O))}}function U(Y,O){const k=Math.floor(O/50),W=Math.max(2,Math.floor(O/2e3));let A=0;for(let V=0;V<Y.length;V++)A+=Y[V]*Y[V];if(A<=1e-8)return 0;let L=-1,G=0;const F=1e-10;for(let V=W;V<=Math.min(k,Y.length-2);V++){let Q=0;const le=Y.length-V;for(let ne=0;ne<le;ne++)Q+=Y[ne]*Y[ne+V];const oe=Q/(le+F)/(A/Y.length+F);oe>G&&(G=oe,L=V)}return L>0&&G>.01?O/L:0}function Z(Y){if(Y.length===0)return[];const O=[];let C=Y[0];for(let $=1;$<Y.length;$++){const k=Y[$];k.pitch===C.pitch&&Math.abs(k.freq-C.freq)<1?C.duration+=k.duration:(O.push(C),C=k)}return O.push(C),O}function ae(){try{const Y=Object.keys(p).length>0?Object.keys(p):["pitchy","ultrastar-wp","aubio","crepe","librosa"],O=(()=>{let ne=0;for(const K of Y){const H=p[K]??[];for(const ie of H)ne=Math.max(ne,ie.start+(ie.duration||0))}return ne||0})(),C=(ne,K)=>!ne||!K?1/0:1200*Math.log2(ne/K),$=(ne,K)=>{if(!ne||!K)return!1;const H=Math.round(Math.log2(K/ne)),ie=ne*Math.pow(2,H),re=Math.abs(C(ie,K));return Math.abs(H)>=1&&re<50},k=ne=>{const K={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!ne||ne.length===0)return K;K.count=ne.length,K.totalDur=ne.reduce((he,J)=>he+(J.duration||0),0);const H=ne.map(he=>he.freq).filter(Boolean);if(H.length===0)return K;const ie=H.reduce((he,J)=>he+J,0)/H.length,re=H.reduce((he,J)=>he+(J-ie)*(J-ie),0)/H.length;return K.meanFreq=ie,K.stdFreq=Math.sqrt(re||0),K.meanDur=K.totalDur/K.count,K.voicedFraction=O>0?K.totalDur/O:null,K},W=(ne,K)=>{let H=0,ie=0;const re=[];for(const J of ne){const ue=J.start,me=J.start+(J.duration||.05);let Se=null,de=0;for(const xe of K){const Me=xe.start,$e=xe.start+(xe.duration||.05),je=Math.max(0,Math.min(me,$e)-Math.max(ue,Me));je>de&&(de=je,Se=xe)}if(Se&&de>0){const xe=Math.abs(C(J.freq,Se.freq));re.push(xe),xe<50&&H++,$(J.freq,Se.freq)&&ie++}}const he=re.length?re.reduce((J,ue)=>J+ue,0)/re.length:null;return{matches:H,compared:ne.length,meanCents:he,octaveErrors:ie}},A=[];A.push("# AudioPitchAnalyzer — Comparative Report"),A.push(`Generated: ${new Date().toISOString()}`),A.push(""),A.push("## Summary"),A.push(`- Selected algorithm in UI: **${l}**`),A.push(`- Total analyzed duration (approx): **${O.toFixed(3)} s**`),A.push(""),A.push("## Per-algorithm statistics"),A.push("| Algorithm | Segments | Total voiced (s) | Voiced fraction | Mean freq (Hz) | Std freq (Hz) | Mean dur (s) |"),A.push("|---|---:|---:|---:|---:|---:|---:|");const L={};for(const ne of Y){const K=p[ne]??[],H=k(K);L[ne]=H,A.push(`| ${ne} | ${H.count||0} | ${(H.totalDur||0).toFixed(3)} | ${H.voicedFraction!==null?(H.voicedFraction*100).toFixed(1)+"%":"N/A"} | ${H.meanFreq?H.meanFreq.toFixed(1):"N/A"} | ${H.stdFreq?H.stdFreq.toFixed(1):"N/A"} | ${H.meanDur?H.meanDur.toFixed(3):"N/A"} |`)}A.push(""),A.push("## Pairwise agreement (reference -> test)");const G=Y.includes("crepe")?"crepe":Y.includes("librosa")?"librosa":Y.includes("pitchy")?"pitchy":Y[0];A.push(`Reference algorithm: **${G}**`),A.push(""),A.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),A.push("|---|---:|---:|---:|---:|---:|");for(const ne of Y){if(ne===G)continue;const K=W(p[G]??[],p[ne]??[]),H=K.compared?(K.matches/K.compared*100).toFixed(1)+"%":"N/A";A.push(`| ${G} -> ${ne} | ${K.matches} | ${K.compared} | ${H} | ${K.meanCents!==null?K.meanCents.toFixed(1):"N/A"} | ${K.octaveErrors} |`)}A.push(""),A.push("## Observations and analysis"),A.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."),A.push("- Pairwise match rate shows how often algorithms agree on the same regions (within ~50 cents). Octave error counts highlight typical autocorrelation octave mistakes."),A.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."),A.push("");for(const ne of Y){A.push(`### ${ne}`);const K=L[ne];A.push(`- Segments: ${K.count||0}`),A.push(`- Total voiced (s): ${(K.totalDur||0).toFixed(3)}`),A.push(`- Voiced fraction: ${K.voicedFraction!==null?(K.voicedFraction*100).toFixed(1)+"%":"N/A"}`),A.push(`- Mean frequency: ${K.meanFreq?K.meanFreq.toFixed(2)+" Hz":"N/A"}`),A.push(`- Std frequency: ${K.stdFreq?K.stdFreq.toFixed(2)+" Hz":"N/A"}`),A.push("")}A.push("## Conclusions & recommendation");const F=[];for(const ne of Y){if(ne===G){F.push({alg:ne,score:100});continue}const K=W(p[G]??[],p[ne]??[]),H=K.compared?K.matches/K.compared:0,ie=K.compared?K.octaveErrors/K.compared:0,re=H-ie*.5;F.push({alg:ne,score:re})}F.sort((ne,K)=>K.score-ne.score),A.push(`- Based on this recording, recommended authoritative detector: **${F[0].alg}** (best agreement with reference).`),A.push("- For live, low-latency feedback use Pitchy (YIN) with smoothing/hysteresis; use Crepe/Librosa for authoritative scoring or post-processing."),A.push("- If octave errors are frequent, consider octave-correction heuristics (prefer lower octave when ambiguity) or combine detectors via voting."),A.push(""),A.push("## Raw data (per-algorithm segments)");for(const ne of Y){const K=p[ne]??[];A.push(`### ${ne} — ${K.length} segments`);for(const ie of K)A.push(`- ${ie.start.toFixed(3)} .. ${(ie.start+(ie.duration||0)).toFixed(3)} : ${ie.freq.toFixed(2)} Hz (pitch ${ie.pitch})`);const H=g[ne];H&&A.push(`- Error: ${H}`),A.push("")}const V=A.join(`
|
|
44
|
-
`),
|
|
42
|
+
Attempted URLs: ${String($.attemptedUrls)}`}return C}const W=G;return W!=null&&W.attemptedUrls?`Error: ${String(W.message??W)}
|
|
43
|
+
Attempted URLs: ${Array.isArray(W.attemptedUrls)?W.attemptedUrls.join(", "):String(W.attemptedUrls)}`:String(G)}catch{return i("audioPitch.unknownError","Unknown error")}}function _(G){if(!G||G<=0)return null;const W=12*Math.log2(G/440)+69;return Math.round(W-12)}async function ee(G){var C;const W=(C=G.target.files)==null?void 0:C[0];W&&await Y(W,h)}async function Y(G,W){j(null),v([]),R(!0);try{const C=await G.arrayBuffer(),$=window.AudioContext??window.webkitAudioContext,B=await new $().decodeAudioData(C),H=B.getChannelData(0);u(H);const z=B.sampleRate,Z=Math.floor(z*.1),E=Z,q=()=>{const J=[],ae=la.PitchDetector.forFloat32Array(Z);for(let ce=0;ce<H.length-Z;ce+=E){const le=H.slice(ce,ce+Z),[ne,pe]=ae.findPitch(le,z),fe=_(ne);fe&&ne>50&&ne<2e3&&pe>.7&&J.push({start:ce/z,duration:Z/z,pitch:fe,freq:ne})}return J},X=()=>{const J=[];for(let ae=0;ae<H.length-Z;ae+=E){const ce=H.slice(ae,ae+Z),le=U(ce,z),ne=_(le);ne&&le>50&&le<2e3&&J.push({start:ae/z,duration:Z/z,pitch:ne,freq:le})}return J};if(W){R(!0),j(null);const J={};try{const ae={};try{J.pitchy=q(),ae.pitchy=null}catch(ce){J.pitchy=[],ae.pitchy=N(ce),rt.warn("pitchy failed",ce)}try{J["ultrastar-wp"]=X(),ae["ultrastar-wp"]=null}catch(ce){J["ultrastar-wp"]=[],ae["ultrastar-wp"]=N(ce),rt.warn("ultrastar-wp failed",ce)}J.aubio=[],ae.aubio="disabled";try{if(!a)throw new Error("CREPE backend not configured");const le=(await a(G)).track??[];J.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:_(ne.hz)??0,freq:ne.hz}}),ae.crepe=null}catch(ce){J.crepe=[],ae.crepe=N(ce),rt.warn("crepe failed",ce)}try{if(!s)throw new Error("Librosa backend not configured");const le=(await s(new File([G],G.name,{type:G.type}))).track??[];J.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:_(ne.hz)??0,freq:ne.hz}}),ae.librosa=null}catch(ce){J.librosa=[],ae.librosa=N(ce),rt.warn("librosa failed",ce)}x(ae),y(J),v(J[o]??[])}catch(ae){rt.error("compareAll overall failed",ae);const ce=ae instanceof Error?ae.message:String(ae);j(i("audioPitch.errorComparing","Error comparing algorithms: ")+ce)}finally{R(!1)}return}const re=[],oe=[];let se=0;if(o==="pitchy"){const J=la.PitchDetector.forFloat32Array(Z);for(let ae=0;ae<H.length-Z;ae+=E){const ce=H.slice(ae,ae+Z);let le=0;for(let me=0;me<ce.length;me++)le+=ce[me]*ce[me];le=Math.sqrt(le/ce.length),oe.push(le);const[ne,pe]=J.findPitch(ce,z),fe=_(ne);fe&&ne>50&&ne<2e3&&pe>.7&&(re.push({start:ae/z,duration:Z/z,pitch:fe,freq:ne}),se++)}}else if(o==="crepe")try{if(!a)throw new Error("CREPE backend not configured");const J=await a(G);if(!J.track||J.track.length===0)j(i("audioPitch.crepeNoNotes","CREPE detected no notes")),rt.warn("Crepe: No notes detected in audio file.");else{const ae=J.track.map((ce,le)=>{const ne=_(ce.hz);return ne&&ce.hz>50&&ce.hz<2e3?{start:ce.t,duration:le<J.track.length-1?J.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(J){j(i("audioPitch.crepeBackendError","CREPE backend error")),I(N(J)),rt.error("Crepe: Error calling backend:",J)}else if(o==="librosa")try{await O(G),f([]),u(null);return}catch(J){j(i("audioPitch.librosaBackendError","Librosa backend error")),I(N(J)),rt.error("Librosa: Error calling backend:",J)}else if(o==="ultrastar-wp")for(let J=0;J<H.length-Z;J+=E){const ae=H.slice(J,J+Z);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=U(ae,z),ne=_(le);ne&&le>50&&le<2e3&&(re.push({start:J/z,duration:Z/z,pitch:ne,freq:le}),se++)}f(oe);const D=V(re);if(v(D),e)try{e(D)}catch(J){rt.error("Error in onSegments:",J)}D.length===0&&o!=="crepe"&&(j(i("audioPitch.noNotesDetected","No notes detected")),rt.warn("No notes detected in audio file."))}catch(C){j(i("audioPitch.errorAnalyzing","Error analyzing the file: ")+(C instanceof Error?C.message:String(C))),I(N(C)),rt.error("Error analyzing audio file:",C)}finally{R(!1)}}d.useEffect(()=>{n&&Y(n,!0)},[n]);async function O(G){try{if(!s)throw new Error("Librosa backend not configured");const W=new File([G],"capture.wav",{type:"audio/wav"}),$=((await s(W)).track??[]).map(S=>({t:S.t,hz:S.hz}));if(e){const S=$.map((B,H)=>{var E;const z=((E=$[H+1])==null?void 0:E.t)??B.t+.1,Z=_(B.hz)??0;return{start:B.t,duration:Math.max(.05,z-B.t),pitch:Z,freq:B.hz}});e(S),v(S)}}catch(W){rt.warn("Librosa analysis failed, falling back to local detectors",W);const $=(typeof W=="object"&&W!==null?W:{}).attemptedUrls;$&&rt.error("Librosa attempted URLs:",$);const S=$?Array.isArray($)?$.join(", "):String($):null,B=W instanceof Error?W.message:String(W);j(i("audioPitch.librosaBackendError","Librosa backend error")+": "+B+(S?" (attempted: "+S+")":"")),I(N(W))}}function U(G,W){const S=Math.floor(W/50),B=Math.max(2,Math.floor(W/2e3));let H=0;for(let q=0;q<G.length;q++)H+=G[q]*G[q];if(H<=1e-8)return 0;let z=-1,Z=0;const E=1e-10;for(let q=B;q<=Math.min(S,G.length-2);q++){let X=0;const re=G.length-q;for(let se=0;se<re;se++)X+=G[se]*G[se+q];const oe=X/(re+E)/(H/G.length+E);oe>Z&&(Z=oe,z=q)}return z>0&&Z>.01?W/z:0}function V(G){if(G.length===0)return[];const W=[];let C=G[0];for(let $=1;$<G.length;$++){const S=G[$];S.pitch===C.pitch&&Math.abs(S.freq-C.freq)<1?C.duration+=S.duration:(W.push(C),C=S)}return W.push(C),W}function K(){try{const G=Object.keys(g).length>0?Object.keys(g):["pitchy","ultrastar-wp","aubio","crepe","librosa"],W=(()=>{let se=0;for(const D of G){const J=g[D]??[];for(const ae of J)se=Math.max(se,ae.start+(ae.duration||0))}return se||0})(),C=(se,D)=>!se||!D?1/0:1200*Math.log2(se/D),$=(se,D)=>{if(!se||!D)return!1;const J=Math.round(Math.log2(D/se)),ae=se*Math.pow(2,J),ce=Math.abs(C(ae,D));return Math.abs(J)>=1&&ce<50},S=se=>{const D={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!se||se.length===0)return D;D.count=se.length,D.totalDur=se.reduce((le,ne)=>le+(ne.duration||0),0);const J=se.map(le=>le.freq).filter(Boolean);if(J.length===0)return D;const ae=J.reduce((le,ne)=>le+ne,0)/J.length,ce=J.reduce((le,ne)=>le+(ne-ae)*(ne-ae),0)/J.length;return D.meanFreq=ae,D.stdFreq=Math.sqrt(ce||0),D.meanDur=D.totalDur/D.count,D.voicedFraction=W>0?D.totalDur/W:null,D},B=(se,D)=>{let J=0,ae=0;const ce=[];for(const ne of se){const pe=ne.start,fe=ne.start+(ne.duration||.05);let me=null,he=0;for(const we of D){const je=we.start,Ne=we.start+(we.duration||.05),Ee=Math.max(0,Math.min(fe,Ne)-Math.max(pe,je));Ee>he&&(he=Ee,me=we)}if(me&&he>0){const we=Math.abs(C(ne.freq,me.freq));ce.push(we),we<50&&J++,$(ne.freq,me.freq)&&ae++}}const le=ce.length?ce.reduce((ne,pe)=>ne+pe,0)/ce.length:null;return{matches:J,compared:se.length,meanCents:le,octaveErrors:ae}},H=[];H.push("# AudioPitchAnalyzer — Comparative Report"),H.push(`Generated: ${new Date().toISOString()}`),H.push(""),H.push("## Summary"),H.push(`- Selected algorithm in UI: **${o}**`),H.push(`- Total analyzed duration (approx): **${W.toFixed(3)} s**`),H.push(""),H.push("## Per-algorithm statistics"),H.push("| Algorithm | Segments | Total voiced (s) | Voiced fraction | Mean freq (Hz) | Std freq (Hz) | Mean dur (s) |"),H.push("|---|---:|---:|---:|---:|---:|---:|");const z={};for(const se of G){const D=g[se]??[],J=S(D);z[se]=J,H.push(`| ${se} | ${J.count||0} | ${(J.totalDur||0).toFixed(3)} | ${J.voicedFraction!==null?(J.voicedFraction*100).toFixed(1)+"%":"N/A"} | ${J.meanFreq?J.meanFreq.toFixed(1):"N/A"} | ${J.stdFreq?J.stdFreq.toFixed(1):"N/A"} | ${J.meanDur?J.meanDur.toFixed(3):"N/A"} |`)}H.push(""),H.push("## Pairwise agreement (reference -> test)");const Z=G.includes("crepe")?"crepe":G.includes("librosa")?"librosa":G.includes("pitchy")?"pitchy":G[0];H.push(`Reference algorithm: **${Z}**`),H.push(""),H.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),H.push("|---|---:|---:|---:|---:|---:|");for(const se of G){if(se===Z)continue;const D=B(g[Z]??[],g[se]??[]),J=D.compared?(D.matches/D.compared*100).toFixed(1)+"%":"N/A";H.push(`| ${Z} -> ${se} | ${D.matches} | ${D.compared} | ${J} | ${D.meanCents!==null?D.meanCents.toFixed(1):"N/A"} | ${D.octaveErrors} |`)}H.push(""),H.push("## Observations and analysis"),H.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."),H.push("- Pairwise match rate shows how often algorithms agree on the same regions (within ~50 cents). Octave error counts highlight typical autocorrelation octave mistakes."),H.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."),H.push("");for(const se of G){H.push(`### ${se}`);const D=z[se];H.push(`- Segments: ${D.count||0}`),H.push(`- Total voiced (s): ${(D.totalDur||0).toFixed(3)}`),H.push(`- Voiced fraction: ${D.voicedFraction!==null?(D.voicedFraction*100).toFixed(1)+"%":"N/A"}`),H.push(`- Mean frequency: ${D.meanFreq?D.meanFreq.toFixed(2)+" Hz":"N/A"}`),H.push(`- Std frequency: ${D.stdFreq?D.stdFreq.toFixed(2)+" Hz":"N/A"}`),H.push("")}H.push("## Conclusions & recommendation");const E=[];for(const se of G){if(se===Z){E.push({alg:se,score:100});continue}const D=B(g[Z]??[],g[se]??[]),J=D.compared?D.matches/D.compared:0,ae=D.compared?D.octaveErrors/D.compared:0,ce=J-ae*.5;E.push({alg:se,score:ce})}E.sort((se,D)=>D.score-se.score),H.push(`- Based on this recording, recommended authoritative detector: **${E[0].alg}** (best agreement with reference).`),H.push("- For live, low-latency feedback use Pitchy (YIN) with smoothing/hysteresis; use Crepe/Librosa for authoritative scoring or post-processing."),H.push("- If octave errors are frequent, consider octave-correction heuristics (prefer lower octave when ambiguity) or combine detectors via voting."),H.push(""),H.push("## Raw data (per-algorithm segments)");for(const se of G){const D=g[se]??[];H.push(`### ${se} — ${D.length} segments`);for(const ae of D)H.push(`- ${ae.start.toFixed(3)} .. ${(ae.start+(ae.duration||0)).toFixed(3)} : ${ae.freq.toFixed(2)} Hz (pitch ${ae.pitch})`);const J=m[se];J&&H.push(`- Error: ${J}`),H.push("")}const q=H.join(`
|
|
44
|
+
`),X=new Blob([q],{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(G){rt.error("generateScientificReport error",G),rt.warn(i("audioPitch.reportError","Could not generate the report: ")+String(G))}}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:G=>l(G.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:G=>p(G.target.checked)})," ",i("audioPitch.compareAll","Compare all algorithms")]}),r.jsx("input",{type:"file",accept:"audio/*",ref:L,onChange:ee,disabled:w})]}),w&&r.jsx("div",{children:i("audioPitch.analyzing","Analyzing...")}),r.jsxs("div",{style:{marginTop:8},children:[r.jsx("b",{children:i("audioPitch.method","Method:")})," ",o]}),M&&r.jsxs("div",{style:{color:"red",marginTop:8},children:[r.jsxs("b",{children:[o,": "]}),r.jsx("div",{children:M}),A&&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:A})]}),T&&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:T}),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(([G,W])=>W).map(([G,W])=>r.jsxs("div",{style:{marginTop:6},children:[r.jsxs("b",{children:[G,":"]}),r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:W})]},G))]})]}),k.length>0&&r.jsxs("div",{style:{marginTop:16},children:[r.jsx("b",{children:i("audioPitch.resultUltrastar","Result (UltraStar format):")}),r.jsxs("pre",{style:{background:"var(--nice-text, #222)",color:"var(--nice-bg, #fff)",padding:8,borderRadius:4},children:[k.map(G=>`: ${Math.round(G.start*10)} ${Math.round(G.duration*10)} ${G.pitch} [${G.freq.toFixed(1)} Hz]`).join(`
|
|
45
45
|
`),`
|
|
46
|
-
-`]})]}),c&&c.length>0&&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":"Waveform and RMS visualization canvas",ref:
|
|
47
|
-
`)})]},Y))]})]})}const _t=1e4,Bs=5e3;function Xr(e,t=.35){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(!n)return e;const a=Math.min(255,Math.round(parseInt(n[1],16)+(255-parseInt(n[1],16))*t)),s=Math.min(255,Math.round(parseInt(n[2],16)+(255-parseInt(n[2],16))*t)),i=Math.min(255,Math.round(parseInt(n[3],16)+(255-parseInt(n[3],16))*t));return`rgb(${a},${s},${i})`}const uh=["var(--nice-warning, #facc15)","var(--nice-text-secondary, #cbd5e1)","var(--nice-warning, #d97706)"],hh=({entry:e,rank:t,animDelay:n})=>{const[a,s]=u.useState(0),[i,l]=u.useState(0),[o,c]=u.useState(0),[d,h]=u.useState(0),f=Math.min(e.classicScore,_t),p=Math.min(e.bonusScore,_t),y=f/_t*Bs,g=p>0?p/_t*Bs:0;return u.useEffect(()=>{let x,v=null;const m=Math.max(y,400),S=Math.max(g,g>0?300:0),b=w=>{v===null&&(v=w);const N=w-v-n;if(N<0){x=requestAnimationFrame(b);return}if(N<=m){const R=Math.min(1,N/m),P=1-Math.pow(1-R,3);s(Math.min(P*(f/_t)*100,100)),c(Math.round(P*e.classicScore)),x=requestAnimationFrame(b);return}if(s(Math.min(f/_t*100,100)),c(e.classicScore),S>0){const R=N-m;if(R<=S){const P=Math.min(1,R/S),j=1-Math.pow(1-P,3);l(Math.min(j*(p/_t)*100,100)),h(Math.round(j*e.bonusScore)),x=requestAnimationFrame(b);return}l(Math.min(p/_t*100,100)),h(e.bonusScore)}};return x=requestAnimationFrame(b),()=>cancelAnimationFrame(x)},[e.classicScore,e.bonusScore,y,g,n]),r.jsxs("div",{className:"karaoke-summary-bar",children:[r.jsx("span",{className:"karaoke-summary-bar-rank",children:t<=3?r.jsx(B.NtdMedal,{size:18,primaryColor:uh[t-1]}):`#${t}`}),r.jsx("span",{className:"karaoke-summary-bar-name",style:{color:e.color},children:e.name}),r.jsxs("div",{className:"karaoke-summary-bar-track",children:[e.bonusScore>0&&r.jsx("div",{className:"karaoke-summary-bar-fill-bonus",style:{width:`${Math.min(a+i,100)}%`,background:Xr(e.color,.45)}}),r.jsx("div",{className:"karaoke-summary-bar-fill-classic",style:{width:`${a}%`,background:`linear-gradient(90deg, ${e.color}, ${Xr(e.color,.15)})`,boxShadow:`0 0 8px ${e.color}55`}}),r.jsxs("div",{className:"karaoke-summary-bar-text",children:[o.toLocaleString(),d>0&&r.jsxs("span",{className:"karaoke-summary-bar-text-bonus",style:{color:Xr(e.color,.5)},children:["+",d.toLocaleString()]})]})]}),r.jsx("span",{className:"karaoke-summary-bar-total",children:(o+d).toLocaleString()})]})},Gs=({title:e,entries:t,highlightNames:n,playerColorMap:a})=>r.jsxs("div",{className:"karaoke-summary-rank",children:[r.jsx("h4",{className:"karaoke-summary-rank-title",children:e}),r.jsx("table",{className:"karaoke-summary-rank-table",children:r.jsx("tbody",{children:t.map((s,i)=>{const l=n.has(s.name),o=a.get(s.name);return r.jsxs("tr",{className:l?"karaoke-summary-rank-row karaoke-summary-rank-row--hl":"karaoke-summary-rank-row",children:[r.jsx("td",{className:`karaoke-summary-rank-pos${i<3?" karaoke-summary-rank-pos--top":""}`,children:s.rank}),r.jsxs("td",{className:"karaoke-summary-rank-name",style:o?{color:o}:void 0,children:[l&&r.jsxs(r.Fragment,{children:[r.jsx(B.NtdCircle,{size:8})," "]}),s.name]}),r.jsx("td",{className:"karaoke-summary-rank-score",children:s.score.toLocaleString()})]},`${s.name}-${i}`)})})})]}),$o=({uploadedSong:e,playerScores:t,topSingings:n,onRestart:a,onContinue:s,t:i,renderReport:l,className:o,style:c,id:d,accessMode:h,"data-testid":f})=>{const[p,y]=u.useState(!1),g=u.useMemo(()=>[...t].sort((w,N)=>N.totalScore-w.totalScore),[t]),x=u.useMemo(()=>{const w=new Map;for(const N of t)w.set(N.name,N.color);return w},[t]),v=u.useMemo(()=>new Set(t.map(w=>w.name)),[t]),m=u.useMemo(()=>g.map((w,N)=>({rank:N+1,name:w.name,score:w.totalScore,color:w.color})),[g]),S=u.useMemo(()=>{const w=n.map(R=>({name:R.playerName,score:R.score})),N=new Set;for(const R of g)N.has(R.id)||(N.add(R.id),w.push({name:R.name,score:R.totalScore}));return w.sort((R,P)=>P.score-R.score),w.slice(0,10).map((R,P)=>({rank:P+1,name:R.name,score:R.score}))},[n,g]),b=e?e.artist?`${e.artist} — ${e.title}`:e.title:i("karaokeSummary.unknownSong","Unknown song");return h==="hidden"?null:r.jsxs("div",{className:`karaoke-summary-overlay${o?` ${o}`:""}`,style:c,id:d,"data-testid":f,children:[r.jsxs("div",{className:"karaoke-summary-card",children:[r.jsx("h1",{className:"karaoke-summary-title",children:b}),r.jsx("div",{className:"karaoke-summary-bars",children:g.length===0?r.jsx("div",{className:"karaoke-summary-empty",children:i("karaokeSummary.noScores","No scores")}):g.map((w,N)=>r.jsx(hh,{entry:w,rank:N+1,animDelay:N*300},w.id))}),(g.length>1||n.length>0)&&r.jsxs("div",{className:"karaoke-summary-ranks",children:[g.length>1&&r.jsx(Gs,{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:m,highlightNames:v,playerColorMap:x}),n.length>0&&r.jsx(Gs,{title:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(B.NtdTrophy,{size:14})," ",i("karaokeSummary.globalRanking","Top 10")]}),entries:S,highlightNames:v,playerColorMap:x})]}),r.jsxs("div",{className:"karaoke-summary-actions",children:[l&&r.jsxs("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--report",onClick:()=>y(!0),children:[r.jsx(B.NtdBarChart,{size:15})," ",i("karaokeSummary.report","Report")]}),r.jsx("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--restart",onClick:a,children:i("karaokeSummary.restart","Restart")}),r.jsx("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--continue",onClick:s,children:i("karaokeSummary.continue","Continue")})]})]}),p&&(l==null?void 0:l(()=>y(!1)))]})},ph=ot.scoped("GenericPlayer"),fh=e=>/youtu(\.be|be\.com)/i.test(e),Po=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),mh=e=>!!e&&/\.(mp3|aac|m4a|flac|wav|ogg)(\?.*)?$/i.test(e),gh=e=>{var i;if(!((i=e==null?void 0:e.sources)!=null&&i.length))return null;const t=l=>e.sources.find(o=>o.kind===l),n=e.sources.find(l=>l.kind==="youtube"&&(l.videoId||l.url&&fh(l.url)))??null;if(n)return n;const a=t("hls")||e.sources.find(l=>l.url&&Po(l.url))||null;if(a)return a;const s=t("audio")||e.sources.find(l=>l.url&&mh(l.url))||null;return s||(e.sources[0]??null)},Er=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")}`},yh=[.25,.5,.75,1,1.25,1.5,1.75,2],Ao=({tracks:e=[],initialIndex:t=0,autoPlay:n=!0,countdownSeconds:a=0,height:s=360,onIndexChange:i,onPlayingChange:l,onTimeUpdate:o,externalRef:c,uiMode:d="full",compactNextCount:h=3,progressBarPosition:f="inline",loop:p=!1,onEnded:y,enableKeyboardShortcuts:g=!0,shuffle:x=!1,repeatMode:v="none",playbackSpeed:m=1,abLoop:S=null,onRepeatModeChange:b,onShuffleChange:w,onSpeedChange:N,sleepTimer:R=0,onSleepTimerExpired:P})=>{const{t:j}=Te(),[M,I]=u.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),T=e[M],E=u.useMemo(()=>gh(T),[T]),[_,D]=u.useState(!1),[q,te]=u.useState(0),[z,U]=u.useState(0),[Z,ae]=u.useState(.9),[Y,O]=u.useState(null),[C,$]=u.useState(null),k=u.useRef(null),[W,A]=u.useState(x),[L,G]=u.useState(v),[F,V]=u.useState(m),[Q,le]=u.useState(S),[oe,ne]=u.useState([]),[K,H]=u.useState(R>0?R*60:null),ie=u.useRef(null),[re,he]=u.useState(()=>Pi()),J=u.useRef(null),ue=u.useRef(null),me=u.useRef(null),Se=u.useRef(null);u.useEffect(()=>{if(W&&e.length>0){const fe=e.map((be,Fe)=>Fe);for(let be=fe.length-1;be>0;be--){const Fe=Math.floor(Math.random()*(be+1));[fe[be],fe[Fe]]=[fe[Fe],fe[be]]}ne(fe)}},[W,e.length]),u.useEffect(()=>(ie.current&&(window.clearInterval(ie.current),ie.current=null),R>0&&_&&(H(R*60),ie.current=window.setInterval(()=>{H(fe=>!fe||fe<=1?(ie.current&&window.clearInterval(ie.current),ie.current=null,P==null||P(),null):fe-1)},1e3)),()=>{ie.current&&window.clearInterval(ie.current)}),[R,_]);const de=u.useCallback(fe=>{const be=Math.min(Math.max(0,fe),Math.max(0,e.length-1));I(be),i==null||i(be)},[e.length,i]),xe=u.useCallback(()=>{if(W&&oe.length>0){const be=oe.indexOf(M)+1;return be<oe.length?oe[be]:L==="all"?oe[0]:-1}return M<e.length-1?M+1:L==="all"?0:-1},[M,e.length,W,oe,L]),Me=u.useCallback(()=>{if(W&&oe.length>0){const fe=oe.indexOf(M);return fe>0?oe[fe-1]:L==="all"?oe[oe.length-1]:-1}return M>0?M-1:L==="all"?e.length-1:-1},[M,e.length,W,oe,L]),$e=u.useCallback(()=>{const fe=xe();fe>=0&&de(fe)},[xe,de]),je=u.useCallback(async()=>{var fe,be;await Zt(),he(!0),(E==null?void 0:E.kind)==="youtube"?(fe=J.current)==null||fe.playVideo():(be=ue.current)==null||be.play(),D(!0),l==null||l(!0)},[E,l]),Xe=u.useCallback(()=>{var fe,be;(E==null?void 0:E.kind)==="youtube"?(fe=J.current)==null||fe.pauseVideo():(be=ue.current)==null||be.pause(),D(!1),l==null||l(!1)},[E,l]),ce=u.useCallback(()=>_?Xe():je(),[_,je,Xe]),ge=u.useCallback(fe=>{var pe;const be=(T==null?void 0:T.startOffset)??0,Fe=fe+be;(E==null?void 0:E.kind)==="youtube"?(pe=J.current)==null||pe.seekTo(Fe,!0):ue.current&&(ue.current.currentTime=Fe);const xt=Math.max(0,fe);U(xt),o==null||o(xt)},[E,o]),ze=u.useCallback(()=>{if(z>3){ge(0);return}const fe=Me();fe>=0&&de(fe)},[Me,de,z,ge]),Ce=u.useCallback(fe=>{var be,Fe;ae(fe),O(null),(E==null?void 0:E.kind)==="youtube"?(Fe=(be=J.current)==null?void 0:be.setVolume)==null||Fe.call(be,Math.round(fe*100)):ue.current&&(ue.current.volume=fe)},[E]),De=u.useCallback(()=>{Y!==null?Ce(Y):(O(Z),Ce(0))},[Z,Y,Ce]),tt=u.useCallback(fe=>{var be,Fe;V(fe),ue.current&&(ue.current.playbackRate=fe),(E==null?void 0:E.kind)==="youtube"&&((Fe=(be=J.current)==null?void 0:be.setPlaybackRate)==null||Fe.call(be,fe)),N==null||N(fe)},[E,N]),Ye=u.useCallback(()=>{const fe=["none","all","one"],be=fe[(fe.indexOf(L)+1)%fe.length];G(be),b==null||b(be)},[L,b]),He=u.useCallback(()=>{const fe=!W;A(fe),w==null||w(fe)},[W,w]),Lt=u.useCallback(fe=>{le(fe)},[]);u.useImperativeHandle(c,()=>({play:je,pause:Xe,toggle:ce,seekTo:ge,setVolume:Ce,setSpeed:tt,setRepeatMode:fe=>{G(fe),b==null||b(fe)},toggleShuffle:He,setABLoop:Lt,getUnderlyingPlayer:()=>(E==null?void 0:E.kind)==="youtube"?J.current:(E==null?void 0:E.kind)==="hls"||(E==null?void 0:E.kind)==="audio"?ue.current:null}),[je,Xe,ce,ge,Ce,tt,He,Lt,E==null?void 0:E.kind]),u.useEffect(()=>{const fe=window.setInterval(()=>{let be=0,Fe=0;(E==null?void 0:E.kind)==="youtube"&&J.current?(be=J.current.getCurrentTime()||0,Fe=J.current.getDuration()||0):ue.current&&(be=ue.current.currentTime||0,Fe=ue.current.duration||0);const xt=(T==null?void 0:T.startOffset)??0,pe=Math.max(0,be-xt);U(pe),te(Fe),o==null||o(pe),Q&&pe>=Q.b&&ge(Q.a)},250);return()=>window.clearInterval(fe)},[E==null?void 0:E.kind,o,Q]),u.useEffect(()=>()=>{k.current&&(window.clearInterval(k.current),k.current=null)},[]),u.useEffect(()=>{if(me.current){try{me.current.destroy()}catch{}me.current=null}if(ue.current&&(ue.current.volume=Z,ue.current.crossOrigin=E!=null&&E.withCredentials?"use-credentials":"anonymous"),(E==null?void 0:E.kind)==="hls"&&Po(E.url)){const fe=ue.current;if(!fe)return;const be=()=>{fe.src=E.url,fe.load();const Fe=(T==null?void 0:T.startOffset)??0;try{Fe&&!isNaN(Fe)&&(fe.currentTime=Fe)}catch{}n&&fe.play().catch(()=>{})};fe.canPlayType("application/vnd.apple.mpegurl")?be():(async()=>{var Fe;try{const pe=(await import("hls.js")).default;if((Fe=pe==null?void 0:pe.isSupported)!=null&&Fe.call(pe)){const ke=new pe({xhrSetup:Ve=>{if(E!=null&&E.withCredentials&&(Ve.withCredentials=!0),E!=null&&E.headers)for(const[Ie,Re]of Object.entries(E.headers))try{Ve.setRequestHeader(Ie,Re)}catch{}}});me.current=ke,ke.loadSource(E.url),ke.attachMedia(fe),ke.on(pe.Events.MANIFEST_PARSED,()=>{n&&fe.play().catch(()=>{})})}else be()}catch(xt){ph.debug("HLS.js setup failed, falling back to native playback",xt),be()}})()}else if((E==null?void 0:E.kind)==="audio"&&E.url&&ue.current){const fe=ue.current;fe.src=E.url,fe.load();const be=(T==null?void 0:T.startOffset)??0;try{be&&!isNaN(be)&&(fe.currentTime=be)}catch{}n&&fe.play().catch(()=>{})}k.current&&(window.clearInterval(k.current),k.current=null),$(null),U(0),te(0),n&&(E==null?void 0:E.kind)==="youtube"&&a>0?($(a),k.current=window.setInterval(()=>{$(fe=>{var be;if(!fe)return null;if(fe<=1){k.current&&(window.clearInterval(k.current),k.current=null);try{(be=J.current)==null||be.playVideo()}catch{}return D(!0),l==null||l(!0),null}return fe-1})},1e3)):D(!!n)},[E==null?void 0:E.url,E==null?void 0:E.kind,E==null?void 0:E.withCredentials,JSON.stringify(E==null?void 0:E.headers),n,Z]);const pt=u.useCallback(()=>{if(L==="one"){ge(0),je();return}const fe=xe();fe>=0?de(fe):(D(!1),l==null||l(!1),ge(0),y==null||y())},[L,xe,de,l,ge,y,je]);u.useEffect(()=>{if(!g)return;const fe=be=>{const Fe=be.target;if(!(Fe.tagName==="INPUT"||Fe.tagName==="TEXTAREA"||Fe.isContentEditable))switch(be.key){case" ":be.preventDefault(),ce();break;case"ArrowRight":be.preventDefault(),ge(Math.min(z+5,q));break;case"ArrowLeft":be.preventDefault(),ge(Math.max(0,z-5));break;case"ArrowUp":be.preventDefault(),Ce(Math.min(1,Z+.05));break;case"ArrowDown":be.preventDefault(),Ce(Math.max(0,Z-.05));break;case"m":case"M":De();break;case"n":case"N":$e();break;case"p":case"P":ze();break;case"r":case"R":Ye();break;case"s":case"S":He();break}};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[g,ce,ge,z,q,Ce,Z,De,$e,ze,Ye,He]);const zt=(E==null?void 0:E.kind)==="youtube"||d==="full"||d==="nobuttons",dt=h>0?e.slice(M+1,M+1+h):[];return r.jsxs("div",{ref:Se,className:"gp-player",style:{display:"grid",gap:12},tabIndex:-1,children:[n&&!re&&r.jsx("div",{className:"gp-audio-activation",onClick:()=>{he(!0),je()},style:{position:"fixed",inset:0,zIndex:200,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",cursor:"pointer"},children:r.jsx("span",{style:{color:"#fff",fontSize:24},children:"Click to activate audio"})}),zt&&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??kh(E.url),onReady:fe=>{J.current=fe.target,Ce(Z);const be=(T==null?void 0:T.startOffset)??0;try{be&&fe.target.seekTo(be,!0)}catch{}if(d==="nobuttons"){try{fe.target.playVideo()}catch{}D(!0)}},onEnd:pt,opts:{width:"100%",height:"100%",playerVars:{autoplay:n||d==="nobuttons"?1:0,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,loop:p?1:0}},style:{width:"100%",height:"100%"}}),C!==null&&r.jsx("div",{style:{position:"absolute",inset:0,zIndex:120,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-70, rgba(0, 0, 0, 0.7))"},children:r.jsx("span",{style:{color:"#fff",fontSize:72,fontWeight:"bold"},children:C})}),d==="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:[d==="full"&&r.jsx("div",{style:{textAlign:"center",color:"var(--nice-overlay-light-90, rgba(255, 255, 255, 0.9))"},children:T!=null&&T.coverUrl?r.jsx("img",{alt:"cover",src:T.coverUrl,style:{height:s-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[T==null?void 0:T.artist," — ",T==null?void 0:T.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:ue,onEnded:pt,onLoadedMetadata:()=>{const fe=ue.current;fe&&te(fe.duration||0)},crossOrigin:E!=null&&E.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]})]}),(d==="minimal"||d==="compact")&&r.jsx("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:r.jsxs("div",{children:[r.jsx("div",{style:{fontWeight:600},children:(T==null?void 0:T.title)??""}),r.jsx("div",{style:{color:"var(--nice-text-secondary, #64748b)",fontSize:13},children:(T==null?void 0:T.artist)??""})]})}),d==="full"&&r.jsxs(r.Fragment,{children:[r.jsx(Eo,{currentTime:z,duration:q}),r.jsx(vh,{isPlaying:_,index:M,count:e.length,currentTime:z,duration:q,volume:Z,onPrev:ze,onNext:$e,onToggle:ce,onSeek:ge,onVolume:Ce}),r.jsx(wh,{shuffleOn:W,repeatMode:L,speed:F,abLoop:Q,currentTime:z,sleepRemaining:K,onToggleShuffle:He,onCycleRepeat:Ye,onSpeedChange:tt,onSetABLoop:Lt,onMuteToggle:De,isMuted:Y!==null})]}),d==="progressOnly"&&r.jsx("div",{style:f==="fixedBottom"?{position:"fixed",left:0,right:0,bottom:0,padding:"8px 12px",background:"var(--nice-overlay-90, rgba(15, 23, 42, 0.9))",backdropFilter:"blur(2px)",zIndex:1e3}:{},children:r.jsx(bh,{currentTime:z,duration:q,onSeek:ge})}),(d==="minimal"||d==="compact")&&r.jsx(xh,{isPlaying:_,canPrev:M>0,canNext:M<e.length-1,onPrev:ze,onNext:$e,onToggle:ce}),d==="compact"&&dt.length>0&&r.jsx(Sh,{items:dt,onSelect:fe=>de(M+1+fe)}),d==="nobuttons"&&r.jsx(r.Fragment,{}),d==="full"&&e.length>0&&r.jsx("div",{className:"gp-list",style:{display:"grid",gap:4},children:e.map((fe,be)=>r.jsxs("button",{onClick:()=>de(be),style:{textAlign:"left",border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"8px 10px",background:be===M?"color-mix(in srgb, var(--nice-color-primary) 14%, transparent)":"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},title:fe.sources.map(Fe=>Fe.kind).join(", "),children:[r.jsx("div",{style:{fontWeight:600},children:fe.title}),r.jsx("div",{style:{color:"var(--nice-text-secondary)",fontSize:12},children:fe.artist})]},fe.id))})]})},vt={border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},Eo=({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:[Er(e)," / ",Er(t)]})]}),vh=({isPlaying:e,index:t,count:n,currentTime:a,duration:s,volume:i,onPrev:l,onNext:o,onToggle:c,onSeek:d,onVolume:h})=>{const{t:f}=Te();return r.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("button",{onClick:l,disabled:t<=0,title:f("player.previousTrack","Previous track"),"aria-label":f("player.previousTrack","Previous track"),style:vt,children:r.jsx(B.NtdSkipBack,{size:16})}),r.jsx("button",{onClick:c,title:e?f("player.pause","Pause"):f("player.play","Play"),"aria-label":e?f("player.pause","Pause"):f("player.play","Play"),style:vt,children:e?r.jsx(B.NtdPause,{size:16}):r.jsx(B.NtdPlay,{size:16})}),r.jsx("button",{onClick:o,disabled:t>=n-1,title:f("player.nextTrack","Next track"),"aria-label":f("player.nextTrack","Next track"),style:vt,children:r.jsx(B.NtdSkipForward,{size:16})})]}),r.jsx("input",{type:"range",min:0,max:Math.max(1,s),step:.1,value:a,onChange:p=>d(parseFloat(p.target.value)),"aria-label":"Seek position"}),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:p=>h(parseFloat(p.target.value)),"aria-label":"Volume"})]})]})},bh=({currentTime:e,duration:t,onSeek:n})=>r.jsxs(r.Fragment,{children:[r.jsx(Eo,{currentTime:e,duration:t}),r.jsx("input",{type:"range",min:0,max:Math.max(1,t),step:.1,value:e,onChange:a=>n(parseFloat(a.target.value)),"aria-label":"Seek position"})]}),xh=({isPlaying:e,canPrev:t,canNext:n,onPrev:a,onNext:s,onToggle:i})=>{const{t:l}=Te();return r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[r.jsx("button",{onClick:a,disabled:!t,title:l("player.previousTrack","Previous track"),"aria-label":l("player.previousTrack","Previous track"),style:vt,children:r.jsx(B.NtdSkipBack,{size:16})}),r.jsx("button",{onClick:i,title:e?l("player.pause","Pause"):l("player.play","Play"),"aria-label":e?l("player.pause","Pause"):l("player.play","Play"),style:vt,children:e?r.jsx(B.NtdPause,{size:16}):r.jsx(B.NtdPlay,{size:16})}),r.jsx("button",{onClick:s,disabled:!n,title:l("player.nextTrack","Next track"),"aria-label":l("player.nextTrack","Next track"),style:vt,children:r.jsx(B.NtdSkipForward,{size:16})})]})},Sh=({items:e,onSelect:t})=>{const{t:n}=Te();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))})]})},wh=({shuffleOn:e,repeatMode:t,speed:n,abLoop:a,currentTime:s,sleepRemaining:i,onToggleShuffle:l,onCycleRepeat:o,onSpeedChange:c,onSetABLoop:d,onMuteToggle:h,isMuted:f})=>{const{t:p}=Te(),y={none:"Off",all:"All",one:"One"},g=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:l,title:p("player.shuffle","Shuffle"),"aria-label":p("player.shuffle","Shuffle"),style:{...vt,opacity:e?1:.4,fontWeight:e?700:400},children:r.jsx(B.NtdShuffle,{size:16})}),r.jsx("button",{onClick:o,title:`${p("player.repeat","Repeat")}: ${y[t]}`,"aria-label":`${p("player.repeat","Repeat")}: ${y[t]}`,style:{...vt,opacity:t==="none"?.4:1},children:g}),r.jsx("select",{value:n,onChange:x=>c(parseFloat(x.target.value)),title:p("player.speed","Speed"),"aria-label":p("player.speed","Speed"),style:{...vt,minWidth:56,fontSize:12},children:yh.map(x=>r.jsxs("option",{value:x,children:[x,"x"]},x))}),r.jsx("button",{onClick:h,title:p("player.mute","Mute"),"aria-label":p("player.mute","Mute"),style:{...vt,opacity:f?1:.6},children:f?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: ",Er(a.a)," — B: ",Er(a.b)]}),r.jsx("button",{onClick:()=>d(null),title:p("player.clearLoop","Clear loop"),style:{...vt,fontSize:11,padding:"2px 6px"},children:r.jsx(B.NtdClose,{size:12})})]}):r.jsx("button",{onClick:()=>d({a:s,b:s+10}),title:p("player.abLoop","A-B Loop"),"aria-label":p("player.abLoop","Set A-B Loop"),style:{...vt,opacity:.4},children:"A-B"}),i!==null&&i>0&&r.jsxs("span",{style:{marginLeft:"auto",fontSize:11,color:"var(--nice-text-secondary, #64748b)",display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.NtdMoon,{size:12})," ",Math.floor(i/60),":",(i%60).toString().padStart(2,"0")]})]})};function kh(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 Io(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 Ch(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 jh(e,t="/backgrounds"){return e.backgroundImage?`${t}/${e.backgroundImage}`:""}function Lo(e,t,n=.01){let a=0;for(let l=0;l<e.length;l++)a+=e[l]*e[l];if(a=Math.sqrt(a/e.length),a<n)return 0;let s=-1,i=0;for(let l=20;l<e.length/2;l++){let o=0;for(let c=0;c<e.length/2;c++)o+=e[c]*e[c+l];o/=e.length/2,o>i&&(i=o,s=l)}return s>0?t/s:0}function Ka(e,t){const n=[];return e.forEach((a,s)=>{a.forEach((i,l)=>{n.push({startTime:i.startTime+t,duration:i.duration,pitch:i.pitch,isGold:i.isGold,line:s,idx:l})})}),n}function zo(e,t,n){const a=[];return e.forEach(s=>{var c;const[i,l]=s.noteKey.split("-").map(Number),o=(c=t[i])==null?void 0:c[l];o&&s.segments.forEach(d=>{a.push({start:d.visualStart-n,end:d.visualEnd-n,pitch:o.pitch,frac:d.frac,isGold:o.isGold,noteStart:o.startTime,noteEnd:o.startTime+o.duration})})}),a}function Do(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 _o(e,t,n){const s=Date.parse(e)-n;return Math.max(0,Math.round(t-s))}const Fo={crepe:"var(--nice-accent, #a78bfa)",librosa:"var(--nice-success-light, #34d399)",pitchy:"var(--nice-primary-light, #60a5fa)",autocorr:"var(--nice-text-secondary, #555555)"};function Mh(e){return e==="autocorr"?"Ultrastar":e.charAt(0).toUpperCase()+e.slice(1)}function Rh(e){return Fo[e]??"var(--nice-text-secondary, #555555)"}function Nh(e){const t=Fo[e]??"var(--nice-text-secondary, #555555)";return`var(--algo-${e}, ${t})`}function Oo(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 l=Io(i);l.youtubeId&&(i=`https://www.youtube.com/watch?v=${l.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 Th(e){const t=e.videoPath??e.video??void 0;return{id:e.id,title:e.title??"",artist:e.artist??"",year:e.year,genre:e.genre,language:e.language,filePath:e.filePath,coverPath:e.coverPath,audioPath:e.audioPath??e.audio??void 0,videoPath:t,format:0,notes:e.notes??[],gap:e.gap,bpm:e.bpm,videoGap:e.videoGap,start:e.start,end:e.end,youtubeId:e.youtubeId,instrumentalPath:e.instrumentalPath,isVerified:e.isVerified,coverImage:e.coverImage,backgroundImage:e.backgroundImage}}var Ya=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(Ya||{});function Bo(e,t="song.txt"){const n=e.split(/\r?\n/),a={},s=[];for(const l of n){const o=l.replace(/\uFEFF/g,"");if(o.trim()){if(o.startsWith("#")){const c=o.indexOf(":");c>0&&(a[o.slice(1,c).trim().toUpperCase()]=o.slice(c+1).trim())}else if(/^[:*\-FG]/.test(o))s.push({noteLine:o});else if(o.trim()==="E")break}}const i=l=>{if(!l)return;const o=parseFloat(l.replace(",","."));return Number.isFinite(o)?o:void 0};return{title:a.TITLE||t.replace(/\.txt$/i,""),artist:a.ARTIST||"",format:Ya.Ultrastar,bpm:i(a.BPM),gap:i(a.GAP),genre:a.GENRE||void 0,language:a.LANGUAGE||void 0,year:a.YEAR||void 0,audioPath:a.MP3||void 0,videoPath:a.VIDEO||a.MP3||void 0,notes:s}}const $h=e=>window.btoa(unescape(encodeURIComponent(e))),Go=({onSongUpload:e,parseSong:t,onError:n,accept:a=".txt",maxFileSize:s=5*1024*1024,t:i})=>{const{t:l}=Te(),o=i??l,c=h=>{const f=new FileReader;f.onload=async p=>{var g;if(!((g=p.target)!=null&&g.result))return;const y=p.target.result;try{const x=t?await t({fileName:h.name,data:$h(y)}):Bo(y,h.name);e(x)}catch(x){n==null||n(x)}},f.readAsText(h,"UTF-8")},d=h=>/\.txt$/i.test(h.name)?h.size===0?o("karaokeUploader.empty","The file is empty."):null:o("karaokeUploader.notTxt","Please choose an UltraStar .txt file.");return r.jsx("div",{className:"nice-karaoke-uploader",children:r.jsx(se.NiceUpload,{accept:a,maxFileSize:s,validateFile:d,multiple:!1,text:o("karaokeUploader.dropPrompt","Click or drag & drop an UltraStar file (.txt)"),onFilesSelected:h=>{const f=h[0];f&&c(f)}})})};function Ph(e,t,n,a,s){const l=a*.45;e.beginPath();for(let o=0;o<10;o++){const c=o%2===0?a:l,d=Math.PI/5*o-Math.PI/2,h=t+Math.cos(d)*c,f=n+Math.sin(d)*c;o===0?e.moveTo(h,f):e.lineTo(h,f)}e.closePath(),e.fillStyle=s,e.fill()}const Vt=60,Ws=4,Qr="#888",Us=["A","B","X","Y","LB","RB","LT","RT"],Wo=({lanes:e,events:t,currentTime:n,activeLanes:a,difficulty:s,feedbackQueue:i,isPlaying:l,height:o=300})=>{const c=e.length,d=u.useRef(null),h=u.useRef([]);return u.useEffect(()=>{h.current=i},[i]),u.useEffect(()=>{var w,N;const f=d.current;if(!f)return;const p=f.getContext("2d");if(!p)return;const y=window.devicePixelRatio||1,g=f.clientWidth,x=f.clientHeight;if(f.width=g*y,f.height=x*y,p.scale(y,y),p.clearRect(0,0,g,x),c===0)return;const v=g/c;for(let R=0;R<c;R++){const P=R*v;p.fillStyle=R%2===0?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",p.fillRect(P,0,v,x),R>0&&(p.strokeStyle="rgba(255,255,255,0.1)",p.lineWidth=1,p.beginPath(),p.moveTo(P,0),p.lineTo(P,x),p.stroke())}const m=x-Vt-10;p.strokeStyle="rgba(255,255,255,0.4)",p.lineWidth=2,p.setLineDash([8,4]),p.beginPath(),p.moveTo(0,m),p.lineTo(g,m),p.stroke(),p.setLineDash([]);const S=e.map(R=>we.resolveCssColor((R==null?void 0:R.color)??Qr,f)),b=(x-Vt-20)/Ws;for(const R of t){const P=R.note.startTime,j=P+R.note.duration,M=P-n;if(M>Ws||j<n-.5)continue;const I=R.lane,T=I*v+4,E=v-8,_=m-M*b,D=R.note.duration*b,q=n>=P-.15&&n<=j+.15,te=n>j+.15,z=S[I]??Qr;te?p.fillStyle="rgba(100,100,100,0.3)":q?(p.fillStyle=z,p.shadowColor=z,p.shadowBlur=12):(p.fillStyle=z,p.globalAlpha=.6);const U=Math.max(D,8),Z=6;p.beginPath(),p.moveTo(T+Z,_),p.lineTo(T+E-Z,_),p.quadraticCurveTo(T+E,_,T+E,_+Z),p.lineTo(T+E,_+U-Z),p.quadraticCurveTo(T+E,_+U,T+E-Z,_+U),p.lineTo(T+Z,_+U),p.quadraticCurveTo(T,_+U,T,_+U-Z),p.lineTo(T,_+Z),p.quadraticCurveTo(T,_,T+Z,_),p.fill(),p.globalAlpha=1,p.shadowBlur=0,R.note.isGold&&Ph(p,T+E/2,_+U/2,Math.min(7,E/4),"#fbbf24")}for(let R=0;R<c;R++){const P=R*v,j=x-Vt,M=a[R],I=S[R]??Qr;p.fillStyle=M?I:"rgba(30,30,30,0.9)",p.fillRect(P+2,j+2,v-4,Vt-4),p.strokeStyle=M?"#fff":I,p.lineWidth=M?3:1,p.strokeRect(P+2,j+2,v-4,Vt-4),p.fillStyle=M?"#000":"#fff",p.font=`bold ${Math.min(24,v*.3)}px monospace`,p.textAlign="center",p.textBaseline="middle",p.fillText(((w=e[R])==null?void 0:w.label)??"",P+v/2,j+Vt/2);const T=((N=e[R])==null?void 0:N.gamepadButton)??-1;T>=0&&T<Us.length&&(p.fillStyle=M?"rgba(0,0,0,0.6)":"rgba(255,255,255,0.4)",p.font="10px sans-serif",p.fillText(Us[T],P+v/2,j+Vt-8))}for(const R of h.current){const P=n-R.time;if(P<0||P>.8)continue;const j=Math.max(0,1-P/.8),M=R.lane*v;p.save(),p.globalAlpha=j,p.font="bold 20px sans-serif",p.textAlign="center",p.textBaseline="bottom",p.fillStyle=R.type==="perfect"?"#10b981":R.type==="good"?"#f59e0b":"#ef4444";const I=R.type==="perfect"?"PERFECT":R.type==="good"?"GOOD":"MISS";p.fillText(I,M+v/2,m-10-P*40),p.restore()}},[n,e,t,a,c,l]),!l||c===0?null:r.jsxs("div",{className:"nice-pad-karaoke-overlay",style:{position:"absolute",top:0,left:0,right:0,height:o,zIndex:35,pointerEvents:"none"},children:[r.jsx("canvas",{ref:d,role:"img","aria-label":"Pad karaoke note highway — hit notes in time with the music",style:{width:"100%",height:"100%",display:"block"}}),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})," PAD — ",s]})]})},In=["var(--player-color-1, #ef4444)","var(--player-color-2, #f59e0b)","var(--player-color-3, #10b981)","var(--player-color-4, #3b82f6)","var(--player-color-5, #8b5cf6)","var(--player-color-6, #ec4899)"],Uo={easy:{keys:["f","j"],buttons:[0,1],labels:["F","J"]},normal:{keys:["d","f","j","k"],buttons:[3,2,0,1],labels:["D","F","J","K"]},hard:{keys:["s","d","f","j","k","l"],buttons:[4,3,2,0,1,5],labels:["S","D","F","J","K","L"]}};function ga(e){return 440*Math.pow(2,(e-69)/12)}function Vo(e,t){const n=Uo[t],a=n.keys.length,s=[];for(const d of e)for(const h of d)s.includes(h.pitch)||s.push(h.pitch);if(s.sort((d,h)=>d-h),s.length===0)return n.keys.map((d,h)=>({index:h,key:d,gamepadButton:n.buttons[h],label:n.labels[h],minPitch:-999,maxPitch:999,color:In[h%In.length]}));const i=s[0],o=s[s.length-1]-i+1,c=[];for(let d=0;d<a;d++){const h=i+Math.floor(o*d/a),f=i+Math.floor(o*(d+1)/a)-1;c.push({index:d,key:n.keys[d],gamepadButton:n.buttons[d],label:n.labels[d],minPitch:d===0?-999:h,maxPitch:d===a-1?999:f,color:In[d%In.length]})}return c}function qo(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,l=Math.abs(e-i);l<a&&(a=l,n=s.index)}return n}function Ho(e,t,n){const a=[];for(let s=0;s<e.length;s++)for(let i=0;i<e[s].length;i++){const l={...e[s][i]};l.startTime+=n,a.push({note:l,lane:qo(l.pitch,t),lineIndex:s,noteIndex:i})}return a.sort((s,i)=>s.note.startTime-i.note.startTime),a}class Ko{constructor(t){this.lanes=[],this.events=[],this.raf=null,this.keysDown=new Set,this.gamepadButtonsDown=new Set,this.running=!1,this.getCurrentTime=()=>0,this.lastFeedbackTime=0,this.lastActiveNote=null,this.preWindow=.15,this.postWindow=.15,this.loop=()=>{var c,d,h,f,p,y,g,x;if(!this.running)return;const s=this.getCurrentTime();this.pollGamepad();const i=this.getActiveLanes();(d=(c=this.config).onLaneActive)==null||d.call(c,i);const l=this.findActiveNote(s);if(l!==this.lastActiveNote&&(this.lastActiveNote=l,(f=(h=this.config).onCurrentNote)==null||f.call(h,l)),i.some(Boolean)&&l){const v=l.lane,m=i.indexOf(!0);if(i[v]){const S=ga(l.note.pitch);this.config.onPitch(S),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(y=(p=this.config).onHitFeedback)==null||y.call(p,{type:"perfect",lane:v,time:s}))}else if(m>=0){const b=Math.abs(m-v)*3,w=ga(l.note.pitch+b);this.config.onPitch(w),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(x=(g=this.config).onHitFeedback)==null||x.call(g,{type:"miss",lane:m,time:s}))}}this.raf=requestAnimationFrame(this.loop)},this.config=t;const n=Hn(t.noteLines,t.bpm),a=(t.gap??0)/1e3;switch(this.lanes=Vo(n,t.difficulty),this.events=Ho(n,this.lanes,a),t.difficulty){case"easy":this.preWindow=.25,this.postWindow=.25;break;case"normal":this.preWindow=.15,this.postWindow=.15;break;case"hard":this.preWindow=.08,this.postWindow=.08;break}}getLanes(){return this.lanes}getEvents(){return this.events}start(t){this.running||(this.running=!0,this.getCurrentTime=t,this.handleKeyDown=this.handleKeyDown.bind(this),this.handleKeyUp=this.handleKeyUp.bind(this),window.addEventListener("keydown",this.handleKeyDown),window.addEventListener("keyup",this.handleKeyUp),this.loop())}stop(){this.running=!1,this.raf&&(cancelAnimationFrame(this.raf),this.raf=null),window.removeEventListener("keydown",this.handleKeyDown),window.removeEventListener("keyup",this.handleKeyUp),this.keysDown.clear(),this.gamepadButtonsDown.clear()}handleKeyDown(t){var a;const n=(a=t.target)==null?void 0:a.tagName;n&&["INPUT","TEXTAREA","SELECT"].includes(n)||this.keysDown.add(t.key.toLowerCase())}handleKeyUp(t){this.keysDown.delete(t.key.toLowerCase())}pollGamepad(){var a;const t=navigator.getGamepads?Array.from(navigator.getGamepads()).filter(Boolean):[];if(!t.length)return;const n=t[0];if(n){this.gamepadButtonsDown.clear();for(let s=0;s<n.buttons.length;s++)(a=n.buttons[s])!=null&&a.pressed&&this.gamepadButtonsDown.add(s)}}getActiveLanes(){const t=new Array(this.lanes.length).fill(!1);for(const n of this.lanes)(this.keysDown.has(n.key)||this.gamepadButtonsDown.has(n.gamepadButton))&&(t[n.index]=!0);return t}findActiveNote(t){for(const n of this.events){const a=n.note.startTime-this.preWindow,s=n.note.startTime+n.note.duration+this.postWindow;if(t>=a&&t<=s)return n}return null}}const mt=ot.scoped("BaseStreamClient");function Vs(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 l=0;l<a;l++){const o=l*i,c=Math.floor(o),d=Math.min(e.length-1,c+1),h=o-c;s[l]=e[c]*(1-h)+e[d]*h}return s}function Ah(e){const t=new Int16Array(e.length);for(let n=0;n<e.length;n++){const a=Math.max(-1,Math.min(1,e[n]));t[n]=a<0?Math.round(a*32768):Math.round(a*32767)}return t}const Sn=16e3,Eh="/scripts/pitch-worklet.js";class Yo{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 Eh}ts(){return new Date().toISOString().slice(11,23)}connectWs(){this.ws&&this.ws.readyState!==WebSocket.CLOSING&&this.ws.readyState!==WebSocket.CLOSED||(mt.info(`[${this.ts()}] connecting to ${this.opts.wsUrl}`),this.ws=new WebSocket(this.opts.wsUrl),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{var t,n,a,s,i,l;try{(n=(t=this.opts).onOpen)==null||n.call(t)}catch{}if(this.reconnectAttempts=0,this.chunksSent=0,this.chunksDropped=0,this.responsesReceived=0,mt.info(`[${this.ts()}] ws OPEN | worklet=${this.usingWorklet}`),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.sendQueue.length){const o=this.sendQueue.length;try{for(const c of this.sendQueue)try{this.ws.send(c),this.chunksSent++,(s=(a=this.opts).onSend)==null||s.call(a,c.byteLength)}catch(d){(l=(i=this.opts).onError)==null||l.call(i,d);break}}finally{this.sendQueue=[]}mt.info(`[${this.ts()}] flushed ${o} queued chunks`)}},this.ws.onclose=t=>{var n,a;try{(a=(n=this.opts).onClose)==null||a.call(n,t)}catch{}if(mt.info(`[${this.ts()}] ws CLOSE code=${t.code} clean=${t.wasClean} | sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived}`),this.sendQueue=[],this.ws=void 0,!this.closed&&this.started)if(this.reconnectAttempts++,this.reconnectAttempts<=this.maxReconnectAttempts){const s=Math.min(300*Math.pow(1.5,this.reconnectAttempts-1),5e3);mt.info(`[${this.ts()}] auto-reconnect #${this.reconnectAttempts} in ${s.toFixed(0)}ms`),this.reconnectTimer=setTimeout(()=>{this.closed||this.connectWs()},s)}else mt.warn(`[${this.ts()}] max reconnect attempts reached`),this.onMaxReconnect();else this.stopAudioNodes()},this.ws.onerror=t=>{var n,a;mt.warn(`[${this.ts()}] ws ERROR`,t);try{(a=(n=this.opts).onError)==null||a.call(n,t)}catch{}},this.ws.onmessage=t=>{var n,a;this.responsesReceived++;try{const s=typeof t.data=="string"?t.data:new TextDecoder().decode(t.data);this.handleWsMessage(s)}catch(s){(a=(n=this.opts).onError)==null||a.call(n,s)}})}handleAudioFrame(t){var p,y,g,x,v,m,S,b;const n=new Float32Array(this.buffer.length+t.length);n.set(this.buffer,0),n.set(t,this.buffer.length),this.buffer=n;const a=this.audioCtx.sampleRate,s=Math.round((this.opts.chunkMs??200)*Sn/1e3),i=Math.floor(this.buffer.length*Sn/a),l=Math.floor(i/s);if(l<=0)return;const o=l*s,c=Math.floor(o*a/Sn),d=this.buffer.slice(0,c);this.buffer=this.buffer.slice(c);const h=Vs(d,a,Sn);let f=0;for(;f+s<=h.length;){const w=h.subarray(f,f+s),R=Ah(w).buffer,P=this.ws;if(P&&P.readyState===WebSocket.OPEN)try{P.send(R),this.chunksSent++,(y=(p=this.opts).onSend)==null||y.call(p,R.byteLength)}catch(M){(x=(g=this.opts).onError)==null||x.call(g,M)}else P&&P.readyState===WebSocket.CONNECTING?this.sendQueue.length<this.maxQueue&&(this.sendQueue.push(R),(m=(v=this.opts).onSend)==null||m.call(v,0)):(this.chunksDropped++,(b=(S=this.opts).onSend)==null||b.call(S,0));const j=Date.now();j-this.lastStatusLog>5e3&&(this.lastStatusLog=j,mt.info(`[${this.ts()}] STATUS: sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived} ws=${(P==null?void 0:P.readyState)??"none"} worklet=${this.usingWorklet}`)),f+=s}if(f<h.length){const w=h.subarray(f),N=Vs(w,Sn,a),R=new Float32Array(N.length+this.buffer.length);R.set(N,0),R.set(this.buffer,N.length),this.buffer=R}}async setupAudioNodes(t){if(this.useWorklet)try{await this.audioCtx.audioWorklet.addModule(this.workletPath);const a=new AudioWorkletNode(this.audioCtx,"pitch-processor");a.port.onmessage=s=>{this.handleAudioFrame(s.data)},t.connect(a),a.connect(this.audioCtx.destination),this.workletNode=a,this.usingWorklet=!0,mt.info(`[${this.ts()}] using AudioWorklet (pitch-processor)`);return}catch(a){mt.warn(`[${this.ts()}] AudioWorklet unavailable, falling back to ScriptProcessorNode`,a)}const n=4096;this.proc=this.audioCtx.createScriptProcessor(n,1,1),t.connect(this.proc),this.proc.connect(this.audioCtx.destination),this.proc.onaudioprocess=a=>{this.handleAudioFrame(a.inputBuffer.getChannelData(0))},this.usingWorklet=!1,mt.info(`[${this.ts()}] using ScriptProcessorNode fallback`)}stopAudioNodes(){try{this.workletNode&&(this.workletNode.port.close(),this.workletNode.disconnect(),this.workletNode=void 0)}catch{}try{this.proc&&(this.proc.onaudioprocess=null,this.proc.disconnect(),this.proc=void 0)}catch{}}async start(){if(this.closed)throw new Error("client closed");if(this.started)return;this.started=!0,(!this.ws||this.ws.readyState===WebSocket.CLOSED)&&this.connectWs(),this.mediaStream||(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:!0})),this.audioCtx=new AudioContext;const t=this.audioCtx.createMediaStreamSource(this.mediaStream);await this.setupAudioNodes(t)}async startWithMediaStream(t){if(this.closed)throw new Error("client closed");if(this.started)return;this.started=!0,this.externalStream=!0,(!this.ws||this.ws.readyState===WebSocket.CLOSED)&&this.connectWs(),this.mediaStream=t,this.audioCtx=new AudioContext;const n=this.audioCtx.createMediaStreamSource(this.mediaStream);await this.setupAudioNodes(n)}stop(){var t,n;if(mt.info(`[${this.ts()}] stop() called | closed=${this.closed} started=${this.started} sent=${this.chunksSent} responses=${this.responsesReceived}`),this.closed=!0,this.started=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.stopAudioNodes(),this.audioCtx&&this.audioCtx.state!=="closed"&&this.audioCtx.close().catch(()=>{}),!this.externalStream)try{(t=this.mediaStream)==null||t.getTracks().forEach(a=>a.stop())}catch{}try{(n=this.ws)==null||n.close()}catch{}this.ws=void 0,this.sendQueue=[]}}const Ih=ot.scoped("CrepeStreaming");class Lh extends Yo{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;Ih.warn(`[${this.tag}] [${this.ts()}] triggering fallback`),this.stopAudioNodes();try{(n=(t=this.crepeOpts).onFallback)==null||n.call(t)}catch{}}}class zh extends Yo{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 Dh(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 _h(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 Zo({isPlaying:e,gameMode:t,players:n,playersMicKey:a,micAlgorithms:s={},defaultPitchAlgorithm:i="pitchy",micRmsThresholds:l={},micOffsets:o={},micGains:c={},micPitchThresholds:d={},micSmoothingWindows:h={},micHysteresisFrames:f={},micUseHanning:p={},micMonitorEnabled:y={},micMonitorVolumes:g={},currentTimeRef:x,isPadMode:v,clockOffsetMsRef:m,currentPartyIdRef:S,rtc:b}){const[w,N]=u.useState({}),R=u.useRef({}),P=u.useRef({}),[j,M]=u.useState({}),I=u.useRef({}),T=u.useRef([]),E=u.useRef(null),_=u.useRef(null),[,D]=u.useState({}),[,q]=u.useState({}),[,te]=u.useState({}),[z,U]=u.useState({}),[Z,ae]=u.useState(!0),[Y,O]=u.useState(!1),C=u.useRef(n);C.current=n;const $=u.useRef(0),k=u.useRef(performance.now());return u.useEffect(()=>{T.current.forEach(F=>F()),T.current=[];const W={current:!1};function A(F,V,Q=0){x.current!==$.current&&($.current=x.current,k.current=performance.now());const le=Math.min(.25,(performance.now()-k.current)/1e3),oe=x.current+le-Q/1e3;N(K=>{const H=K[F]||[];return{...K,[F]:[...H,{t:oe,hz:V}]}}),R.current[F]=(R.current[F]||[]).concat({t:oe,hz:V});const ne=R.current[F];ne.length>500&&(R.current[F]=ne.slice(-500))}function L(F,V,Q,le=.02,oe=0,ne=.6,K=0,H=0,ie=0,re=!1){let he=null,J=null,ue=null;return(async()=>{try{he=new AudioContext;let de=he.createMediaStreamSource(V);if(K>0){const ge=he.createGain();ge.gain.value=K,de.connect(ge),de=ge}const xe=he.createAnalyser();xe.fftSize=2048,de.connect(xe);const Me=new Float32Array(xe.fftSize),$e=re?Dh(xe.fftSize):null,je=[];let Xe=0;if(Q==="pitchy")try{const{PitchDetector:ge}=await import("pitchy");ue=ge.forFloat32Array(xe.fftSize)}catch(ge){It.warn("pitchy import failed, falling back to autocorrelation",ge)}const ce=()=>{try{xe.getFloatTimeDomainData(Me)}catch{}const ge=$e?_h(Me,$e):Me;let ze=0;for(let De=0;De<ge.length;De++)ze+=ge[De]*ge[De];ze=Math.sqrt(ze/ge.length);let Ce=0;if(ze>=le)if(ue)try{const[De,tt]=ue.findPitch(ge,he.sampleRate);De>50&&De<3e3&&tt>ne&&(Ce=De)}catch{}else Ce=Lo(ge,he.sampleRate,le),(Ce<50||Ce>3e3)&&(Ce=0);if(Ce>0&&H>1&&(je.push(Ce),je.length>H&&je.shift(),Ce=je.reduce((De,tt)=>De+tt,0)/je.length),Ce>0)Xe=0,A(F,Ce,oe);else if(Xe++,ie>0&&Xe<=ie&&je.length>0){const De=je[je.length-1];De>0&&A(F,De,oe)}J=requestAnimationFrame(ce),I.current[F]=J};ce()}catch(Se){It.warn("startLocalPitch error",Se)}})(),()=>{J&&cancelAnimationFrame(J),he&&he.close().catch(()=>{})}}function G(F,V,Q,le=0){Q==="crepe"&&_.current?(_.current.stop(),_.current=null):Q==="librosa"&&E.current&&(E.current.stop(),E.current=null);const oe=window.location,ne=oe.protocol==="https:"?"wss:":"ws:",K=Q==="librosa"?`${ne}//${oe.host}/api/librosa/ws/pyin`:`${ne}//${oe.host}/api/ai/audio/pitch/ws/pitch_server`,H=Q==="librosa"?D:q;H(ue=>({...ue,[F]:"connecting"}));const ie=[],re=ue=>{if(ue>0){for(ie.push(x.current);ie.length>200;)ie.shift();Q==="crepe"&&te(me=>({...me,[F]:(me[F]||0)+1}))}},he=()=>{H(ue=>({...ue,[F]:"closed"})),ie.length=0},J=ue=>{if(typeof ue.hz=="number"&&ue.hz>0){const me=ue.hz,de=(ie.length>0?ie.shift():x.current)-le/1e3;N(xe=>{const Me=xe[F]||[];return{...xe,[F]:[...Me,{t:de,hz:me}]}})}else ie.length>0&&ie.shift()};if(Q==="librosa"){const ue=new zh({wsUrl:K,onOpen:()=>H(me=>({...me,[F]:"connected"})),onClose:he,onError:me=>{H(Se=>({...Se,[F]:"error"})),It.warn("Librosa WS error",me)},onMessage:J,onSend:re});return E.current=ue,ue.startWithMediaStream(V).catch(me=>{It.warn("Librosa client start failed",me),H(Se=>({...Se,[F]:"failed"}))}),()=>{ue.stop(),E.current=null,H(me=>({...me,[F]:""}))}}else{const ue=new Lh({wsUrl:K,onOpen:()=>H(me=>({...me,[F]:"connected"})),onClose:he,onError:me=>{H(Se=>({...Se,[F]:"error"})),It.warn("Crepe WS error",me)},onMessage:J,onSend:re,onFallback:()=>{H(Se=>({...Se,[F]:"fallback-pitchy"})),_.current=null;const me=L(F,V,"pitchy",.02,le);T.current.push(me)}});return _.current=ue,ue.startWithMediaStream(V).catch(me=>{It.warn("Crepe client start failed",me),H(Se=>({...Se,[F]:"failed"}))}),()=>{ue.stop(),_.current=null,H(me=>({...me,[F]:""}))}}}if(e){if(N({}),t!=="pad"){const F={};C.current.forEach(V=>{if(!V.micId)return;const Q=s[V.id]||i,le=V.micId&&l[V.micId]||.02,oe=V.micId&&o[V.micId]||0,ne=V.micId&&c[V.micId]||0,K=V.micId&&d[V.micId]||.6,H=V.micId&&h[V.micId]||0,ie=V.micId&&f[V.micId]||0,re=V.micId&&p[V.micId]||!1,he=V.micId&&y[V.micId]||!1,J=(V.micId?g[V.micId]:void 0)??100,ue=new La;ue.startRecording({deviceId:V.micId,onLevel:()=>{},gain:ne,monitorEnabled:he,monitorVolume:J}).then(()=>{if(W.current){ue.stopRecording().catch(()=>{});return}F[V.id]=ue;const me=ue.getStream();if(!me){It.warn(`No stream from recorder for player ${V.id}`);return}if(Q==="librosa"||Q==="crepe"){const Se=G(V.id,me,Q,oe);T.current.push(Se)}else{const Se=L(V.id,me,Q,le,oe,K,ne,H,ie,re);T.current.push(Se)}}).catch(me=>It.warn(`recorder start failed for player ${V.id}`,me))}),P.current=F}}else{const F=P.current,V=Object.keys(F).map(Number);Promise.allSettled(V.map(async Q=>{const le=await F[Q].stopRecording();return{pid:Q,blob:le}})).then(Q=>{const le={};for(const oe of Q)oe.status==="fulfilled"&&oe.value.blob&&(le[oe.value.pid]=oe.value.blob);Object.keys(le).length>0&&M(oe=>({...oe,...le}))}),P.current={},Object.values(I.current).forEach(Q=>Q&&cancelAnimationFrame(Q)),I.current={}}return()=>{W.current=!0,T.current.forEach(F=>F()),T.current=[],Object.values(P.current).forEach(F=>F.stopRecording().catch(()=>{})),P.current={},Object.values(I.current).forEach(F=>F&&cancelAnimationFrame(F)),I.current={}}},[e,t,a,s,i,l,o,c,d,h,f,p,y,g]),u.useEffect(()=>{if(!b)return;const W=300,A=async()=>{try{const G={...R.current};for(const F of Object.keys(G)){const V=Number(F),Q=G[V]||[];if(!Q||Q.length===0)continue;R.current[V]=[];const le=Do(Q,120),oe={playerId:V,points:le,clientNowUtc:new Date().toISOString(),quantized:!0};S!=null&&S.current&&(oe.EventId=S.current);try{b.isConnected()&&await b.publishTimelineUpdate(oe)}catch(ne){It.warn("failed to publish timeline update, will retry",ne),R.current[V]=(R.current[V]||[]).concat(Q).slice(-1e3)}}}catch{}},L=window.setInterval(A,W);return()=>{L&&window.clearInterval(L)}},[b,S]),u.useEffect(()=>{if(!b)return;const W=A=>{try{const L=A;if(!L||typeof L.playerId>"u"||!Array.isArray(L.points))return;const G=Number(L.playerId),F=L.points.map(V=>({t:V.t,hz:V.hz}));if(!F.length)return;if(L.serverTimeUtc){const V=_o(L.serverTimeUtc,Date.now(),(m==null?void 0:m.current)||0);U(Q=>({...Q,[G]:V}))}N(V=>{const Q=V[G]||[];return{...V,[G]:[...Q,...F]}})}catch{}};return b.onTimelineUpdate(W),()=>b.offTimelineUpdate(W)},[b,m]),{livePitch:w,setLivePitch:N,recordings:j,recordersRef:P,unsentPitchRef:R,pitchCleanupsRef:T,remoteLatencyMs:z,showRemoteTimelines:Z,setShowRemoteTimelines:ae,compactTimelines:Y,setCompactTimelines:O}}function Xo(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function Qo(e){return e>=50?3:e>=30?2.5:e>=20?2:e>=10?1.5:1}function Jo(e,t,n){const{semitoneTolerance:a,preWindow:s,postExtra:i}=n,l=n.segMs??.25,o=typeof n.completionBonusFactor=="number"?n.completionBonusFactor:.15,c=typeof n.goldFullBonusFactor=="number"?n.goldFullBonusFactor:.3,d=typeof n.difficultyMult=="number"?n.difficultyMult:1,h=!!n.disableGoldNotes;let f=0,p=0,y=0;const g=[];let x=0,v=0,m=0;const S=new Map;e.forEach((M,I)=>{const T=M.startTime,E=M.startTime+M.duration,_=T-s,D=E+i,q=t.filter(C=>C.t>=_&&C.t<=D&&C.hz>0);if(!q||q.length===0)return;const te=Math.max(1,Math.ceil((M.duration||.25)/l)),z=Math.max(10,Math.round(100*(M.duration||1))),U=Math.max(1,Math.round(z/te));let Z=0;const ae=[];for(let C=0;C<te;C++){const $=T+C*(M.duration/te),k=T+(C+1)*(M.duration/te),W=Math.min(.06,M.duration/te*.2),A=$-W,L=k+W,G=t.filter(ne=>ne.t>=A&&ne.t<=L&&ne.hz>0);if(!G||G.length===0)continue;let F=0;G.forEach(ne=>{let H=((12*Math.log2(ne.hz/440)+69)%12+12)%12;for(;H-M.pitch>6;)H-=12;for(;H-M.pitch<-6;)H+=12;const ie=Math.abs(H-M.pitch);F+=ie});const V=F/G.length;let Q=0;if(a<=0)Q=V===0?1:0;else{const ne=a*2;Q=Math.max(0,1-Math.min(V/ne,1))}if(Q<=0)continue;const le=!h&&M.isGold?2:1,oe=Math.round(U*le*Q);oe>0&&(f+=oe,Z+=oe,ae.push({segIndex:C,frac:Q,add:oe,segStart:A,segEnd:L,visualStart:$,visualEnd:k}))}const Y=M.line??0;S.has(Y)||S.set(Y,{total:0,hit:0,comboBonus:0});const O=S.get(Y);if(O.total++,Z>0){x++,x>v&&(v=x),O.hit++;const C=Qo(x),$=C>1?Math.round(Z*(C-1)):0;m+=$,O.comboBonus+=$;const k=Math.max(1,Math.ceil((M.duration||.25)/l)),A=ae.length>=k,L=A?Math.round(Math.max(10,Math.round(100*(M.duration||1)))*o*(!h&&M.isGold?1.5:1)*d):0,G=A&&!h&&M.isGold?Math.round(Math.max(10,Math.round(100*(M.duration||1)))*c*d):0;p+=L,y+=G,g.push({noteKey:`${M.line??0}-${M.idx??0}`,segments:ae,totalAdded:Z,completed:A,completionBonus:L,goldFullBonus:G})}else x=0});const b=[];for(const[M,I]of S.entries()){const T=I.total>0?I.hit/I.total:0;b.push({verseIndex:M,hitFraction:T,label:Xo(T),comboBonus:I.comboBonus})}const w={maxCombo:v,currentCombo:0,totalComboBonus:m},N=m+p+y,R=g.length,P=g.filter(M=>M.completed).length,j={hits:R,misses:e.length-R,good:R-P,perfect:P,maxCombo:v};return{classicScore:f,bonusScore:N,totalScore:f+N,perNote:g,combo:w,verseRatings:b,noteStats:j}}function el(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 tl(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function nl(e,t,n){const a=el(t,n);if(a<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0};const s=tl(e.classicScore,a),i=Math.round(e.bonusScore/a*1e4);return{...e,classicScore:s,bonusScore:i,totalScore:s+i}}const wn={maxCombo:0,currentCombo:0,totalComboBonus:0},qs={hits:0,misses:0,good:0,perfect:0,maxCombo:0};function rl({livePitch:e,uploadedSong:t,isPlaying:n,difficulty:a,players:s,isPadMode:i}){const[l,o]=u.useState(0),[c,d]=u.useState(0),[h,f]=u.useState(0),[p,y]=u.useState([]),[g,x]=u.useState(wn),[v,m]=u.useState([]),[S,b]=u.useState([]),[w,N]=u.useState({}),[R,P]=u.useState({}),[j,M]=u.useState({}),[I,T]=u.useState({}),[E,_]=u.useState({});return u.useEffect(()=>{if(!t||!n)return;const D=Hn(t.notes.map(G=>G.noteLine),t.bpm??void 0),q=(t.gap??0)/1e3,te=Ka(D,q),z=Dr(a),U=[];let Z=null,ae=null,Y=null,O=[];const C={},$={},k={},W={},A={},L=i?s[0]:s.find(G=>!!G.micId)||s[0];for(let G=0;G<s.length;G++){const F=s[G],V=(F==null?void 0:F.id)!=null?e[F.id]||[]:[];if(V.length===0){U.push({id:F.id,name:F.name||`Player ${F.id}`,color:F.color||et[G%et.length],classicScore:0,bonusScore:0,totalScore:0}),C[F.id]=[],$[F.id]={...wn},k[F.id]=[],W[F.id]=0,A[F.id]={...qs};continue}const Q=Va(F.id),le=!!(Q!=null&&Q.disableGoldNotes),oe=Jo(te,V,{semitoneTolerance:z.semitoneTolerance,preWindow:z.preWindow,postExtra:z.postExtra,difficultyMult:z.difficultyMult,disableGoldNotes:le}),ne=nl(oe,te,le);U.push({id:F.id,name:F.name||`Player ${F.id}`,color:F.color||et[G%et.length],classicScore:ne.classicScore,bonusScore:ne.bonusScore,totalScore:ne.totalScore}),C[F.id]=zo(oe.perNote,D,q),$[F.id]=oe.combo??{...wn},k[F.id]=oe.verseRatings??[],W[F.id]=ne.totalScore,A[F.id]=oe.noteStats??{...qs},F.id===(L==null?void 0:L.id)&&(Z=ne,ae=oe.combo??null,Y=oe.verseRatings??null,O=C[F.id])}b(U),N(C),P($),M(k),T(W),_(A),Z?(o(Z.classicScore),d(Z.bonusScore),f(Z.totalScore),y(O),x(ae??wn),m(Y??[])):(o(0),d(0),f(0),y([]),x(wn),m([]))},[e,t,n,a,s,i]),{liveScore:l,liveBonusScore:c,liveTotalScore:h,liveSegmentScores:p,liveCombo:g,liveVerseRatings:v,perPlayerScores:S,perPlayerSegmentScores:w,perPlayerCombo:R,perPlayerVerseRatings:j,perPlayerTotalScores:I,perPlayerNoteStats:E}}const Fh=e=>!!e&&/youtu(\.be|be\.com)/i.test(e),Oh=({players:e,song:t,initialSong:n=null,difficulty:a="normal",gameMode:s="normal",height:i=480,showTimelines:l=!0,showLyrics:o=!0,singleTimeline:c=!1,requestMicPermission:d=!0,initiallyActivated:h=!1,showUploader:f=!1,parseSong:p,micAlgorithms:y,defaultPitchAlgorithm:g="pitchy",micRmsThresholds:x,micOffsets:v,micGains:m,micPitchThresholds:S,micSmoothingWindows:b,micHysteresisFrames:w,micUseHanning:N,micMonitorEnabled:R,micMonitorVolumes:P,searchYouTubeByArtistTitle:j,fetchTopSingings:M,onSaveResults:I,rtc:T,onSongChange:E,onPlayingChange:_,onTimeUpdate:D,onEnded:q,onContinue:te,renderReport:z,t:U,className:Z,style:ae,id:Y,accessMode:O,"data-testid":C})=>{var Oe;const{t:$}=Te(),k=U??$,[W,A]=u.useState(t??n??null),[L,G]=u.useState(!1),[F,V]=u.useState(0),[Q,le]=u.useState(h),[oe,ne]=u.useState(!1),[K,H]=u.useState([]),[ie,re]=u.useState(""),[he,J]=u.useState(null),[ue,me]=u.useState(0),Se=s==="pad",[de,xe]=u.useState([]),[Me,$e]=u.useState([]),[je,Xe]=u.useState([]),[ce,ge]=u.useState([]),ze=u.useRef(null),Ce=u.useRef(null),De=u.useRef(null),tt=u.useRef(!1),Ye=u.useRef(0);u.useEffect(()=>{Ye.current=F},[F]);const He=u.useRef(t);u.useEffect(()=>{t!==void 0&&t!==He.current&&(He.current=t,A(t),ne(!1),V(0),me(ve=>ve+1))},[t]);const Lt=u.useMemo(()=>JSON.stringify(e.map(ve=>({id:ve.id,micId:ve.micId}))),[e]),{livePitch:pt,setLivePitch:zt,recordings:dt,remoteLatencyMs:fe}=Zo({isPlaying:L,gameMode:s,players:e,playersMicKey:Lt,micAlgorithms:y,defaultPitchAlgorithm:g,micRmsThresholds:x,micOffsets:v,micGains:m,micPitchThresholds:S,micSmoothingWindows:b,micHysteresisFrames:w,micUseHanning:N,micMonitorEnabled:R,micMonitorVolumes:P,currentTimeRef:Ye,isPadMode:Se,rtc:T}),be=rl({livePitch:pt,uploadedSong:W,isPlaying:L,difficulty:a,players:e,isPadMode:Se}),Fe=u.useRef(be);Fe.current=be;const xt=u.useMemo(()=>W?Oo(W,s):null,[W,s]),pe=((Oe=e[0])==null?void 0:Oe.id)??1;u.useEffect(()=>{var Ne;if(!Se||!L||!W){(Ne=ze.current)==null||Ne.stop(),ze.current=null,xe([]),$e([]),Xe([]),ge([]);return}const ve=new Ko({difficulty:a,noteLines:W.notes.map(Ae=>Ae.noteLine),bpm:W.bpm??void 0,gap:W.gap??0,onPitch:Ae=>{const We=Ye.current;zt(_e=>{const rt=_e[pe]||[];return{..._e,[pe]:[...rt,{t:We,hz:Ae}]}})},onHitFeedback:Ae=>ge(We=>[...We.slice(-20),Ae]),onLaneActive:Ae=>Xe(Ae)});return xe(ve.getLanes()),$e(ve.getEvents()),Xe(new Array(ve.getLanes().length).fill(!1)),ve.start(()=>Ye.current),ze.current=ve,()=>{ve.stop(),ze.current=null}},[Se,L,W,a,pe,zt]);const ke=u.useCallback(ve=>{G(ve),_==null||_(ve)},[_]),Ve=u.useCallback(ve=>{V(ve),D==null||D(ve)},[D]),Ie=u.useCallback(()=>{var Ne;try{Zt()}catch{}const ve=()=>{le(!0),tt.current=!0};!Se&&d&&((Ne=navigator.mediaDevices)!=null&&Ne.getUserMedia)?navigator.mediaDevices.getUserMedia({audio:!0}).then(Ae=>Ae.getTracks().forEach(We=>We.stop())).catch(()=>{}).finally(ve):ve()},[Se,d]);u.useEffect(()=>{if(!Q||!tt.current)return;tt.current=!1;const ve=window.setInterval(()=>{Ce.current&&(window.clearInterval(ve),Ce.current.play())},100),Ne=window.setTimeout(()=>window.clearInterval(ve),3e3);return()=>{window.clearInterval(ve),window.clearTimeout(Ne)}},[Q]);const Re=u.useCallback(()=>{ne(!0),q==null||q();const ve=(W==null?void 0:W.id)??0,Ne=Fe.current,Ae=[];for(const _e of e){const rt=Ne.perPlayerTotalScores[_e.id]??0;if(rt<=0)continue;const Ze=Ne.perPlayerNoteStats[_e.id];Ae.push({playerId:_e.id,songId:ve,score:rt,hits:(Ze==null?void 0:Ze.hits)??0,misses:(Ze==null?void 0:Ze.misses)??0,good:(Ze==null?void 0:Ze.good)??0,perfect:(Ze==null?void 0:Ze.perfect)??0,combo:(Ze==null?void 0:Ze.maxCombo)??0})}const We=()=>{M&&ve>0&&Promise.resolve(M(ve)).then(H).catch(()=>{})};I&&Ae.length>0?Promise.resolve(I(Ae)).then(We).catch(We):We()},[e,W,I,M,q]);u.useEffect(()=>{var ve;s==="demo"&&L&&F>=12&&((ve=Ce.current)==null||ve.pause(),Re())},[s,L,F,Re]),u.useEffect(()=>{if(!W||ue===0||!j||Fh(W.videoPath))return;if(W.youtubeId){const Ne=`https://www.youtube.com/watch?v=${W.youtubeId}`;A(Ae=>Ae&&{...Ae,videoPath:Ne});return}if(!W.artist||!W.title)return;let ve=!1;return re(k("karaokeManager.ytSearching","Searching YouTube…")),J("searching"),Promise.resolve(j(W.artist,W.title)).then(Ne=>{if(!ve)if(Ne){const Ae=`https://www.youtube.com/watch?v=${Ne}`;A(We=>We&&{...We,videoPath:Ae}),re(""),J(null)}else re(k("karaokeManager.ytNotFound","Not found on YouTube")),J("error"),window.setTimeout(()=>{ve||(re(""),J(null))},4e3)}).catch(()=>{ve||(re(k("karaokeManager.ytSearchError","Search error")),J("error"))}),()=>{ve=!0}},[ue,W,j,k]);const Pe=u.useCallback(()=>{var ve,Ne;ne(!1),zt({}),(ve=Ce.current)==null||ve.seekTo(0),(Ne=Ce.current)==null||Ne.play()},[zt]),Be=u.useCallback(()=>{ne(!1),te==null||te()},[te]),Ge=u.useCallback(ve=>{A(ve),ne(!1),V(0),me(Ne=>Ne+1),E==null||E(ve)},[E]),Je=u.useMemo(()=>{if(!c)return e;const ve=e.find(Ne=>!!Ne.micId)||e[0];return ve?[ve]:[]},[e,c]),Ee=((W==null?void 0:W.gap)??0)/1e3;return O==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-manager${Z?` ${Z}`:""}`,style:{position:"relative",textAlign:"center",minHeight:i,...ae},id:Y,"data-testid":C,children:[ie&&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:[he==="error"?r.jsx(B.NtdClose,{size:16}):r.jsx(B.NtdSearch,{size:16}),ie]}),!W&&f&&r.jsx(Go,{onSongUpload:Ge,parseSong:p,t:k}),W&&!Q&&r.jsxs("button",{type:"button",className:"nice-karaoke-manager__activate",onClick:Ie,style:{position:"absolute",inset:0,zIndex:30,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:16,border:"none",cursor:"pointer",background:"var(--nice-overlay-80, rgba(0,0,0,0.82))",color:"#fff"},children:[r.jsx("div",{style:{fontSize:56,lineHeight:0},children:Se?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:k("karaokeManager.activateAudio","Tap to start")}),r.jsx("p",{style:{margin:0,maxWidth:360,fontSize:14,color:"var(--nice-text-muted, #94a3b8)"},children:Se?k("karaokeManager.padHint","Hit the notes with your keys or pad!"):k("karaokeManager.micHint","Your browser needs a tap to unlock the microphone and audio.")})]}),W&&r.jsxs("div",{ref:De,style:{position:"relative",width:"100%",maxWidth:1200,margin:"0 auto"},children:[r.jsx("div",{style:{width:"100%",position:"relative",zIndex:10},children:r.jsx(Ao,{tracks:xt?[xt]:[],autoPlay:!1,uiMode:"nobuttons",height:i,externalRef:Ce,onPlayingChange:ke,onTimeUpdate:Ve,onEnded:Re})}),l&&Q&&r.jsx("div",{style:{position:"absolute",inset:0,zIndex:20,pointerEvents:"none"},children:Je.map((ve,Ne)=>{const Ae=pt[ve.id]||[],We=Ee?Ae.map(_e=>({t:_e.t-Ee,hz:_e.hz})):Ae;return r.jsx(Ro,{song:W,currentTime:F,playerRef:De,userPitch:We,segmentScores:be.perPlayerSegmentScores[ve.id],combo:be.perPlayerCombo[ve.id],verseRatings:be.perPlayerVerseRatings[ve.id],config:{playerName:ve.name,score:be.perPlayerTotalScores[ve.id]??0,playerBgColor:ve.color||et[Ne%et.length],difficultyLevel:a,isPlaying:L,playerCount:Je.length,latencyMs:fe[ve.id]??null,top:30+Ne*160}},ve.id)})}),Se&&de.length>0&&r.jsx(Wo,{lanes:de,events:Me,currentTime:F,activeLanes:je,difficulty:a,feedbackQueue:ce,isPlaying:L}),o&&Q&&r.jsx("div",{style:{position:"absolute",bottom:20,left:0,right:0,zIndex:25,pointerEvents:"none"},children:r.jsx(ho,{song:W,currentTime:F})})]}),oe&&Object.keys(dt).length>0&&r.jsx(Bh,{recordings:dt,players:e,t:k}),oe&&r.jsx($o,{uploadedSong:W,playerScores:be.perPlayerScores,topSingings:K,onRestart:Pe,onContinue:Be,t:k,renderReport:z})]})},Bh=({recordings:e,players:t,t:n})=>{const a=u.useMemo(()=>{const s={};for(const[i,l]of Object.entries(e))l&&(s[Number(i)]=URL.createObjectURL(l));return s},[e]);return u.useEffect(()=>()=>{for(const s of Object.values(a))URL.revokeObjectURL(s)},[a]),r.jsxs("div",{style:{margin:"24px auto",maxWidth:640,background:"var(--nice-bg-tertiary)",borderRadius:12,padding:16,textAlign:"left"},children:[r.jsxs("h4",{style:{marginTop:0,color:"var(--nice-text-primary, #fff)"},children:[r.jsx(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||`Player ${s.id}`}),a[s.id]?r.jsxs(r.Fragment,{children:[r.jsx("audio",{controls:!0,src:a[s.id],style:{flex:1,maxWidth:300}}),r.jsxs("a",{href:a[s.id],download:`${s.name||`player-${s.id}`}-recording.webm`,style:{color:"var(--nice-accent-light, #4fc3f7)",whiteSpace:"nowrap"},children:[r.jsx(B.NtdDownload,{size:13})," ",n("karaokeManager.download","Download")]})]}):r.jsx("span",{style:{opacity:.6},children:n("karaokeManager.noRecording","No recording")})]},s.id))})]})},al=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function on(e){return 12*Math.log2(e/440)+69}function Jn(e){const t=al[Math.round(e)%12],n=Math.floor(Math.round(e)/12)-1;return`${t}${n}`}function Jr(e,t){const n=e-t;return n-12*Math.round(n/12)}function er(e,t){if(e.length===0)return 0;const n=t/100*(e.length-1),a=Math.floor(n),s=Math.ceil(n);return a===s?e[a]:e[a]+(e[s]-e[a])*(n-a)}function sl(e){const{playerName:t,playerColor:n,songTitle:a,songArtist:s,songBpm:i,difficulty:l,pitchPoints:o,notes:c,verseRatings:d,combo:h,classicScore:f,bonusScore:p,totalScore:y,micSettings:g}=e,x=o.filter(ce=>ce.hz>0),v=x.map(ce=>on(ce.hz)),m=[],S=[],b=[...c].sort((ce,ge)=>ce.startTime-ge.startTime);function w(ce){let ge=0,ze=b.length-1;for(;ge<=ze;){const Ce=ge+ze>>>1,De=b[Ce];if(ce<De.startTime)ze=Ce-1;else if(ce>De.startTime+De.duration)ge=Ce+1;else return De.pitch}return null}const N=[];for(const ce of o){const ge=ce.hz>0?on(ce.hz):0,ze=w(ce.t);N.push({t:ce.t,sung:ge,expected:ze}),ge>0&&ze!==null&&m.push(Jr(ge,ze)*100)}const R=N.flatMap(ce=>ce.sung>0&&ce.expected!==null?[ce.sung-ce.expected]:[]).sort((ce,ge)=>ce-ge),P=R.length>0?12*Math.round(er(R,50)/12):0,j=N.map(ce=>({t:ce.t,sung:ce.sung,expected:ce.expected===null?0:ce.expected+P}));let M=0;for(const ce of b){const ge=ce.startTime-.3,ze=ce.startTime+ce.duration;for(;M<x.length&&x[M].t<ge;)M++;M<x.length&&x[M].t<=ze&&S.push((x[M].t-ce.startTime)*1e3)}const I=m.map(Math.abs),T=[...I].sort((ce,ge)=>ce-ge),E=I.length>0?I.reduce((ce,ge)=>ce+ge,0)/I.length:0,_=er(T,50),D=I.length>1?Math.sqrt(I.reduce((ce,ge)=>ce+(ge-E)**2,0)/(I.length-1)):0,q=I.filter(ce=>ce<=50).length,te=I.filter(ce=>ce<=15).length,z=I.length>0?q/I.length*100:0,U=I.length>0?te/I.length*100:0,Z=["< −100","−100 to −50","−50 to −25","−25 to −15","−15 to 0","0 to +15","+15 to +25","+25 to +50","+50 to +100","> +100"],ae=new Array(10).fill(0);for(const ce of m){const ge=ce<-100?0:ce<-50?1:ce<-25?2:ce<-15?3:ce<0?4:ce<15?5:ce<25?6:ce<50?7:ce<100?8:9;ae[ge]++}const Y=Z.map((ce,ge)=>({centRange:ce,count:ae[ge],pct:m.length>0?ae[ge]/m.length*100:0})),O=x.map(ce=>ce.hz).sort((ce,ge)=>ce-ge),C=O.length>0?O[0]:0,$=O.length>0?O[O.length-1]:0,k=C>0?on(C):0,W=$>0?on($):0,A=W-k,L=[...v].sort((ce,ge)=>ce-ge),G=er(L,10),F=er(L,90),V=new Array(12).fill(0);for(const ce of v){const ge=Math.round(ce)%12;ge>=0&&ge<12&&V[ge]++}const Q=V.reduce((ce,ge)=>ce+ge,0),le=al.map((ce,ge)=>({note:ce,count:V[ge],pct:Q>0?V[ge]/Q*100:0})),oe=Gh(x),ne=S.length>0?S.reduce((ce,ge)=>ce+ge,0)/S.length:0,K=S.length>1?Math.sqrt(S.reduce((ce,ge)=>ce+(ge-ne)**2,0)/(S.length-1)):0,H=K>0?Math.max(0,Math.min(100,100-K/2)):100;let ie=0,re=0;for(let ce=1;ce<v.length;ce++){const ge=Math.abs(v[ce]-v[ce-1]);ie+=ge,re++}const he=re>0?ie/re*100/12:0,J=o.filter(ce=>ce.hz<=0).length,ue=o.length>0?(1-J/o.length)*100:0,me=new Map;for(const ce of c){const ge=ce.line??0;me.has(ge)||me.set(ge,[]),me.get(ge).push(ce)}const Se=new Map;for(const ce of x){const ge=w(ce.t);if(ge===null)continue;let ze=0,Ce=b.length-1,De=-1;for(;ze<=Ce;){const Ye=ze+Ce>>>1,He=b[Ye];if(ce.t<He.startTime)Ce=Ye-1;else if(ce.t>He.startTime+He.duration)ze=Ye+1;else{De=He.line??0;break}}if(De<0)continue;const tt=Math.abs(Jr(on(ce.hz),ge)*100);Se.has(De)||Se.set(De,[]),Se.get(De).push(tt)}const de=d.map(ce=>{const ge=me.get(ce.verseIndex)??[],ze=Se.get(ce.verseIndex)??[],Ce=ze.length>0?ze.reduce((De,tt)=>De+tt,0)/ze.length:0;return{verseIndex:ce.verseIndex,label:ce.label,hitFraction:ce.hitFraction,avgCentDeviation:Math.round(Ce*10)/10,noteCount:ge.length,notesHit:Math.round(ce.hitFraction*ge.length),comboBonus:ce.comboBonus}}),xe=2,Me=.5,$e=o.length>0?o[o.length-1].t:0,je=[],Xe=N.flatMap(ce=>ce.sung>0&&ce.expected!==null?[{t:ce.t,hit:Math.abs(Jr(ce.sung,ce.expected))<=.5}]:[]);if(Xe.length>0){let ce=0,ge=0,ze=0;for(let Ce=0;Ce<=$e;Ce+=Me){const De=Ce-xe/2,tt=Ce+xe/2;for(;ge<Xe.length&&Xe[ge].t<tt;)Xe[ge].hit&&ze++,ge++;for(;ce<ge&&Xe[ce].t<De;)Xe[ce].hit&&ze--,ce++;const Ye=ge-ce;je.push({t:Ce,accuracy:Ye>0?ze/Ye*100:0})}}else for(let ce=0;ce<=$e;ce+=Me)je.push({t:ce,accuracy:0});return{playerName:t,playerColor:n,songTitle:a,songArtist:s,songBpm:i,difficulty:l,timestamp:new Date().toISOString(),classicScore:f,bonusScore:p,totalScore:y,maxCombo:(h==null?void 0:h.maxCombo)??0,totalComboBonus:(h==null?void 0:h.totalComboBonus)??0,totalPitchPoints:o.length,avgCentDeviation:Math.round(E*10)/10,medianCentDeviation:Math.round(_*10)/10,stdDevCents:Math.round(D*10)/10,intonationAccuracyPct:Math.round(z*10)/10,perfectHitPct:Math.round(U*10)/10,pitchDeviationHistogram:Y,lowestHz:Math.round(C*10)/10,highestHz:Math.round($*10)/10,lowestNote:k>0?Jn(k):"—",highestNote:W>0?Jn(W):"—",rangeInSemitones:Math.round(A*10)/10,tessituraLow:G>0?Jn(G):"—",tessituraHigh:F>0?Jn(F):"—",pitchClassDistribution:le,vibrato:oe,avgOnsetDeviationMs:Math.round(ne*10)/10,rhythmStabilityPct:Math.round(H*10)/10,jitterPct:Math.round(he*100)/100,shimmerProxy:Math.round(ue*10)/10,verseMetrics:de,micSettings:g,pitchOverTime:j,accuracyOverTime:je}}function Gh(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(y=>on(y.hz)),n=e.map(y=>y.t),a=.5,s=[],i=[];let l=0,o=0,c=0;for(let y=0;y<e.length;y++){for(o+=t[y],c++;l<y&&n[y]-n[l]>=a;)o-=t[l],c--,l++;if(c<6||(y-l)%10!==0)continue;const g=o/c;let x=0,v=t[l]-g,m=Math.abs(v);for(let w=l+1;w<=y;w++){const N=t[w]-g;N*v<0&&x++,v=N;const R=Math.abs(N);R>m&&(m=R)}const S=n[y]-n[l];if(S<=0)continue;const b=x/2/S;b>=3&&b<=12&&(s.push(b),i.push(m*100))}if(s.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const d=s.reduce((y,g)=>y+g,0)/s.length,h=i.reduce((y,g)=>y+g,0)/i.length,f=Math.sqrt(s.reduce((y,g)=>y+(g-d)**2,0)/s.length),p=Math.max(0,Math.min(100,100-f*20));return{detected:!0,avgRateHz:Math.round(d*10)/10,avgExtentCents:Math.round(h*10)/10,regularityPct:Math.round(p)}}const X={overlay:{position:"fixed",inset:0,background:"var(--nice-overlay-90, rgba(0,0,0,0.92))",display:"flex",alignItems:"flex-start",justifyContent:"center",zIndex:250,color:"var(--nice-text, #e2e8f0)",overflowY:"auto",padding:"24px 12px"},container:{background:"var(--nice-bg, #0f172a)",borderRadius:16,padding:32,width:"min(960px, 95vw)",boxShadow:"0 16px 48px var(--nice-overlay-60, rgba(0,0,0,0.6))",fontFamily:"'Segoe UI', system-ui, -apple-system, sans-serif"},header:{textAlign:"center",marginBottom:24,borderBottom:"2px solid var(--nice-border, #334155)",paddingBottom:20},title:{fontSize:28,fontWeight:800,color:"var(--nice-text, #f1f5f9)",margin:"0 0 4px"},subtitle:{fontSize:14,color:"var(--nice-text-muted, #64748b)",margin:0},sectionTitle:{fontSize:18,fontWeight:700,color:"var(--nice-accent, #38bdf8)",margin:"28px 0 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",paddingBottom:6,display:"flex",alignItems:"center",gap:8},table:{width:"100%",borderCollapse:"collapse",fontSize:13,margin:"8px 0"},th:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"left",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},thRight:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"right",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},td:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-secondary, #cbd5e1)"},tdRight:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",textAlign:"right",color:"var(--nice-text, #e2e8f0)",fontWeight:500},tdBold:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text, #f1f5f9)",fontWeight:700},kpiGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:12,margin:"12px 0"},kpiCard:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:"14px 16px",textAlign:"center",border:"1px solid var(--nice-border, #334155)"},kpiValue:{fontSize:26,fontWeight:800,color:"var(--nice-warning, #fbbf24)"},kpiLabel:{fontSize:11,color:"var(--nice-text-muted, #64748b)",marginTop:2,textTransform:"uppercase",letterSpacing:.8},kpiUnit:{fontSize:13,fontWeight:400,color:"var(--nice-text-muted, #94a3b8)",marginLeft:2},chartWrap:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:16,margin:"12px 0",border:"1px solid var(--nice-border, #334155)"},chartTitle:{fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:8,textAlign:"center"},badge:e=>({display:"inline-block",padding:"2px 10px",borderRadius:20,background:e,color:"#fff",fontSize:12,fontWeight:700}),btnPrimary:{background:"var(--nice-info, #3b82f6)",color:"#fff",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:700,cursor:"pointer"},btnSecondary:{background:"var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:600,cursor:"pointer"},row:{display:"flex",gap:16,flexWrap:"wrap"},half:{flex:"1 1 45%",minWidth:280},footer:{textAlign:"center",marginTop:24,paddingTop:16,borderTop:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #475569)",fontSize:11}};function gt(e){return e>=90?"#22c55e":e>=70?"#84cc16":e>=50?"#eab308":e>=30?"#f97316":"#ef4444"}function Hs(e){switch(e){case"Perfect":return"#22c55e";case"Great":return"#84cc16";case"Good":return"#eab308";case"OK":return"#f97316";default:return"#ef4444"}}function Wh(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 qt=e=>Math.round(e*10)/10;function Ks(e,t,n){return e.map((a,s)=>({name:a,color:n[s],data:t.map((i,l)=>l===s?qt(i):0)}))}function Ys(e,t){if(e.length<=t)return e;const n=Math.ceil(e.length/t);return e.filter((a,s)=>s%n===0)}function Zs(e){const t=e.length>1?e[e.length-1]-e[0]:0,n=[1,2,5,10,15,30,60,120,300].find(s=>t/s<=10)??600;let a=Math.ceil((e[0]??0)/n)*n;return e.map(s=>{if(s+1e-9<a)return"";for(;a<=s+1e-9;)a+=n;return`${Math.round(s)}s`})}const Xs=240,Uh=({reports:e,noteCount:t,uploadedSong:n=null,playerScores:a,livePitch:s,liveVerseRatings:i,liveCombo:l,difficulty:o="normal",micSettings:c,onClose:d,t:h,className:f,style:p,id:y,accessMode:g,"data-testid":x})=>{const{t:v}=Te(),m=h??v,S=u.useRef(null),b=u.useMemo(()=>{if(e||!n)return[];const k=Hn(n.notes.map(A=>A.noteLine),n.bpm??void 0),W=(n.gap??0)/1e3;return Ka(k,W)},[e,n]),w=u.useMemo(()=>e||(!n||!a||!l?[]:a.map(k=>{const W=(s==null?void 0:s[k.id])||[];return sl({playerName:k.name,playerColor:k.color,songTitle:n.title,songArtist:n.artist,songBpm:n.bpm??0,difficulty:o,pitchPoints:W,notes:b,verseRatings:i??[],combo:l,classicScore:k.classicScore,bonusScore:k.bonusScore,totalScore:k.totalScore,micSettings:(c==null?void 0:c[k.id])??null})})),[e,n,a,s,i,l,o,b,c]),N=u.useCallback(()=>{var G,F;if(!S.current)return;const k=`<!DOCTYPE html>
|
|
46
|
+
-`]})]}),c&&c.length>0&&r.jsxs("div",{style:{marginTop:24},children:[r.jsx("b",{children:i("audioPitch.waveformRms","Waveform and RMS:")}),r.jsx("canvas",{width:600,height:100,style:{background:"var(--nice-bg-secondary, #222)",borderRadius:4,width:"100%",maxWidth:600,display:"block"},role:"img","aria-label":i("audioPitch.waveformAndRmsVisualizationCanvas","Waveform and RMS visualization canvas"),ref:G=>{if(!G)return;const W=G.getContext("2d");if(W){W.clearRect(0,0,600,100),W.strokeStyle=ke.resolveCssColor("var(--nice-info, #0ff)",W.canvas),W.beginPath();for(let C=0;C<c.length;C+=Math.ceil(c.length/600)){const $=C/c.length*600,S=50-c[C]*48;C===0?W.moveTo($,S):W.lineTo($,S)}if(W.stroke(),b.length>0){W.strokeStyle=ke.resolveCssColor("var(--nice-warning, #ff0)",W.canvas),W.beginPath();for(let C=0;C<b.length;C++){const $=C/b.length*600,S=100-b[C]*90;C===0?W.moveTo($,S):W.lineTo($,S)}W.stroke()}}}}),r.jsxs("div",{style:{color:"var(--nice-text-muted, #aaa)",fontSize:12,marginTop:4},children:[r.jsx("span",{style:{color:"var(--nice-info, #0ff)"},children:i("audioPitch.waveform","Waveform")})," "," | ",r.jsx("span",{style:{color:"var(--nice-warning, #ff0)"},children:"RMS"})]})]}),!w&&k.length===0&&!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(([G,W])=>r.jsxs("div",{style:{marginBottom:12},children:[r.jsx("b",{children:G}),": ",i("audioPitch.detectedSegments","detected segments:")," ",W.length,r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-text-inverse, #ddd)",padding:8,borderRadius:4,marginTop:8},children:W.map(C=>`: ${Math.round(C.start*10)} ${Math.round(C.duration*10)} ${C.pitch} [${C.freq.toFixed(1)} Hz]`).join(`
|
|
47
|
+
`)})]},G))]})]})}const zt=1e4,Bs=5e3;function Xr(e,t=.35){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(!n)return e;const a=Math.min(255,Math.round(parseInt(n[1],16)+(255-parseInt(n[1],16))*t)),s=Math.min(255,Math.round(parseInt(n[2],16)+(255-parseInt(n[2],16))*t)),i=Math.min(255,Math.round(parseInt(n[3],16)+(255-parseInt(n[3],16))*t));return`rgb(${a},${s},${i})`}const fh=["var(--nice-warning, #facc15)","var(--nice-text-secondary, #cbd5e1)","var(--nice-warning, #d97706)"],mh=({entry:e,rank:t,animDelay:n})=>{const[a,s]=d.useState(0),[i,o]=d.useState(0),[l,c]=d.useState(0),[u,h]=d.useState(0),p=Math.min(e.classicScore,zt),g=Math.min(e.bonusScore,zt),y=p/zt*Bs,m=g>0?g/zt*Bs:0;return d.useEffect(()=>{let x,b=null;const f=Math.max(y,400),k=Math.max(m,m>0?300:0),v=w=>{b===null&&(b=w);const R=w-b-n;if(R<0){x=requestAnimationFrame(v);return}if(R<=f){const M=Math.min(1,R/f),j=1-Math.pow(1-M,3);s(Math.min(j*(p/zt)*100,100)),c(Math.round(j*e.classicScore)),x=requestAnimationFrame(v);return}if(s(Math.min(p/zt*100,100)),c(e.classicScore),k>0){const M=R-f;if(M<=k){const j=Math.min(1,M/k),T=1-Math.pow(1-j,3);o(Math.min(T*(g/zt)*100,100)),h(Math.round(T*e.bonusScore)),x=requestAnimationFrame(v);return}o(Math.min(g/zt*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(F.NtdMedal,{size:18,primaryColor:fh[t-1]}):`#${t}`}),r.jsx("span",{className:"nice-karaoke-summary__bar-name",style:{color:e.color},children:e.name}),r.jsxs("div",{className:"nice-karaoke-summary__bar-track",children:[e.bonusScore>0&&r.jsx("div",{className:"nice-karaoke-summary__bar-fill-bonus",style:{width:`${Math.min(a+i,100)}%`,background:Xr(e.color,.45)}}),r.jsx("div",{className:"nice-karaoke-summary__bar-fill-classic",style:{width:`${a}%`,background:`linear-gradient(90deg, ${e.color}, ${Xr(e.color,.15)})`,boxShadow:`0 0 8px ${e.color}55`}}),r.jsxs("div",{className:"nice-karaoke-summary__bar-text",children:[l.toLocaleString(),u>0&&r.jsxs("span",{className:"nice-karaoke-summary__bar-text-bonus",style:{color:Xr(e.color,.5)},children:["+",u.toLocaleString()]})]})]}),r.jsx("span",{className:"nice-karaoke-summary__bar-total",children:(l+u).toLocaleString()})]})},Gs=({title:e,entries:t,highlightNames:n,playerColorMap:a})=>r.jsxs("div",{className:"nice-karaoke-summary__rank",children:[r.jsx("h4",{className:"nice-karaoke-summary__rank-title",children:e}),r.jsx("table",{className:"nice-karaoke-summary__rank-table",children:r.jsx("tbody",{children:t.map((s,i)=>{const o=n.has(s.name),l=a.get(s.name);return r.jsxs("tr",{className:`nice-karaoke-summary__rank-row ${o?"nice-karaoke-summary__rank-row--hl":""}`,children:[r.jsx("td",{className:`nice-karaoke-summary__rank-pos ${i<3?"nice-karaoke-summary__rank-pos--top":""}`,children:s.rank}),r.jsxs("td",{className:"nice-karaoke-summary__rank-name",style:l?{color:l}:void 0,children:[o&&r.jsxs(r.Fragment,{children:[r.jsx(F.NtdCircle,{size:8})," "]}),s.name]}),r.jsx("td",{className:"nice-karaoke-summary__rank-score",children:s.score.toLocaleString()})]},`${s.name}-${i}`)})})})]}),$o=({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((w,R)=>R.totalScore-w.totalScore),[t]),x=d.useMemo(()=>{const w=new Map;for(const R of t)w.set(R.name,R.color);return w},[t]),b=d.useMemo(()=>new Set(t.map(w=>w.name)),[t]),f=d.useMemo(()=>m.map((w,R)=>({rank:R+1,name:w.name,score:w.totalScore,color:w.color})),[m]),k=d.useMemo(()=>{const w=n.map(M=>({name:M.playerName,score:M.score})),R=new Set;for(const M of m)R.has(M.id)||(R.add(M.id),w.push({name:M.name,score:M.totalScore}));return w.sort((M,j)=>j.score-M.score),w.slice(0,10).map((M,j)=>({rank:j+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((w,R)=>r.jsx(mh,{entry:w,rank:R+1,animDelay:R*300},w.id))}),(m.length>1||n.length>0)&&r.jsxs("div",{className:"nice-karaoke-summary__ranks",children:[m.length>1&&r.jsx(Gs,{title:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(F.NtdHome,{size:14})," ",i("karaokeSummary.localRanking","Session ranking")]}),entries:f,highlightNames:b,playerColorMap:x}),n.length>0&&r.jsx(Gs,{title:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(F.NtdTrophy,{size:14})," ",i("karaokeSummary.globalRanking","Top 10")]}),entries:k,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(F.NtdBarChart,{size:15})," ",i("karaokeSummary.report","Report")]}),r.jsx("button",{type:"button",className:"nice-karaoke-summary__btn nice-karaoke-summary__btn--restart",onClick:a,children:i("karaokeSummary.restart","Restart")}),r.jsx("button",{type:"button",className:"nice-karaoke-summary__btn nice-karaoke-summary__btn--continue",onClick:s,children:i("karaokeSummary.continue","Continue")})]})]}),g&&(o==null?void 0:o(()=>y(!1)))]})},gh=st.scoped("GenericPlayer"),yh=e=>/youtu(\.be|be\.com)/i.test(e),Ao=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),vh=e=>!!e&&/\.(mp3|aac|m4a|flac|wav|ogg)(\?.*)?$/i.test(e),bh=e=>{var i;if(!((i=e==null?void 0:e.sources)!=null&&i.length))return null;const t=o=>e.sources.find(l=>l.kind===o),n=e.sources.find(o=>o.kind==="youtube"&&(o.videoId||o.url&&yh(o.url)))??null;if(n)return n;const a=t("hls")||e.sources.find(o=>o.url&&Ao(o.url))||null;if(a)return a;const s=t("audio")||e.sources.find(o=>o.url&&vh(o.url))||null;return s||(e.sources[0]??null)},Ar=e=>{(!isFinite(e)||e<0)&&(e=0);const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`},xh=[.25,.5,.75,1,1.25,1.5,1.75,2],Io=({tracks:e=[],initialIndex:t=0,autoPlay:n=!0,countdownSeconds:a=0,height:s=360,onIndexChange:i,onPlayingChange:o,onTimeUpdate:l,externalRef:c,uiMode: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:k=null,onRepeatModeChange:v,onShuffleChange:w,onSpeedChange:R,sleepTimer:M=0,onSleepTimerExpired:j})=>{const{t:T}=xe(),{t:P}=xe(),[A,I]=d.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),L=e[A],N=d.useMemo(()=>bh(L),[L]),_=(L==null?void 0:L.startOffset)??0,[ee,Y]=d.useState(!1),[O,U]=d.useState(0),[V,K]=d.useState(0),[G,W]=d.useState(.9),[C,$]=d.useState(null),[S,B]=d.useState(null),H=d.useRef(null),[z,Z]=d.useState(x),[E,q]=d.useState(b),[X,re]=d.useState(f),[oe,se]=d.useState(k),[D,J]=d.useState([]),[ae,ce]=d.useState(M>0?M*60:null),le=d.useRef(null),[ne,pe]=d.useState(()=>Ei()),fe=d.useRef(null),me=d.useRef(null),he=d.useRef(null),we=d.useRef(null);d.useEffect(()=>{if(z&&e.length>0){const de=Array.from({length:e.length},(ge,Ae)=>Ae);for(let ge=de.length-1;ge>0;ge--){const Ae=Math.floor(Math.random()*(ge+1));[de[ge],de[Ae]]=[de[Ae],de[ge]]}J(de)}},[z,e.length]);const je=d.useRef(j);je.current=j,d.useEffect(()=>(le.current&&(window.clearInterval(le.current),le.current=null),M>0&&ee&&(ce(M*60),le.current=window.setInterval(()=>{ce(de=>{var ge;return!de||de<=1?(le.current&&window.clearInterval(le.current),le.current=null,(ge=je.current)==null||ge.call(je),null):de-1})},1e3)),()=>{le.current&&window.clearInterval(le.current)}),[M,ee]);const Ne=d.useCallback(de=>{const ge=Math.min(Math.max(0,de),Math.max(0,e.length-1));I(ge),i==null||i(ge)},[e.length,i]),Ee=d.useCallback(()=>{if(z&&D.length>0){const ge=D.indexOf(A)+1;return ge<D.length?D[ge]:E==="all"?D[0]:-1}return A<e.length-1?A+1:E==="all"?0:-1},[A,e.length,z,D,E]),Ye=d.useCallback(()=>{if(z&&D.length>0){const de=D.indexOf(A);return de>0?D[de-1]:E==="all"?D[D.length-1]:-1}return A>0?A-1:E==="all"?e.length-1:-1},[A,e.length,z,D,E]),ue=d.useCallback(()=>{const de=Ee();de>=0&&Ne(de)},[Ee,Ne]),be=d.useCallback(async()=>{var de,ge;await Yt(),pe(!0),(N==null?void 0:N.kind)==="youtube"?(de=fe.current)==null||de.playVideo():(ge=me.current)==null||ge.play(),Y(!0),o==null||o(!0)},[N,o]),Oe=d.useCallback(()=>{var de,ge;(N==null?void 0:N.kind)==="youtube"?(de=fe.current)==null||de.pauseVideo():(ge=me.current)==null||ge.pause(),Y(!1),o==null||o(!1)},[N,o]),Me=d.useCallback(()=>ee?Oe():be(),[ee,be,Oe]),Ie=d.useCallback(de=>{var Te;const ge=de+_;(N==null?void 0:N.kind)==="youtube"?(Te=fe.current)==null||Te.seekTo(ge,!0):me.current&&(me.current.currentTime=ge);const Ae=Math.max(0,de);K(Ae),l==null||l(Ae)},[N==null?void 0:N.kind,l,_]),Qe=d.useCallback(()=>{if(V>3){Ie(0);return}const de=Ye();de>=0&&Ne(de)},[Ye,Ne,V,Ie]),Be=d.useCallback(de=>{var ge,Ae;W(de),$(null),(N==null?void 0:N.kind)==="youtube"?(Ae=(ge=fe.current)==null?void 0:ge.setVolume)==null||Ae.call(ge,Math.round(de*100)):me.current&&(me.current.volume=de)},[N]),He=d.useCallback(()=>{C!==null?Be(C):($(G),Be(0))},[G,C,Be]),Lt=d.useCallback(de=>{var ge,Ae;re(de),me.current&&(me.current.playbackRate=de),(N==null?void 0:N.kind)==="youtube"&&((Ae=(ge=fe.current)==null?void 0:ge.setPlaybackRate)==null||Ae.call(ge,de)),R==null||R(de)},[N,R]),ct=d.useCallback(()=>{const de=["none","all","one"],ge=de[(de.indexOf(E)+1)%de.length];q(ge),v==null||v(ge)},[E,v]),ht=d.useCallback(()=>{const de=!z;Z(de),w==null||w(de)},[z,w]),it=d.useCallback(de=>{se(de)},[]);d.useImperativeHandle(c,()=>({play:be,pause:Oe,toggle:Me,seekTo:Ie,setVolume:Be,setSpeed:Lt,setRepeatMode:de=>{q(de),v==null||v(de)},toggleShuffle:ht,setABLoop:it,getUnderlyingPlayer:()=>(N==null?void 0:N.kind)==="youtube"?fe.current:(N==null?void 0:N.kind)==="hls"||(N==null?void 0:N.kind)==="audio"?me.current:null}),[be,Oe,Me,Ie,Be,Lt,v,ht,it,N==null?void 0:N.kind]),d.useEffect(()=>{const de=window.setInterval(()=>{let ge=0,Ae=0;(N==null?void 0:N.kind)==="youtube"&&fe.current?(ge=fe.current.getCurrentTime()||0,Ae=fe.current.getDuration()||0):me.current&&(ge=me.current.currentTime||0,Ae=me.current.duration||0);const Te=Math.max(0,ge-_);K(Te),U(Ae),l==null||l(Te),oe&&Te>=oe.b&&Ie(oe.a)},250);return()=>window.clearInterval(de)},[N==null?void 0:N.kind,l,oe,_,Ie]),d.useEffect(()=>()=>{H.current&&(window.clearInterval(H.current),H.current=null)},[]);const wt=N==null?void 0:N.url,Je=N==null?void 0:N.kind,Pt=N==null?void 0:N.withCredentials,Xt=JSON.stringify((N==null?void 0:N.headers)??null),Se=d.useRef(G);Se.current=G;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(me.current&&(me.current.volume=Se.current,me.current.crossOrigin=Pt?"use-credentials":"anonymous"),Je==="hls"&&Ao(wt)){const de=me.current;if(!de)return;const ge=()=>{de.src=wt,de.load();try{_&&!isNaN(_)&&(de.currentTime=_)}catch{}n&&de.play().catch(()=>{})};de.canPlayType("application/vnd.apple.mpegurl")?ge():(async()=>{var Ae;try{const _e=(await import("hls.js")).default;if((Ae=_e==null?void 0:_e.isSupported)!=null&&Ae.call(_e)){const ve=JSON.parse(Xt),Re=new _e({xhrSetup:Le=>{if(Pt&&(Le.withCredentials=!0),ve)for(const[Ge,De]of Object.entries(ve))try{Le.setRequestHeader(Ge,De)}catch{}}});he.current=Re,Re.loadSource(wt),Re.attachMedia(de),Re.on(_e.Events.MANIFEST_PARSED,()=>{n&&de.play().catch(()=>{})})}else ge()}catch(Te){gh.debug("HLS.js setup failed, falling back to native playback",Te),ge()}})()}else if(Je==="audio"&&wt&&me.current){const de=me.current;de.src=wt,de.load();try{_&&!isNaN(_)&&(de.currentTime=_)}catch{}n&&de.play().catch(()=>{})}H.current&&(window.clearInterval(H.current),H.current=null),B(null),K(0),U(0),n&&Je==="youtube"&&Ce.current>0?(B(Ce.current),H.current=window.setInterval(()=>{B(de=>{var ge,Ae;if(!de)return null;if(de<=1){H.current&&(window.clearInterval(H.current),H.current=null);try{(ge=fe.current)==null||ge.playVideo()}catch{}return Y(!0),(Ae=We.current)==null||Ae.call(We,!0),null}return de-1})},1e3)):Y(!!n)},[wt,Je,Pt,Xt,_,n]);const ze=d.useCallback(()=>{if(E==="one"){Ie(0),be();return}const de=Ee();de>=0?Ne(de):(Y(!1),o==null||o(!1),Ie(0),y==null||y())},[E,Ee,Ne,o,Ie,y,be]);d.useEffect(()=>{if(!m)return;const de=ge=>{const Ae=ge.target;if(!(Ae.tagName==="INPUT"||Ae.tagName==="TEXTAREA"||Ae.isContentEditable))switch(ge.key){case" ":ge.preventDefault(),Me();break;case"ArrowRight":ge.preventDefault(),Ie(Math.min(V+5,O));break;case"ArrowLeft":ge.preventDefault(),Ie(Math.max(0,V-5));break;case"ArrowUp":ge.preventDefault(),Be(Math.min(1,G+.05));break;case"ArrowDown":ge.preventDefault(),Be(Math.max(0,G-.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,O,Be,G,He,ue,Qe,ct,ht]);const $e=(N==null?void 0:N.kind)==="youtube"||u==="full"||u==="nobuttons",Pe=h>0?e.slice(A+1,A+1+h):[];return r.jsxs("div",{ref:we,className:"gp-player",style:{display:"grid",gap:12},tabIndex:-1,children:[n&&!ne&&r.jsx("div",{className:"gp-audio-activation",onClick:()=>{pe(!0),be()},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:T("player.clickToActivateAudio","Click to activate audio")})}),$e&&r.jsxs("div",{className:"gp-stage",style:{width:"100%",height:s,background:(N==null?void 0:N.kind)==="youtube"?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(N==null?void 0:N.kind)==="youtube"&&r.jsx(Pa,{videoId:N.videoId??Mh(N.url),onReady:de=>{fe.current=de.target,Be(G);const ge=(L==null?void 0:L.startOffset)??0;try{ge&&de.target.seekTo(ge,!0)}catch{}if(u==="nobuttons"){try{de.target.playVideo()}catch{}Y(!0)}},onEnd:ze,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"}}),((N==null?void 0:N.kind)==="audio"||(N==null?void 0:N.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:(N==null?void 0:N.label)??`${(N==null?void 0:N.codec)??""} ${(N==null?void 0:N.quality)??""}`.trim()})]})}),r.jsx("audio",{ref:me,onEnded:ze,onLoadedMetadata:()=>{const de=me.current;de&&U(de.duration||0)},crossOrigin:N!=null&&N.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(Lo,{currentTime:V,duration:O}),r.jsx(Sh,{isPlaying:ee,index:A,count:e.length,currentTime:V,duration:O,volume:G,onPrev:Qe,onNext:ue,onToggle:Me,onSeek:Ie,onVolume:Be}),r.jsx(jh,{shuffleOn:z,repeatMode:E,speed:X,abLoop:oe,currentTime:V,sleepRemaining:ae,onToggleShuffle:ht,onCycleRepeat:ct,onSpeedChange:Lt,onSetABLoop:it,onMuteToggle:He,isMuted:C!==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(kh,{currentTime:V,duration:O,onSeek:Ie})}),(u==="minimal"||u==="compact")&&r.jsx(wh,{isPlaying:ee,canPrev:A>0,canNext:A<e.length-1,onPrev:Qe,onNext:ue,onToggle:Me}),u==="compact"&&Pe.length>0&&r.jsx(Ch,{items:Pe,onSelect:de=>Ne(A+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,ge)=>r.jsxs("button",{onClick:()=>Ne(ge),style:{textAlign:"left",border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"8px 10px",background:ge===A?"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(Ae=>Ae.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"},Lo=({currentTime:e,duration:t})=>r.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[r.jsx("div",{}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-secondary, #64748b)"},children:[Ar(e)," / ",Ar(t)]})]}),Sh=({isPlaying:e,index:t,count:n,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek: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(F.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(F.NtdPause,{size:16}):r.jsx(F.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(F.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(F.NtdVolume,{size:16}),r.jsx("input",{type:"range",min:0,max:1,step:.01,value:i,onChange:g=>h(parseFloat(g.target.value)),"aria-label":p("player.volume","Volume")})]})]})},kh=({currentTime:e,duration:t,onSeek:n})=>{const{t:a}=xe();return r.jsxs(r.Fragment,{children:[r.jsx(Lo,{currentTime:e,duration:t}),r.jsx("input",{type:"range",min:0,max:Math.max(1,t),step:.1,value:e,onChange:s=>n(parseFloat(s.target.value)),"aria-label":a("player.seekPosition","Seek position")})]})},wh=({isPlaying:e,canPrev:t,canNext:n,onPrev:a,onNext:s,onToggle:i})=>{const{t:o}=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(F.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(F.NtdPause,{size:16}):r.jsx(F.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(F.NtdSkipForward,{size:16})})]})},Ch=({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))})]})},jh=({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(F.NtdRepeat,{size:16}),r.jsx("span",{style:{position:"absolute",right:-3,bottom:-3,fontSize:8,fontWeight:700},children:"1"})]}):t==="all"?r.jsx(F.NtdRepeat,{size:16}):r.jsx(F.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(F.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:xh.map(x=>r.jsxs("option",{value:x,children:[x,"x"]},x))}),r.jsx("button",{onClick:h,title:g("player.mute","Mute"),"aria-label":g("player.mute","Mute"),style:{...yt,opacity:p?1:.6},children:p?r.jsx(F.NtdVolumeMute,{size:16}):r.jsx(F.NtdVolume,{size:16})}),a?r.jsxs("span",{style:{display:"flex",gap:4,alignItems:"center"},children:[r.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #64748b)"},children:["A: ",Ar(a.a)," — B: ",Ar(a.b)]}),r.jsx("button",{onClick:()=>u(null),title:g("player.clearLoop","Clear loop"),style:{...yt,fontSize:11,padding:"2px 6px"},children:r.jsx(F.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(F.NtdMoon,{size:12})," ",Math.floor(i/60),":",(i%60).toString().padStart(2,"0")]})]})};function Mh(e){if(!e)return;const t=e.match(/youtu\.be\/([A-Za-z0-9_-]{6,})/);if(t)return t[1];const n=e.match(/[?&]v=([A-Za-z0-9_-]{6,})/);if(n)return n[1]}function _o(e){const t={};if(!e)return t;const n=e.split(",");for(const a of n){const s=a.trim();s.startsWith("v=")?t.youtubeId=s.substring(2):s.startsWith("co=")?t.coverImage=s.substring(3):s.startsWith("bg=")&&(t.backgroundImage=s.substring(3))}return t}function Rh(e,t="/api/karaoke/cover"){var a,s;const n=((a=e.coverImage)==null?void 0:a.startsWith("http://"))||((s=e.coverImage)==null?void 0:s.startsWith("https://"));return e.coverImage&&n?e.coverImage:e.youtubeId?`https://img.youtube.com/vi/${e.youtubeId}/hqdefault.jpg`:e.coverImage?`${t}?filePath=${encodeURIComponent(e.coverImage)}`:"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='320' height='180'%3E%3Crect width='320' height='180' fill='%23333'/%3E%3Ctext x='160' y='95' text-anchor='middle' fill='%23999' font-size='16'%3ENo Cover%3C/text%3E%3C/svg%3E"}function Nh(e,t="/backgrounds"){return e.backgroundImage?`${t}/${e.backgroundImage}`:""}function zo(e,t,n=.01){let a=0;for(let o=0;o<e.length;o++)a+=e[o]*e[o];if(a=Math.sqrt(a/e.length),a<n)return 0;let s=-1,i=0;for(let o=20;o<e.length/2;o++){let l=0;for(let c=0;c<e.length/2;c++)l+=e[c]*e[c+o];l/=e.length/2,l>i&&(i=l,s=o)}return s>0?t/s:0}function Ka(e,t){const n=[];return e.forEach((a,s)=>{a.forEach((i,o)=>{n.push({startTime:i.startTime+t,duration:i.duration,pitch:i.pitch,isGold:i.isGold,line:s,idx:o})})}),n}function Do(e,t,n){const a=[];return e.forEach(s=>{var c;const[i,o]=s.noteKey.split("-").map(Number),l=(c=t[i])==null?void 0:c[o];l&&s.segments.forEach(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 Fo(e,t=120){let n=e;if(e.length>t){const a=e.length/t,s=[];for(let i=0;i<t;i++)s.push(e[Math.floor(i*a)]);n=s}return n.map(a=>({t:Math.round(a.t*1e3)/1e3,hz:Math.round(a.hz)}))}function Oo(e,t,n){const s=Date.parse(e)-n;return Math.max(0,Math.round(t-s))}const Bo={crepe:"var(--nice-accent, #a78bfa)",librosa:"var(--nice-success-light, #34d399)",pitchy:"var(--nice-primary-light, #60a5fa)",autocorr:"var(--nice-text-secondary, #555555)"};function Th(e){return e==="autocorr"?"Ultrastar":e.charAt(0).toUpperCase()+e.slice(1)}function Ph(e){return Bo[e]??"var(--nice-text-secondary, #555555)"}function Eh(e){const t=Bo[e]??"var(--nice-text-secondary, #555555)";return`var(--algo-${e}, ${t})`}function Go(e,t){const n=!(t!=null&&t.includes("no-music")),a=t==null?void 0:t.includes("instrumental"),s=[];if(n){if(e.videoPath){let i=e.videoPath;if(i.startsWith("v=")){const o=_o(i);o.youtubeId&&(i=`https://www.youtube.com/watch?v=${o.youtubeId}`)}/youtu(\.be|be\.com)/i.test(i)?s.push({kind:"youtube",url:i}):/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(e.videoPath)&&s.push({kind:"audio",url:e.videoPath})}if(s.length===0){const i=a?e.instrumentalPath:e.audioPath;i&&/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(i)&&s.push({kind:"audio",url:i})}s.length===0&&e.youtubeId&&s.push({kind:"youtube",url:`https://www.youtube.com/watch?v=${e.youtubeId}`})}return{id:String(e.id??e.title??"song"),title:e.title??"—",artist:e.artist??"—",coverUrl:e.coverPath??void 0,sources:s}}function $h(e){const t=e.videoPath??e.video??void 0;return{id:e.id,title:e.title??"",artist:e.artist??"",year:e.year,genre:e.genre,language:e.language,filePath:e.filePath,coverPath:e.coverPath,audioPath:e.audioPath??e.audio??void 0,videoPath:t,format:0,notes:e.notes??[],gap:e.gap,bpm:e.bpm,videoGap:e.videoGap,start:e.start,end:e.end,youtubeId:e.youtubeId,instrumentalPath:e.instrumentalPath,isVerified:e.isVerified,coverImage:e.coverImage,backgroundImage:e.backgroundImage}}var Ya=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(Ya||{});function Wo(e,t="song.txt"){const n=e.split(/\r?\n/),a={},s=[];for(const o of n){const l=o.replace(/\uFEFF/g,"");if(l.trim()){if(l.startsWith("#")){const c=l.indexOf(":");c>0&&(a[l.slice(1,c).trim().toUpperCase()]=l.slice(c+1).trim())}else if(/^[:*\-FG]/.test(l))s.push({noteLine:l});else if(l.trim()==="E")break}}const i=o=>{if(!o)return;const l=parseFloat(o.replace(",","."));return Number.isFinite(l)?l:void 0};return{title:a.TITLE||t.replace(/\.txt$/i,""),artist:a.ARTIST||"",format:Ya.Ultrastar,bpm:i(a.BPM),gap:i(a.GAP),genre:a.GENRE||void 0,language:a.LANGUAGE||void 0,year:a.YEAR||void 0,audioPath:a.MP3||void 0,videoPath:a.VIDEO||a.MP3||void 0,notes:s}}const Ah=e=>window.btoa(unescape(encodeURIComponent(e))),Vo=({onSongUpload:e,parseSong:t,onError:n,accept:a=".txt",maxFileSize:s=5*1024*1024,t:i})=>{const{t:o}=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:Ah(y)}):Wo(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)}})})},Ih=[],Lh=[],_h=[],zh=[];function Dh(e,t,n,a,s){const o=a*.45;e.beginPath();for(let l=0;l<10;l++){const c=l%2===0?a:o,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 Vt=60,Ws=4,Qr="#888",Vs=["A","B","X","Y","LB","RB","LT","RT"],Uo=({lanes:e=Ih,events:t=Lh,currentTime:n,activeLanes:a=_h,difficulty:s,feedbackQueue:i=zh,isPlaying:o,height:l=300})=>{const{t:c}=xe(),u=e.length,h=d.useRef(null),p=d.useRef([]);return d.useEffect(()=>{p.current=i},[i]),d.useEffect(()=>{var R,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 j=0;j<u;j++){const T=j*f;y.fillStyle=j%2===0?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",y.fillRect(T,0,f,b),j>0&&(y.strokeStyle="rgba(255,255,255,0.1)",y.lineWidth=1,y.beginPath(),y.moveTo(T,0),y.lineTo(T,b),y.stroke())}const k=b-Vt-10;y.strokeStyle="rgba(255,255,255,0.4)",y.lineWidth=2,y.setLineDash([8,4]),y.beginPath(),y.moveTo(0,k),y.lineTo(x,k),y.stroke(),y.setLineDash([]);const v=e.map(j=>ke.resolveCssColor((j==null?void 0:j.color)??Qr,g)),w=(b-Vt-20)/Ws;for(const j of t){const T=j.note.startTime,P=T+j.note.duration,A=T-n;if(A>Ws||P<n-.5)continue;const I=j.lane,L=I*f+4,N=f-8,_=k-A*w,ee=j.note.duration*w,Y=n>=T-.15&&n<=P+.15,O=n>P+.15,U=v[I]??Qr;O?y.fillStyle="rgba(100,100,100,0.3)":Y?(y.fillStyle=U,y.shadowColor=U,y.shadowBlur=12):(y.fillStyle=U,y.globalAlpha=.6);const V=Math.max(ee,8),K=6;y.beginPath(),y.moveTo(L+K,_),y.lineTo(L+N-K,_),y.quadraticCurveTo(L+N,_,L+N,_+K),y.lineTo(L+N,_+V-K),y.quadraticCurveTo(L+N,_+V,L+N-K,_+V),y.lineTo(L+K,_+V),y.quadraticCurveTo(L,_+V,L,_+V-K),y.lineTo(L,_+K),y.quadraticCurveTo(L,_,L+K,_),y.fill(),y.globalAlpha=1,y.shadowBlur=0,j.note.isGold&&Dh(y,L+N/2,_+V/2,Math.min(7,N/4),"#fbbf24")}for(let j=0;j<u;j++){const T=j*f,P=b-Vt,A=a[j],I=v[j]??Qr;y.fillStyle=A?I:"rgba(30,30,30,0.9)",y.fillRect(T+2,P+2,f-4,Vt-4),y.strokeStyle=A?"#fff":I,y.lineWidth=A?3:1,y.strokeRect(T+2,P+2,f-4,Vt-4),y.fillStyle=A?"#000":"#fff",y.font=`bold ${Math.min(24,f*.3)}px monospace`,y.textAlign="center",y.textBaseline="middle",y.fillText(((R=e[j])==null?void 0:R.label)??"",T+f/2,P+Vt/2);const L=((M=e[j])==null?void 0:M.gamepadButton)??-1;L>=0&&L<Vs.length&&(y.fillStyle=A?"rgba(0,0,0,0.6)":"rgba(255,255,255,0.4)",y.font="10px sans-serif",y.fillText(Vs[L],T+f/2,P+Vt-8))}for(const j of p.current){const T=n-j.time;if(T<0||T>.8)continue;const P=Math.max(0,1-T/.8),A=j.lane*f;y.save(),y.globalAlpha=P,y.font="bold 20px sans-serif",y.textAlign="center",y.textBaseline="bottom",y.fillStyle=j.type==="perfect"?"#10b981":j.type==="good"?"#f59e0b":"#ef4444";const I=j.type==="perfect"?c("padKaraokeOverlay.perfect","PERFECT"):j.type==="good"?c("padKaraokeOverlay.good","GOOD"):c("padKaraokeOverlay.miss","MISS");y.fillText(I,A+f/2,k-10-T*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(F.NtdGamepad,{size:14})," ",c("padKaraokeOverlay.pad","PAD — {difficulty}").replace("{difficulty}",String(s))]})]})},In=["var(--player-color-1, #ef4444)","var(--player-color-2, #f59e0b)","var(--player-color-3, #10b981)","var(--player-color-4, #3b82f6)","var(--player-color-5, #8b5cf6)","var(--player-color-6, #ec4899)"],qo={easy:{keys:["f","j"],buttons:[0,1],labels:["F","J"]},normal:{keys:["d","f","j","k"],buttons:[3,2,0,1],labels:["D","F","J","K"]},hard:{keys:["s","d","f","j","k","l"],buttons:[4,3,2,0,1,5],labels:["S","D","F","J","K","L"]}};function ga(e){return 440*Math.pow(2,(e-69)/12)}function Ho(e,t){const n=qo[t],a=n.keys.length,s=[];for(const 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:In[h%In.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:In[u%In.length]})}return c}function Ko(e,t){for(const s of t)if(e>=s.minPitch&&e<=s.maxPitch)return s.index;let n=0,a=1/0;for(const s of t){const i=(s.minPitch+s.maxPitch)/2,o=Math.abs(e-i);o<a&&(a=o,n=s.index)}return n}function Yo(e,t,n){const a=[];for(let s=0;s<e.length;s++)for(let i=0;i<e[s].length;i++){const o={...e[s][i]};o.startTime+=n,a.push({note:o,lane:Ko(o.pitch,t),lineIndex:s,noteIndex:i})}return a.sort((s,i)=>s.note.startTime-i.note.startTime),a}class Zo{constructor(t){this.lanes=[],this.events=[],this.raf=null,this.keysDown=new Set,this.gamepadButtonsDown=new Set,this.running=!1,this.getCurrentTime=()=>0,this.lastFeedbackTime=0,this.lastActiveNote=null,this.preWindow=.15,this.postWindow=.15,this.loop=()=>{var c,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 k=ga(o.note.pitch);this.config.onPitch(k),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(y=(g=this.config).onHitFeedback)==null||y.call(g,{type:"perfect",lane:b,time:s}))}else if(f>=0){const v=Math.abs(f-b)*3,w=ga(o.note.pitch+v);this.config.onPitch(w),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(x=(m=this.config).onHitFeedback)==null||x.call(m,{type:"miss",lane:f,time:s}))}}this.raf=requestAnimationFrame(this.loop)},this.config=t;const n=Hn(t.noteLines,t.bpm),a=(t.gap??0)/1e3;switch(this.lanes=Ho(n,t.difficulty),this.events=Yo(n,this.lanes,a),t.difficulty){case"easy":this.preWindow=.25,this.postWindow=.25;break;case"normal":this.preWindow=.15,this.postWindow=.15;break;case"hard":this.preWindow=.08,this.postWindow=.08;break}}getLanes(){return this.lanes}getEvents(){return this.events}start(t){this.running||(this.running=!0,this.getCurrentTime=t,this.handleKeyDown=this.handleKeyDown.bind(this),this.handleKeyUp=this.handleKeyUp.bind(this),window.addEventListener("keydown",this.handleKeyDown),window.addEventListener("keyup",this.handleKeyUp),this.loop())}stop(){this.running=!1,this.raf&&(cancelAnimationFrame(this.raf),this.raf=null),window.removeEventListener("keydown",this.handleKeyDown),window.removeEventListener("keyup",this.handleKeyUp),this.keysDown.clear(),this.gamepadButtonsDown.clear()}handleKeyDown(t){var a;const n=(a=t.target)==null?void 0:a.tagName;n&&["INPUT","TEXTAREA","SELECT"].includes(n)||this.keysDown.add(t.key.toLowerCase())}handleKeyUp(t){this.keysDown.delete(t.key.toLowerCase())}pollGamepad(){var a;const t=navigator.getGamepads?Array.from(navigator.getGamepads()).filter(Boolean):[];if(!t.length)return;const n=t[0];if(n){this.gamepadButtonsDown.clear();for(let s=0;s<n.buttons.length;s++)(a=n.buttons[s])!=null&&a.pressed&&this.gamepadButtonsDown.add(s)}}getActiveLanes(){const t=new Array(this.lanes.length).fill(!1);for(const n of this.lanes)(this.keysDown.has(n.key)||this.gamepadButtonsDown.has(n.gamepadButton))&&(t[n.index]=!0);return t}findActiveNote(t){for(const n of this.events){const a=n.note.startTime-this.preWindow,s=n.note.startTime+n.note.duration+this.postWindow;if(t>=a&&t<=s)return n}return null}}const ft=st.scoped("BaseStreamClient");function Us(e,t,n){if(t===n)return e.slice();const a=Math.round(e.length*n/t),s=new Float32Array(a),i=e.length/a;for(let o=0;o<a;o++){const l=o*i,c=Math.floor(l),u=Math.min(e.length-1,c+1),h=l-c;s[o]=e[c]*(1-h)+e[u]*h}return s}function Fh(e){const t=new Int16Array(e.length);for(let n=0;n<e.length;n++){const a=Math.max(-1,Math.min(1,e[n]));t[n]=a<0?Math.round(a*32768):Math.round(a*32767)}return t}const Sn=16e3,Oh="/scripts/pitch-worklet.js";class Xo{constructor(t){this.sendQueue=[],this.maxQueue=20,this.reconnectAttempts=0,this.maxReconnectAttempts=3,this.buffer=new Float32Array(0),this.externalStream=!1,this.usingWorklet=!1,this.closed=!1,this.started=!1,this.chunksSent=0,this.chunksDropped=0,this.responsesReceived=0,this.lastStatusLog=0,this.opts=t}onMaxReconnect(){var t,n;try{(n=(t=this.opts).onMaxReconnect)==null||n.call(t)}catch{}this.stopAudioNodes()}get useWorklet(){return!0}get workletPath(){return Oh}ts(){return new Date().toISOString().slice(11,23)}connectWs(){this.ws&&this.ws.readyState!==WebSocket.CLOSING&&this.ws.readyState!==WebSocket.CLOSED||(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,k,v;const n=new Float32Array(this.buffer.length+t.length);n.set(this.buffer,0),n.set(t,this.buffer.length),this.buffer=n;const a=this.audioCtx.sampleRate,s=Math.round((this.opts.chunkMs??200)*Sn/1e3),i=Math.floor(this.buffer.length*Sn/a),o=Math.floor(i/s);if(o<=0)return;const l=o*s,c=Math.floor(l*a/Sn),u=this.buffer.slice(0,c);this.buffer=this.buffer.slice(c);const h=Us(u,a,Sn);let p=0;for(;p+s<=h.length;){const w=h.subarray(p,p+s),M=Fh(w).buffer,j=this.ws;if(j&&j.readyState===WebSocket.OPEN)try{j.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 j&&j.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=(k=this.opts).onSend)==null||v.call(k,0));const T=Date.now();T-this.lastStatusLog>5e3&&(this.lastStatusLog=T,ft.info(`[${this.ts()}] STATUS: sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived} ws=${(j==null?void 0:j.readyState)??"none"} worklet=${this.usingWorklet}`)),p+=s}if(p<h.length){const w=h.subarray(p),R=Us(w,Sn,a),M=new Float32Array(R.length+this.buffer.length);M.set(R,0),M.set(this.buffer,R.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 Bh=st.scoped("CrepeStreaming");class Gh extends Xo{constructor(t){super({...t,chunkMs:t.chunkMs??200}),this.crepeOpts=t}get tag(){return"CrepeStreamClient"}handleWsMessage(t){var a,s;const n=JSON.parse(t);(s=(a=this.crepeOpts).onMessage)==null||s.call(a,n)}onMaxReconnect(){var t,n;Bh.warn(`[${this.tag}] [${this.ts()}] triggering fallback`),this.stopAudioNodes();try{(n=(t=this.crepeOpts).onFallback)==null||n.call(t)}catch{}}}class Wh extends Xo{constructor(t){super({...t,chunkMs:t.chunkMs??100}),this.librosaOpts=t}get tag(){return"LibrosaStreamClient"}handleWsMessage(t){var a,s;const n=JSON.parse(t);(s=(a=this.librosaOpts).onMessage)==null||s.call(a,n)}get useWorklet(){return!1}}const It={debug:(...e)=>{},warn:(...e)=>{typeof console<"u"&&console.warn("[KaraokePitch]",...e)}};function Vh(e){const t=new Float32Array(e);for(let n=0;n<e;n++)t[n]=.5*(1-Math.cos(2*Math.PI*n/(e-1)));return t}function Uh(e,t){const n=new Float32Array(e.length);for(let a=0;a<e.length;a++)n[a]=e[a]*t[a];return n}function Qo({isPlaying:e,gameMode:t,players:n,playersMicKey:a,micAlgorithms:s={},defaultPitchAlgorithm:i="pitchy",micRmsThresholds:o={},micOffsets:l={},micGains:c={},micPitchThresholds:u={},micSmoothingWindows:h={},micHysteresisFrames:p={},micUseHanning:g={},micMonitorEnabled:y={},micMonitorVolumes:m={},currentTimeRef:x,isPadMode:b,clockOffsetMsRef:f,currentPartyIdRef:k,rtc:v}){const[w,R]=d.useState({}),M=d.useRef({}),j=d.useRef({}),[T,P]=d.useState({}),A=d.useRef({}),I=d.useRef([]),L=d.useRef(null),N=d.useRef(null),[,_]=d.useState({}),[,ee]=d.useState({}),[,Y]=d.useState({}),[O,U]=d.useState({}),[V,K]=d.useState(!0),[G,W]=d.useState(!1),C=d.useRef(n);C.current=n;const $=d.useRef(0),S=d.useRef(performance.now());return d.useEffect(()=>{I.current.forEach(E=>E()),I.current=[];const B={current:!1};function H(E,q,X=0){x.current!==$.current&&($.current=x.current,S.current=performance.now());const re=Math.min(.25,(performance.now()-S.current)/1e3),oe=x.current+re-X/1e3;R(D=>{const J=D[E]||[];return{...D,[E]:[...J,{t:oe,hz:q}]}}),M.current[E]=(M.current[E]||[]).concat({t:oe,hz:q});const se=M.current[E];se.length>500&&(M.current[E]=se.slice(-500))}function z(E,q,X,re=.02,oe=0,se=.6,D=0,J=0,ae=0,ce=!1){let le=null,ne=null,pe=null;return(async()=>{try{le=new AudioContext;let he=le.createMediaStreamSource(q);if(D>0){const be=le.createGain();be.gain.value=D,he.connect(be),he=be}const we=le.createAnalyser();we.fftSize=2048,he.connect(we);const je=new Float32Array(we.fftSize),Ne=ce?Vh(we.fftSize):null,Ee=[];let Ye=0;if(X==="pitchy")try{const{PitchDetector:be}=await import("pitchy");pe=be.forFloat32Array(we.fftSize)}catch(be){It.warn("pitchy import failed, falling back to autocorrelation",be)}const ue=()=>{try{we.getFloatTimeDomainData(je)}catch{}const be=Ne?Uh(je,Ne):je;let Oe=0;for(let Ie=0;Ie<be.length;Ie++)Oe+=be[Ie]*be[Ie];Oe=Math.sqrt(Oe/be.length);let Me=0;if(Oe>=re)if(pe)try{const[Ie,Qe]=pe.findPitch(be,le.sampleRate);Ie>50&&Ie<3e3&&Qe>se&&(Me=Ie)}catch{}else Me=zo(be,le.sampleRate,re),(Me<50||Me>3e3)&&(Me=0);if(Me>0&&J>1&&(Ee.push(Me),Ee.length>J&&Ee.shift(),Me=Ee.reduce((Ie,Qe)=>Ie+Qe,0)/Ee.length),Me>0)Ye=0,H(E,Me,oe);else if(Ye++,ae>0&&Ye<=ae&&Ee.length>0){const Ie=Ee[Ee.length-1];Ie>0&&H(E,Ie,oe)}ne=requestAnimationFrame(ue),A.current[E]=ne};ue()}catch(me){It.warn("startLocalPitch error",me)}})(),()=>{ne&&cancelAnimationFrame(ne),le&&le.close().catch(()=>{})}}function Z(E,q,X,re=0){X==="crepe"&&N.current?(N.current.stop(),N.current=null):X==="librosa"&&L.current&&(L.current.stop(),L.current=null);const oe=window.location,se=oe.protocol==="https:"?"wss:":"ws:",D=X==="librosa"?`${se}//${oe.host}/api/librosa/ws/pyin`:`${se}//${oe.host}/api/ai/audio/pitch/ws/pitch_server`,J=X==="librosa"?_:ee;J(pe=>({...pe,[E]:"connecting"}));const ae=[],ce=pe=>{if(pe>0){for(ae.push(x.current);ae.length>200;)ae.shift();X==="crepe"&&Y(fe=>({...fe,[E]:(fe[E]||0)+1}))}},le=()=>{J(pe=>({...pe,[E]:"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;R(we=>{const je=we[E]||[];return{...we,[E]:[...je,{t:he,hz:fe}]}})}else ae.length>0&&ae.shift()};if(X==="librosa"){const pe=new Wh({wsUrl:D,onOpen:()=>J(fe=>({...fe,[E]:"connected"})),onClose:le,onError:fe=>{J(me=>({...me,[E]:"error"})),It.warn("Librosa WS error",fe)},onMessage:ne,onSend:ce});return L.current=pe,pe.startWithMediaStream(q).catch(fe=>{It.warn("Librosa client start failed",fe),J(me=>({...me,[E]:"failed"}))}),()=>{pe.stop(),L.current=null,J(fe=>({...fe,[E]:""}))}}else{const pe=new Gh({wsUrl:D,onOpen:()=>J(fe=>({...fe,[E]:"connected"})),onClose:le,onError:fe=>{J(me=>({...me,[E]:"error"})),It.warn("Crepe WS error",fe)},onMessage:ne,onSend:ce,onFallback:()=>{J(me=>({...me,[E]:"fallback-pitchy"})),N.current=null;const fe=z(E,q,"pitchy",.02,re);I.current.push(fe)}});return N.current=pe,pe.startWithMediaStream(q).catch(fe=>{It.warn("Crepe client start failed",fe),J(me=>({...me,[E]:"failed"}))}),()=>{pe.stop(),N.current=null,J(fe=>({...fe,[E]:""}))}}}if(e){if(R({}),t!=="pad"){const E={};C.current.forEach(q=>{if(!q.micId)return;const X=s[q.id]||i,re=q.micId&&o[q.micId]||.02,oe=q.micId&&l[q.micId]||0,se=q.micId&&c[q.micId]||0,D=q.micId&&u[q.micId]||.6,J=q.micId&&h[q.micId]||0,ae=q.micId&&p[q.micId]||0,ce=q.micId&&g[q.micId]||!1,le=q.micId&&y[q.micId]||!1,ne=(q.micId?m[q.micId]:void 0)??100,pe=new La;pe.startRecording({deviceId:q.micId,onLevel:()=>{},gain:se,monitorEnabled:le,monitorVolume:ne}).then(()=>{if(B.current){pe.stopRecording().catch(()=>{});return}E[q.id]=pe;const fe=pe.getStream();if(!fe){It.warn(`No stream from recorder for player ${q.id}`);return}if(X==="librosa"||X==="crepe"){const me=Z(q.id,fe,X,oe);I.current.push(me)}else{const me=z(q.id,fe,X,re,oe,D,se,J,ae,ce);I.current.push(me)}}).catch(fe=>It.warn(`recorder start failed for player ${q.id}`,fe))}),j.current=E}}else{const E=j.current,q=Object.keys(E).map(Number);Promise.allSettled(q.map(async X=>{const re=await E[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}))}),j.current={},Object.values(A.current).forEach(X=>X&&cancelAnimationFrame(X)),A.current={}}return()=>{B.current=!0,I.current.forEach(E=>E()),I.current=[],Object.values(j.current).forEach(E=>E.stopRecording().catch(()=>{})),j.current={},Object.values(A.current).forEach(E=>E&&cancelAnimationFrame(E)),A.current={}}},[e,t,a,s,i,o,l,c,u,h,p,g,y,m]),d.useEffect(()=>{if(!v)return;const B=300,H=async()=>{try{const Z={...M.current};for(const E of Object.keys(Z)){const q=Number(E),X=Z[q]||[];if(!X||X.length===0)continue;M.current[q]=[];const re=Fo(X,120),oe={playerId:q,points:re,clientNowUtc:new Date().toISOString(),quantized:!0};k!=null&&k.current&&(oe.EventId=k.current);try{v.isConnected()&&await v.publishTimelineUpdate(oe)}catch(se){It.warn("failed to publish timeline update, will retry",se),M.current[q]=(M.current[q]||[]).concat(X).slice(-1e3)}}}catch{}},z=window.setInterval(H,B);return()=>{z&&window.clearInterval(z)}},[v,k]),d.useEffect(()=>{if(!v)return;const B=H=>{try{const z=H;if(!z||typeof z.playerId>"u"||!Array.isArray(z.points))return;const Z=Number(z.playerId),E=z.points.map(q=>({t:q.t,hz:q.hz}));if(!E.length)return;if(z.serverTimeUtc){const q=Oo(z.serverTimeUtc,Date.now(),(f==null?void 0:f.current)||0);U(X=>({...X,[Z]:q}))}R(q=>{const X=q[Z]||[];return{...q,[Z]:[...X,...E]}})}catch{}};return v.onTimelineUpdate(B),()=>v.offTimelineUpdate(B)},[v,f]),{livePitch:w,setLivePitch:R,recordings:T,recordersRef:j,unsentPitchRef:M,pitchCleanupsRef:I,remoteLatencyMs:O,showRemoteTimelines:V,setShowRemoteTimelines:K,compactTimelines:G,setCompactTimelines:W}}function Jo(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function el(e){return e>=50?3:e>=30?2.5:e>=20?2:e>=10?1.5:1}function tl(e,t,n){const{semitoneTolerance:a,preWindow:s,postExtra:i}=n,o=n.segMs??.25,l=typeof n.completionBonusFactor=="number"?n.completionBonusFactor:.15,c=typeof n.goldFullBonusFactor=="number"?n.goldFullBonusFactor:.3,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 k=new Map;e.forEach((P,A)=>{const I=P.startTime,L=P.startTime+P.duration,N=I-s,_=L+i,ee=t.filter(C=>C.t>=N&&C.t<=_&&C.hz>0);if(!ee||ee.length===0)return;const Y=Math.max(1,Math.ceil((P.duration||.25)/o)),O=Math.max(10,Math.round(100*(P.duration||1))),U=Math.max(1,Math.round(O/Y));let V=0;const K=[];for(let C=0;C<Y;C++){const $=I+C*(P.duration/Y),S=I+(C+1)*(P.duration/Y),B=Math.min(.06,P.duration/Y*.2),H=$-B,z=S+B,Z=t.filter(se=>se.t>=H&&se.t<=z&&se.hz>0);if(!Z||Z.length===0)continue;let E=0;Z.forEach(se=>{let J=((12*Math.log2(se.hz/440)+69)%12+12)%12;for(;J-P.pitch>6;)J-=12;for(;J-P.pitch<-6;)J+=12;const ae=Math.abs(J-P.pitch);E+=ae});const q=E/Z.length;let X=0;if(a<=0)X=q===0?1:0;else{const se=a*2;X=Math.max(0,1-Math.min(q/se,1))}if(X<=0)continue;const re=!h&&P.isGold?2:1,oe=Math.round(U*re*X);oe>0&&(p+=oe,V+=oe,K.push({segIndex:C,frac:X,add:oe,segStart:H,segEnd:z,visualStart:$,visualEnd:S}))}const G=P.line??0;k.has(G)||k.set(G,{total:0,hit:0,comboBonus:0});const W=k.get(G);if(W.total++,V>0){x++,x>b&&(b=x),W.hit++;const C=el(x),$=C>1?Math.round(V*(C-1)):0;f+=$,W.comboBonus+=$;const S=Math.max(1,Math.ceil((P.duration||.25)/o)),H=K.length>=S,z=H?Math.round(Math.max(10,Math.round(100*(P.duration||1)))*l*(!h&&P.isGold?1.5:1)*u):0,Z=H&&!h&&P.isGold?Math.round(Math.max(10,Math.round(100*(P.duration||1)))*c*u):0;g+=z,y+=Z,m.push({noteKey:`${P.line??0}-${P.idx??0}`,segments:K,totalAdded:V,completed:H,completionBonus:z,goldFullBonus:Z})}else x=0});const v=[];for(const[P,A]of k.entries()){const I=A.total>0?A.hit/A.total:0;v.push({verseIndex:P,hitFraction:I,label:Jo(I),comboBonus:A.comboBonus})}const w={maxCombo:b,currentCombo:0,totalComboBonus:f},R=f+g+y,M=m.length,j=m.filter(P=>P.completed).length,T={hits:M,misses:e.length-M,good:M-j,perfect:j,maxCombo:b};return{classicScore:p,bonusScore:R,totalScore:p+R,perNote:m,combo:w,verseRatings:v,noteStats:T}}function nl(e,t){let n=0;for(const a of e){const s=Math.max(10,Math.round(100*(a.duration||1))),i=!t&&a.isGold?2:1;n+=s*i}return n}function rl(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function al(e,t,n){const a=nl(t,n);if(a<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0};const s=rl(e.classicScore,a),i=Math.round(e.bonusScore/a*1e4);return{...e,classicScore:s,bonusScore:i,totalScore:s+i}}const kn={maxCombo:0,currentCombo:0,totalComboBonus:0},qs={hits:0,misses:0,good:0,perfect:0,maxCombo:0};function sl({livePitch:e,uploadedSong:t,isPlaying:n,difficulty:a,players:s,isPadMode:i}){const[o,l]=d.useState(0),[c,u]=d.useState(0),[h,p]=d.useState(0),[g,y]=d.useState([]),[m,x]=d.useState(kn),[b,f]=d.useState([]),[k,v]=d.useState([]),[w,R]=d.useState({}),[M,j]=d.useState({}),[T,P]=d.useState({}),[A,I]=d.useState({}),[L,N]=d.useState({});return d.useEffect(()=>{if(!t||!n)return;const _=Hn(t.notes.map(Z=>Z.noteLine),t.bpm??void 0),ee=(t.gap??0)/1e3,Y=Ka(_,ee),O=zr(a),U=[];let V=null,K=null,G=null,W=[];const C={},$={},S={},B={},H={},z=i?s[0]:s.find(Z=>!!Z.micId)||s[0];for(let Z=0;Z<s.length;Z++){const E=s[Z],q=(E==null?void 0:E.id)!=null?e[E.id]||[]:[];if(q.length===0){U.push({id:E.id,name:E.name||`Player ${E.id}`,color:E.color||Xe[Z%Xe.length],classicScore:0,bonusScore:0,totalScore:0}),C[E.id]=[],$[E.id]={...kn},S[E.id]=[],B[E.id]=0,H[E.id]={...qs};continue}const X=Ua(E.id),re=!!(X!=null&&X.disableGoldNotes),oe=tl(Y,q,{semitoneTolerance:O.semitoneTolerance,preWindow:O.preWindow,postExtra:O.postExtra,difficultyMult:O.difficultyMult,disableGoldNotes:re}),se=al(oe,Y,re);U.push({id:E.id,name:E.name||`Player ${E.id}`,color:E.color||Xe[Z%Xe.length],classicScore:se.classicScore,bonusScore:se.bonusScore,totalScore:se.totalScore}),C[E.id]=Do(oe.perNote,_,ee),$[E.id]=oe.combo??{...kn},S[E.id]=oe.verseRatings??[],B[E.id]=se.totalScore,H[E.id]=oe.noteStats??{...qs},E.id===(z==null?void 0:z.id)&&(V=se,K=oe.combo??null,G=oe.verseRatings??null,W=C[E.id])}v(U),R(C),j($),P(S),I(B),N(H),V?(l(V.classicScore),u(V.bonusScore),p(V.totalScore),y(W),x(K??kn),f(G??[])):(l(0),u(0),p(0),y([]),x(kn),f([]))},[e,t,n,a,s,i]),{liveScore:o,liveBonusScore:c,liveTotalScore:h,liveSegmentScores:g,liveCombo:m,liveVerseRatings:b,perPlayerScores:k,perPlayerSegmentScores:w,perPlayerCombo:M,perPlayerVerseRatings:T,perPlayerTotalScores:A,perPlayerNoteStats:L}}const qh=[],Hh=e=>!!e&&/youtu(\.be|be\.com)/i.test(e),Kh=({players:e=qh,song:t,initialSong:n=null,difficulty:a="normal",gameMode:s="normal",height:i=480,showTimelines:o=!0,showLyrics:l=!0,singleTimeline:c=!1,requestMicPermission:u=!0,initiallyActivated:h=!1,showUploader:p=!1,parseSong:g,micAlgorithms:y,defaultPitchAlgorithm:m="pitchy",micRmsThresholds:x,micOffsets:b,micGains:f,micPitchThresholds:k,micSmoothingWindows:v,micHysteresisFrames:w,micUseHanning:R,micMonitorEnabled:M,micMonitorVolumes:j,searchYouTubeByArtistTitle:T,fetchTopSingings:P,onSaveResults:A,rtc:I,onSongChange:L,onPlayingChange:N,onTimeUpdate:_,onEnded:ee,onContinue:Y,renderReport:O,t:U,className:V,style:K,id:G,accessMode:W,"data-testid":C})=>{var _e;const{t:$}=xe(),S=U??$,[B,H]=d.useState(t??n??null),[z,Z]=d.useState(!1),[E,q]=d.useState(0),[X,re]=d.useState(h),[oe,se]=d.useState(!1),[D,J]=d.useState([]),[ae,ce]=d.useState(""),[le,ne]=d.useState(null),[pe,fe]=d.useState(0),me=s==="pad",[he,we]=d.useState([]),[je,Ne]=d.useState([]),[Ee,Ye]=d.useState([]),[ue,be]=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=E},[E]);const He=d.useRef(t);d.useEffect(()=>{t!==void 0&&t!==He.current&&(He.current=t,H(t),se(!1),q(0),fe(ve=>ve+1))},[t]);const Lt=d.useMemo(()=>JSON.stringify(e.map(ve=>({id:ve.id,micId:ve.micId}))),[e]),{livePitch:ct,setLivePitch:ht,recordings:it,remoteLatencyMs:wt}=Qo({isPlaying:z,gameMode:s,players:e,playersMicKey:Lt,micAlgorithms:y,defaultPitchAlgorithm:m,micRmsThresholds:x,micOffsets:b,micGains:f,micPitchThresholds:k,micSmoothingWindows:v,micHysteresisFrames:w,micUseHanning:R,micMonitorEnabled:M,micMonitorVolumes:j,currentTimeRef:Be,isPadMode:me,rtc:I}),Je=sl({livePitch:ct,uploadedSong:B,isPlaying:z,difficulty:a,players:e,isPadMode:me}),Pt=d.useRef(Je);Pt.current=Je;const Xt=d.useMemo(()=>B?Go(B,s):null,[B,s]),Se=((_e=e[0])==null?void 0:_e.id)??1;d.useEffect(()=>{var Re;if(!me||!z||!B){(Re=Oe.current)==null||Re.stop(),Oe.current=null,we([]),Ne([]),Ye([]),be([]);return}const ve=new Zo({difficulty:a,noteLines:B.notes.map(Le=>Le.noteLine),bpm:B.bpm??void 0,gap:B.gap??0,onPitch:Le=>{const Ge=Be.current;ht(De=>{const tt=De[Se]||[];return{...De,[Se]:[...tt,{t:Ge,hz:Le}]}})},onHitFeedback:Le=>be(Ge=>[...Ge.slice(-20),Le]),onLaneActive:Le=>Ye(Le)});return we(ve.getLanes()),Ne(ve.getEvents()),Ye(new Array(ve.getLanes().length).fill(!1)),ve.start(()=>Be.current),Oe.current=ve,()=>{ve.stop(),Oe.current=null}},[me,z,B,a,Se,ht]);const Ce=d.useCallback(ve=>{Z(ve),N==null||N(ve)},[N]),We=d.useCallback(ve=>{q(ve),_==null||_(ve)},[_]),ze=d.useCallback(()=>{var Re;try{Yt()}catch{}const ve=()=>{re(!0),Qe.current=!0};!me&&u&&((Re=navigator.mediaDevices)!=null&&Re.getUserMedia)?navigator.mediaDevices.getUserMedia({audio:!0}).then(Le=>Le.getTracks().forEach(Ge=>Ge.stop())).catch(()=>{}).finally(ve):ve()},[me,u]);d.useEffect(()=>{if(!X||!Qe.current)return;Qe.current=!1;const ve=window.setInterval(()=>{Me.current&&(window.clearInterval(ve),Me.current.play())},100),Re=window.setTimeout(()=>window.clearInterval(ve),3e3);return()=>{window.clearInterval(ve),window.clearTimeout(Re)}},[X]);const $e=d.useCallback(()=>{se(!0),ee==null||ee();const ve=(B==null?void 0:B.id)??0,Re=Pt.current,Le=[];for(const De of e){const tt=Re.perPlayerTotalScores[De.id]??0;if(tt<=0)continue;const Ke=Re.perPlayerNoteStats[De.id];Le.push({playerId:De.id,songId:ve,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&&ve>0&&Promise.resolve(P(ve)).then(J).catch(()=>{})};A&&Le.length>0?Promise.resolve(A(Le)).then(Ge).catch(Ge):Ge()},[e,B,A,P,ee]);d.useEffect(()=>{var ve;s==="demo"&&z&&E>=12&&((ve=Me.current)==null||ve.pause(),$e())},[s,z,E,$e]),d.useEffect(()=>{if(!B||pe===0||!T||Hh(B.videoPath))return;if(B.youtubeId){const Re=`https://www.youtube.com/watch?v=${B.youtubeId}`;H(Le=>Le&&{...Le,videoPath:Re});return}if(!B.artist||!B.title)return;let ve=!1;return ce(S("karaokeManager.ytSearching","Searching YouTube…")),ne("searching"),Promise.resolve(T(B.artist,B.title)).then(Re=>{if(!ve)if(Re){const Le=`https://www.youtube.com/watch?v=${Re}`;H(Ge=>Ge&&{...Ge,videoPath:Le}),ce(""),ne(null)}else ce(S("karaokeManager.ytNotFound","Not found on YouTube")),ne("error"),window.setTimeout(()=>{ve||(ce(""),ne(null))},4e3)}).catch(()=>{ve||(ce(S("karaokeManager.ytSearchError","Search error")),ne("error"))}),()=>{ve=!0}},[pe,B,T,S]);const Pe=d.useCallback(()=>{var ve,Re;se(!1),ht({}),(ve=Me.current)==null||ve.seekTo(0),(Re=Me.current)==null||Re.play()},[ht]),de=d.useCallback(()=>{se(!1),Y==null||Y()},[Y]),ge=d.useCallback(ve=>{H(ve),se(!1),q(0),fe(Re=>Re+1),L==null||L(ve)},[L]),Ae=d.useMemo(()=>{if(!c)return e;const ve=e.find(Re=>!!Re.micId)||e[0];return ve?[ve]:[]},[e,c]),Te=((B==null?void 0:B.gap)??0)/1e3;return W==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-manager${V?` ${V}`:""}`,style:{position:"relative",textAlign:"center",minHeight:i,...K},id:G,"data-testid":C,children:[ae&&r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,margin:"10px auto",padding:"8px 16px",maxWidth:420,borderRadius:8,fontSize:14,fontWeight:500,background:"var(--nice-accent, #3b82f6)",color:"var(--nice-text-on-primary, #fff)"},children:[le==="error"?r.jsx(F.NtdClose,{size:16}):r.jsx(F.NtdSearch,{size:16}),ae]}),!B&&p&&r.jsx(Vo,{onSongUpload:ge,parseSong:g,t:S}),B&&!X&&r.jsxs("button",{type:"button",className:"nice-karaoke-manager__activate",onClick:ze,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:me?r.jsx(F.NtdGamepad,{size:56}):r.jsx(F.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:me?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.")})]}),B&&r.jsxs("div",{ref:Ie,style:{position:"relative",width:"100%",maxWidth:1200,margin:"0 auto"},children:[r.jsx("div",{style:{width:"100%",position:"relative",zIndex:10},children:r.jsx(Io,{tracks:Xt?[Xt]:[],autoPlay:!1,uiMode:"nobuttons",height:i,externalRef:Me,onPlayingChange:Ce,onTimeUpdate:We,onEnded:$e})}),o&&X&&r.jsx("div",{style:{position:"absolute",inset:0,zIndex:20,pointerEvents:"none"},children:Ae.map((ve,Re)=>{const Le=ct[ve.id]||[],Ge=Te?Le.map(De=>({t:De.t-Te,hz:De.hz})):Le;return r.jsx(To,{song:B,currentTime:E,playerRef:Ie,userPitch:Ge,segmentScores:Je.perPlayerSegmentScores[ve.id],combo:Je.perPlayerCombo[ve.id],verseRatings:Je.perPlayerVerseRatings[ve.id],config:{playerName:ve.name,score:Je.perPlayerTotalScores[ve.id]??0,playerBgColor:ve.color||Xe[Re%Xe.length],difficultyLevel:a,isPlaying:z,playerCount:Ae.length,latencyMs:wt[ve.id]??null,top:30+Re*160}},ve.id)})}),me&&he.length>0&&r.jsx(Uo,{lanes:he,events:je,currentTime:E,activeLanes:Ee,difficulty:a,feedbackQueue:ue,isPlaying:z}),l&&X&&r.jsx("div",{style:{position:"absolute",bottom:20,left:0,right:0,zIndex:25,pointerEvents:"none"},children:r.jsx(po,{song:B,currentTime:E})})]}),oe&&Object.keys(it).length>0&&r.jsx(Yh,{recordings:it,players:e,t:S}),oe&&r.jsx($o,{uploadedSong:B,playerScores:Je.perPlayerScores,topSingings:D,onRestart:Pe,onContinue:de,t:S,renderReport:O})]})},Yh=({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(F.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(F.NtdDownload,{size:13})," ",n("karaokeManager.download","Download")]})]}):r.jsx("span",{style:{opacity:.6},children:n("karaokeManager.noRecording","No recording")})]},s.id))})]})},il=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function on(e){return 12*Math.log2(e/440)+69}function Jn(e){const t=il[Math.round(e)%12],n=Math.floor(Math.round(e)/12)-1;return`${t}${n}`}function Jr(e,t){const n=e-t;return n-12*Math.round(n/12)}function er(e,t){if(e.length===0)return 0;const n=t/100*(e.length-1),a=Math.floor(n),s=Math.ceil(n);return a===s?e[a]:e[a]+(e[s]-e[a])*(n-a)}function ol(e){const{playerName:t,playerColor:n,songTitle:a,songArtist:s,songBpm:i,difficulty:o,pitchPoints:l,notes:c,verseRatings:u,combo:h,classicScore:p,bonusScore:g,totalScore:y,micSettings:m}=e,x=l.filter(ue=>ue.hz>0),b=x.map(ue=>on(ue.hz)),f=[],k=[],v=[...c].sort((ue,be)=>ue.startTime-be.startTime);function w(ue){let be=0,Oe=v.length-1;for(;be<=Oe;){const Me=be+Oe>>>1,Ie=v[Me];if(ue<Ie.startTime)Oe=Me-1;else if(ue>Ie.startTime+Ie.duration)be=Me+1;else return Ie.pitch}return null}const R=[];for(const ue of l){const be=ue.hz>0?on(ue.hz):0,Oe=w(ue.t);R.push({t:ue.t,sung:be,expected:Oe}),be>0&&Oe!==null&&f.push(Jr(be,Oe)*100)}const M=R.flatMap(ue=>ue.sung>0&&ue.expected!==null?[ue.sung-ue.expected]:[]).sort((ue,be)=>ue-be),j=M.length>0?12*Math.round(er(M,50)/12):0,T=R.map(ue=>({t:ue.t,sung:ue.sung,expected:ue.expected===null?0:ue.expected+j}));let P=0;for(const ue of v){const be=ue.startTime-.3,Oe=ue.startTime+ue.duration;for(;P<x.length&&x[P].t<be;)P++;P<x.length&&x[P].t<=Oe&&k.push((x[P].t-ue.startTime)*1e3)}const A=f.map(Math.abs),I=[...A].sort((ue,be)=>ue-be),L=A.length>0?A.reduce((ue,be)=>ue+be,0)/A.length:0,N=er(I,50),_=A.length>1?Math.sqrt(A.reduce((ue,be)=>ue+(be-L)**2,0)/(A.length-1)):0,ee=A.filter(ue=>ue<=50).length,Y=A.filter(ue=>ue<=15).length,O=A.length>0?ee/A.length*100:0,U=A.length>0?Y/A.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 be=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[be]++}const G=V.map((ue,be)=>({centRange:ue,count:K[be],pct:f.length>0?K[be]/f.length*100:0})),W=x.map(ue=>ue.hz).sort((ue,be)=>ue-be),C=W.length>0?W[0]:0,$=W.length>0?W[W.length-1]:0,S=C>0?on(C):0,B=$>0?on($):0,H=B-S,z=[...b].sort((ue,be)=>ue-be),Z=er(z,10),E=er(z,90),q=new Array(12).fill(0);for(const ue of b){const be=Math.round(ue)%12;be>=0&&be<12&&q[be]++}const X=q.reduce((ue,be)=>ue+be,0),re=il.map((ue,be)=>({note:ue,count:q[be],pct:X>0?q[be]/X*100:0})),oe=Zh(x),se=k.length>0?k.reduce((ue,be)=>ue+be,0)/k.length:0,D=k.length>1?Math.sqrt(k.reduce((ue,be)=>ue+(be-se)**2,0)/(k.length-1)):0,J=D>0?Math.max(0,Math.min(100,100-D/2)):100;let ae=0,ce=0;for(let ue=1;ue<b.length;ue++){const be=Math.abs(b[ue]-b[ue-1]);ae+=be,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 be=ue.line??0;fe.has(be)||fe.set(be,[]),fe.get(be).push(ue)}const me=new Map;for(const ue of x){const be=w(ue.t);if(be===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(Jr(on(ue.hz),be)*100);me.has(Ie)||me.set(Ie,[]),me.get(Ie).push(Qe)}const he=u.map(ue=>{const be=fe.get(ue.verseIndex)??[],Oe=me.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:be.length,notesHit:Math.round(ue.hitFraction*be.length),comboBonus:ue.comboBonus}}),we=2,je=.5,Ne=l.length>0?l[l.length-1].t:0,Ee=[],Ye=R.flatMap(ue=>ue.sung>0&&ue.expected!==null?[{t:ue.t,hit:Math.abs(Jr(ue.sung,ue.expected))<=.5}]:[]);if(Ye.length>0){let ue=0,be=0,Oe=0;for(let Me=0;Me<=Ne;Me+=je){const Ie=Me-we/2,Qe=Me+we/2;for(;be<Ye.length&&Ye[be].t<Qe;)Ye[be].hit&&Oe++,be++;for(;ue<be&&Ye[ue].t<Ie;)Ye[ue].hit&&Oe--,ue++;const Be=be-ue;Ee.push({t:Me,accuracy:Be>0?Oe/Be*100:0})}}else for(let ue=0;ue<=Ne;ue+=je)Ee.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(N*10)/10,stdDevCents:Math.round(_*10)/10,intonationAccuracyPct:Math.round(O*10)/10,perfectHitPct:Math.round(U*10)/10,pitchDeviationHistogram:G,lowestHz:Math.round(C*10)/10,highestHz:Math.round($*10)/10,lowestNote:S>0?Jn(S):"—",highestNote:B>0?Jn(B):"—",rangeInSemitones:Math.round(H*10)/10,tessituraLow:Z>0?Jn(Z):"—",tessituraHigh:E>0?Jn(E):"—",pitchClassDistribution:re,vibrato:oe,avgOnsetDeviationMs:Math.round(se*10)/10,rhythmStabilityPct:Math.round(J*10)/10,jitterPct:Math.round(le*100)/100,shimmerProxy:Math.round(pe*10)/10,verseMetrics:he,micSettings:m,pitchOverTime:T,accuracyOverTime:Ee}}function Zh(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(y=>on(y.hz)),n=e.map(y=>y.t),a=.5,s=[],i=[];let o=0,l=0,c=0;for(let y=0;y<e.length;y++){for(l+=t[y],c++;o<y&&n[y]-n[o]>=a;)l-=t[o],c--,o++;if(c<6||(y-o)%10!==0)continue;const m=l/c;let x=0,b=t[o]-m,f=Math.abs(b);for(let w=o+1;w<=y;w++){const R=t[w]-m;R*b<0&&x++,b=R;const M=Math.abs(R);M>f&&(f=M)}const k=n[y]-n[o];if(k<=0)continue;const v=x/2/k;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 Q={overlay:{position:"fixed",inset:0,background:"var(--nice-overlay-90, rgba(0,0,0,0.92))",display:"flex",alignItems:"flex-start",justifyContent:"center",zIndex:250,color:"var(--nice-text, #e2e8f0)",overflowY:"auto",padding:"24px 12px"},container:{background:"var(--nice-bg, #0f172a)",borderRadius:16,padding:32,width:"min(960px, 95vw)",boxShadow:"0 16px 48px var(--nice-overlay-60, rgba(0,0,0,0.6))",fontFamily:"'Segoe UI', system-ui, -apple-system, sans-serif"},header:{textAlign:"center",marginBottom:24,borderBottom:"2px solid var(--nice-border, #334155)",paddingBottom:20},title:{fontSize:28,fontWeight:800,color:"var(--nice-text, #f1f5f9)",margin:"0 0 4px"},subtitle:{fontSize:14,color:"var(--nice-text-muted, #64748b)",margin:0},sectionTitle:{fontSize:18,fontWeight:700,color:"var(--nice-accent, #38bdf8)",margin:"28px 0 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",paddingBottom:6,display:"flex",alignItems:"center",gap:8},table:{width:"100%",borderCollapse:"collapse",fontSize:13,margin:"8px 0"},th:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"left",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},thRight:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"right",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},td:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-secondary, #cbd5e1)"},tdRight:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",textAlign:"right",color:"var(--nice-text, #e2e8f0)",fontWeight:500},tdBold:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text, #f1f5f9)",fontWeight:700},kpiGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:12,margin:"12px 0"},kpiCard:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:"14px 16px",textAlign:"center",border:"1px solid var(--nice-border, #334155)"},kpiValue:{fontSize:26,fontWeight:800,color:"var(--nice-warning, #fbbf24)"},kpiLabel:{fontSize:11,color:"var(--nice-text-muted, #64748b)",marginTop:2,textTransform:"uppercase",letterSpacing:.8},kpiUnit:{fontSize:13,fontWeight:400,color:"var(--nice-text-muted, #94a3b8)",marginLeft:2},chartWrap:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:16,margin:"12px 0",border:"1px solid var(--nice-border, #334155)"},chartTitle:{fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:8,textAlign:"center"},badge:e=>({display:"inline-block",padding:"2px 10px",borderRadius:20,background:e,color:"#fff",fontSize:12,fontWeight:700}),btnPrimary:{background:"var(--nice-info, #3b82f6)",color:"#fff",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:700,cursor:"pointer"},btnSecondary:{background:"var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:600,cursor:"pointer"},row:{display:"flex",gap:16,flexWrap:"wrap"},half:{flex:"1 1 45%",minWidth:280},footer:{textAlign:"center",marginTop:24,paddingTop:16,borderTop:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #475569)",fontSize:11}};function mt(e){return e>=90?"#22c55e":e>=70?"#84cc16":e>=50?"#eab308":e>=30?"#f97316":"#ef4444"}function Hs(e){switch(e){case"Perfect":return"#22c55e";case"Great":return"#84cc16";case"Good":return"#eab308";case"OK":return"#f97316";default:return"#ef4444"}}function Xh(e){return e.includes("−15 to 0")||e.includes("0 to +15")?"var(--nice-success, #22c55e)":e.includes("25")?"var(--nice-warning, #eab308)":"var(--nice-danger, #ef4444)"}const Ut=e=>Math.round(e*10)/10;function Ks(e,t,n){return e.map((a,s)=>({name:a,color:n[s],data:t.map((i,o)=>o===s?Ut(i):0)}))}function Ys(e,t){if(e.length<=t)return e;const n=Math.ceil(e.length/t);return e.filter((a,s)=>s%n===0)}function Zs(e){const t=e.length>1?e[e.length-1]-e[0]:0,n=[1,2,5,10,15,30,60,120,300].find(s=>t/s<=10)??600;let a=Math.ceil((e[0]??0)/n)*n;return e.map(s=>{if(s+1e-9<a)return"";for(;a<=s+1e-9;)a+=n;return`${Math.round(s)}s`})}const Xs=240,Qh=({reports:e,noteCount:t,uploadedSong:n=null,playerScores:a,livePitch:s,liveVerseRatings:i,liveCombo:o,difficulty:l="normal",micSettings:c,onClose:u,t:h,className:p,style:g,id:y,accessMode:m,"data-testid":x})=>{const{t:b}=xe(),f=h??b,k=d.useRef(null),v=d.useMemo(()=>{if(e||!n)return[];const S=Hn(n.notes.map(H=>H.noteLine),n.bpm??void 0),B=(n.gap??0)/1e3;return Ka(S,B)},[e,n]),w=d.useMemo(()=>e||(!n||!a||!o?[]:a.map(S=>{const B=(s==null?void 0:s[S.id])||[];return ol({playerName:S.name,playerColor:S.color,songTitle:n.title,songArtist:n.artist,songBpm:n.bpm??0,difficulty:l,pitchPoints:B,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]),R=d.useCallback(()=>{var Z,E;if(!k.current)return;const S=`<!DOCTYPE html>
|
|
48
48
|
<html lang="en"><head><meta charset="utf-8">
|
|
49
|
-
<title>Vocal Performance Report — ${((
|
|
49
|
+
<title>Vocal Performance Report — ${((Z=w[0])==null?void 0:Z.songTitle)??"Karaoke"}</title>
|
|
50
50
|
<style>
|
|
51
51
|
body{margin:0;padding:24px;background:var(--nice-bg, #0f172a);color:var(--nice-text, #e2e8f0);font-family:'Segoe UI',system-ui,sans-serif}
|
|
52
52
|
table{border-collapse:collapse;width:100%}th,td{padding:6px 10px;border-bottom:1px solid var(--nice-bg-secondary, #1e293b);text-align:left}
|
|
@@ -56,19 +56,19 @@ th{background:var(--nice-bg-secondary, #1e293b);color:var(--nice-text-muted, #94
|
|
|
56
56
|
.nice-chart__grid-line,.nice-chart__axis{stroke:var(--nice-border, #334155)}.nice-chart__axis-label,.nice-chart__legend-text{fill:var(--nice-text-muted, #94a3b8);font-size:11px}
|
|
57
57
|
@media print{body{background:#fff;color:#000}th{background:var(--nice-bg-secondary, #f0f0f0);color:var(--nice-text-muted, #333)}td{color:var(--nice-text-muted, #333);border-color:var(--nice-border, #ddd)}}
|
|
58
58
|
</style></head><body>
|
|
59
|
-
${
|
|
60
|
-
</body></html>`,
|
|
59
|
+
${k.current.innerHTML}
|
|
60
|
+
</body></html>`,B=new Blob([S],{type:"text/html"}),H=URL.createObjectURL(B),z=document.createElement("a");z.href=H,z.download=`vocal-report-${(((E=w[0])==null?void 0:E.songTitle)??"karaoke").replace(/[^a-z0-9]/gi,"_")}.html`,z.click(),URL.revokeObjectURL(H)},[w]),M=d.useCallback(()=>window.print(),[]),j=d.useCallback(()=>{var Z;const S=JSON.stringify(w,null,2),B=new Blob([S],{type:"application/json"}),H=URL.createObjectURL(B),z=document.createElement("a");z.href=H,z.download=`vocal-data-${(((Z=w[0])==null?void 0:Z.songTitle)??"karaoke").replace(/[^a-z0-9]/gi,"_")}.json`,z.click(),URL.revokeObjectURL(H)},[w]);if(m==="hidden")return null;if(w.length===0)return r.jsx("div",{className:p,style:{...Q.overlay,...g},id:y,"data-testid":x,onClick:S=>S.target===S.currentTarget&&(u==null?void 0:u()),onKeyDown:S=>S.key==="Escape"&&(u==null?void 0:u()),children:r.jsxs("div",{style:{...Q.container,textAlign:"center"},children:[r.jsxs("div",{style:Q.header,children:[r.jsxs("h2",{style:Q.title,children:[r.jsx(F.NtdBarChart,{size:24})," ",f("karaoke.report.title","Vocal Performance Report")]}),r.jsx("p",{style:Q.subtitle,children:f("karaoke.report.empty","No performance data yet — sing a song to see the report.")})]}),u&&r.jsxs("button",{style:Q.btnSecondary,onClick:u,children:[r.jsx(F.NtdClose,{size:16})," ",f("common.close","Close")]})]})});const T=w[0],P=t??v.length,A=zr(l),I=T.intonationAccuracyPct*.3+T.perfectHitPct*.2+T.rhythmStabilityPct*.15+T.shimmerProxy*.1+Math.min(100,T.maxCombo/Math.max(P,1)*100)*.1+Math.min(100,T.totalScore/1e4*100)*.15,L=I>=95?"A+":I>=90?"A":I>=85?"A−":I>=80?"B+":I>=75?"B":I>=70?"B−":I>=65?"C+":I>=60?"C":I>=55?"C−":I>=50?"D+":I>=45?"D":I>=40?"D−":"F",N={"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 _=0;const ee=[{metric:f("vocalReport.radarIntonation","Intonation"),value:T.intonationAccuracyPct,max:100},{metric:f("vocalReport.radarPerfectHits","Perfect hits"),value:T.perfectHitPct,max:100},{metric:f("vocalReport.radarRhythm","Rhythm"),value:T.rhythmStabilityPct,max:100},{metric:f("vocalReport.radarVocalRange","Range"),value:Math.min(100,T.rangeInSemitones/24*100),max:100},{metric:f("vocalReport.radarStability","Stability"),value:T.shimmerProxy,max:100},{metric:f("vocalReport.radarCombo","Combo"),value:Math.min(100,T.maxCombo/Math.max(P,1)*100),max:100}],Y=[{name:f("vocalReport.perfLabel","Perfect"),value:T.perfectHitPct,fill:"var(--nice-success, #22c55e)"},{name:f("vocalReport.goodLabel","Good"),value:T.intonationAccuracyPct-T.perfectHitPct,fill:"var(--nice-success, #84cc16)"},{name:f("vocalReport.offPitch","Off-pitch"),value:100-T.intonationAccuracyPct,fill:"var(--nice-danger, #ef4444)"}].filter(S=>S.value>0),O=T.pitchClassDistribution.filter(S=>S.count>0).sort((S,B)=>B.pct-S.pct),U=T.verseMetrics.map(S=>({verse:`V${S.verseIndex+1}`,accuracy:Math.round(S.hitFraction*100),label:S.label})),V=Ys(T.pitchOverTime,Xs),K=Ys(T.accuracyOverTime,Xs),G=T.pitchDeviationHistogram,W=f("vocalReport.samples","Samples"),C=f("vocalReport.hitPct","Hit %"),$=f("vocalReport.cents","cents");return r.jsxs("div",{className:p,style:{...Q.overlay,...g},id:y,"data-testid":x,onClick:S=>S.target===S.currentTarget&&(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:S,style:X.container,children:[r.jsxs("div",{style:X.header,children:[r.jsxs("h1",{style:{...X.title,display:"inline-flex",alignItems:"center",gap:8},children:[r.jsx(B.NtdBarChart,{size:26})," ",m("vocalReport.title","Vocal Performance Report")]}),r.jsxs("p",{style:X.subtitle,children:[j.songArtist," — ",j.songTitle," | ",m("vocalReport.difficulty","Difficulty"),": ",r.jsx("strong",{children:j.difficulty})," "," | ",new Date(j.timestamp).toLocaleString()]}),r.jsxs("div",{style:{marginTop:16,display:"flex",justifyContent:"center",alignItems:"center",gap:16},children:[r.jsx("div",{style:{width:72,height:72,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:`linear-gradient(135deg, ${gt(T)}44, ${gt(T)})`,border:`3px solid ${gt(T)}`,boxShadow:`0 0 20px ${gt(T)}44`},children:r.jsx("span",{style:{fontSize:28,fontWeight:900,color:"#fff"},children:E})}),r.jsxs("div",{style:{textAlign:"left"},children:[r.jsxs("div",{style:{fontSize:14,fontWeight:700,color:gt(T)},children:[m("vocalReport.overallGrade","Overall grade"),": ",T.toFixed(1),"%"]}),r.jsx("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",maxWidth:360},children:_[E]??""})]})]})]}),r.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end",marginBottom:16,flexWrap:"wrap"},children:[r.jsxs("button",{style:X.btnPrimary,onClick:N,children:[r.jsx(B.NtdDownload,{size:14})," ",m("vocalReport.downloadHtml","Download HTML")]}),r.jsxs("button",{style:X.btnSecondary,onClick:R,children:[r.jsx(B.NtdPrint,{size:14})," ",m("vocalReport.printPdf","Print / PDF")]}),r.jsxs("button",{style:X.btnSecondary,onClick:P,children:[r.jsx(B.NtdCode,{size:14})," ",m("vocalReport.exportJson","Export JSON")]}),r.jsxs("button",{style:X.btnSecondary,onClick:d,children:[r.jsx(B.NtdClose,{size:14})," ",m("vocalReport.close","Close")]})]}),r.jsxs("h2",{style:X.sectionTitle,children:[++D,". ",m("vocalReport.scoreOverview","Score overview")]}),r.jsxs("div",{style:X.kpiGrid,children:[r.jsxs("div",{style:X.kpiCard,children:[r.jsx("div",{style:X.kpiValue,children:j.totalScore.toLocaleString()}),r.jsx("div",{style:X.kpiLabel,children:m("vocalReport.totalScore","Total score")})]}),r.jsxs("div",{style:X.kpiCard,children:[r.jsx("div",{style:X.kpiValue,children:j.classicScore.toLocaleString()}),r.jsx("div",{style:X.kpiLabel,children:m("vocalReport.classicScore","Classic score")})]}),r.jsxs("div",{style:X.kpiCard,children:[r.jsx("div",{style:X.kpiValue,children:j.bonusScore.toLocaleString()}),r.jsx("div",{style:X.kpiLabel,children:m("vocalReport.bonusScore","Bonus score")})]}),r.jsxs("div",{style:X.kpiCard,children:[r.jsxs("div",{style:X.kpiValue,children:[j.maxCombo,"×"]}),r.jsx("div",{style:X.kpiLabel,children:m("vocalReport.maxCombo","Max combo")})]}),r.jsxs("div",{style:X.kpiCard,children:[r.jsxs("div",{style:{...X.kpiValue,color:gt(j.intonationAccuracyPct)},children:[j.intonationAccuracyPct,"%"]}),r.jsx("div",{style:X.kpiLabel,children:m("vocalReport.intonationAccuracy","Intonation accuracy")})]}),r.jsxs("div",{style:X.kpiCard,children:[r.jsxs("div",{style:{...X.kpiValue,color:gt(j.perfectHitPct)},children:[j.perfectHitPct,"%"]}),r.jsx("div",{style:X.kpiLabel,children:m("vocalReport.perfectHits","Perfect hits")})]})]}),w.length>1&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:X.sectionTitle,children:[++D,". ",m("vocalReport.playerComparison","Player comparison")]}),r.jsxs("table",{style:X.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:X.th,children:"#"}),r.jsx("th",{style:X.th,children:m("vocalReport.player","Player")}),r.jsx("th",{style:X.thRight,children:m("vocalReport.classic","Classic")}),r.jsx("th",{style:X.thRight,children:m("vocalReport.bonus","Bonus")}),r.jsx("th",{style:X.thRight,children:m("vocalReport.total","Total")}),r.jsx("th",{style:X.thRight,children:m("vocalReport.intonation","Intonation")}),r.jsx("th",{style:X.thRight,children:m("vocalReport.perfect","Perfect")}),r.jsx("th",{style:X.thRight,children:m("vocalReport.range","Range")})]})}),r.jsx("tbody",{children:w.map((k,W)=>r.jsxs("tr",{children:[r.jsx("td",{style:X.td,children:W+1}),r.jsx("td",{style:{...X.tdBold,color:k.playerColor},children:k.playerName}),r.jsx("td",{style:X.tdRight,children:k.classicScore.toLocaleString()}),r.jsx("td",{style:X.tdRight,children:k.bonusScore.toLocaleString()}),r.jsx("td",{style:{...X.tdRight,fontWeight:700,color:"var(--nice-warning, #fbbf24)"},children:k.totalScore.toLocaleString()}),r.jsx("td",{style:X.tdRight,children:r.jsxs("span",{style:X.badge(gt(k.intonationAccuracyPct)),children:[k.intonationAccuracyPct,"%"]})}),r.jsx("td",{style:X.tdRight,children:r.jsxs("span",{style:X.badge(gt(k.perfectHitPct)),children:[k.perfectHitPct,"%"]})}),r.jsxs("td",{style:X.tdRight,children:[k.lowestNote,"–",k.highestNote]})]},W))})]})]}),r.jsxs("h2",{style:X.sectionTitle,children:[++D,". ",m("vocalReport.pitchAccuracy","Pitch accuracy")]}),r.jsxs("table",{style:X.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:X.th,children:m("vocalReport.metric","Metric")}),r.jsx("th",{style:X.thRight,children:m("vocalReport.value","Value")}),r.jsx("th",{style:X.th,children:m("vocalReport.description","Description")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.meanAbsDev","Mean abs. deviation")}),r.jsxs("td",{style:X.tdRight,children:[j.avgCentDeviation,r.jsxs("span",{style:X.kpiUnit,children:[" ",$]})]}),r.jsx("td",{style:X.td,children:m("vocalReport.meanAbsDevDesc","Average distance from the target pitch.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.medianDev","Median deviation")}),r.jsxs("td",{style:X.tdRight,children:[j.medianCentDeviation,r.jsxs("span",{style:X.kpiUnit,children:[" ",$]})]}),r.jsx("td",{style:X.td,children:m("vocalReport.medianDevDesc","Typical deviation, robust to outliers.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.stdDev","Std. deviation")}),r.jsxs("td",{style:X.tdRight,children:[j.stdDevCents,r.jsxs("span",{style:X.kpiUnit,children:[" ",$]})]}),r.jsx("td",{style:X.td,children:m("vocalReport.stdDevDesc","Consistency of pitch (lower = steadier).")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.intonationAccuracyLabel","Intonation accuracy")}),r.jsxs("td",{style:{...X.tdRight,color:gt(j.intonationAccuracyPct)},children:[j.intonationAccuracyPct,"%"]}),r.jsx("td",{style:X.td,children:m("vocalReport.intonationAccuracyDesc","Share of frames within tolerance.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.perfectHitRate","Perfect-hit rate")}),r.jsxs("td",{style:{...X.tdRight,color:gt(j.perfectHitPct)},children:[j.perfectHitPct,"%"]}),r.jsx("td",{style:X.td,children:m("vocalReport.perfectHitRateDesc","Notes hit dead-on.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.totalPitchSamples","Total pitch samples")}),r.jsx("td",{style:X.tdRight,children:j.totalPitchPoints.toLocaleString()}),r.jsx("td",{style:X.td,children:m("vocalReport.totalPitchSamplesDesc","Number of analysed pitch frames.")})]})]})]}),r.jsxs("div",{style:X.chartWrap,children:[r.jsx("div",{style:X.chartTitle,children:m("vocalReport.deviationDistribution","Deviation distribution")}),r.jsx("div",{style:{height:220},children:r.jsx(se.NiceChart,{width:860,height:220,stacked:!0,showLegend:!1,categories:Y.map(k=>k.centRange),series:Ks(Y.map(k=>`${O} (${k.centRange})`),Y.map(k=>k.count),Y.map(k=>Wh(k.centRange)))})})]}),r.jsxs("div",{style:X.row,children:[r.jsxs("div",{style:{...X.chartWrap,...X.half},children:[r.jsx("div",{style:X.chartTitle,children:m("vocalReport.hitClassification","Hit classification")}),r.jsx("div",{style:{height:220},children:r.jsx(se.NicePieChart,{width:400,height:260,data:te.map(k=>({label:k.name,value:qt(k.value),color:k.fill}))})})]}),r.jsxs("div",{style:{...X.chartWrap,...X.half},children:[r.jsx("div",{style:X.chartTitle,children:m("vocalReport.performanceProfile","Performance profile")}),r.jsx("div",{style:{height:220},children:r.jsx(se.NiceChart,{width:400,height:220,showLegend:!1,categories:q.map(k=>k.metric),series:[{name:m("vocalReport.performanceProfile","Performance profile"),type:"radar",color:"var(--nice-info, #3b82f6)",data:q.map(k=>qt(k.value))},{name:"100%",type:"radar",color:"transparent",data:q.map(k=>k.max)}]})})]})]}),r.jsxs("h2",{style:X.sectionTitle,children:[++D,". ",m("vocalReport.pitchTracking","Pitch tracking")]}),r.jsxs("div",{style:X.chartWrap,children:[r.jsx("div",{style:X.chartTitle,children:m("vocalReport.sungVsExpected","Sung vs expected")}),r.jsx("div",{style:{height:260},children:r.jsx(se.NiceChart,{width:860,height:230,categories:Zs(Z.map(k=>k.t)),series:[{name:m("vocalReport.expected","Expected"),type:"line",color:"var(--nice-success, #22c55e)",data:Z.map(k=>qt(k.expected))},{name:m("vocalReport.sung","Sung"),type:"line",color:"var(--nice-info, #3b82f6)",data:Z.map(k=>qt(k.sung))}]})})]}),r.jsxs("div",{style:X.chartWrap,children:[r.jsx("div",{style:X.chartTitle,children:m("vocalReport.rollingAccuracy","Rolling accuracy")}),r.jsx("div",{style:{height:180},children:r.jsx(se.NiceChart,{width:860,height:180,showLegend:!1,categories:Zs(ae.map(k=>k.t)),series:[{name:m("vocalReport.rollingAccuracy","Rolling accuracy"),type:"area",color:"var(--nice-accent, #8b5cf6)",data:ae.map(k=>qt(k.accuracy))}]})})]}),r.jsxs("h2",{style:X.sectionTitle,children:[++D,". ",m("vocalReport.vocalRange","Vocal range")]}),r.jsxs("div",{style:X.row,children:[r.jsx("div",{style:X.half,children:r.jsx("table",{style:X.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.lowestNote","Lowest note")}),r.jsxs("td",{style:X.tdRight,children:[j.lowestNote," (",j.lowestHz," Hz)"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.highestNote","Highest note")}),r.jsxs("td",{style:X.tdRight,children:[j.highestNote," (",j.highestHz," Hz)"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.rangeLabel","Range")}),r.jsxs("td",{style:X.tdRight,children:[j.rangeInSemitones," ",m("vocalReport.semitones","semitones")]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.tessitura","Tessitura")}),r.jsxs("td",{style:X.tdRight,children:[j.tessituraLow," — ",j.tessituraHigh]})]})]})})}),r.jsxs("div",{style:{...X.chartWrap,...X.half},children:[r.jsx("div",{style:X.chartTitle,children:m("vocalReport.chromagram","Chromagram")}),r.jsx("div",{style:{height:180},children:r.jsx(se.NiceChart,{width:400,height:180,showLegend:!1,categories:z.map(k=>k.note),series:[{name:m("vocalReport.usagePct","Usage %"),type:"bar",color:"var(--nice-primary, #6366f1)",data:z.map(k=>qt(k.pct))}]})})]})]}),r.jsxs("h2",{style:X.sectionTitle,children:[++D,". ",m("vocalReport.vibratoStability","Vibrato & stability")]}),r.jsxs("div",{style:X.row,children:[r.jsx("div",{style:X.half,children:r.jsx("table",{style:X.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.vibratoDetected","Vibrato detected")}),r.jsx("td",{style:X.tdRight,children:r.jsx("span",{style:X.badge(j.vibrato.detected?"var(--nice-success, #22c55e)":"var(--nice-text-muted, #64748b)"),children:j.vibrato.detected?m("vocalReport.yes","Yes"):m("vocalReport.no","No")})})]}),j.vibrato.detected&&r.jsxs(r.Fragment,{children:[r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.avgRate","Avg. rate")}),r.jsxs("td",{style:X.tdRight,children:[j.vibrato.avgRateHz," Hz"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.avgExtent","Avg. extent")}),r.jsxs("td",{style:X.tdRight,children:["±",j.vibrato.avgExtentCents," ",$]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.regularity","Regularity")}),r.jsxs("td",{style:X.tdRight,children:[j.vibrato.regularityPct,"%"]})]})]})]})})}),r.jsx("div",{style:X.half,children:r.jsx("table",{style:X.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.jitter","Jitter")}),r.jsxs("td",{style:X.tdRight,children:[j.jitterPct,"%"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.vocalPresence","Vocal presence")}),r.jsxs("td",{style:X.tdRight,children:[j.shimmerProxy,"%"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.avgOnsetDev","Avg. onset deviation")}),r.jsxs("td",{style:X.tdRight,children:[j.avgOnsetDeviationMs," ms"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.rhythmStability","Rhythm stability")}),r.jsx("td",{style:X.tdRight,children:r.jsxs("span",{style:X.badge(gt(j.rhythmStabilityPct)),children:[j.rhythmStabilityPct,"%"]})})]})]})})})]}),j.verseMetrics.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:X.sectionTitle,children:[++D,". ",m("vocalReport.verseBreakdown","Per-verse breakdown")]}),r.jsxs("div",{style:X.chartWrap,children:[r.jsx("div",{style:X.chartTitle,children:m("vocalReport.accuracyByVerse","Accuracy by verse")}),r.jsx("div",{style:{height:200},children:r.jsx(se.NiceChart,{width:860,height:200,stacked:!0,showLegend:!1,categories:U.map(k=>k.verse),series:Ks(U.map(k=>`${C} (${k.verse})`),U.map(k=>k.accuracy),U.map(k=>Hs(k.label)))})})]}),r.jsxs("table",{style:X.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:X.th,children:m("vocalReport.verse","Verse")}),r.jsx("th",{style:X.th,children:m("vocalReport.rating","Rating")}),r.jsx("th",{style:X.thRight,children:m("vocalReport.hitPct","Hit %")}),r.jsx("th",{style:X.thRight,children:m("vocalReport.avgDeviation","Avg. dev.")}),r.jsx("th",{style:X.thRight,children:m("vocalReport.notes","Notes")}),r.jsx("th",{style:X.thRight,children:m("vocalReport.notesHit","Hit")}),r.jsx("th",{style:X.thRight,children:m("vocalReport.comboBonus","Combo bonus")})]})}),r.jsx("tbody",{children:j.verseMetrics.map((k,W)=>r.jsxs("tr",{children:[r.jsxs("td",{style:X.td,children:[m("vocalReport.verse","Verse")," ",k.verseIndex+1]}),r.jsx("td",{style:X.td,children:r.jsx("span",{style:X.badge(Hs(k.label)),children:k.label})}),r.jsxs("td",{style:X.tdRight,children:[(k.hitFraction*100).toFixed(1),"%"]}),r.jsxs("td",{style:X.tdRight,children:[k.avgCentDeviation," ¢"]}),r.jsx("td",{style:X.tdRight,children:k.noteCount}),r.jsx("td",{style:X.tdRight,children:k.notesHit}),r.jsxs("td",{style:X.tdRight,children:["+",k.comboBonus]})]},W))})]})]}),r.jsxs("h2",{style:X.sectionTitle,children:[++D,". ",m("vocalReport.scoringConfig","Scoring configuration")]}),r.jsxs("table",{style:X.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:X.th,children:m("vocalReport.parameter","Parameter")}),r.jsx("th",{style:X.thRight,children:m("vocalReport.value","Value")}),r.jsx("th",{style:X.th,children:m("vocalReport.description","Description")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.difficultyLevel","Difficulty level")}),r.jsx("td",{style:X.tdRight,children:j.difficulty}),r.jsx("td",{style:X.td,children:m("vocalReport.difficultyLevelDesc","Affects tolerance and multiplier.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.semitoneTolerance","Semitone tolerance")}),r.jsx("td",{style:X.tdRight,children:I.semitoneTolerance}),r.jsx("td",{style:X.td,children:m("vocalReport.semitoneToleranceDesc","Pitch window counted as a hit.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.preWindow","Pre window")}),r.jsxs("td",{style:X.tdRight,children:[I.preWindow," s"]}),r.jsx("td",{style:X.td,children:m("vocalReport.preWindowDesc","Lead-in time before a note.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.postExtra","Post extra")}),r.jsxs("td",{style:X.tdRight,children:[I.postExtra," s"]}),r.jsx("td",{style:X.td,children:m("vocalReport.postExtraDesc","Grace time after a note.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.difficultyMultiplier","Difficulty multiplier")}),r.jsxs("td",{style:X.tdRight,children:[I.difficultyMult,"×"]}),r.jsx("td",{style:X.td,children:m("vocalReport.difficultyMultiplierDesc","Score scaling for difficulty.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.songBpm","Song BPM")}),r.jsx("td",{style:X.tdRight,children:j.songBpm}),r.jsx("td",{style:X.td,children:m("vocalReport.songBpmDesc","Tempo used for note timing.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.totalNotes","Total notes")}),r.jsx("td",{style:X.tdRight,children:M}),r.jsx("td",{style:X.td,children:m("vocalReport.totalNotesDesc","Number of scored notes in the song.")})]})]})]}),w.some(k=>k.micSettings)&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:X.sectionTitle,children:[++D,". ",m("vocalReport.micConfig","Microphone configuration")]}),w.map((k,W)=>k.micSettings&&r.jsxs("div",{style:{marginBottom:16},children:[w.length>1&&r.jsx("h4",{style:{color:k.playerColor,margin:"0 0 8px",fontSize:14},children:k.playerName}),r.jsxs("table",{style:X.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:X.th,children:m("vocalReport.setting","Setting")}),r.jsx("th",{style:X.thRight,children:m("vocalReport.value","Value")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.device","Device")}),r.jsx("td",{style:X.tdRight,children:k.micSettings.deviceLabel||k.micSettings.deviceId})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.pitchAlgorithm","Pitch algorithm")}),r.jsx("td",{style:X.tdRight,children:k.micSettings.algorithm})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.inputGain","Input gain")}),r.jsxs("td",{style:X.tdRight,children:[k.micSettings.gain,"×"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.rmsThreshold","RMS threshold")}),r.jsx("td",{style:X.tdRight,children:k.micSettings.rmsThreshold})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.pitchThreshold","Pitch threshold")}),r.jsx("td",{style:X.tdRight,children:k.micSettings.pitchThreshold})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.smoothingWindow","Smoothing window")}),r.jsxs("td",{style:X.tdRight,children:[k.micSettings.smoothingWindow," ",m("vocalReport.frames","frames")]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.hysteresisFrames","Hysteresis frames")}),r.jsx("td",{style:X.tdRight,children:k.micSettings.hysteresisFrames})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.hanningWindow","Hanning window")}),r.jsx("td",{style:X.tdRight,children:k.micSettings.useHanning?m("vocalReport.enabled","Enabled"):m("vocalReport.disabled","Disabled")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.latencyOffset","Latency offset")}),r.jsxs("td",{style:X.tdRight,children:[k.micSettings.latencyOffsetMs," ms"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:X.tdBold,children:m("vocalReport.monitor","Monitor")}),r.jsx("td",{style:X.tdRight,children:k.micSettings.monitorEnabled?`${m("vocalReport.on","On")} (${Math.round(k.micSettings.monitorVolume*100)}%)`:m("vocalReport.off","Off")})]})]})]})]},W))]}),r.jsx("div",{style:X.footer,children:r.jsxs("p",{children:[m("vocalReport.footerGenerated","Report generated")," ·"," ",j.timestamp.replace(/[-:T.Z]/g,"").slice(0,14)]})})]})]})},Vh="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 qh(e){if(!e)return"";const t=Math.floor(e/60),n=Math.round(e%60);return`${t}:${n.toString().padStart(2,"0")}`}function Qs(e){return Array.from(new Set(e.filter(t=>!!t))).sort((t,n)=>t.localeCompare(n))}const il=u.memo(({song:e,index:t,active:n,coverUrl:a,topScore:s,selected:i,multiSelect:l,disabled:o,t:c,onPlay:d,onToggleSelect:h,onFocusRow:f})=>{const p=()=>{l?h(e.id):o||d==null||d(e)};return r.jsxs("div",{className:`nice-ksb-row${i?" nice-ksb-row--selected":""}${n?" nice-ksb-row--active":""}`,role:"option","aria-selected":i,"data-ksb-index":t,tabIndex:n?0:-1,onClick:p,onFocus:()=>f(t),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),p())},children:[l&&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:qh(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()]})]}),!l&&r.jsxs("button",{type:"button",className:"nice-ksb-row__play",disabled:o,onClick:y=>{y.stopPropagation(),d==null||d(e)},children:[r.jsx(B.NtdPlay,{size:13})," ",c("karaokeBrowser.play","Play")]})]})});il.displayName="NiceKaraokeSongRow";const Hh=({songs:e,fetchSongs:t,loading:n=!1,getCover:a,getTopScore:s,onPlay:i,onSelect:l,multiSelect:o=!1,maxSelections:c=0,showSidebar:d=!0,enableGamepad:h=!0,disabled:f=!1,disabledReason:p,t:y,className:g,style:x,id:v,accessMode:m,"data-testid":S})=>{const{t:b}=Te(),w=y??b,[N,R]=u.useState(""),[P,j]=u.useState(""),[M,I]=u.useState(""),[T,E]=u.useState(""),[_,D]=u.useState("artist"),[q,te]=u.useState("asc"),[z,U]=u.useState({type:"all"}),[Z,ae]=u.useState(new Set),[Y,O]=u.useState([]),[C,$]=u.useState(!1);u.useEffect(()=>{const de=setTimeout(()=>j(N),300);return()=>clearTimeout(de)},[N]),u.useEffect(()=>{if(e||!t)return;let de=!1;return $(!0),Promise.resolve(t({searchQuery:P.trim()||void 0,genres:M?[M]:void 0,languages:T?[T]:void 0})).then(xe=>!de&&O(xe)).catch(()=>!de&&O([])).finally(()=>!de&&$(!1)),()=>{de=!0}},[e,t,P,M,T]);const k=e??Y,W=u.useMemo(()=>Qs(k.map(de=>de.genre)),[k]),A=u.useMemo(()=>Qs(k.map(de=>de.language)),[k]),L=u.useMemo(()=>{let de=k;const xe=P.trim().toLowerCase();xe&&(de=de.filter($e=>`${$e.title} ${$e.artist}`.toLowerCase().includes(xe))),M&&(de=de.filter($e=>$e.genre===M)),T&&(de=de.filter($e=>$e.language===T)),z.type==="genre"&&(de=de.filter($e=>$e.genre===z.value)),z.type==="language"&&(de=de.filter($e=>$e.language===z.value));const Me=q==="asc"?1:-1;return[...de].sort(($e,je)=>{const Xe=$e[_]??"",ce=je[_]??"";return typeof Xe=="number"&&typeof ce=="number"?(Xe-ce)*Me:String(Xe).localeCompare(String(ce))*Me})},[k,P,M,T,z,_,q]),G=de=>{ae(xe=>{const Me=new Set(xe);return Me.has(de)?Me.delete(de):(c===0||Me.size<c)&&Me.add(de),Me})},F=()=>{const de=k.filter(xe=>Z.has(xe.id));l==null||l({songs:de})},V=n||C,Q=de=>{de===_?te(xe=>xe==="asc"?"desc":"asc"):(D(de),te("asc"))},le=u.useRef(null),[oe,ne]=u.useState(0),K=u.useRef(0),H=u.useRef(L);H.current=L,u.useEffect(()=>{ne(de=>{const xe=Math.min(Math.max(0,de),Math.max(0,L.length-1));return K.current=xe,xe})},[L.length]);const ie=u.useCallback(de=>{var Me;const xe=(Me=le.current)==null?void 0:Me.querySelector(`[data-ksb-index="${de}"]`);xe==null||xe.focus(),xe==null||xe.scrollIntoView({block:"nearest"})},[]),re=u.useCallback(de=>{K.current=de,ne(de)},[]),he=u.useCallback((de,xe=!0)=>{const Me=H.current.length;if(Me===0)return;const $e=Math.min(Me-1,Math.max(0,de));K.current=$e,ne($e),xe&&requestAnimationFrame(()=>ie($e))},[ie]),J=u.useCallback(de=>he(K.current+de),[he]),ue=de=>{const xe=H.current[de];xe&&(o?G(xe.id):f||i==null||i(xe))},me=de=>{switch(de.key){case"ArrowDown":de.preventDefault(),J(1);break;case"ArrowUp":de.preventDefault(),J(-1);break;case"Home":de.preventDefault(),he(0);break;case"End":de.preventDefault(),he(H.current.length-1);break;case"PageDown":de.preventDefault(),J(5);break;case"PageUp":de.preventDefault(),J(-5);break}},Se=we.useGamepad({enabled:h,actions:{navUp:{button:"DpadUp",onPress:()=>J(-1),repeatDelay:350,repeatRate:110},navDown:{button:"DpadDown",onPress:()=>J(1),repeatDelay:350,repeatRate:110},stickUp:{axis:"LeftY",axisDirection:"negative",onPress:()=>J(-1),repeatDelay:350,repeatRate:130},stickDown:{axis:"LeftY",axisDirection:"positive",onPress:()=>J(1),repeatDelay:350,repeatRate:130},select:{button:"A",onPress:()=>ue(K.current)},confirm:{button:"Start",onPress:()=>{o&&F()}}}});return m==="hidden"?null:r.jsxs("div",{className:`nice-ksb${g?` ${g}`:""}`,style:x,id:v,"data-testid":S,children:[d&&r.jsxs("aside",{className:"nice-ksb__sidebar",children:[r.jsxs("button",{type:"button",className:`nice-ksb__node${z.type==="all"?" nice-ksb__node--active":""}`,onClick:()=>U({type:"all"}),children:[r.jsx(B.NtdMusic,{size:14})," ",w("karaokeBrowser.allSongs","All songs")," (",k.length,")"]}),W.length>0&&r.jsxs("div",{className:"nice-ksb__facet",children:[r.jsx("div",{className:"nice-ksb__facet-title",children:w("karaokeBrowser.genres","Genres")}),W.map(de=>r.jsx("button",{type:"button",className:`nice-ksb__node${z.type==="genre"&&z.value===de?" nice-ksb__node--active":""}`,onClick:()=>U({type:"genre",value:de}),children:de},de))]}),A.length>0&&r.jsxs("div",{className:"nice-ksb__facet",children:[r.jsx("div",{className:"nice-ksb__facet-title",children:w("karaokeBrowser.languages","Languages")}),A.map(de=>r.jsx("button",{type:"button",className:`nice-ksb__node${z.type==="language"&&z.value===de?" nice-ksb__node--active":""}`,onClick:()=>U({type:"language",value:de}),children:de},de))]})]}),r.jsxs("div",{className:"nice-ksb__main",children:[r.jsxs("div",{className:"nice-ksb__toolbar",children:[r.jsx("input",{className:"nice-ksb__search",type:"search",value:N,placeholder:w("karaokeBrowser.search","Search title or artist…"),onChange:de=>R(de.target.value)}),r.jsx("div",{className:"nice-ksb__sort",children:["artist","title","year","genre"].map(de=>r.jsxs("button",{type:"button",className:`nice-ksb__sort-btn${_===de?" nice-ksb__sort-btn--active":""}`,onClick:()=>Q(de),children:[w(`karaokeBrowser.sort.${de}`,de),_===de&&(q==="asc"?r.jsx(B.NtdChevronUp,{size:12}):r.jsx(B.NtdChevronDown,{size:12}))]},de))}),r.jsxs("span",{className:`nice-ksb__navhint${Se.connected?" nice-ksb__navhint--pad":""}`,title:w("karaokeBrowser.navHint","Navigate with ↑ ↓ or the D-pad · Enter / A to play"),children:[Se.connected?r.jsx(B.NtdGamepad,{size:14}):r.jsx(B.NtdMove,{size:14}),r.jsx("span",{className:"nice-ksb__navhint-keys",children:Se.connected?"D-pad · A":"↑ ↓ · Enter"})]})]}),f&&p&&r.jsx("div",{className:"nice-ksb__disabled",children:p}),r.jsx("div",{className:"nice-ksb__list",role:"listbox","aria-multiselectable":o,"aria-label":w("karaokeBrowser.songs","Songs"),ref:le,onKeyDown:me,children:V?r.jsx("div",{className:"nice-ksb__empty",children:w("karaokeBrowser.loading","Loading…")}):L.length===0?r.jsx("div",{className:"nice-ksb__empty",children:w("karaokeBrowser.noResults","No songs found")}):L.map((de,xe)=>r.jsx(il,{song:de,index:xe,active:xe===oe,coverUrl:(a==null?void 0:a(de))||de.coverImage||de.externalCoverUrl||de.coverPath||Vh,topScore:s==null?void 0:s(de),selected:Z.has(de.id),multiSelect:o,disabled:f,t:w,onPlay:i,onToggleSelect:G,onFocusRow:re},de.id))}),o&&r.jsxs("div",{className:"nice-ksb__footer",children:[r.jsxs("span",{children:[Z.size,c>0?` / ${c}`:""," ",w("karaokeBrowser.selected","selected")]}),r.jsx("button",{type:"button",className:"nice-ksb__confirm",disabled:Z.size===0,onClick:F,children:w("karaokeBrowser.confirm","Add selected")})]})]})]})};function ol(e,t,n=50,a=30){const s=Math.round(e/1e3*t),i=Math.round(n/1e3*t),l=Math.max(1,Math.round(a/1e3*t)),o=new Float32Array(s);for(let c=0;c<l;c++){const d=.5*(1-Math.cos(2*Math.PI*c/(l-1))),h=i+c-Math.floor(l/2);h>=0&&h<s&&(o[h]=d)}return o}function Js(e,t,n=1e3){const a=Math.max(1,Math.round(t/n)),s=Math.ceil(e.length/a),i=new Float32Array(s);for(let o=0;o<s;o++){const c=o*a,d=Math.min(e.length,c+a);let h=0;for(let f=c;f<d;f++)h+=Math.abs(e[f]);i[o]=h/(d-c||1)}let l=0;for(let o=0;o<i.length;o++)i[o]>l&&(l=i[o]);if(l>0)for(let o=0;o<i.length;o++)i[o]=i[o]/l;return{env:i,factor:a}}function Kh(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 l=-i;l<=i;l++){let o=0,c=0,d=0;for(let p=0;p<n;p++){const y=p+l+Math.floor((a-n)/2);if(y<0||y>=a)continue;const g=e[p],x=t[y];o+=g*x,c+=g*g,d+=x*x}const h=Math.sqrt(Math.max(1e-9,c*d)),f=o/h;f>s.score&&(s={lag:l,score:f})}return s.lag}function ll(e,t,n=50,a=30){try{const s=Math.max(300,Math.round(e.length/t*1e3)),i=ol(s,t,n,a),l=Js(e,t,1e3),o=Js(i,t,1e3),d=Kh(o.env,l.env)*1e3/1e3;return Math.round(d)}catch{return null}}const Yh=({deviceId:e,initialOffsetMs:t=null,onSave:n,onClose:a,rounds:s=3,t:i,className:l,style:o,id:c,accessMode:d,"data-testid":h})=>{const{t:f}=Te(),p=i??f,[y,g]=u.useState(null),[x,v]=u.useState(t),[m,S]=u.useState(!1),[b,w]=u.useState([]),[N,R]=u.useState(0),[P,j]=u.useState(!1),M=u.useRef(!1);u.useEffect(()=>{v(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}}),q=new AudioContext,te=q.sampleRate,z=q.createMediaStreamSource(D),U=q.createScriptProcessor(2048,1,1);z.connect(U),U.connect(q.destination);const Z=1200,ae=Math.round(Z/1e3*te),Y=new Float32Array(ae);let O=0,C=!1;U.onaudioprocess=G=>{if(C)return;const F=G.inputBuffer.getChannelData(0),V=Math.min(F.length,ae-O);V>0&&(Y.set(F.subarray(0,V),O),O+=V),O>=ae&&(C=!0)},await new Promise(G=>setTimeout(G,80));const $=new AudioContext,k=$.createOscillator(),W=$.createGain();k.type="sine",k.frequency.value=1e3,W.gain.value=1e-4,k.connect(W),W.connect($.destination);const A=$.currentTime+.05;W.gain.setValueAtTime(1e-4,A-.01),W.gain.linearRampToValueAtTime(1,A),W.gain.linearRampToValueAtTime(1e-4,A+.06),k.start(A-.02),k.stop(A+.1),await new Promise(G=>{const F=()=>{if(C||O>=ae){G();return}setTimeout(F,50)};setTimeout(()=>{C=!0,G()},Z+500),F()}),U.onaudioprocess=null;try{U.disconnect()}catch{}try{z.disconnect()}catch{}try{await $.close()}catch{}try{await q.close()}catch{}D.getTracks().forEach(G=>G.stop());const L=Y.subarray(0,O);return ll(L,te,130,30)},T=async()=>{if(!M.current){M.current=!0,j(!0),g(p("latencyCalibrator.requestingMic","Requesting microphone — click allow if prompted")),v(null),w([]),R(0);try{const D=[];for(let te=0;te<s;te++){g(`${p("latencyCalibrator.playingTone","Playing test tone and recording…")} (${te+1}/${s})`),R(Math.round(te/s*100));const z=await I();z!==null&&(D.push(Math.max(-500,Math.min(2e3,Math.round(z)))),w([...D])),te<s-1&&await new Promise(U=>setTimeout(U,400))}if(R(100),D.length===0){g(p("latencyCalibrator.noSignal","No signal detected — try louder or check the microphone"));return}let q;if(D.length>=3){const z=[...D].sort((U,Z)=>U-Z).slice(1,-1);q=Math.round(z.reduce((U,Z)=>U+Z,0)/z.length)}else q=Math.round(D.reduce((te,z)=>te+z,0)/D.length);v(q),g(`${p("latencyCalibrator.measured","Measured")} ~${q} ms (${D.length}: ${D.join(", ")} ms)`)}catch(D){g(`${p("latencyCalibrator.calibrationError","Calibration error: ")}${D instanceof Error?D.message:String(D)}`)}finally{M.current=!1,j(!1)}}},E=async()=>{if(!(x===null||!n)){S(!0);try{await n(Math.round(x)),g(p("latencyCalibrator.saved","Saved"))}catch(D){g(`${p("latencyCalibrator.saveError","Save error: ")}${String(D)}`)}finally{S(!1)}}},_={padding:"7px 16px",border:"none",borderRadius:8,cursor:"pointer",fontWeight:600};return d==="hidden"?null:r.jsxs("div",{className:`nice-latency-calibrator${l?` ${l}`:""}`,style:{padding:12,color:"var(--nice-text, inherit)",...o},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})," ",p("latencyCalibrator.title","Latency calibrator — microphone")]}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:[p("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:T,disabled:P,style:{..._,background:"var(--nice-accent, #3b82f6)",color:"var(--nice-text-on-primary, #fff)"},children:p("latencyCalibrator.calibrate","Calibrate")}),r.jsx("button",{type:"button",onClick:()=>{v(null),g(null),w([]),R(0)},style:{..._,background:"var(--nice-bg-tertiary)",color:"var(--nice-text, #e2e8f0)"},children:p("latencyCalibrator.clear","Clear")})]}),P&&r.jsx("div",{style:{marginTop:8,height:6,borderRadius:3,background:"var(--nice-bg-tertiary)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${N}%`,background:"var(--nice-accent, #3b82f6)",transition:"width 0.2s"}})}),b.length>0&&r.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:[p("latencyCalibrator.rounds","Rounds"),": ",b.join(", ")," ms"]}),r.jsxs("div",{style:{marginTop:8,fontSize:13},children:[r.jsxs("div",{children:[p("latencyCalibrator.status","Status"),": ",y??p("latencyCalibrator.none","none")]}),r.jsxs("div",{children:[p("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:E,disabled:x===null||m,style:{..._,background:"var(--nice-success, #22c55e)",color:"var(--nice-text-on-primary, #fff)",opacity:x===null||m?.5:1},children:p("latencyCalibrator.save","Save")}),a&&r.jsx("button",{type:"button",onClick:a,style:{..._,background:"transparent",border:"1px solid var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)"},children:p("latencyCalibrator.close","Close")})]})]})},Zh=[{value:"normal",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.NtdMicrophone,{size:14})," Mic"]})},{value:"pad",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.NtdGamepad,{size:14})," Pad"]})},{value:"demo",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.NtdStopwatch,{size:14})," Demo"]})}],cl=({players:e,defaultPlayers:t,onPlayersChange:n,gameMode:a="normal",onGameModeChange:s,gameModes:i=Zh,difficulty:l="normal",onDifficultyChange:o,audioInputs:c,maxPlayers:d=4,onCalibrate:h,t:f,className:p,style:y,id:g,accessMode:x,"data-testid":v})=>{const{t:m}=Te(),S=f??m,[b,w]=we.useControllableState({value:e,defaultValue:t,fallbackValue:[],onChange:n,componentName:"NiceKaraokeSetupPanel"}),[N,R]=u.useState([]);u.useEffect(()=>{var D,q,te;if(c||!((D=navigator.mediaDevices)!=null&&D.enumerateDevices))return;let E=!1;const _=()=>navigator.mediaDevices.enumerateDevices().then(z=>!E&&R(z.filter(U=>U.kind==="audioinput"))).catch(()=>{});return _(),(te=(q=navigator.mediaDevices).addEventListener)==null||te.call(q,"devicechange",_),()=>{var z,U;E=!0,(U=(z=navigator.mediaDevices).removeEventListener)==null||U.call(z,"devicechange",_)}},[c]);const P=c??N,j=u.useMemo(()=>[{value:"",label:S("karaokeSetup.noMic","No microphone")},...P.map((E,_)=>({value:E.deviceId,label:E.label||`${S("karaokeSetup.microphone","Microphone")} ${_+1}`}))],[P,S]),M=(E,_)=>w(b.map(D=>D.id===E?{...D,..._}:D)),I=()=>{if(b.length>=d)return;const E=b.reduce((_,D)=>Math.max(_,D.id),0)+1;w([...b,{id:E,name:`${S("karaokeSetup.player","Player")} ${b.length+1}`,color:et[b.length%et.length],micId:null}])},T=E=>w(b.filter(_=>_.id!==E));return x==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-setup${p?` ${p}`:""}`,style:{display:"flex",flexDirection:"column",gap:16,...y},id:g,"data-testid":v,children:[r.jsxs("div",{style:{display:"flex",gap:24,flexWrap:"wrap"},children:[r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:12,fontWeight:600,marginBottom:6,color:"var(--nice-text-muted, #94a3b8)"},children:S("karaokeSetup.mode","Game mode")}),r.jsx(se.NiceSegmentedControl,{options:i,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:S("karaokeSetup.difficulty","Difficulty")}),r.jsx(se.NiceSegmentedControl,{options:[{value:"easy",label:S("karaokeSetup.easy","Easy")},{value:"normal",label:S("karaokeSetup.normal","Normal")},{value:"hard",label:S("karaokeSetup.hard","Hard")}],value:l,onChange:E=>o==null?void 0:o(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:[S("karaokeSetup.players","Players")," (",b.length,"/",d,")"]}),b.map(E=>r.jsx(se.NiceCard,{children:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[r.jsx(se.NiceColorPicker,{value:E.color||et[0],onChange:_=>M(E.id,{color:_})}),r.jsx("div",{style:{flex:"1 1 160px",minWidth:140},children:r.jsx(se.NiceTextInput,{value:E.name,onChange:_=>M(E.id,{name:_}),placeholder:S("karaokeSetup.playerName","Player name"),size:"sm"})}),r.jsx("div",{style:{flex:"1 1 180px",minWidth:150},children:r.jsx(se.NiceSelect,{options:j,value:E.micId??"",onChange:_=>M(E.id,{micId:(typeof _=="string"?_:_[0])||null}),placeholder:S("karaokeSetup.selectMic","Microphone"),size:"sm"})}),h&&E.micId&&r.jsxs(se.NiceButton,{variant:"ghost",size:"sm",onClick:()=>h(E.micId),children:[r.jsx(B.NtdSettings,{size:14})," ",S("karaokeSetup.calibrate","Calibrate")]}),r.jsx(se.NiceButton,{variant:"danger",size:"sm",onClick:()=>T(E.id),"aria-label":S("karaokeSetup.remove","Remove"),children:r.jsx(B.NtdClose,{size:14})})]})},E.id)),r.jsx("div",{children:r.jsxs(se.NiceButton,{variant:"primary",onClick:I,disabled:b.length>=d,children:[r.jsx(B.NtdPlus,{size:14})," ",S("karaokeSetup.addPlayer","Add player")]})})]})]})},Xh=["freeForAll","roundRobin","hostOnly","firstCome"],Qh={freeForAll:B.NtdDice,roundRobin:B.NtdRepeat,hostOnly:B.NtdCrown,firstCome:B.NtdLightning},Jh={freeForAll:"success",roundRobin:"warning",hostOnly:"info",firstCome:"danger"},dl=({players:e,mode:t,defaultMode:n,onModeChange:a,turnTimeSec:s=30,hostIndex:i=0,onActivePlayerChange:l,myPlayerIndex:o,t:c,className:d,style:h,id:f,accessMode:p,"data-testid":y})=>{const{t:g}=Te(),x=c??g,[v,m]=we.useControllableState({value:t,defaultValue:n,fallbackValue:"freeForAll",onChange:a,componentName:"NiceKaraokeSelectionMode"}),S={freeForAll:x("songSelection.freeForAll","Free for all"),roundRobin:x("songSelection.roundRobin","Round robin"),hostOnly:x("songSelection.hostOnly","Host only"),firstCome:x("songSelection.firstCome","First come")},[b,w]=u.useState(0),[N,R]=u.useState(s),P=u.useRef(null),[j,M]=u.useState(null),[I,T]=u.useState(!1),[E,_]=u.useState(null),D=u.useRef(null),q=u.useMemo(()=>v==="hostOnly"?i:v==="roundRobin"?b%Math.max(1,e.length):v==="firstCome"?I?-1:E??-1:-1,[v,b,e.length,i,I,E]);u.useEffect(()=>{l==null||l(q)},[q,l]),u.useEffect(()=>{if(v!=="roundRobin"||s<=0){P.current&&clearInterval(P.current);return}return R(s),P.current=setInterval(()=>{R(ae=>ae<=1?(w(Y=>Y+1),s):ae-1)},1e3),()=>{P.current&&clearInterval(P.current)}},[v,s,b]);const te=u.useCallback(()=>{_(null),T(!1),M(3),D.current&&clearInterval(D.current),D.current=setInterval(()=>{M(ae=>ae===null||ae<=1?(D.current&&clearInterval(D.current),T(!0),null):ae-1)},1e3)},[]);u.useEffect(()=>()=>{D.current&&clearInterval(D.current)},[]),u.useEffect(()=>{v!=="firstCome"&&(M(null),T(!1),_(null))},[v]);const z=u.useCallback(()=>{w(ae=>ae+1),R(s)},[s]),U=ae=>{var Y;return((Y=e[ae])==null?void 0:Y.name)||`${x("songSelection.player","Player")} ${ae+1}`},Z=q>=0&&q<e.length?e[q]:null;return p==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-selection-mode${d?` ${d}`:""}`,style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,padding:"8px 12px",background:"var(--nice-bg-secondary)",borderRadius:10,border:"1px solid var(--nice-border, #333)",...h},id:f,"data-testid":y,children:[r.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:Xh.map(ae=>r.jsxs(se.NiceButton,{size:"sm",variant:v===ae?Jh[ae]:"outline",onClick:()=>m(ae),children:[u.createElement(Qh[ae],{size:14})," ",S[ae]]},ae))}),v!=="freeForAll"&&v!=="firstCome"&&Z&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsxs(se.NiceBadge,{variant:q===o?"success":"secondary",children:[r.jsx(B.NtdMicrophone,{size:12})," ",U(q)]}),q===o&&r.jsx("span",{style:{color:"var(--nice-success, #4caf50)",fontSize:12,fontWeight:600},children:x("songSelection.yourTurn","Your turn!")})]}),v==="roundRobin"&&s>0&&r.jsx("div",{style:{flex:1,minWidth:120,maxWidth:200},children:r.jsx(se.NiceProgress,{value:N,max:s,variant:N<=5?"error":N<=10?"warning":"info",showValue:!0,formatValue:ae=>`${ae}s`})}),v==="roundRobin"&&r.jsxs(se.NiceButton,{size:"sm",variant:"ghost",onClick:z,children:[x("songSelection.next","Next")," ",r.jsx(B.NtdPlay,{size:12})]}),v==="firstCome"&&r.jsxs(r.Fragment,{children:[j!==null&&r.jsx("div",{style:{fontSize:32,fontWeight:900,color:"var(--nice-error, #f44336)",minWidth:60,textAlign:"center"},children:j}),I&&E===null&&r.jsxs(se.NiceBadge,{variant:"danger",children:[r.jsx(B.NtdLightning,{size:12})," ",x("songSelection.raceGo","GO! Pick a song!")]}),E!==null&&E<e.length&&r.jsxs(se.NiceBadge,{variant:"success",children:[r.jsx(B.NtdTrophy,{size:12})," ",U(E)," ",x("songSelection.raceWon","picks!")]}),r.jsx(se.NiceButton,{size:"sm",variant:j!==null?"secondary":"danger",onClick:te,disabled:j!==null,children:E!==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 ep(e,t,n,a){return u.useMemo(()=>e==="freeForAll"?!0:e==="firstCome"?t===-1:e==="hostOnly"?a===n:e==="roundRobin"?a===t:!1,[e,t,n,a])}const tp=({players:e,defaultPlayers:t,onPlayersChange:n,gameMode:a,onGameModeChange:s,gameModes:i,difficulty:l,onDifficultyChange:o,audioInputs:c,maxPlayers:d=4,onCalibrate:h,initialSelectionMode:f="freeForAll",turnTimeSec:p=30,hostIndex:y=0,myPlayerIndex:g,onChange:x,variant:v="bar",t:m,className:S,style:b,id:w,accessMode:N,"data-testid":R})=>{const{t:P}=Te(),j=m??P,[M,I]=we.useControllableState({value:e,defaultValue:t,fallbackValue:[],onChange:n,componentName:"NiceKaraokeSessionJoin"}),[T,E]=u.useState([]);u.useEffect(()=>{var A,L,G;if(c||!((A=navigator.mediaDevices)!=null&&A.enumerateDevices))return;let k=!1;const W=()=>navigator.mediaDevices.enumerateDevices().then(F=>!k&&E(F.filter(V=>V.kind==="audioinput"))).catch(()=>{});return W(),(G=(L=navigator.mediaDevices).addEventListener)==null||G.call(L,"devicechange",W),()=>{var F,V;k=!0,(V=(F=navigator.mediaDevices).removeEventListener)==null||V.call(F,"devicechange",W)}},[c]);const _=c??T,D=_.length===0,q=M.some(k=>!k.micId),te=!q,[z,U]=u.useState(f),[Z,ae]=u.useState(-1),Y=u.useCallback((k,W)=>{x==null||x({selectionMode:k,activePickerIndex:W,allMicsAssigned:te,noInputDevices:D})},[x,te,D]),O=u.useCallback(k=>{U(k),Y(k,Z)},[Y,Z]),C=u.useCallback(k=>{ae(k),Y(z,k)},[Y,z]),$=u.useMemo(()=>({padding:10,borderRadius:8,fontWeight:700,marginTop:8,textAlign:"center"}),[]);return N==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-session-join${S?` ${S}`:""}`,style:v==="card"?{background:"var(--nice-bg-secondary)",borderRadius:12,padding:16,...b}:b,id:w,"data-testid":R,children:[r.jsx(cl,{players:M,onPlayersChange:I,gameMode:a,onGameModeChange:s,gameModes:i,difficulty:l,onDifficultyChange:o,audioInputs:_,maxPlayers:d,onCalibrate:h,t:j}),D&&r.jsxs("div",{style:{...$,background:"var(--nice-error, #ef4444)",color:"#fff"},children:[j("karaokeSessionJoin.noInputDevices","No microphone detected"),r.jsx("br",{}),r.jsx("span",{style:{fontWeight:400,fontSize:13},children:j("karaokeSessionJoin.noInputDevicesHint","Connect a microphone to sing.")})]}),!D&&q&&r.jsx("div",{style:{...$,background:"var(--nice-warning, #f59e0b)",color:"var(--nice-text-on-primary, #222)",fontSize:14},children:j("karaokeSessionJoin.assignMicWarning","Assign a microphone to each player.")}),M.length>1&&r.jsx("div",{style:{marginTop:12},children:r.jsx(dl,{players:M,mode:z,onModeChange:O,onActivePlayerChange:C,turnTimeSec:p,hostIndex:y,myPlayerIndex:g,t:j})})]})};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 np=[Ue("Belagak","BelagakRegular-dr1zE.otf"),Ue("Big Scratch Brush","BigScratchBrush-PVY9g.ttf"),Ue("Gerhaus","Gerhaus-PK69E.ttf"),Ue("Gerhaus Italic","GerhausItalic-d96l7.ttf"),Ue("Handone Medium","HandoneMedium-nAevO.otf"),Ue("Handson Bold","HandsonBold-9MnrL.otf"),Ue("Kineks Round Bold","KineksRoundBold-7OR34.ttf"),Ue("Kineks Round Light","KineksRoundLight-m2r35.ttf"),Ue("Kineks Round Medium","KineksRoundMedium-drejZ.ttf"),Ue("Kineks Round","KineksRoundRegular-PVRl7.ttf"),Ue("Kineks Round SemiBold","KineksRoundSemiBold-LVWG3.ttf"),Ue("Lemon Jelly","LemonJellyPersonalUse-dEqR.ttf"),Ue("Lemon Milk Bold","LemonMilkBold-gx2B3.otf"),Ue("Lemon Milk Bold Italic","LemonMilkBoldItalic-PKZ3P.otf"),Ue("Lemon Milk Light","LemonMilkLight-owxMq.otf"),Ue("Lemon Milk Light Italic","LemonMilkLightItalic-7BjPE.otf"),Ue("Lemon Milk Medium","LemonMilkMedium-mLZYV.otf"),Ue("Lemon Milk Medium Italic","LemonMilkMediumItalic-d95nl.otf"),Ue("Lemon Milk","LemonMilkRegular-X3XE2.otf"),Ue("Lemon Milk Italic","LemonMilkRegularItalic-L3AEy.otf"),Ue("Pemage","PemageRegular-YqrdO.otf"),Ue("Rosmatika","RosmatikaRegular-BWA45.ttf"),Ue("Scabber","Scabber-q2Mn0.ttf"),Ue("Stylish Calligraphy","StylishCalligraphyDemo-XPZZ.ttf"),Ue("Super Adorable","SuperAdorable-MAvyp.ttf"),Ue("Super Chiby","SuperChiby-BL62V.ttf"),Ue("Super Joyful","SuperJoyful-lxwPq.ttf"),Ue("Super Kindly","SuperKindly-drE8E.ttf"),Ue("Super Meatball","SuperMeatball-Yq1Gy.ttf")],Za="nice2dev-karaoke-display",rp=[{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"},...np.map(e=>({value:e.family,label:e.family}))],ul=[{id:"default",name:"Cyan ? Yellow ? Amber",sungGradient:["#00e5ff","#ffe600","#ffab00"],goldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,229,255,0.6)"},{id:"neon-pink",name:"Neon Pink ? Violet ? Blue",sungGradient:["#ff1493","#9b59b6","var(--nice-primary, #3498db)"],goldGradient:["var(--nice-warning, #FFD700)","#FF69B4","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,20,147,0.6)"},{id:"fire",name:"Red ? Orange ? Yellow",sungGradient:["#ff1744","#ff9100","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#FF6D00","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,23,68,0.6)"},{id:"ocean",name:"Deep Blue ? Teal ? Aqua",sungGradient:["#1a237e","#00897b","#00e5ff"],goldGradient:["var(--nice-warning, #FFD700)","#00BCD4","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,137,123,0.6)"},{id:"forest",name:"Green ? Lime ? Yellow",sungGradient:["#1b5e20","#76ff03","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#76ff03","var(--nice-warning, #FFD700)"],glowColor:"rgba(118,255,3,0.6)"},{id:"retro",name:"Orange ? Pink ? Purple",sungGradient:["#ff6d00","var(--nice-color-accent-pink, #e91e63)","#7b1fa2"],goldGradient:["var(--nice-warning, #FFD700)","var(--nice-color-accent-pink, #e91e63)","var(--nice-warning, #FFD700)"],glowColor:"rgba(233,30,99,0.6)"}],gn={presetId:"default",customSungGradient:["#00e5ff","#ffe600","#ffab00"],customGoldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],customGlowColor:"rgba(0,229,255,0.6)",animationMode:"ball",fontFamily:"Arial",transitionEffect:"none",curtainPrimaryColor:"#8b0000",curtainSecondaryColor:"#1a0000",curtainDurationMs:900,immersiveMode:!1};let ei=!1;function hl(){try{const e=localStorage.getItem(Za);if(e){const t=JSON.parse(e);return{...gn,...t}}}catch{}return{...gn}}async function ap(e){if(ei||(ei=!0,!e))return;const t=await e();if(t)try{const n=JSON.parse(t),a={...gn,...n};localStorage.setItem(Za,JSON.stringify(a))}catch{}}function sp(e){const t=JSON.stringify(e);localStorage.setItem(Za,t),Xa(e)}function pl(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=ul.find(n=>n.id===e.presetId);return t?{sungGradient:t.sungGradient,goldGradient:t.goldGradient,glowColor:t.glowColor}:{sungGradient:gn.customSungGradient,goldGradient:gn.customGoldGradient,glowColor:gn.customGlowColor}}function Xa(e){const{sungGradient:t,goldGradient:n,glowColor:a}=pl(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 ip(){const e=hl();Xa(e)}function op(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+/),l=parseInt(i[0]||"0",10),o=parseInt(i[1]||"0",10),c=isNaN(l)?0:l/10,d=isNaN(o)?0:o/10;n.push({lineIndex:a,start:c,duration:d,raw:t[a]})}}return n}const lp=({index:e,data:t})=>{const{lines:n,notes:a,currentIndex:s,animationConfig:i}=t,l=n[e]??"",o=a.findIndex(m=>m.lineIndex===e),c=o>=0&&o===s,d=(i==null?void 0:i.enabled)??!0,h=(i==null?void 0:i.durationMs)??300,f=(i==null?void 0:i.translateX)??8,p=(i==null?void 0:i.scale)??1.01,y=(i==null?void 0:i.easing)??"cubic-bezier(.22,1,.36,1)",g=(i==null?void 0:i.opacityInactive)??.9,x=(i==null?void 0:i.boxShadow)??"0 6px 18px var(--nice-primary-tint-8, rgba(3,102,214,0.08))",v={transition:d?`transform ${h}ms ${y}, opacity ${h}ms ${y}`:"none",transform:c?`translateX(${f}px) scale(${p})`:"translateX(0px) scale(1)",opacity:c?1:g,boxShadow:c?x:"none"};return r.jsx("div",{style:{height:"100%",padding:"4px 6px",borderRadius:4},"data-note-idx":o>=0?o:void 0,children:r.jsx("div",{style:{...v,background:c?"var(--nice-primary-tint-12, rgba(0,130,200,0.12))":"transparent",padding:"4px 6px",borderRadius:4},children:r.jsx("code",{style:{fontFamily:"monospace",whiteSpace:"pre-wrap"},children:l})})})},cp=({ultrastarText:e,audioUrl:t,audioRef:n,animationConfig:a})=>{const{t:s}=Te(),i=u.useRef(null),l=n??i,[o,c]=u.useState(!1),d=u.useMemo(()=>op(e),[e]),h=u.useRef(null),f=u.useRef(null),p=u.useRef(0),y=u.useRef(0),[g,x]=u.useState(-1),v=u.useMemo(()=>(e||"").split(/\r?\n/),[e]),m=28,S=v.length*m,b=u.useMemo(()=>({lines:v,notes:d,currentIndex:g,animationConfig:a}),[v,d,g,a]),w=u.useCallback((N,R)=>r.jsx(lp,{index:R,data:b}),[b]);return u.useEffect(()=>{const N=l.current;N&&(o?N.play().catch(()=>c(!1)):N.pause())},[o,l]),u.useEffect(()=>{const N=l.current;if(!N)return;let R=-1;const P=a??null,j=P&&typeof P.scrollSmooth=="number"?P.scrollSmooth:.18;let M=performance.now();const I=()=>{var Y,O;const T=performance.now(),E=Math.max(0,Math.min(.2,(T-M)/1e3));M=T;const _=N.currentTime||0;p.current=_;let D=-1;for(let C=0;C<d.length;C++){const $=d[C];if(_>=$.start&&_<$.start+Math.max(.001,$.duration)){D=C;break}}D!==R&&(R=D,x(D));let q=0;if(R>=0){const C=((Y=d[R])==null?void 0:Y.lineIndex)??0,$=((O=h.current)==null?void 0:O.clientHeight)??220;q=C*m-$/2+m/2;const k=Math.max(0,S-$);(isNaN(q)||!isFinite(q))&&(q=0),q=Math.max(0,Math.min(q,k))}const te=1-Math.pow(Math.max(0,1-j),Math.min(4,E*60)),ae=(((a==null?void 0:a.scrollEasing)||"easeOutCubic")==="linear"?C=>C:C=>1-Math.pow(1-C,3))(te);y.current=y.current+(q-y.current)*ae;try{const C=h.current;C&&typeof C.scrollTop=="number"&&(C.scrollTop=Math.round(y.current))}catch{}f.current=requestAnimationFrame(I)};return f.current=requestAnimationFrame(I),()=>{f.current&&cancelAnimationFrame(f.current)}},[l,d,S,a]),r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[r.jsx("button",{onClick:()=>c(N=>!N),disabled:!t,children:o?"Pause":"Play"}),r.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-secondary, #666)"},children:[(p.current||0).toFixed(2),"s"]}),r.jsxs("div",{style:{marginLeft:"auto",fontSize:13,color:"var(--nice-text-secondary, #666)"},children:["Notes: ",d.length]})]}),r.jsx("div",{style:{border:"1px solid var(--nice-border, #ddd)",height:220,overflow:"hidden",padding:8,position:"relative"},children:e?r.jsx(se.NiceVirtualScroller,{ref:h,items:v,itemHeight:m,height:220,renderItem:w,style:{border:"none",borderRadius:0,background:"transparent",fontSize:"inherit"}}):r.jsx("div",{style:{color:"var(--nice-text-secondary, #888)"},children:s("karaokeEditor.noText","No text")})}),!n&&r.jsx("audio",{ref:i,src:t||void 0,preload:"metadata",style:{display:"none"}})]})};function dp(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+/),l=parseInt(i[0]||"0",10)/10||0,o=parseInt(i[1]||"0",10)/10||.1;n.push({lineIndex:a,start:l,duration:o})}}return{lines:t,notes:n}}const up=new Set;function hp({ultrastarText:e,audioUrl:t,audioRef:n,ytRef:a}){const{lines:s,notes:i}=u.useMemo(()=>dp(e),[e]),[l,o]=u.useState(up),c=u.useRef(i);c.current=i;const d=u.useRef(t);return d.current=t,u.useEffect(()=>{let h=null,f=null;if(!(a!=null&&a.current))if(n!=null&&n.current)h=n.current;else{const x=document.querySelector("audio");x instanceof HTMLAudioElement?h=x:d.current&&(f=document.createElement("audio"),f.src=d.current,f.preload="metadata",f.style.display="none",document.body.appendChild(f),h=f)}let p=0,y="";const g=()=>{let x=0;const v=a==null?void 0:a.current;if(v&&typeof v.getCurrentTime=="function")try{x=v.getCurrentTime()||0}catch{x=0}else x=h&&h.currentTime||0;const m=new Set;for(const b of c.current)x>=b.start&&x<b.start+Math.max(.001,b.duration)&&m.add(b.lineIndex);const S=[...m].join(",");S!==y&&(y=S,o(m)),p=requestAnimationFrame(g)};return p=requestAnimationFrame(g),()=>{cancelAnimationFrame(p),f==null||f.remove()}},[]),r.jsx("div",{style:{width:"100%",height:340,overflow:"hidden",background:"#101010",padding:"20px 0",boxSizing:"border-box"},children:s.map((h,f)=>{const p=l.has(f);return r.jsx("div",{"aria-current":p||void 0,style:{font:"18px monospace",lineHeight:"22px",whiteSpace:"pre",padding:"0 10px",color:p?"var(--nice-info, #00aaff)":"var(--nice-overlay-light-90, #e2e8f0)",background:p?"rgba(0,130,200,0.16)":void 0},children:h||" "},f)})})}const pp=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),ti=e=>{(!isFinite(e)||e<0)&&(e=0);const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`},ea={border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},fp=({isPlaying:e,index:t,count:n,currentTime:a,duration:s,volume:i,onPrev:l,onNext:o,onToggle:c,onSeek:d,onVolume:h})=>{const{t:f}=Te();return r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[r.jsx("div",{}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-secondary)"},children:[ti(a)," / ",ti(s)]})]}),r.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("button",{onClick:l,disabled:t<=0,title:f("playerControls.prev","Prev"),"aria-label":f("playerControls.previousTrack","Previous track"),style:ea,children:r.jsx(B.NtdSkipBack,{size:16})}),r.jsx("button",{onClick:c,title:e?f("playerControls.pause","Pause"):f("playerControls.play","Play"),"aria-label":e?f("playerControls.pause","Pause"):f("playerControls.play","Play"),style:ea,children:e?r.jsx(B.NtdPause,{size:16}):r.jsx(B.NtdPlay,{size:16})}),r.jsx("button",{onClick:o,disabled:t>=n-1,title:f("playerControls.next","Next"),"aria-label":f("playerControls.nextTrack","Next track"),style:ea,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":f("playerControls.seekPosition","Seek position"),onChange:p=>d(parseFloat(p.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":f("playerControls.volume","Volume"),onChange:p=>h(parseFloat(p.target.value))})]})]})]})},mp=u.memo(fp);function gp(e,t,n,a,s){const l=Math.max(1,Math.floor(a.length/48)),o=t/48;for(let c=0;c<48;c++){const d=a[c*l]/255,h=d*(n-6),f=c*o,p=n-h,y=c/48*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(f+1,p,o-2,h)}}function yp(e,t,n,a,s,i){if(!i.current){const f=[];for(let y=0;y<24;y++)f.push({ang:y/24*Math.PI*2,phase:Math.random()*Math.PI*2,baseR:Math.min(t,n)*.22+Math.random()*30});i.current={nodes:f}}const l=i.current,o=t/2,c=n/2,d=26+a*80,h=[];for(const f of l.nodes){f.phase+=.02+a*.06;const p=f.baseR+Math.sin(f.phase)*d,y=o+Math.cos(f.ang)*p,g=c+Math.sin(f.ang)*p;h.push([y,g])}e.fillStyle=`hsla(${s}, 70%, 55%, .22)`,e.strokeStyle=`hsla(${(s+40)%360}, 90%, 65%, .9)`,e.lineWidth=2,e.beginPath();for(let f=0;f<h.length;f++){const[p,y]=h[f],[g,x]=h[(f+1)%h.length],v=(p+g)/2,m=(y+x)/2;f===0?e.moveTo(v,m):e.quadraticCurveTo(p,y,v,m)}e.closePath(),e.fill(),e.stroke()}function vp(e,t,n,a,s,i){i.current||(i.current={items:[]});const l=i.current;Math.random()<.06+a*.25&&l.items.push({x:Math.random()*t,y:Math.random()*n,r:8+Math.random()*24,life:1,hue:(s+Math.random()*120)%360});const o=[];for(const c of l.items){c.r+=2+a*14,c.life*=.975-a*.02,c.life>.04&&o.push(c);const d=e.createRadialGradient(c.x,c.y,1,c.x,c.y,c.r);d.addColorStop(0,`hsla(${c.hue}, 90%, 60%, ${.35*c.life})`),d.addColorStop(.6,`hsla(${(c.hue+40)%360}, 80%, 55%, ${.18*c.life})`),d.addColorStop(1,`hsla(${(c.hue+80)%360}, 70%, 50%, 0)`),e.fillStyle=d,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}l.items=o}const bp="var(--nice-text-muted, #94a3b8)",xp=({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:bp},children:s??a??"—"})]})});function tn(e,t){return e+Math.random()*(t-e)}function Sp(e,t,n,a,s,i,l){l.current||(l.current={embers:[],t:0});const o=l.current,c=e.createLinearGradient(0,n,0,n*.4);c.addColorStop(0,`hsla(${(i+30)%360}, 90%, 50%, .35)`),c.addColorStop(1,`hsla(${(i+10)%360}, 90%, 50%, 0)`),e.fillStyle=c,e.fillRect(0,0,t,n);const d=6;for(let f=0;f<d;f++){const p=(f+.5)/d*t,y=(a[Math.floor((f+1)/(d+1)*a.length)]||0)/255,g=n*.18+(.25+s*.6+y*.7)*n*.55,x=e.createLinearGradient(p,n,p,n-g);x.addColorStop(0,`hsla(${(i+40)%360},100%,55%,.9)`),x.addColorStop(.5,`hsla(${(i+10)%360},100%,60%,.75)`),x.addColorStop(1,`hsla(${(i-20)%360},100%,80%,.05)`);const v=Math.sin(o.t*1.2+f*.8)*(15+s*30);e.fillStyle=x,e.beginPath(),e.moveTo(p-20,n),e.bezierCurveTo(p-35,n-g*.45,p-25+v,n-g*.75,p+v,n-g),e.bezierCurveTo(p+25+v*.3,n-g*.65,p+35,n-g*.35,p+20,n),e.closePath(),e.fill()}const h=Math.floor(1+s*6);for(let f=0;f<h;f++)o.embers.push({x:tn(t*.25,t*.75),y:n-tn(4,14),r:tn(1,3),vx:tn(-.15,.15),vy:-tn(.6,1.8)-s*1.2,life:tn(.8,1.6)});e.save(),e.globalCompositeOperation="lighter";for(let f=o.embers.length-1;f>=0;f--){const p=o.embers[f];if(p.x+=p.vx,p.y+=p.vy,p.vy-=.01,p.life-=.015+s*.02,p.life<=0||p.y<-10){o.embers.splice(f,1);continue}const y=e.createRadialGradient(p.x,p.y,0,p.x,p.y,p.r*3);y.addColorStop(0,`hsla(${(i+25)%360},100%,65%,.9)`),y.addColorStop(1,`hsla(${(i+25)%360},100%,65%,0)`),e.fillStyle=y,e.beginPath(),e.arc(p.x,p.y,p.r*3,0,Math.PI*2),e.fill()}e.restore(),e.fillStyle="rgba(60,36,22,.9)",e.fillRect(t*.2,n-10,t*.6,6),o.t+=.02+s*.08}function wp(e,t,n,a,s){const i=t/2,l=n/2,o=Math.min(t,n)*.28,c=96,d=Math.max(1,Math.floor(a.length/c));for(let h=0;h<c;h++){const f=(a[h*d]??0)/255,p=h/c*Math.PI*2,y=f*(Math.min(t,n)*.22)+6,g=i+Math.cos(p)*o,x=l+Math.sin(p)*o,v=i+Math.cos(p)*(o+y),m=l+Math.sin(p)*(o+y);e.strokeStyle=`hsl(${(s+h*3)%360}, 90%, ${40+f*40}%)`,e.lineWidth=3,e.beginPath(),e.moveTo(g,x),e.lineTo(v,m),e.stroke()}e.fillStyle=`hsla(${(s+180)%360}, 60%, 15%, .4)`,e.beginPath(),e.arc(i,l,o-8,0,Math.PI*2),e.fill()}function kp(e,t,n,a,s){const o=t/14,c=n/8;for(let d=0;d<8;d++)for(let h=0;h<14;h++){const f=Math.min(a.length-1,d*14+h),p=a[f]/255,y=(s+h/14*210+d/8*90)%360,g=65+p*30,x=20+p*40,v=(1-p)*4;e.fillStyle=`hsl(${y}, ${g}%, ${x}%)`,e.fillRect(h*o+v,d*c+v,Math.max(1,o-2*v),Math.max(1,c-2*v))}}function Cp(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 jp(e,t,n,a,s){e.current||(e.current={sprites:[],loadedUrls:[],ready:!1});const i=e.current,l=t.join("|")!==i.loadedUrls.join("|");if(!i.ready||l){const o=await Cp(t.length?t:[]);i.loadedUrls=t,i.sprites=[],i.ready=!0;const c=d=>o[d%Math.max(1,o.length)]??new Image;for(let d=0;d<n;d++){const h=Math.random()*Math.min(a,s)*.38+40;i.sprites.push({img:c(d),x:(Math.random()-.5)*h*.4,y:(Math.random()-.5)*h*.4,z:Math.random()*600+100,ang:Math.random()*Math.PI*2,spin:(Math.random()*.03+.01)*(Math.random()<.5?-1:1),vz:Math.random()*1.2+.2,size:Math.random()*.35+.65})}}}function Mp(e,t,n,a,s,i,l,o){const c=i.current;if(!(c!=null&&c.ready))return;const d=t/2,h=n/2,f=900,p=1+a*2;for(const g of c.sprites){g.ang+=g.spin*p,g.z-=g.vz*(.8+a*2.4),g.z<40&&(g.z=f);const x=Math.min(t,n)*.32+Math.sin(g.ang*.8)*18;g.x=Math.cos(g.ang)*x,g.y=Math.sin(g.ang*1.1)*x*.6}const y=[...c.sprites].sort((g,x)=>x.z-g.z);for(const g of y){const x=f/(f-g.z)*.6*g.size,v=d+g.x*x,m=h+g.y*x,S=64*x,b=64*x;e.save(),e.globalAlpha=.12+(1-g.z/f)*.2,e.fillStyle=`hsl(${(s+(1-g.z/f)*60)%360}, 90%, 60%)`,e.beginPath(),e.ellipse(v,m,S*.7,b*.7,0,0,Math.PI*2),e.fill(),e.restore(),g.img&&g.img.width?e.drawImage(g.img,v-S/2,m-b/2,S,b):(e.save(),e.fillStyle=`hsl(${(s+180)%360}, 40%, 55%)`,e.fillRect(v-S/2,m-b/2,S,b),e.restore())}}function kn(e,t){return e+Math.random()*(t-e)}function Rp(e,t,n,a,s,i){i.current||(i.current={blobs:Array.from({length:7},(d,h)=>({x:kn(t*.2,t*.8),y:kn(n*.2,n*.8),r:kn(Math.min(t,n)*.05,Math.min(t,n)*.12),vx:kn(-.6,.6),vy:kn(-.6,.6),hue:(s+h*10)%360}))});const l=i.current,o=.6+a*2.2;e.save(),e.globalCompositeOperation="lighter";for(const c of l.blobs){c.x+=c.vx*o,c.y+=c.vy*o,c.vy-=.01-a*.015,c.x<c.r&&(c.x=c.r,c.vx=Math.abs(c.vx)),c.x>t-c.r&&(c.x=t-c.r,c.vx=-Math.abs(c.vx)),c.y<c.r&&(c.y=c.r,c.vy=Math.abs(c.vy)),c.y>n-c.r&&(c.y=n-c.r,c.vy=-Math.abs(c.vy));const d=(c.hue+a*120)%360,h=e.createRadialGradient(c.x,c.y,c.r*.2,c.x,c.y,c.r);h.addColorStop(0,`hsla(${d}, 95%, 70%, .8)`),h.addColorStop(1,`hsla(${(d+40)%360}, 90%, 30%, 0)`),e.fillStyle=h,e.shadowBlur=18,e.shadowColor=`hsl(${d}, 100%, 60%)`,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}e.restore(),e.strokeStyle=we.resolveCssColor("var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",e.canvas),e.lineWidth=2,e.strokeRect(1,1,t-2,n-2)}function Np(e,t,n,a,s,i){i.current||(i.current={tris:[]});const l=i.current,o=6;for(;l.tris.length<o;)l.tris.push({a:Math.random()*Math.PI*2,r:30+Math.random()*Math.min(t,n)*.35,dr:(Math.random()*.6+.2)*(Math.random()<.5?-1:1)});const c=t/2,d=n/2;for(const h of l.tris){h.a+=.002+a*.02*(h.dr>0?1:-1),h.r+=Math.sin(h.a*2)*(.3+a*1.4);const f=Math.max(40,Math.min(h.r,Math.min(t,n)*.48));e.save(),e.translate(c,d),e.rotate(h.a),e.strokeStyle=`hsla(${(s+f*.2)%360}, 90%, 60%, .9)`,e.lineWidth=2.5,e.beginPath(),e.moveTo(f,0);for(let p=1;p<3;p++){const y=p*Math.PI*2/3;e.lineTo(Math.cos(y)*f,Math.sin(y)*f)}e.closePath(),e.shadowBlur=12,e.shadowColor=e.strokeStyle,e.stroke(),e.restore()}}function Tp(e,t,n,a,s,i){const l=t/2,o=n/2,c=5,d=Math.min(t,n)*.42;i.current+=.01;for(let h=0;h<c;h++){const f=(h+1)/(c+1),p=f*d;e.strokeStyle=`hsla(${(s+h*30)%360}, 70%, 45%, 0.35)`,e.lineWidth=1,e.beginPath(),e.arc(l,o,p,0,Math.PI*2),e.stroke();const y=Math.floor(a.length*f|0),g=(a[y]??0)/255,x=6+h*2;for(let v=0;v<x;v++){const m=i.current*(1+h*.15)+v/x*Math.PI*2,S=p+Math.sin(m*2)*6*g,b=l+Math.cos(m)*S,w=o+Math.sin(m)*S;e.fillStyle=`hsla(${(s+h*30+v*6)%360}, 90%, ${55+g*30}%, ${.6+g*.3})`,e.beginPath(),e.arc(b,w,2+g*4,0,Math.PI*2),e.fill()}}}function $p(e,t,n,a,s){const o=t/12,c=n/6;for(let d=0;d<6;d++)for(let h=0;h<12;h++){const f=(d*12+h)%a.length,p=a[f]/255,y=(s+h/12*180+d/6*90)%360,g=70+p*25,x=25+p*35;e.fillStyle=`hsl(${y}, ${g}%, ${x}%)`,e.fillRect(h*o,d*c,Math.ceil(o),Math.ceil(c))}}function Pp(e,t,n,a,s,i){const l=t/2,o=n/2,c=2+Math.floor(a*14);for(let h=0;h<c;h++){const f=Math.random()*Math.PI*2,p=.5+Math.random()*(2.5+a*4);i.current.push({x:l,y:o,vx:Math.cos(f)*p,vy:Math.sin(f)*p,life:0,max:40+Math.random()*60,hue:(s+Math.random()*60)%360})}e.fillStyle="rgba(2,6,23,0.2)",e.fillRect(0,0,t,n);const d=i.current;for(let h=d.length-1;h>=0;h--){const f=d[h];f.x+=f.vx,f.y+=f.vy,f.life+=1;const p=1-f.life/f.max;e.fillStyle=`hsla(${f.hue},85%,60%,${Math.max(0,p)})`,e.beginPath(),e.arc(f.x,f.y,2+p*3,0,Math.PI*2),e.fill(),(f.life>=f.max||f.x<-20||f.y<-20||f.x>t+20||f.y>n+20)&&d.splice(h,1)}d.length>1200&&d.splice(0,d.length-1200)}function Ap(e,t,n,a,s,i){e.fillStyle="rgba(10,16,28,0.25)",e.fillRect(0,0,t,n);const l=t/2,o=n/2,c=Math.min(t,n)*(.38+s*.12),d=e.createRadialGradient(l,o,c*.1,l,o,c);d.addColorStop(0,`hsla(${(i+200)%360},90%,70%,0.95)`),d.addColorStop(.5,`hsla(${(i+260)%360},80%,55%,0.6)`),d.addColorStop(1,"transparent"),e.fillStyle=d,e.beginPath(),e.arc(l,o,c,0,Math.PI*2),e.fill();const h=18+Math.floor(s*50);for(let f=0;f<h;f++){const p=f/h*Math.PI*2+a*(.6+s*1.4),y=(Math.sin(a*2+f*1.7)+Math.cos(a*1.3+f*2.1))*.15,g=c*(.4+.55*Math.abs(Math.sin(a*1.2+f))),x=6;e.save(),e.translate(l,o),e.rotate(p+y),e.beginPath(),e.moveTo(0,0);for(let m=1;m<=x;m++){const S=g/x*m,b=(Math.sin(a*3+f*.8+m)*.6+Math.cos(a*2+f+m*.7))*(8+24*s),w=S,N=b;e.lineTo(N,w)}e.globalCompositeOperation="lighter";const v=(i+f*(240/h))%360;e.strokeStyle=`hsla(${v}, 90%, ${60+s*20}%, ${.35+s*.4})`,e.lineWidth=2+s*2,e.stroke(),e.restore()}e.beginPath(),e.arc(l,o,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 Ep(e,t,n,a,s){const l=Math.max(1,Math.floor(a.length/96)),o=t/2,c=n/2,d=Math.min(t,n)*.22,h=Math.min(t,n)*.48;for(let f=0;f<96;f++){const p=a[f*l]/255,y=f/96*Math.PI*2,g=d,x=d+p*(h-d),v=o+Math.cos(y)*g,m=c+Math.sin(y)*g,S=o+Math.cos(y)*x,b=c+Math.sin(y)*x;e.strokeStyle=`hsl(${f/96*360+s},85%,60%)`,e.lineWidth=3,e.beginPath(),e.moveTo(v,m),e.lineTo(S,b),e.stroke()}e.fillStyle=we.resolveCssColor("var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.canvas),e.beginPath(),e.arc(o,c,d*.85,0,Math.PI*2),e.fill()}function Ip(e,t,n,a,s,i){const l=t/2,o=n/2,c=Math.min(t,n)*.5,d=ni(a,0,Math.floor(a.length*.1))/255,h=ni(a,Math.floor(a.length*.6),a.length)/255;i.current+=.01+h*.03;const f=24;for(let p=0;p<f;p++){const y=i.current+p/f*Math.PI*2,g=(.35+d*.55)*c,x=l+Math.cos(y)*g,v=o+Math.sin(y)*g,m=e.createRadialGradient(l,o,0,l,o,g),S=p/f*360+s;m.addColorStop(0,`hsla(${S},85%,65%,0.0)`),m.addColorStop(1,`hsla(${S},85%,65%,0.9)`),e.strokeStyle=m,e.lineWidth=6+h*8,e.beginPath(),e.moveTo(l,o),e.lineTo(x,v),e.stroke()}e.fillStyle="rgba(2,6,23,0.25)",e.fillRect(0,0,t,n)}function ni(e,t,n){let a=0,s=0;for(let i=t;i<n;i++)a+=e[i],s++;return s?a/s:0}function Lp(e,t,n,a,s,i){e.fillStyle="rgba(10,16,28,0.35)",e.fillRect(0,0,t,n);const l=n/2,o=Math.max(8,18-s*10),c=n*.35*(.6+s*.7),d=a.length,h=t/(d-1);e.beginPath();for(let y=0;y<d;y++){const g=(a[y]-128)/128,x=Math.sin(i*1.5+y*.03)*.12,v=y*h,m=l-o-(g+x)*c;y===0?e.moveTo(v,m):e.lineTo(v,m)}const f=e.createLinearGradient(0,0,0,l-o);f.addColorStop(0,"hsla(260,90%,75%,0.9)"),f.addColorStop(1,"hsla(220,85%,60%,0.4)"),e.strokeStyle=f,e.lineWidth=2,e.stroke(),e.beginPath();for(let y=0;y<d;y++){const g=(a[y]-128)/128,x=Math.cos(i*1.3+y*.035)*.12,v=y*h,m=l+o+(g+x)*c;y===0?e.moveTo(v,m):e.lineTo(v,m)}const p=e.createLinearGradient(0,l+o,0,n);p.addColorStop(0,"hsla(190,90%,65%,0.9)"),p.addColorStop(1,"hsla(160,85%,55%,0.4)"),e.strokeStyle=p,e.lineWidth=2,e.stroke(),e.globalCompositeOperation="lighter",e.strokeStyle=we.resolveCssColor("var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.canvas),e.lineWidth=6,e.beginPath(),e.moveTo(0,l-o),e.lineTo(t,l-o),e.stroke(),e.beginPath(),e.moveTo(0,l+o),e.lineTo(t,l+o),e.stroke(),e.globalCompositeOperation="source-over"}function zp(e,t,n,a,s,i){const l=t/2,o=n/2,c=5,d=Math.min(t,n)*.12;for(let h=0;h<c;h++){const f=Math.floor(h/c*a.length),p=a[f]/255,y=d+h*d*.55+p*d*.5,g=(i+h*40)%360;e.lineWidth=3+p*6,e.strokeStyle=`hsla(${g},80%,60%,${.5+.5*s})`,e.beginPath(),e.arc(l,o,y,0,Math.PI*2),e.stroke()}}function Dp(e,t,n,a,s){const i=Math.min(a.length,256),l=Math.max(1,Math.floor(a.length/i)),o=t/i;for(let c=0;c<i;c++){const d=a[c*l]/255,h=d*(n-6),f=c*o,p=n-h,y=c/i*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(f+1,p,o-2,h)}}function _p(e,t,n,a){e.current||(e.current={stars:[],ready:!1});const s=e.current;if(!s.ready||s.stars.length!==t){const i=[];for(let l=0;l<t;l++){const o={x:(Math.random()-.5)*n,y:(Math.random()-.5)*a,z:Math.random()*800+100,pz:0};i.push(o)}s.stars=i,s.ready=!0}}function Fp(e,t,n,a,s,i){const l=i.current,o=t/2,c=n/2,d=4+a*18;e.save(),e.translate(o,c);for(const h of l.stars){h.z-=d,h.z<20&&(h.x=(Math.random()-.5)*t,h.y=(Math.random()-.5)*n,h.z=900,h.pz=h.z);const f=h.x/h.z*600,p=h.y/h.z*600,y=h.x/h.pz*600,g=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,g),e.lineTo(f,p),e.stroke()}e.restore()}function Op(e,t,n,a){e.lineWidth=2,e.strokeStyle=we.resolveCssColor("var(--nice-primary-light, #c7d2fe)",e.canvas),e.beginPath();const s=t/a.length;for(let i=0;i<a.length;i++){const l=(a[i]-128)/128,o=i*s,c=n/2+l*(n*.45);i===0?e.moveTo(o,c):e.lineTo(o,c)}e.stroke()}const Bp=({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?"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}),fl=({modes:e=[],active:t,setActive:n,rows:a=2})=>{const{t:s}=Te(),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(l=>r.jsx(Bp,{active:t===l,onClick:()=>n(l),title:`${s("visualizer.mode","Mode")}: ${l}`,children:l},l))})})};function Gp(e,t){const[n,a]=u.useState(()=>{try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}});return u.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(n))}catch{}},[e,n]),[n,a]}const Wp=({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 l=120*(i/n);return r.jsx("div",{style:{width:6,height:18,borderRadius:2,background:i<a?`hsl(${l}, 80%, 50%)`:"var(--nice-text, #1f2937)"}},i)})})},Up="var(--player-bg, #0f172a)";function Vp(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 qp(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 ml=({kind:e,audioRef:t,width:n="100%",height:a=360,coverUrl:s,title:i,subtitle:l,label:o,defaultMode:c="cover",storageKey:d="gp-stage:mode",allowedModes:h,imageUrls:f,imageCount:p=14,autoAnimate:y=!1})=>{const g=u.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette","radial","rays","particles","rings","grid","imageTornado","colorRipples","starfield","orbitals","eqcircle","triangles","blob","plasma","lavaLamp","cozyFire","rift"],[e,h]),x=u.useMemo(()=>{const Y=g.includes(c)?c:g[0];try{const O=localStorage.getItem(d);if(!O)return Y;const C=JSON.parse(O);return g.includes(C)?C:Y}catch{return Y}},[g,c,d]),[v,m]=Gp(d,x),S=u.useRef(null),b=u.useRef(null),w=u.useRef(null),N=u.useRef(null),R=u.useRef(null),P=u.useRef(null),j=u.useRef(0),M=u.useRef(0),I=u.useRef([]),[T,E]=u.useState(0),_=u.useRef(null),D=u.useRef(null),q=u.useRef(null),te=u.useRef(null),z=u.useRef(null),U=u.useRef(null),Z=u.useRef(null),ae=v!=="cover"&&v!=="video";return u.useEffect(()=>{var A;if(e==="youtube"||(b.current&&(cancelAnimationFrame(b.current),b.current=null),!ae))return;Zt();const Y=qn(),O=t.current;if(!O&&!y)return;if(O&&!w.current)try{w.current=Y.createMediaElementSource(O)}catch{}if(O&&!N.current){const L=Y.createAnalyser();L.fftSize=2048,L.smoothingTimeConstant=.85,N.current=L;try{(A=w.current)==null||A.connect(L)}catch{}try{L.connect(Y.destination)}catch{}}const C=N.current;R.current=new Uint8Array(C?C.frequencyBinCount:1024),P.current=new Uint8Array(C?C.fftSize:2048);const $=()=>{const L=S.current,G=Math.max(1,Math.floor(window.devicePixelRatio||1));L.width=Math.floor(L.clientWidth*G),L.height=Math.floor(L.clientHeight*G);const F=L.getContext("2d");F==null||F.setTransform(1,0,0,1,0,0),F==null||F.scale(G,G)};$();const k=()=>$();window.addEventListener("resize",k),_p(q,220,S.current.width,S.current.height);const W=async()=>{const L=S.current;if(!L)return;const G=L.getContext("2d");if(!G)return;const F=Math.max(1,Math.floor(window.devicePixelRatio||1)),V=L.width/F,Q=L.height/F,le=performance.now()*.001,oe=v==="waveform"||v==="rift";C&&(oe?C.getByteTimeDomainData(P.current):C.getByteFrequencyData(R.current)),y&&(Vp(R.current,le),qp(P.current,le));let ne=0;const K=oe?P.current:R.current;for(let H=0;H<K.length;H++){const ie=oe?(K[H]-128)/128:K[H]/255;ne+=ie*ie}if(ne=Math.sqrt(ne/K.length),E(Math.min(1,ne)),G.clearRect(0,0,V,Q),v==="spectrum")Dp(G,V,Q,R.current,j.current);else if(v==="bars")gp(G,V,Q,R.current,j.current);else if(v==="waveform")Op(G,V,Q,P.current);else if(v==="palette"){const H=(j.current+ne*120)%360;$p(G,V,Q,R.current,H)}else if(v==="radial")Ep(G,V,Q,R.current,j.current);else if(v==="rays")Ip(G,V,Q,R.current,j.current,M);else if(v==="particles")Pp(G,V,Q,ne,j.current,I);else if(v==="rings")zp(G,V,Q,R.current,ne,j.current);else if(v==="grid"){const H=(j.current+ne*160)%360;kp(G,V,Q,R.current,H)}else if(v==="imageTornado"){const H=f!=null&&f.length?f:s?[s]:[];await jp(_,H,p,V,Q);const ie=(j.current+ne*100)%360;Mp(G,V,Q,ne,ie,_)}else if(v==="colorRipples"){const H=(j.current+ne*120)%360;vp(G,V,Q,ne,H,D)}else if(v==="starfield"){const H=(j.current+60)%360;Fp(G,V,Q,ne,H,q)}else if(v==="orbitals"){const H=(j.current+ne*180)%360;Tp(G,V,Q,R.current,H,M)}else if(v==="eqcircle"){const H=(j.current+120)%360;wp(G,V,Q,R.current,H)}else if(v==="triangles"){const H=(j.current+40)%360;Np(G,V,Q,ne,H,te)}else if(v==="blob"){const H=(j.current+90)%360;yp(G,V,Q,ne,H,z)}else if(v==="plasma"){const H=(j.current+ne*200)%360;Ap(G,V,Q,le,ne,H)}else if(v==="rift")Lp(G,V,Q,P.current,ne,le);else if(v==="lavaLamp"){const H=(j.current+ne*80)%360;Rp(G,V,Q,ne,H,U)}else if(v==="cozyFire"){const H=(j.current+ne*140)%360;Sp(G,V,Q,R.current,ne,H,Z)}j.current=(j.current+.4)%360,b.current=requestAnimationFrame(W)};return b.current=requestAnimationFrame(W),()=>{window.removeEventListener("resize",k),b.current&&cancelAnimationFrame(b.current)}},[ae,e,t,v,f,p,s,y]),r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none",background:v==="cover"?"transparent":Up},children:v==="cover"?r.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:r.jsx(xp,{height:a,coverUrl:s,title:i,subtitle:l,label:o})}):r.jsx("canvas",{ref:S,style:{width:typeof n=="number"?`${n}px`:n,height:a,borderRadius:8},role:"img","aria-label":"Stage visualizer canvas"})}),r.jsxs("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:[r.jsx(fl,{modes:g,active:v,setActive:m,rows:2}),r.jsx(Wp,{vu:T,hide:e==="youtube"})]})]})},Hp=({height:e,autoPlay:t,track:n,source:a,ytRef:s,audioRef:i,hlsRef:l,setVol:o,onEnd:c,volume:d,extractVideoId:h})=>{u.useEffect(()=>{const g=i.current;if(g){if(g.volume=d,g.crossOrigin=a!=null&&a.withCredentials?"use-credentials":"anonymous",(a==null?void 0:a.kind)==="hls"&&pp(a.url)){const x=()=>{g.src=a.url,g.load(),t&&g.play().catch(()=>{})};if(g.canPlayType("application/vnd.apple.mpegurl")){x();return}(async()=>{const m=(await import("hls.js")).default;if(m.isSupported()){const S=new m({xhrSetup:b=>{if(a!=null&&a.withCredentials&&(b.withCredentials=!0),a!=null&&a.headers)for(const[w,N]of Object.entries(a.headers))b.setRequestHeader(w,String(N))}});l.current=S,S.loadSource(a.url),S.attachMedia(g),S.on(m.Events.MANIFEST_PARSED,()=>t&&g.play().catch(()=>{}))}else x()})()}(a==null?void 0:a.kind)==="audio"&&a.url&&(g.src=a.url,g.load(),t&&g.play().catch(()=>{}))}},[a==null?void 0:a.url,a==null?void 0:a.kind,a==null?void 0:a.withCredentials,d,t]);const f=(a==null?void 0:a.kind)==="youtube",p=f?"video":"cover",y=`gp-stage:mode:${(a==null?void 0:a.kind)??"none"}`;return r.jsxs("div",{className:"gp-stage",style:{width:"100%",height:e,background:f?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(a==null?void 0:a.kind)==="youtube"&&r.jsx($a,{videoId:a.videoId??h(a.url),onReady:g=>{s.current=g.target,o(d),t&&g.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(ml,{kind:(a==null?void 0:a.kind)==="hls"?"hls":(a==null?void 0:a.kind)??"audio",audioRef:i,hlsRef:l,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:p,storageKey:y},`vis-${y}`)]})},Kp=({artist:e,title:t,hideControls:n=!0,isPlaying:a,onTimeUpdate:s,searchYouTubeByArtistTitle:i})=>{const{t:l}=Te(),[o,c]=u.useState(e||""),[d,h]=u.useState(t||""),[f,p]=u.useState(null),[y,g]=u.useState(null),x=u.useRef(null),[v,m]=u.useState({width:Math.min(560,window.innerWidth-32),height:Math.min(315,(window.innerWidth-32)*9/16)});u.useEffect(()=>{e&&t&&i&&i(e,t).then(p)},[e,t,i]),u.useEffect(()=>{y&&(a?y.playVideo():y.pauseVideo())},[a,y]),u.useEffect(()=>{if(y&&s){const b=setInterval(()=>{const w=y.getCurrentTime();s(w)},100);return()=>clearInterval(b)}},[y,s]),u.useEffect(()=>{const b=()=>{if(x.current){const w=x.current.clientWidth,N=Math.round(w*(9/16));m({width:w,height:N})}};return b(),window.addEventListener("resize",b),()=>window.removeEventListener("resize",b)},[]);const S=async()=>{if(!i)return;const b=await i(o,d);p(b)};return r.jsxs("div",{ref:x,style:{width:"100%",maxWidth:"900px",margin:"0 auto"},children:[(!e||!t||!f)&&r.jsxs("div",{children:[r.jsx("input",{value:o,onChange:b=>c(b.target.value),placeholder:l("youtubePlayer.artist","Artist"),"aria-label":l("youtubePlayer.artist","Artist")}),r.jsx("input",{value:d,onChange:b=>h(b.target.value),placeholder:l("youtubePlayer.title","Title"),"aria-label":l("youtubePlayer.title","Title")}),r.jsx("button",{onClick:S,children:l("youtubePlayer.search","Search")})]}),f&&r.jsxs("div",{children:[r.jsx($a,{videoId:f,opts:{width:v.width.toString(),height:v.height.toString(),playerVars:{autoplay:1,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,annotations:0}},onReady:b=>g(b.target)}),!n&&r.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px"},children:[r.jsxs("button",{onClick:()=>y==null?void 0:y.playVideo(),children:[r.jsx(B.NtdPlay,{size:14})," ",l("youtubePlayer.play","Play")]}),r.jsxs("button",{onClick:()=>y==null?void 0:y.pauseVideo(),children:[r.jsx(B.NtdPause,{size:14})," ",l("youtubePlayer.pause","Pause")]})]})]})]})},ri=e=>({name:e,dirs:new Map,files:[]}),Yp=e=>(e??[]).map(t=>t instanceof File?{file:t}:t),Zp=e=>e.replace(/\\/g,"/"),Xp=e=>{const t=ri("/");for(const n of e){const a=Zp(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 l=a[i];s.dirs.has(l)||s.dirs.set(l,ri(l)),s=s.dirs.get(l)}s.files.push({file:n.file,path:a[a.length-1]??n.file.name})}return t},ya=e=>e.slice().sort((t,n)=>(t.path??t.file.name).localeCompare(n.path??n.file.name)),Qp={tidal:B.NtdWave,spotify:B.NtdMusic,youtube:B.NtdPlay},va=({q:e,setQ:t,t:n})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[r.jsx("div",{style:{flex:1},children:r.jsx(se.NiceTextInput,{value:e,onChange:t,placeholder:n("libraryExplorer.searchPlaceholder","Search…"),size:"sm"})}),e&&r.jsx(se.NiceButton,{variant:"ghost",size:"sm",onClick:()=>t(""),children:r.jsx(B.NtdClose,{size:14})})]}),ba=({files:e,t,onOpenInEditor:n,onPlayFile:a})=>e.length?r.jsx("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:r.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[r.jsx("thead",{children:r.jsxs("tr",{style:{color:"var(--nice-text-muted, #94a3b8)",textAlign:"left"},children:[r.jsx("th",{style:{padding:"8px 12px",fontWeight:600},children:t("libraryExplorer.colFile","File")}),r.jsx("th",{style:{padding:"8px 12px",fontWeight:600},children:t("libraryExplorer.colType","Type")}),r.jsx("th",{style:{padding:"8px 12px",fontWeight:600,width:200},children:t("libraryExplorer.colActions","Actions")})]})}),r.jsx("tbody",{children:e.map(s=>{const i=s.path??s.file.name;return r.jsxs("tr",{style:{borderTop:"1px solid var(--nice-border, #1e293b)"},children:[r.jsx("td",{style:{padding:"6px 12px",maxWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),r.jsx("td",{style:{padding:"6px 12px",color:"var(--nice-text-muted, #94a3b8)"},children:s.file.type||"—"}),r.jsxs("td",{style:{padding:"6px 12px",display:"flex",gap:6},children:[n&&r.jsxs(se.NiceButton,{variant:"outline",size:"sm",onClick:()=>n(s.file),children:[r.jsx(B.NtdEdit,{size:13})," ",t("libraryExplorer.openInEditor","Edit")]}),a&&r.jsxs(se.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")}),gl=({streams:e,t,onPlayStream:n})=>e.length?r.jsxs("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:[r.jsx("div",{style:{padding:"8px 12px",fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:t("libraryExplorer.streaming","Streaming")}),r.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:e.map(a=>r.jsxs("li",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,borderTop:"1px solid var(--nice-border, #1e293b)",padding:"8px 12px"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.title}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",display:"flex",alignItems:"center",gap:4},children:[u.createElement(Qp[a.provider],{size:12})," ",a.provider.toUpperCase(),a.artist?` • ${a.artist}`:""]})]}),n&&r.jsxs(se.NiceButton,{variant:"primary",size:"sm",onClick:()=>n(a),children:[r.jsx(B.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]},`${a.provider}:${a.id}`))})]}):null,ta=({name:e,enabled:t})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 8px",fontSize:13},children:[r.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:t?"var(--nice-success, #10b981)":"var(--nice-border, #d1d5db)"}}),r.jsx("span",{style:{color:t?"inherit":"var(--nice-text-muted, #94a3b8)"},children:e})]}),Jp=({variant:e="full",files:t=[],streams:n=[],enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:l,className:o,t:c,style:d,id:h,accessMode:f,"data-testid":p})=>{const{t:y}=Te(),g=c??y,[x,v]=u.useState(""),m=u.useMemo(()=>Yp(t),[t]),S=u.useCallback(N=>{const R=x.trim().toLowerCase();return!R||N.toLowerCase().includes(R)},[x]),b=u.useMemo(()=>ya(m).filter(N=>S(`${N.path??N.file.name} ${N.file.type||""}`)),[m,S]),w=u.useMemo(()=>n.filter(N=>S(`${N.title} ${N.artist??""} ${N.provider}`)),[n,S]);return f==="hidden"?null:e==="minimal"?r.jsxs("div",{className:o,style:{display:"flex",flexDirection:"column",gap:12,...d},id:h,"data-testid":p,children:[r.jsx(va,{q:x,setQ:v,t:g}),r.jsx(ba,{files:b,t:g,onOpenInEditor:s,onPlayFile:i}),r.jsx(gl,{streams:w,t:g,onPlayStream:l})]}):e==="onlyFiles"?r.jsxs("div",{className:o,style:{display:"flex",flexDirection:"column",gap:12,...d},id:h,"data-testid":p,children:[r.jsx(va,{q:x,setQ:v,t:g}),r.jsx(ba,{files:b,t:g,onOpenInEditor:s,onPlayFile:i})]}):r.jsx(ef,{q:x,setQ:v,normFiles:m,filteredStreams:w,enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:l,className:o,style:d,id:h,"data-testid":p,t:g})},ef=({q:e,setQ:t,normFiles:n,filteredStreams:a,enableProviders:s,onOpenInEditor:i,onPlayFile:l,onPlayStream:o,className:c,style:d,id:h,"data-testid":f,t:p})=>{const y=u.useMemo(()=>Xp(n),[n]),[g,x]=u.useState({}),[v,m]=u.useState("/"),S=R=>x(P=>({...P,[R]:!P[R]})),b=(R,P)=>{const j=P==="/"?`/${R.name}`:`${P}${R.name}/`,M=P==="/"&&R.name==="/",I=g[j]??M,T=Array.from(R.dirs.keys()).sort();return r.jsxs("div",{children:[!M&&r.jsxs("button",{type:"button",onClick:()=>{S(j),m(j)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"4px 8px",border:"none",borderRadius:6,cursor:"pointer",textAlign:"left",background:v===j?"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:R.name})]}),(M||I)&&r.jsx("div",{style:{paddingLeft:M?0:16},children:T.map(E=>b(R.dirs.get(E),j))})]},j)},w=u.useMemo(()=>{let R;if(v==="/")R=ya(n);else{const P=v.replace(/^\//,"").split("/").filter(Boolean);let j=y;for(const M of P){const I=j.dirs.get(M);if(!I)return[];j=I}R=ya(j.files)}return e?R.filter(P=>(P.path??P.file.name).toLowerCase().includes(e.toLowerCase())):R},[v,y,n,e]),N={tidal:(s==null?void 0:s.tidal)??!0,spotify:(s==null?void 0:s.spotify)??!0,youtube:(s==null?void 0:s.youtube)??!0};return r.jsxs("div",{className:c,style:{display:"flex",gap:12,color:"var(--nice-text, #e2e8f0)",...d},id:h,"data-testid":f,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:p("libraryExplorer.library","Library")}),b(y,"/"),r.jsxs("div",{style:{marginTop:16,borderTop:"1px solid var(--nice-border, #1e293b)",paddingTop:8},children:[r.jsx("div",{style:{padding:"0 8px 4px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:p("libraryExplorer.streaming","Streaming")}),r.jsx(ta,{name:"Tidal",enabled:N.tidal}),r.jsx(ta,{name:"Spotify",enabled:N.spotify}),r.jsx(ta,{name:"YouTube",enabled:N.youtube})]})]}),r.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[r.jsx(va,{q:e,setQ:t,t:p}),r.jsx(ba,{files:w,t:p,onOpenInEditor:i,onPlayFile:l}),(N.tidal||N.spotify||N.youtube)&&r.jsx(gl,{streams:a.filter(R=>N[R.provider]),t:p,onPlayStream:o})]})]})},tf=({kind:e,color:t})=>{const n={width:14,height:14,viewBox:"0 0 24 24",fill:t,"aria-hidden":!0};switch(e){case"youtube":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M23 7.2s-.2-1.6-.9-2.3c-.8-.9-1.7-.9-2.1-1C16.9 3.5 12 3.5 12 3.5s-4.9 0-8 .4c-.4.1-1.3.1-2.1 1C1.2 5.6 1 7.2 1 7.2S.8 9.1.8 11v1.8c0 1.9.2 3.8.2 3.8s.2 1.6.9 2.3c.8.9 1.9.9 2.4 1 1.7.2 7.7.4 7.7.4s4.9 0 8-.4c.4-.1 1.3-.1 2.1-1 .7-.7.9-2.3.9-2.3s.2-1.9.2-3.8V11c0-1.9-.2-3.8-.2-3.8zM9.7 14.6V8.2l6.3 3.2-6.3 3.2z"})});case"spotify":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.59 14.42c-.18.3-.57.4-.87.21-2.39-1.46-5.4-1.79-8.95-.98-.34.08-.68-.13-.76-.47-.08-.34.13-.68.47-.76 3.88-.89 7.21-.5 9.89 1.13.31.19.4.58.22.87zm1.23-2.72c-.23.37-.71.49-1.08.26-2.74-1.69-6.92-2.18-10.16-1.19-.41.13-.85-.11-.97-.52-.13-.41.11-.85.52-.97 3.7-1.12 8.31-.58 11.45 1.34.37.23.49.71.24 1.08zm.11-2.84C14.55 8.84 9.5 8.66 6.43 9.6c-.49.15-1.01-.13-1.16-.62-.15-.49.13-1.01.62-1.16 3.52-1.07 9.1-.86 12.69 1.27.43.26.57.82.31 1.25-.26.43-.82.57-1.25.31z"})});case"tidal":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 2L8 6l4 4 4-4-4-4zM4 6L0 10l4 4 4-4-4-4zm16 0l-4 4 4 4 4-4-4-4zm-8 8l-4 4 4 4 4-4-4-4z"})});case"hls":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M2 12h2v6H2v-6zm4-4h2v10H6V8zm4-4h2v14h-2V4zm4 4h2v10h-2V8zm4 4h2v6h-2v-6z"})});case"audio":default:return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"})})}},Qa=({data:e,display:t,callbacks:n,state:a})=>{const{id:s,index:i,artist:l,title:o,version:c,lp:d,sourcesAvailable:h=[]}=e,{allowVersion:f=!0,dragHandleProps:p}=t,{onChange:y,onRemove:g,onMoveUp:x,onMoveDown:v,onChangeLp:m,onSelectSource:S}=n,{readOnly:b=!1,canMoveUp:w=!0,canMoveDown:N=!0,activeSource:R}=a,{t:P}=Te(),j=u.useRef(null);u.useEffect(()=>{!l&&j.current&&j.current.focus()},[l]);const M=_=>{if(!b&&_.key==="Enter"){const D=_.target.closest("div.gpi-row"),q=D==null?void 0:D.querySelectorAll("input[data-role='field']");if(!q||q.length===0)return;const te=Array.from(q).indexOf(_.target),z=q[te+1]??q[0];z==null||z.focus()}},I=_=>{const D=h.includes(_),q=R===_,te={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid var(--nice-border, #e5e7eb)",background:q?"var(--nice-selected-bg, #eef2ff)":"var(--nice-bg, #fff)",opacity:D?1:.35,cursor:D&&S&&!b?"pointer":"default",transition:"transform .05s ease"},z=_==="youtube"?"var(--nice-danger, #ff0000)":_==="spotify"?"var(--nice-success, #1db954)":_==="tidal"?"var(--nice-text, #111827)":_==="hls"?"var(--nice-accent, #7c3aed)":"var(--nice-text, #374151)",U=_==="youtube"?"YouTube":_==="spotify"?"Spotify":_==="tidal"?"TIDAL":_==="hls"?"HLS":"Audio",Z=P("playlistItem.sourceLabel","Source")+": "+U+(q?` ${P("playlistItem.sourceSelected","(selected)")}`:""),ae=()=>{!D||!S||b||S(_)};return r.jsx("button",{type:"button",title:U,onClick:ae,disabled:!D||b,style:te,"aria-pressed":q,"aria-label":Z,children:r.jsx(tf,{kind:_,color:z})},_)},T=["youtube","tidal","spotify","hls","audio"],E=typeof d=="number"?d:i+1;return r.jsxs("div",{className:"gpi-row",role:"group","aria-label":P("playlistItem.trackNumber","Track")+" "+(i+1),style:{display:"grid",gridTemplateColumns:f?"56px 1fr 1fr 1fr auto auto":"56px 1fr 1fr auto auto",gap:8,alignItems:"center"},children:[r.jsx("input",{type:"number",min:1,value:E,onChange:_=>m==null?void 0:m(Number(_.target.value)),disabled:b||!m,"aria-label":"Lp",title:P("playlistItem.positionOnList","Position in the list"),style:nf}),r.jsx("input",{ref:j,"data-role":"field",type:"text",value:l,onChange:_=>y({artist:_.target.value}),placeholder:"Artist",onKeyDown:M,disabled:b,"aria-label":"Artist",className:"gpi-input",style:na}),r.jsx("input",{"data-role":"field",type:"text",value:o,onChange:_=>y({title:_.target.value}),placeholder:"Title",onKeyDown:M,disabled:b,"aria-label":"Title",className:"gpi-input",style:na}),f&&r.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:_=>y({version:_.target.value||void 0}),placeholder:P("playlistItem.versionOptional","Version (optional)"),onKeyDown:M,disabled:b,"aria-label":"Version",className:"gpi-input",style:na}),r.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":P("playlistItem.availableSources","Available sources"),children:T.map(I)}),r.jsxs("div",{className:"gpi-actions",style:{display:"flex",gap:6,justifyContent:"flex-end"},children:[p&&r.jsx("button",{type:"button",...p,draggable:!0,"aria-label":P("playlistItem.dragReorder","Drag to reorder"),title:P("playlistItem.dragReorder","Drag to reorder"),style:tr,children:r.jsx(B.NtdMenu,{size:14})}),r.jsx("button",{type:"button",onClick:x,disabled:!w||b,"aria-label":P("playlistItem.moveUp","Move up"),title:P("playlistItem.moveUp","Move up"),style:tr,children:r.jsx(B.NtdArrowUp,{size:14})}),r.jsx("button",{type:"button",onClick:v,disabled:!N||b,"aria-label":P("playlistItem.moveDown","Move down"),title:P("playlistItem.moveDown","Move down"),style:tr,children:r.jsx(B.NtdArrowDown,{size:14})}),r.jsx("button",{type:"button",onClick:g,disabled:b,"aria-label":P("common.delete","Delete"),title:P("common.delete","Delete"),style:{...tr,color:"var(--nice-color-danger, #b91c1c)"},children:r.jsx(B.NtdClose,{size:14})})]})]})},nf={width:48,border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 6px",fontSize:14,textAlign:"center"},na={width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 10px",fontSize:14},tr={border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg, #fff)",padding:"6px 8px",borderRadius:6,cursor:"pointer"},xa=()=>Math.random().toString(36).slice(2,10),nr=e=>(e??[]).map(t=>({id:xa(),...t})),rf=e=>e.map(({id:t,...n})=>n),af=null,sf=e=>{const t=e.trim();if(!t)return null;const n=t.split(/\s[-–—]\s/);if(n.length<2){const l=t.split(/[;|]/).map(o=>o.trim());return l.length>=2?{artist:l[0],title:l[1],version:l[2]||void 0}:null}const a=n[0].trim(),s=n.slice(1).join(" - ").trim(),i=s.match(/^(.*?)\s*[([](.+?)[)\]]\s*$/);if(i){const l=i[1].trim(),o=i[2].trim();return{artist:a,title:l,version:o||void 0}}return{artist:a,title:s,version:void 0}},of=({value:e,defaultValue:t,onChange:n,allowVersion:a=!0,maxItems:s,addButtonLabel:i,emptyState:l=af,readOnly:o=!1,autoFocusNewItem:c=!0,enableBulkPaste:d=!0})=>{const{t:h}=Te(),f=e!==void 0,[p,y]=u.useState(()=>nr(e||t)),[g,x]=u.useState(""),v=u.useRef(null),[m,S]=u.useState(null);u.useEffect(()=>{f&&y(nr(e))},[f,JSON.stringify(e)]);const b=u.useCallback(Z=>{n==null||n(rf(Z))},[n]),w=u.useCallback(Z=>{if(f){const ae=Z(nr(e));b(ae)}else y(ae=>{const Y=Z(ae);return b(Y),Y})},[b,f,e]),N=s?p.length<s:!0,R=u.useCallback(()=>{!N||o||w(Z=>[...Z,{id:xa(),artist:"",title:"",version:void 0}])},[N,o,w]),P=u.useCallback((Z,ae)=>{w(Y=>Y.map(O=>O.id===Z?{...O,...ae}:O))},[w]),j=u.useCallback(Z=>{o||w(ae=>ae.filter(Y=>Y.id!==Z))},[o,w]),M=u.useCallback((Z,ae)=>{w(Y=>{const O=Y.findIndex(W=>W.id===Z);if(O<0)return Y;const C=O+ae;if(C<0||C>=Y.length)return Y;const $=[...Y],[k]=$.splice(O,1);return $.splice(C,0,k),$})},[w]),I=u.useCallback((Z,ae)=>{w(Y=>{const O=Y.findIndex(W=>W.id===Z);if(O<0)return Y;const C=Math.max(0,Math.min(Y.length-1,ae-1));if(O===C)return Y;const $=[...Y],[k]=$.splice(O,1);return $.splice(C,0,k),$})},[w]),T=Z=>ae=>{o||(v.current=Z,ae.dataTransfer.effectAllowed="move",ae.dataTransfer.setData("text/plain",Z))},E=Z=>ae=>{o||(ae.preventDefault(),ae.dataTransfer.dropEffect="move",S(Z))},_=Z=>()=>S(ae=>ae===Z?null:ae),D=Z=>ae=>{if(o)return;ae.preventDefault();const Y=v.current??ae.dataTransfer.getData("text/plain");S(null),v.current=null,!(!Y||Y===Z)&&w(O=>{const C=O.findIndex(A=>A.id===Y),$=O.findIndex(A=>A.id===Z);if(C<0||$<0||C===$)return O;const k=[...O],[W]=k.splice(C,1);return k.splice($,0,W),k})},q=()=>{v.current=null,S(null)},te=u.useCallback(()=>{if(!d||o)return;const ae=g.split(/\r?\n/).map(Y=>Y.trim()).filter(Boolean).map(sf).filter(Y=>!!Y);ae.length!==0&&(w(Y=>{const O=(s??1/0)-Y.length,C=ae.slice(0,Math.max(0,O)).map($=>({id:xa(),...$}));return[...Y,...C]}),x(""))},[d,o,g,s,w]);u.useEffect(()=>{},[p.length,c]);const z=l??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.")}),U=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:R,disabled:!N||o,className:"gp-add",style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},"aria-label":U,children:["+ ",U]})})]}),p.length===0?r.jsx("div",{className:"gp-empty",children:z}):r.jsx("ol",{className:"gp-list",style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:8},children:p.map((Z,ae)=>{const Y=m===Z.id;return r.jsx("li",{draggable:!o,onDragStart:T(Z.id),onDragOver:E(Z.id),onDragLeave:_(Z.id),onDrop:D(Z.id),onDragEnd:q,style:{border:Y?"2px dashed var(--nice-info, #6366f1)":"2px solid transparent",borderRadius:8,padding:Y?4:0},children:r.jsx(Qa,{data:{id:Z.id,index:ae,lp:ae+1,artist:Z.artist,title:Z.title,version:a?Z.version??void 0:void 0,sourcesAvailable:void 0},display:{allowVersion:a,dragHandleProps:{onDragStart:T(Z.id)}},callbacks:{onChange:O=>P(Z.id,O),onRemove:()=>j(Z.id),onMoveUp:()=>M(Z.id,-1),onMoveDown:()=>M(Z.id,1),onChangeLp:O=>I(Z.id,O)},state:{readOnly:o,canMoveUp:ae>0,canMoveDown:ae<p.length-1}})},Z.id)})}),d&&!o&&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:g,onChange:Z=>x(Z.target.value),placeholder:h("genericPlaylist.bulkPastePlaceholder",`Paste lines in format:
|
|
65
|
+
`}),r.jsxs("div",{ref:k,style:Q.container,children:[r.jsxs("div",{style:Q.header,children:[r.jsxs("h1",{style:{...Q.title,display:"inline-flex",alignItems:"center",gap:8},children:[r.jsx(F.NtdBarChart,{size:26})," ",f("vocalReport.title","Vocal Performance Report")]}),r.jsxs("p",{style:Q.subtitle,children:[T.songArtist," — ",T.songTitle," | ",f("vocalReport.difficulty","Difficulty"),": ",r.jsx("strong",{children:T.difficulty})," "," | ",new Date(T.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(I)}44, ${mt(I)})`,border:`3px solid ${mt(I)}`,boxShadow:`0 0 20px ${mt(I)}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(I)},children:[f("vocalReport.overallGrade","Overall grade"),": ",I.toFixed(1),"%"]}),r.jsx("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",maxWidth:360},children:N[L]??""})]})]})]}),r.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end",marginBottom:16,flexWrap:"wrap"},children:[r.jsxs("button",{style:Q.btnPrimary,onClick:R,children:[r.jsx(F.NtdDownload,{size:14})," ",f("vocalReport.downloadHtml","Download HTML")]}),r.jsxs("button",{style:Q.btnSecondary,onClick:M,children:[r.jsx(F.NtdPrint,{size:14})," ",f("vocalReport.printPdf","Print / PDF")]}),r.jsxs("button",{style:Q.btnSecondary,onClick:j,children:[r.jsx(F.NtdCode,{size:14})," ",f("vocalReport.exportJson","Export JSON")]}),r.jsxs("button",{style:Q.btnSecondary,onClick:u,children:[r.jsx(F.NtdClose,{size:14})," ",f("vocalReport.close","Close")]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++_,". ",f("vocalReport.scoreOverview","Score overview")]}),r.jsxs("div",{style:Q.kpiGrid,children:[r.jsxs("div",{style:Q.kpiCard,children:[r.jsx("div",{style:Q.kpiValue,children:T.totalScore.toLocaleString()}),r.jsx("div",{style:Q.kpiLabel,children:f("vocalReport.totalScore","Total score")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsx("div",{style:Q.kpiValue,children:T.classicScore.toLocaleString()}),r.jsx("div",{style:Q.kpiLabel,children:f("vocalReport.classicScore","Classic score")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsx("div",{style:Q.kpiValue,children:T.bonusScore.toLocaleString()}),r.jsx("div",{style:Q.kpiLabel,children:f("vocalReport.bonusScore","Bonus score")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsxs("div",{style:Q.kpiValue,children:[T.maxCombo,"×"]}),r.jsx("div",{style:Q.kpiLabel,children:f("vocalReport.maxCombo","Max combo")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsxs("div",{style:{...Q.kpiValue,color:mt(T.intonationAccuracyPct)},children:[T.intonationAccuracyPct,"%"]}),r.jsx("div",{style:Q.kpiLabel,children:f("vocalReport.intonationAccuracy","Intonation accuracy")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsxs("div",{style:{...Q.kpiValue,color:mt(T.perfectHitPct)},children:[T.perfectHitPct,"%"]}),r.jsx("div",{style:Q.kpiLabel,children:f("vocalReport.perfectHits","Perfect hits")})]})]}),w.length>1&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:Q.sectionTitle,children:[++_,". ",f("vocalReport.playerComparison","Player comparison")]}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:"#"}),r.jsx("th",{style:Q.th,children:f("vocalReport.player","Player")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.classic","Classic")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.bonus","Bonus")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.total","Total")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.intonation","Intonation")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.perfect","Perfect")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.range","Range")})]})}),r.jsx("tbody",{children:w.map((S,B)=>r.jsxs("tr",{children:[r.jsx("td",{style:Q.td,children:B+1}),r.jsx("td",{style:{...Q.tdBold,color:S.playerColor},children:S.playerName}),r.jsx("td",{style:Q.tdRight,children:S.classicScore.toLocaleString()}),r.jsx("td",{style:Q.tdRight,children:S.bonusScore.toLocaleString()}),r.jsx("td",{style:{...Q.tdRight,fontWeight:700,color:"var(--nice-warning, #fbbf24)"},children:S.totalScore.toLocaleString()}),r.jsx("td",{style:Q.tdRight,children:r.jsxs("span",{style:Q.badge(mt(S.intonationAccuracyPct)),children:[S.intonationAccuracyPct,"%"]})}),r.jsx("td",{style:Q.tdRight,children:r.jsxs("span",{style:Q.badge(mt(S.perfectHitPct)),children:[S.perfectHitPct,"%"]})}),r.jsxs("td",{style:Q.tdRight,children:[S.lowestNote,"–",S.highestNote]})]},B))})]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++_,". ",f("vocalReport.pitchAccuracy","Pitch accuracy")]}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:f("vocalReport.metric","Metric")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.value","Value")}),r.jsx("th",{style:Q.th,children:f("vocalReport.description","Description")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.meanAbsDev","Mean abs. deviation")}),r.jsxs("td",{style:Q.tdRight,children:[T.avgCentDeviation,r.jsxs("span",{style:Q.kpiUnit,children:[" ",$]})]}),r.jsx("td",{style:Q.td,children:f("vocalReport.meanAbsDevDesc","Average distance from the target pitch.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.medianDev","Median deviation")}),r.jsxs("td",{style:Q.tdRight,children:[T.medianCentDeviation,r.jsxs("span",{style:Q.kpiUnit,children:[" ",$]})]}),r.jsx("td",{style:Q.td,children:f("vocalReport.medianDevDesc","Typical deviation, robust to outliers.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.stdDev","Std. deviation")}),r.jsxs("td",{style:Q.tdRight,children:[T.stdDevCents,r.jsxs("span",{style:Q.kpiUnit,children:[" ",$]})]}),r.jsx("td",{style:Q.td,children:f("vocalReport.stdDevDesc","Consistency of pitch (lower = steadier).")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.intonationAccuracyLabel","Intonation accuracy")}),r.jsxs("td",{style:{...Q.tdRight,color:mt(T.intonationAccuracyPct)},children:[T.intonationAccuracyPct,"%"]}),r.jsx("td",{style:Q.td,children:f("vocalReport.intonationAccuracyDesc","Share of frames within tolerance.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.perfectHitRate","Perfect-hit rate")}),r.jsxs("td",{style:{...Q.tdRight,color:mt(T.perfectHitPct)},children:[T.perfectHitPct,"%"]}),r.jsx("td",{style:Q.td,children:f("vocalReport.perfectHitRateDesc","Notes hit dead-on.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.totalPitchSamples","Total pitch samples")}),r.jsx("td",{style:Q.tdRight,children:T.totalPitchPoints.toLocaleString()}),r.jsx("td",{style:Q.td,children:f("vocalReport.totalPitchSamplesDesc","Number of analysed pitch frames.")})]})]})]}),r.jsxs("div",{style:Q.chartWrap,children:[r.jsx("div",{style:Q.chartTitle,children:f("vocalReport.deviationDistribution","Deviation distribution")}),r.jsx("div",{style:{height:220},children:r.jsx(ie.NiceChart,{width:860,height:220,stacked:!0,showLegend:!1,categories:G.map(S=>S.centRange),series:Ks(G.map(S=>`${W} (${S.centRange})`),G.map(S=>S.count),G.map(S=>Xh(S.centRange)))})})]}),r.jsxs("div",{style:Q.row,children:[r.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[r.jsx("div",{style:Q.chartTitle,children:f("vocalReport.hitClassification","Hit classification")}),r.jsx("div",{style:{height:220},children:r.jsx(ie.NicePieChart,{width:400,height:260,data:Y.map(S=>({label:S.name,value:Ut(S.value),color:S.fill}))})})]}),r.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[r.jsx("div",{style:Q.chartTitle,children:f("vocalReport.performanceProfile","Performance profile")}),r.jsx("div",{style:{height:220},children:r.jsx(ie.NiceChart,{width:400,height:220,showLegend:!1,categories:ee.map(S=>S.metric),series:[{name:f("vocalReport.performanceProfile","Performance profile"),type:"radar",color:"var(--nice-info, #3b82f6)",data:ee.map(S=>Ut(S.value))},{name:"100%",type:"radar",color:"transparent",data:ee.map(S=>S.max)}]})})]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++_,". ",f("vocalReport.pitchTracking","Pitch tracking")]}),r.jsxs("div",{style:Q.chartWrap,children:[r.jsx("div",{style:Q.chartTitle,children:f("vocalReport.sungVsExpected","Sung vs expected")}),r.jsx("div",{style:{height:260},children:r.jsx(ie.NiceChart,{width:860,height:230,categories:Zs(V.map(S=>S.t)),series:[{name:f("vocalReport.expected","Expected"),type:"line",color:"var(--nice-success, #22c55e)",data:V.map(S=>Ut(S.expected))},{name:f("vocalReport.sung","Sung"),type:"line",color:"var(--nice-info, #3b82f6)",data:V.map(S=>Ut(S.sung))}]})})]}),r.jsxs("div",{style:Q.chartWrap,children:[r.jsx("div",{style:Q.chartTitle,children:f("vocalReport.rollingAccuracy","Rolling accuracy")}),r.jsx("div",{style:{height:180},children:r.jsx(ie.NiceChart,{width:860,height:180,showLegend:!1,categories:Zs(K.map(S=>S.t)),series:[{name:f("vocalReport.rollingAccuracy","Rolling accuracy"),type:"area",color:"var(--nice-accent, #8b5cf6)",data:K.map(S=>Ut(S.accuracy))}]})})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++_,". ",f("vocalReport.vocalRange","Vocal range")]}),r.jsxs("div",{style:Q.row,children:[r.jsx("div",{style:Q.half,children:r.jsx("table",{style:Q.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.lowestNote","Lowest note")}),r.jsx("td",{style:Q.tdRight,children:f("vocalReport.hz","{lowestNote} ({lowestHz} Hz)").replace("{lowestNote}",String(T.lowestNote)).replace("{lowestHz}",String(T.lowestHz))})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.highestNote","Highest note")}),r.jsx("td",{style:Q.tdRight,children:f("vocalReport.hz2","{highestNote} ({highestHz} Hz)").replace("{highestNote}",String(T.highestNote)).replace("{highestHz}",String(T.highestHz))})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.rangeLabel","Range")}),r.jsxs("td",{style:Q.tdRight,children:[T.rangeInSemitones," ",f("vocalReport.semitones","semitones")]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.tessitura","Tessitura")}),r.jsxs("td",{style:Q.tdRight,children:[T.tessituraLow," — ",T.tessituraHigh]})]})]})})}),r.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[r.jsx("div",{style:Q.chartTitle,children:f("vocalReport.chromagram","Chromagram")}),r.jsx("div",{style:{height:180},children:r.jsx(ie.NiceChart,{width:400,height:180,showLegend:!1,categories:O.map(S=>S.note),series:[{name:f("vocalReport.usagePct","Usage %"),type:"bar",color:"var(--nice-primary, #6366f1)",data:O.map(S=>Ut(S.pct))}]})})]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++_,". ",f("vocalReport.vibratoStability","Vibrato & stability")]}),r.jsxs("div",{style:Q.row,children:[r.jsx("div",{style:Q.half,children:r.jsx("table",{style:Q.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.vibratoDetected","Vibrato detected")}),r.jsx("td",{style:Q.tdRight,children:r.jsx("span",{style:Q.badge(T.vibrato.detected?"var(--nice-success, #22c55e)":"var(--nice-text-muted, #64748b)"),children:T.vibrato.detected?f("vocalReport.yes","Yes"):f("vocalReport.no","No")})})]}),T.vibrato.detected&&r.jsxs(r.Fragment,{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.avgRate","Avg. rate")}),r.jsxs("td",{style:Q.tdRight,children:[T.vibrato.avgRateHz," Hz"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.avgExtent","Avg. extent")}),r.jsxs("td",{style:Q.tdRight,children:["±",T.vibrato.avgExtentCents," ",$]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.regularity","Regularity")}),r.jsxs("td",{style:Q.tdRight,children:[T.vibrato.regularityPct,"%"]})]})]})]})})}),r.jsx("div",{style:Q.half,children:r.jsx("table",{style:Q.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.jitter","Jitter")}),r.jsxs("td",{style:Q.tdRight,children:[T.jitterPct,"%"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.vocalPresence","Vocal presence")}),r.jsxs("td",{style:Q.tdRight,children:[T.shimmerProxy,"%"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.avgOnsetDev","Avg. onset deviation")}),r.jsxs("td",{style:Q.tdRight,children:[T.avgOnsetDeviationMs," ms"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.rhythmStability","Rhythm stability")}),r.jsx("td",{style:Q.tdRight,children:r.jsxs("span",{style:Q.badge(mt(T.rhythmStabilityPct)),children:[T.rhythmStabilityPct,"%"]})})]})]})})})]}),T.verseMetrics.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:Q.sectionTitle,children:[++_,". ",f("vocalReport.verseBreakdown","Per-verse breakdown")]}),r.jsxs("div",{style:Q.chartWrap,children:[r.jsx("div",{style:Q.chartTitle,children:f("vocalReport.accuracyByVerse","Accuracy by verse")}),r.jsx("div",{style:{height:200},children:r.jsx(ie.NiceChart,{width:860,height:200,stacked:!0,showLegend:!1,categories:U.map(S=>S.verse),series:Ks(U.map(S=>`${C} (${S.verse})`),U.map(S=>S.accuracy),U.map(S=>Hs(S.label)))})})]}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:f("vocalReport.verse","Verse")}),r.jsx("th",{style:Q.th,children:f("vocalReport.rating","Rating")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.hitPct","Hit %")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.avgDeviation","Avg. dev.")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.notes","Notes")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.notesHit","Hit")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.comboBonus","Combo bonus")})]})}),r.jsx("tbody",{children:T.verseMetrics.map((S,B)=>r.jsxs("tr",{children:[r.jsxs("td",{style:Q.td,children:[f("vocalReport.verse","Verse")," ",S.verseIndex+1]}),r.jsx("td",{style:Q.td,children:r.jsx("span",{style:Q.badge(Hs(S.label)),children:S.label})}),r.jsxs("td",{style:Q.tdRight,children:[(S.hitFraction*100).toFixed(1),"%"]}),r.jsxs("td",{style:Q.tdRight,children:[S.avgCentDeviation," ¢"]}),r.jsx("td",{style:Q.tdRight,children:S.noteCount}),r.jsx("td",{style:Q.tdRight,children:S.notesHit}),r.jsxs("td",{style:Q.tdRight,children:["+",S.comboBonus]})]},B))})]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++_,". ",f("vocalReport.scoringConfig","Scoring configuration")]}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:f("vocalReport.parameter","Parameter")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.value","Value")}),r.jsx("th",{style:Q.th,children:f("vocalReport.description","Description")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.difficultyLevel","Difficulty level")}),r.jsx("td",{style:Q.tdRight,children:T.difficulty}),r.jsx("td",{style:Q.td,children:f("vocalReport.difficultyLevelDesc","Affects tolerance and multiplier.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.semitoneTolerance","Semitone tolerance")}),r.jsx("td",{style:Q.tdRight,children:A.semitoneTolerance}),r.jsx("td",{style:Q.td,children:f("vocalReport.semitoneToleranceDesc","Pitch window counted as a hit.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.preWindow","Pre window")}),r.jsxs("td",{style:Q.tdRight,children:[A.preWindow," s"]}),r.jsx("td",{style:Q.td,children:f("vocalReport.preWindowDesc","Lead-in time before a note.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.postExtra","Post extra")}),r.jsxs("td",{style:Q.tdRight,children:[A.postExtra," s"]}),r.jsx("td",{style:Q.td,children:f("vocalReport.postExtraDesc","Grace time after a note.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.difficultyMultiplier","Difficulty multiplier")}),r.jsxs("td",{style:Q.tdRight,children:[A.difficultyMult,"×"]}),r.jsx("td",{style:Q.td,children:f("vocalReport.difficultyMultiplierDesc","Score scaling for difficulty.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.songBpm","Song BPM")}),r.jsx("td",{style:Q.tdRight,children:T.songBpm}),r.jsx("td",{style:Q.td,children:f("vocalReport.songBpmDesc","Tempo used for note timing.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.totalNotes","Total notes")}),r.jsx("td",{style:Q.tdRight,children:P}),r.jsx("td",{style:Q.td,children:f("vocalReport.totalNotesDesc","Number of scored notes in the song.")})]})]})]}),w.some(S=>S.micSettings)&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:Q.sectionTitle,children:[++_,". ",f("vocalReport.micConfig","Microphone configuration")]}),w.map((S,B)=>S.micSettings&&r.jsxs("div",{style:{marginBottom:16},children:[w.length>1&&r.jsx("h4",{style:{color:S.playerColor,margin:"0 0 8px",fontSize:14},children:S.playerName}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:f("vocalReport.setting","Setting")}),r.jsx("th",{style:Q.thRight,children:f("vocalReport.value","Value")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.device","Device")}),r.jsx("td",{style:Q.tdRight,children:S.micSettings.deviceLabel||S.micSettings.deviceId})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.pitchAlgorithm","Pitch algorithm")}),r.jsx("td",{style:Q.tdRight,children:S.micSettings.algorithm})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.inputGain","Input gain")}),r.jsxs("td",{style:Q.tdRight,children:[S.micSettings.gain,"×"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.rmsThreshold","RMS threshold")}),r.jsx("td",{style:Q.tdRight,children:S.micSettings.rmsThreshold})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.pitchThreshold","Pitch threshold")}),r.jsx("td",{style:Q.tdRight,children:S.micSettings.pitchThreshold})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.smoothingWindow","Smoothing window")}),r.jsxs("td",{style:Q.tdRight,children:[S.micSettings.smoothingWindow," ",f("vocalReport.frames","frames")]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.hysteresisFrames","Hysteresis frames")}),r.jsx("td",{style:Q.tdRight,children:S.micSettings.hysteresisFrames})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.hanningWindow","Hanning window")}),r.jsx("td",{style:Q.tdRight,children:S.micSettings.useHanning?f("vocalReport.enabled","Enabled"):f("vocalReport.disabled","Disabled")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.latencyOffset","Latency offset")}),r.jsxs("td",{style:Q.tdRight,children:[S.micSettings.latencyOffsetMs," ms"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:f("vocalReport.monitor","Monitor")}),r.jsx("td",{style:Q.tdRight,children:S.micSettings.monitorEnabled?`${f("vocalReport.on","On")} (${Math.round(S.micSettings.monitorVolume*100)}%)`:f("vocalReport.off","Off")})]})]})]})]},B))]}),r.jsx("div",{style:Q.footer,children:r.jsxs("p",{children:[f("vocalReport.footerGenerated","Report generated")," ·"," ",T.timestamp.replace(/[-:T.Z]/g,"").slice(0,14)]})})]})]})},Jh="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100'%3E%3Crect width='100' height='100' fill='%23334155'/%3E%3Ccircle cx='42' cy='64' r='8' fill='%2394a3b8'/%3E%3Crect x='48' y='34' width='3' height='32' fill='%2394a3b8'/%3E%3C/svg%3E";function ep(e){if(!e)return"";const t=Math.floor(e/60),n=Math.round(e%60);return`${t}:${n.toString().padStart(2,"0")}`}function Qs(e){return Array.from(new Set(e.filter(t=>!!t))).sort((t,n)=>t.localeCompare(n))}const tp=Object.assign(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:ep(e.durationSec)}):null,e.externalSource&&r.jsx("span",{className:"nice-ksb-badge nice-ksb-badge--src",children:e.externalSource}),s&&r.jsxs("span",{className:"nice-ksb-badge nice-ksb-badge--score",title:s.playerName,children:[r.jsx(F.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(F.NtdPlay,{size:13})," ",c("karaokeBrowser.play","Play")]})]})}),{displayName:"NiceKaraokeSongRow"}),np={artist:"Artist",title:"Title",year:"Year",genre:"Genre"},rp=({songs:e,fetchSongs:t,loading:n=!1,getCover:a,getTopScore:s,onPlay:i,onSelect:o,multiSelect:l=!1,maxSelections:c=0,showSidebar:u=!0,enableGamepad:h=!0,disabled:p=!1,disabledReason:g,t:y,className:m,style:x,id:b,accessMode:f,"data-testid":k})=>{const{t:v}=xe(),w=y??v,[R,M]=d.useState(""),[j,T]=d.useState(""),[P,A]=d.useState(""),[I,L]=d.useState(""),[N,_]=d.useState("artist"),[ee,Y]=d.useState("asc"),[O,U]=d.useState({type:"all"}),[V,K]=d.useState(new Set),[G,W]=d.useState([]),[C,$]=d.useState(!1);d.useEffect(()=>{const he=setTimeout(()=>T(R),300);return()=>clearTimeout(he)},[R]),d.useEffect(()=>{if(e||!t)return;let he=!1;return $(!0),Promise.resolve(t({searchQuery:j.trim()||void 0,genres:P?[P]:void 0,languages:I?[I]:void 0})).then(we=>!he&&W(we)).catch(()=>!he&&W([])).finally(()=>!he&&$(!1)),()=>{he=!0}},[e,t,j,P,I]);const S=e??G,B=d.useMemo(()=>Qs(S.map(he=>he.genre)),[S]),H=d.useMemo(()=>Qs(S.map(he=>he.language)),[S]),z=d.useMemo(()=>{let he=S;const we=j.trim().toLowerCase();we&&(he=he.filter(Ne=>`${Ne.title} ${Ne.artist}`.toLowerCase().includes(we))),P&&(he=he.filter(Ne=>Ne.genre===P)),I&&(he=he.filter(Ne=>Ne.language===I)),O.type==="genre"&&(he=he.filter(Ne=>Ne.genre===O.value)),O.type==="language"&&(he=he.filter(Ne=>Ne.language===O.value));const je=ee==="asc"?1:-1;return[...he].sort((Ne,Ee)=>{const Ye=Ne[N]??"",ue=Ee[N]??"";return typeof Ye=="number"&&typeof ue=="number"?(Ye-ue)*je:String(Ye).localeCompare(String(ue))*je})},[S,j,P,I,O,N,ee]),Z=he=>{K(we=>{const je=new Set(we);return je.has(he)?je.delete(he):(c===0||je.size<c)&&je.add(he),je})},E=()=>{const he=S.filter(we=>V.has(we.id));o==null||o({songs:he})},q=n||C,X=he=>{he===N?Y(we=>we==="asc"?"desc":"asc"):(_(he),Y("asc"))},re=d.useRef(null),[oe,se]=d.useState(0),D=d.useRef(0),J=d.useRef(z);J.current=z,d.useEffect(()=>{se(he=>{const we=Math.min(Math.max(0,he),Math.max(0,z.length-1));return D.current=we,we})},[z.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=>{D.current=he,se(he)},[]),le=d.useCallback((he,we=!0)=>{const je=J.current.length;if(je===0)return;const Ne=Math.min(je-1,Math.max(0,he));D.current=Ne,se(Ne),we&&requestAnimationFrame(()=>ae(Ne))},[ae]),ne=d.useCallback(he=>le(D.current+he),[le]),pe=he=>{const we=J.current[he];we&&(l?Z(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(J.current.length-1);break;case"PageDown":he.preventDefault(),ne(5);break;case"PageUp":he.preventDefault(),ne(-5);break}},me=ke.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(D.current)},confirm:{button:"Start",onPress:()=>{l&&E()}}}});return f==="hidden"?null:r.jsxs("div",{className:`nice-ksb${m?` ${m}`:""}`,style:x,id:b,"data-testid":k,children:[u&&r.jsxs("aside",{className:"nice-ksb__sidebar",children:[r.jsxs("button",{type:"button",className:`nice-ksb__node${O.type==="all"?" nice-ksb__node--active":""}`,onClick:()=>U({type:"all"}),children:[r.jsx(F.NtdMusic,{size:14})," ",w("karaokeBrowser.allSongs","All songs")," (",S.length,")"]}),B.length>0&&r.jsxs("div",{className:"nice-ksb__facet",children:[r.jsx("div",{className:"nice-ksb__facet-title",children:w("karaokeBrowser.genres","Genres")}),B.map(he=>r.jsx("button",{type:"button",className:`nice-ksb__node${O.type==="genre"&&O.value===he?" nice-ksb__node--active":""}`,onClick:()=>U({type:"genre",value:he}),children:he},he))]}),H.length>0&&r.jsxs("div",{className:"nice-ksb__facet",children:[r.jsx("div",{className:"nice-ksb__facet-title",children:w("karaokeBrowser.languages","Languages")}),H.map(he=>r.jsx("button",{type:"button",className:`nice-ksb__node${O.type==="language"&&O.value===he?" nice-ksb__node--active":""}`,onClick:()=>U({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:R,placeholder:w("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${N===he?" nice-ksb__sort-btn--active":""}`,onClick:()=>X(he),children:[w(`karaokeBrowser.sort.${he}`,np[he]??he),N===he&&(ee==="asc"?r.jsx(F.NtdChevronUp,{size:12}):r.jsx(F.NtdChevronDown,{size:12}))]},he))}),r.jsxs("span",{className:`nice-ksb__navhint${me.connected?" nice-ksb__navhint--pad":""}`,title:w("karaokeBrowser.navHint","Navigate with ↑ ↓ or the D-pad · Enter / A to play"),children:[me.connected?r.jsx(F.NtdGamepad,{size:14}):r.jsx(F.NtdMove,{size:14}),r.jsx("span",{className:"nice-ksb__navhint-keys",children:me.connected?"D-pad · A":"↑ ↓ · Enter"})]})]}),p&&g&&r.jsx("div",{className:"nice-ksb__disabled",children:g}),r.jsx("div",{className:"nice-ksb__list",role:"listbox","aria-multiselectable":l,"aria-label":w("karaokeBrowser.songs","Songs"),ref:re,onKeyDown:fe,children:q?r.jsx("div",{className:"nice-ksb__empty",children:w("karaokeBrowser.loading","Loading…")}):z.length===0?r.jsx("div",{className:"nice-ksb__empty",children:w("karaokeBrowser.noResults","No songs found")}):z.map((he,we)=>r.jsx(tp,{song:he,index:we,active:we===oe,coverUrl:(a==null?void 0:a(he))||he.coverImage||he.externalCoverUrl||he.coverPath||Jh,topScore:s==null?void 0:s(he),selected:V.has(he.id),multiSelect:l,disabled:p,t:w,onPlay:i,onToggleSelect:Z,onFocusRow:ce},he.id))}),l&&r.jsxs("div",{className:"nice-ksb__footer",children:[r.jsxs("span",{children:[V.size,c>0?` / ${c}`:""," ",w("karaokeBrowser.selected","selected")]}),r.jsx("button",{type:"button",className:"nice-ksb__confirm",disabled:V.size===0,onClick:E,children:w("karaokeBrowser.confirm","Add selected")})]})]})]})};function ll(e,t,n=50,a=30){const s=Math.round(e/1e3*t),i=Math.round(n/1e3*t),o=Math.max(1,Math.round(a/1e3*t)),l=new Float32Array(s);for(let c=0;c<o;c++){const 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 Js(e,t,n=1e3){const a=Math.max(1,Math.round(t/n)),s=Math.ceil(e.length/a),i=new Float32Array(s);for(let l=0;l<s;l++){const c=l*a,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 ap(e,t){const n=e.length,a=t.length;if(n===0||a===0)return 0;let s={lag:0,score:-1/0};const i=Math.min(2e3,a);for(let o=-i;o<=i;o++){let l=0,c=0,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 cl(e,t,n=50,a=30){try{const s=Math.max(300,Math.round(e.length/t*1e3)),i=ll(s,t,n,a),o=Js(e,t,1e3),l=Js(i,t,1e3),u=ap(l.env,o.env)*1e3/1e3;return Math.round(u)}catch{return null}}const sp=({deviceId:e,initialOffsetMs:t=null,onSave:n,onClose:a,rounds:s=3,t:i,className:o,style:l,id:c,accessMode:u,"data-testid":h})=>{const{t:p}=xe(),g=i??p,[y,m]=d.useState(null),[x,b]=d.useState(t),[f,k]=d.useState(!1),[v,w]=d.useState([]),[R,M]=d.useState(0),[j,T]=d.useState(!1),P=d.useRef(!1);d.useEffect(()=>{b(t??null)},[t,e]);const A=async()=>{const _=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),ee=new AudioContext,Y=ee.sampleRate,O=ee.createMediaStreamSource(_),U=ee.createScriptProcessor(2048,1,1);O.connect(U),U.connect(ee.destination);const V=1200,K=Math.round(V/1e3*Y),G=new Float32Array(K);let W=0,C=!1;U.onaudioprocess=Z=>{if(C)return;const E=Z.inputBuffer.getChannelData(0),q=Math.min(E.length,K-W);q>0&&(G.set(E.subarray(0,q),W),W+=q),W>=K&&(C=!0)},await new Promise(Z=>setTimeout(Z,80));const $=new AudioContext,S=$.createOscillator(),B=$.createGain();S.type="sine",S.frequency.value=1e3,B.gain.value=1e-4,S.connect(B),B.connect($.destination);const H=$.currentTime+.05;B.gain.setValueAtTime(1e-4,H-.01),B.gain.linearRampToValueAtTime(1,H),B.gain.linearRampToValueAtTime(1e-4,H+.06),S.start(H-.02),S.stop(H+.1),await new Promise(Z=>{const E=()=>{if(C||W>=K){Z();return}setTimeout(E,50)};setTimeout(()=>{C=!0,Z()},V+500),E()}),U.onaudioprocess=null;try{U.disconnect()}catch{}try{O.disconnect()}catch{}try{await $.close()}catch{}try{await ee.close()}catch{}_.getTracks().forEach(Z=>Z.stop());const z=G.subarray(0,W);return cl(z,Y,130,30)},I=async()=>{if(!P.current){P.current=!0,T(!0),m(g("latencyCalibrator.requestingMic","Requesting microphone — click allow if prompted")),b(null),w([]),M(0);try{const _=[];for(let Y=0;Y<s;Y++){m(`${g("latencyCalibrator.playingTone","Playing test tone and recording…")} (${Y+1}/${s})`),M(Math.round(Y/s*100));const O=await A();O!==null&&(_.push(Math.max(-500,Math.min(2e3,Math.round(O)))),w([..._])),Y<s-1&&await new Promise(U=>setTimeout(U,400))}if(M(100),_.length===0){m(g("latencyCalibrator.noSignal","No signal detected — try louder or check the microphone"));return}let ee;if(_.length>=3){const O=[..._].sort((U,V)=>U-V).slice(1,-1);ee=Math.round(O.reduce((U,V)=>U+V,0)/O.length)}else ee=Math.round(_.reduce((Y,O)=>Y+O,0)/_.length);b(ee),m(`${g("latencyCalibrator.measured","Measured")} ~${ee} ms (${_.length}: ${_.join(", ")} ms)`)}catch(_){m(`${g("latencyCalibrator.calibrationError","Calibration error: ")}${_ instanceof Error?_.message:String(_)}`)}finally{P.current=!1,T(!1)}}},L=async()=>{if(!(x===null||!n)){k(!0);try{await n(Math.round(x)),m(g("latencyCalibrator.saved","Saved"))}catch(_){m(`${g("latencyCalibrator.saveError","Save error: ")}${String(_)}`)}finally{k(!1)}}},N={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(F.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:I,disabled:j,style:{...N,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),w([]),M(0)},style:{...N,background:"var(--nice-bg-tertiary)",color:"var(--nice-text, #e2e8f0)"},children:g("latencyCalibrator.clear","Clear")})]}),j&&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:`${R}%`,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:{...N,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:{...N,background:"transparent",border:"1px solid var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)"},children:g("latencyCalibrator.close","Close")})]})]})},ip=e=>[{value:"normal",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(F.NtdMicrophone,{size:14})," ",e("karaokeSetup.modeMic","Mic")]})},{value:"pad",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(F.NtdGamepad,{size:14})," ",e("karaokeSetup.modePad","Pad")]})},{value:"demo",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(F.NtdStopwatch,{size:14})," ",e("karaokeSetup.modeDemo","Demo")]})}],dl=({players:e,defaultPlayers:t,onPlayersChange:n,gameMode:a="normal",onGameModeChange:s,gameModes:i,difficulty:o="normal",onDifficultyChange:l,audioInputs:c,maxPlayers:u=4,onCalibrate:h,t:p,className:g,style:y,id:m,accessMode:x,"data-testid":b})=>{const{t:f}=xe(),k=p??f,v=d.useMemo(()=>i??ip(k),[i,k]),[w,R]=ke.useControllableState({value:e,defaultValue:t,fallbackValue:[],onChange:n,componentName:"NiceKaraokeSetupPanel"}),[M,j]=d.useState([]);d.useEffect(()=>{var ee,Y,O;if(c||!((ee=navigator.mediaDevices)!=null&&ee.enumerateDevices))return;let N=!1;const _=()=>navigator.mediaDevices.enumerateDevices().then(U=>!N&&j(U.filter(V=>V.kind==="audioinput"))).catch(()=>{});return _(),(O=(Y=navigator.mediaDevices).addEventListener)==null||O.call(Y,"devicechange",_),()=>{var U,V;N=!0,(V=(U=navigator.mediaDevices).removeEventListener)==null||V.call(U,"devicechange",_)}},[c]);const T=c??M,P=d.useMemo(()=>[{value:"",label:k("karaokeSetup.noMic","No microphone")},...T.map((N,_)=>({value:N.deviceId,label:N.label||`${k("karaokeSetup.microphone","Microphone")} ${_+1}`}))],[T,k]),A=(N,_)=>R(w.map(ee=>ee.id===N?{...ee,..._}:ee)),I=()=>{if(w.length>=u)return;const N=w.reduce((_,ee)=>Math.max(_,ee.id),0)+1;R([...w,{id:N,name:`${k("karaokeSetup.player","Player")} ${w.length+1}`,color:Xe[w.length%Xe.length],micId:null}])},L=N=>R(w.filter(_=>_.id!==N));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:k("karaokeSetup.mode","Game mode")}),r.jsx(ie.NiceSegmentedControl,{options:v,value:a,onChange:N=>s==null?void 0:s(N)})]}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:12,fontWeight:600,marginBottom:6,color:"var(--nice-text-muted, #94a3b8)"},children:k("karaokeSetup.difficulty","Difficulty")}),r.jsx(ie.NiceSegmentedControl,{options:[{value:"easy",label:k("karaokeSetup.easy","Easy")},{value:"normal",label:k("karaokeSetup.normal","Normal")},{value:"hard",label:k("karaokeSetup.hard","Hard")}],value:o,onChange:N=>l==null?void 0:l(N)})]})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[r.jsxs("div",{style:{fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:[k("karaokeSetup.players","Players")," (",w.length,"/",u,")"]}),w.map(N=>r.jsx(ie.NiceCard,{children:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[r.jsx(ie.NiceColorPicker,{value:N.color||Xe[0],onChange:_=>A(N.id,{color:_})}),r.jsx("div",{style:{flex:"1 1 160px",minWidth:140},children:r.jsx(ie.NiceTextInput,{value:N.name,onChange:_=>A(N.id,{name:_}),placeholder:k("karaokeSetup.playerName","Player name"),size:"sm"})}),r.jsx("div",{style:{flex:"1 1 180px",minWidth:150},children:r.jsx(ie.NiceSelect,{options:P,value:N.micId??"",onChange:_=>A(N.id,{micId:(typeof _=="string"?_:_[0])||null}),placeholder:k("karaokeSetup.selectMic","Microphone"),size:"sm"})}),h&&N.micId&&r.jsxs(ie.NiceButton,{variant:"ghost",size:"sm",onClick:()=>h(N.micId),children:[r.jsx(F.NtdSettings,{size:14})," ",k("karaokeSetup.calibrate","Calibrate")]}),r.jsx(ie.NiceButton,{variant:"danger",size:"sm",onClick:()=>L(N.id),"aria-label":k("karaokeSetup.remove","Remove"),children:r.jsx(F.NtdClose,{size:14})})]})},N.id)),r.jsx("div",{children:r.jsxs(ie.NiceButton,{variant:"primary",onClick:I,disabled:w.length>=u,children:[r.jsx(F.NtdPlus,{size:14})," ",k("karaokeSetup.addPlayer","Add player")]})})]})]})},op=[],lp=["freeForAll","roundRobin","hostOnly","firstCome"],cp={freeForAll:F.NtdDice,roundRobin:F.NtdRepeat,hostOnly:F.NtdCrown,firstCome:F.NtdLightning},dp={freeForAll:"success",roundRobin:"warning",hostOnly:"info",firstCome:"danger"},ul=({players:e=op,mode:t,defaultMode:n,onModeChange:a,turnTimeSec:s=30,hostIndex:i=0,onActivePlayerChange:o,myPlayerIndex:l,t:c,className:u,style:h,id:p,accessMode:g,"data-testid":y})=>{const{t:m}=xe(),x=c??m,[b,f]=ke.useControllableState({value:t,defaultValue:n,fallbackValue:"freeForAll",onChange:a,componentName:"NiceKaraokeSelectionMode"}),k={freeForAll:x("songSelection.freeForAll","Free for all"),roundRobin:x("songSelection.roundRobin","Round robin"),hostOnly:x("songSelection.hostOnly","Host only"),firstCome:x("songSelection.firstCome","First come")},[v,w]=d.useState(0),[R,M]=d.useState(s),j=d.useRef(null),[T,P]=d.useState(null),[A,I]=d.useState(!1),[L,N]=d.useState(null),_=d.useRef(null),ee=d.useMemo(()=>b==="hostOnly"?i:b==="roundRobin"?v%Math.max(1,e.length):b==="firstCome"?A?-1:L??-1:-1,[b,v,e.length,i,A,L]);d.useEffect(()=>{o==null||o(ee)},[ee,o]),d.useEffect(()=>{if(b!=="roundRobin"||s<=0){j.current&&clearInterval(j.current);return}return M(s),j.current=setInterval(()=>{M(K=>K<=1?(w(G=>G+1),s):K-1)},1e3),()=>{j.current&&clearInterval(j.current)}},[b,s,v]);const Y=d.useCallback(()=>{N(null),I(!1),P(3),_.current&&clearInterval(_.current),_.current=setInterval(()=>{P(K=>K===null||K<=1?(_.current&&clearInterval(_.current),I(!0),null):K-1)},1e3)},[]);d.useEffect(()=>()=>{_.current&&clearInterval(_.current)},[]),d.useEffect(()=>{b!=="firstCome"&&(P(null),I(!1),N(null))},[b]);const O=d.useCallback(()=>{w(K=>K+1),M(s)},[s]),U=K=>{var G;return((G=e[K])==null?void 0:G.name)||`${x("songSelection.player","Player")} ${K+1}`},V=ee>=0&&ee<e.length?e[ee]: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:lp.map(K=>r.jsxs(ie.NiceButton,{size:"sm",variant:b===K?dp[K]:"outline",onClick:()=>f(K),children:[d.createElement(cp[K],{size:14})," ",k[K]]},K))}),b!=="freeForAll"&&b!=="firstCome"&&V&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsxs(ie.NiceBadge,{variant:ee===l?"success":"secondary",children:[r.jsx(F.NtdMicrophone,{size:12})," ",U(ee)]}),ee===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:R,max:s,variant:R<=5?"error":R<=10?"warning":"info",showValue:!0,formatValue:K=>`${K}s`})}),b==="roundRobin"&&r.jsxs(ie.NiceButton,{size:"sm",variant:"ghost",onClick:O,children:[x("songSelection.next","Next")," ",r.jsx(F.NtdPlay,{size:12})]}),b==="firstCome"&&r.jsxs(r.Fragment,{children:[T!==null&&r.jsx("div",{style:{fontSize:32,fontWeight:900,color:"var(--nice-error, #f44336)",minWidth:60,textAlign:"center"},children:T}),A&&L===null&&r.jsxs(ie.NiceBadge,{variant:"danger",children:[r.jsx(F.NtdLightning,{size:12})," ",x("songSelection.raceGo","GO! Pick a song!")]}),L!==null&&L<e.length&&r.jsxs(ie.NiceBadge,{variant:"success",children:[r.jsx(F.NtdTrophy,{size:12})," ",U(L)," ",x("songSelection.raceWon","picks!")]}),r.jsx(ie.NiceButton,{size:"sm",variant:T!==null?"secondary":"danger",onClick:Y,disabled:T!==null,children:L!==null?r.jsxs(r.Fragment,{children:[r.jsx(F.NtdRepeat,{size:12})," ",x("songSelection.raceAgain","New race")]}):r.jsxs(r.Fragment,{children:[r.jsx(F.NtdLightning,{size:12})," ",x("songSelection.raceStart","Start race")]})})]})]})};function up(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 hp=({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:k,style:v,id:w,accessMode:R,"data-testid":M})=>{const{t:j}=xe(),T=f??j,[P,A]=ke.useControllableState({value:e,defaultValue:t,fallbackValue:[],onChange:n,componentName:"NiceKaraokeSessionJoin"}),[I,L]=d.useState([]);d.useEffect(()=>{var H,z,Z;if(c||!((H=navigator.mediaDevices)!=null&&H.enumerateDevices))return;let S=!1;const B=()=>navigator.mediaDevices.enumerateDevices().then(E=>!S&&L(E.filter(q=>q.kind==="audioinput"))).catch(()=>{});return B(),(Z=(z=navigator.mediaDevices).addEventListener)==null||Z.call(z,"devicechange",B),()=>{var E,q;S=!0,(q=(E=navigator.mediaDevices).removeEventListener)==null||q.call(E,"devicechange",B)}},[c]);const N=c??I,_=N.length===0,ee=P.some(S=>!S.micId),Y=!ee,[O,U]=d.useState(p),[V,K]=d.useState(-1),G=d.useCallback((S,B)=>{x==null||x({selectionMode:S,activePickerIndex:B,allMicsAssigned:Y,noInputDevices:_})},[x,Y,_]),W=d.useCallback(S=>{U(S),G(S,V)},[G,V]),C=d.useCallback(S=>{K(S),G(O,S)},[G,O]),$=d.useMemo(()=>({padding:10,borderRadius:8,fontWeight:700,marginTop:8,textAlign:"center"}),[]);return R==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-session-join${k?` ${k}`:""}`,style:b==="card"?{background:"var(--nice-bg-secondary)",borderRadius:12,padding:16,...v}:v,id:w,"data-testid":M,children:[r.jsx(dl,{players:P,onPlayersChange:A,gameMode:a,onGameModeChange:s,gameModes:i,difficulty:o,onDifficultyChange:l,audioInputs:N,maxPlayers:u,onCalibrate:h,t:T}),_&&r.jsxs("div",{style:{...$,background:"var(--nice-error, #ef4444)",color:"#fff"},children:[T("karaokeSessionJoin.noInputDevices","No microphone detected"),r.jsx("br",{}),r.jsx("span",{style:{fontWeight:400,fontSize:13},children:T("karaokeSessionJoin.noInputDevicesHint","Connect a microphone to sing.")})]}),!_&&ee&&r.jsx("div",{style:{...$,background:"var(--nice-warning, #f59e0b)",color:"var(--nice-text-on-primary, #222)",fontSize:14},children:T("karaokeSessionJoin.assignMicWarning","Assign a microphone to each player.")}),P.length>1&&r.jsx("div",{style:{marginTop:12},children:r.jsx(ul,{players:P,mode:O,onModeChange:W,onActivePlayerChange:C,turnTimeSec:g,hostIndex:y,myPlayerIndex:m,t:T})})]})};function Ve(e,t){var s;const n=((s=t.split(".").pop())==null?void 0:s.toLowerCase())??"",a=n==="otf"?"opentype":n==="woff2"?"woff2":n==="woff"?"woff":"truetype";return{family:e,url:`/fonts/${t}`,format:a}}const pp=[Ve("Belagak","BelagakRegular-dr1zE.otf"),Ve("Big Scratch Brush","BigScratchBrush-PVY9g.ttf"),Ve("Gerhaus","Gerhaus-PK69E.ttf"),Ve("Gerhaus Italic","GerhausItalic-d96l7.ttf"),Ve("Handone Medium","HandoneMedium-nAevO.otf"),Ve("Handson Bold","HandsonBold-9MnrL.otf"),Ve("Kineks Round Bold","KineksRoundBold-7OR34.ttf"),Ve("Kineks Round Light","KineksRoundLight-m2r35.ttf"),Ve("Kineks Round Medium","KineksRoundMedium-drejZ.ttf"),Ve("Kineks Round","KineksRoundRegular-PVRl7.ttf"),Ve("Kineks Round SemiBold","KineksRoundSemiBold-LVWG3.ttf"),Ve("Lemon Jelly","LemonJellyPersonalUse-dEqR.ttf"),Ve("Lemon Milk Bold","LemonMilkBold-gx2B3.otf"),Ve("Lemon Milk Bold Italic","LemonMilkBoldItalic-PKZ3P.otf"),Ve("Lemon Milk Light","LemonMilkLight-owxMq.otf"),Ve("Lemon Milk Light Italic","LemonMilkLightItalic-7BjPE.otf"),Ve("Lemon Milk Medium","LemonMilkMedium-mLZYV.otf"),Ve("Lemon Milk Medium Italic","LemonMilkMediumItalic-d95nl.otf"),Ve("Lemon Milk","LemonMilkRegular-X3XE2.otf"),Ve("Lemon Milk Italic","LemonMilkRegularItalic-L3AEy.otf"),Ve("Pemage","PemageRegular-YqrdO.otf"),Ve("Rosmatika","RosmatikaRegular-BWA45.ttf"),Ve("Scabber","Scabber-q2Mn0.ttf"),Ve("Stylish Calligraphy","StylishCalligraphyDemo-XPZZ.ttf"),Ve("Super Adorable","SuperAdorable-MAvyp.ttf"),Ve("Super Chiby","SuperChiby-BL62V.ttf"),Ve("Super Joyful","SuperJoyful-lxwPq.ttf"),Ve("Super Kindly","SuperKindly-drE8E.ttf"),Ve("Super Meatball","SuperMeatball-Yq1Gy.ttf")],Za="nice2dev-karaoke-display",fp=(function(){return[{value:"Arial",label:"Arial (default)"},{value:"Georgia, serif",label:"Georgia"},{value:"'Courier New', monospace",label:"Courier New"},{value:"'Trebuchet MS', sans-serif",label:"Trebuchet MS"},{value:"Impact, sans-serif",label:"Impact"},...pp.map(e=>({value:e.family,label:e.family}))]})(),hl=[{id:"default",name:"Cyan ? Yellow ? Amber",sungGradient:["#00e5ff","#ffe600","#ffab00"],goldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,229,255,0.6)"},{id:"neon-pink",name:"Neon Pink ? Violet ? Blue",sungGradient:["#ff1493","#9b59b6","var(--nice-primary, #3498db)"],goldGradient:["var(--nice-warning, #FFD700)","#FF69B4","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,20,147,0.6)"},{id:"fire",name:"Red ? Orange ? Yellow",sungGradient:["#ff1744","#ff9100","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#FF6D00","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,23,68,0.6)"},{id:"ocean",name:"Deep Blue ? Teal ? Aqua",sungGradient:["#1a237e","#00897b","#00e5ff"],goldGradient:["var(--nice-warning, #FFD700)","#00BCD4","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,137,123,0.6)"},{id:"forest",name:"Green ? Lime ? Yellow",sungGradient:["#1b5e20","#76ff03","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#76ff03","var(--nice-warning, #FFD700)"],glowColor:"rgba(118,255,3,0.6)"},{id:"retro",name:"Orange ? Pink ? Purple",sungGradient:["#ff6d00","var(--nice-color-accent-pink, #e91e63)","#7b1fa2"],goldGradient:["var(--nice-warning, #FFD700)","var(--nice-color-accent-pink, #e91e63)","var(--nice-warning, #FFD700)"],glowColor:"rgba(233,30,99,0.6)"}],gn={presetId:"default",customSungGradient:["#00e5ff","#ffe600","#ffab00"],customGoldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],customGlowColor:"rgba(0,229,255,0.6)",animationMode:"ball",fontFamily:"Arial",transitionEffect:"none",curtainPrimaryColor:"#8b0000",curtainSecondaryColor:"#1a0000",curtainDurationMs:900,immersiveMode:!1};let ei=!1;function pl(){try{const e=localStorage.getItem(Za);if(e){const t=JSON.parse(e);return{...gn,...t}}}catch{}return{...gn}}async function mp(e){if(ei||(ei=!0,!e))return;const t=await e();if(t)try{const n=JSON.parse(t),a={...gn,...n};localStorage.setItem(Za,JSON.stringify(a))}catch{}}function gp(e){const t=JSON.stringify(e);localStorage.setItem(Za,t),Xa(e)}function fl(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=hl.find(n=>n.id===e.presetId);return t?{sungGradient:t.sungGradient,goldGradient:t.goldGradient,glowColor:t.glowColor}:{sungGradient:gn.customSungGradient,goldGradient:gn.customGoldGradient,glowColor:gn.customGlowColor}}function Xa(e){const{sungGradient:t,goldGradient:n,glowColor:a}=fl(e),s=document.documentElement;s.style.setProperty("--karaoke-sung-gradient",`linear-gradient(90deg, ${t[0]} 0%, ${t[1]} 60%, ${t[2]} 100%)`),s.style.setProperty("--karaoke-gold-gradient",`linear-gradient(90deg, ${n[0]}, ${n[1]}, ${n[2]})`),s.style.setProperty("--karaoke-gold-glow-first",`0 0 12px ${n[0]}`),s.style.setProperty("--karaoke-active-glow",`0 0 10px ${a}, 0 0 4px ${t[1]}80`),s.style.setProperty("--karaoke-active-drop-first",`0 0 6px ${a}`),s.style.setProperty("--karaoke-active-bg",`linear-gradient(90deg, transparent 0%, ${t[0]}14 20%, ${t[1]}10 80%, transparent 100%)`),s.style.setProperty("--karaoke-font-family",e.fontFamily||"Arial")}function yp(){const e=pl();Xa(e)}function vp(e){const t=(e||"").split(/\r?\n/),n=[];for(let a=0;a<t.length;a++){const s=t[a].trim();if(s&&/^[:*F]\s/.test(s)){const i=s.slice(1).trim().split(/\s+/),o=parseInt(i[0]||"0",10),l=parseInt(i[1]||"0",10),c=isNaN(o)?0:o/10,u=isNaN(l)?0:l/10;n.push({lineIndex:a,start:c,duration:u,raw:t[a]})}}return n}const bp=({index:e,data:t})=>{const{lines:n,notes:a,currentIndex:s,animationConfig:i}=t,o=n[e]??"",l=a.findIndex(f=>f.lineIndex===e),c=l>=0&&l===s,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})})})},xp=({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(()=>vp(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,k=b.length*f,v=d.useMemo(()=>({lines:b,notes:u,currentIndex:m,animationConfig:a}),[b,u,m,a]),w=d.useCallback((R,M)=>r.jsx(bp,{index:M,data:v}),[v]);return d.useEffect(()=>{const R=o.current;R&&(l?R.play().catch(()=>c(!1)):R.pause())},[l,o]),d.useEffect(()=>{const R=o.current;if(!R)return;let M=-1;const j=a??null,T=j&&typeof j.scrollSmooth=="number"?j.scrollSmooth:.18;let P=performance.now();const A=()=>{var G,W;const I=performance.now(),L=Math.max(0,Math.min(.2,(I-P)/1e3));P=I;const N=R.currentTime||0;g.current=N;let _=-1;for(let C=0;C<u.length;C++){const $=u[C];if(N>=$.start&&N<$.start+Math.max(.001,$.duration)){_=C;break}}_!==M&&(M=_,x(_));let ee=0;if(M>=0){const C=((G=u[M])==null?void 0:G.lineIndex)??0,$=((W=h.current)==null?void 0:W.clientHeight)??220;ee=C*f-$/2+f/2;const S=Math.max(0,k-$);(isNaN(ee)||!isFinite(ee))&&(ee=0),ee=Math.max(0,Math.min(ee,S))}const Y=1-Math.pow(Math.max(0,1-T),Math.min(4,L*60)),K=(((a==null?void 0:a.scrollEasing)||"easeOutCubic")==="linear"?C=>C:C=>1-Math.pow(1-C,3))(Y);y.current=y.current+(ee-y.current)*K;try{const C=h.current;C&&typeof C.scrollTop=="number"&&(C.scrollTop=Math.round(y.current))}catch{}p.current=requestAnimationFrame(A)};return p.current=requestAnimationFrame(A),()=>{p.current&&cancelAnimationFrame(p.current)}},[o,u,k,a]),r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[r.jsx("button",{onClick:()=>c(R=>!R),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:w,style:{border:"none",borderRadius:0,background:"transparent",fontSize:"inherit"}}):r.jsx("div",{style:{color:"var(--nice-text-secondary, #888)"},children:s("karaokeEditor.noText","No text")})}),!n&&r.jsx("audio",{ref:i,src:t||void 0,preload:"metadata",style:{display:"none"}})]})};function Sp(e){const t=(e||"").split(/\r?\n/).map(a=>a.replace(/\s+$/,"")),n=[];for(let a=0;a<t.length;a++){const s=t[a].trim();if(/^[:*F]\s/.test(s)){const i=s.slice(1).trim().split(/\s+/),o=parseInt(i[0]||"0",10)/10||0,l=parseInt(i[1]||"0",10)/10||.1;n.push({lineIndex:a,start:o,duration:l})}}return{lines:t,notes:n}}const kp=new Set;function wp({ultrastarText:e,audioUrl:t,audioRef:n,ytRef:a}){const{lines:s,notes:i}=d.useMemo(()=>Sp(e),[e]),[o,l]=d.useState(kp),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 k=[...f].join(",");k!==y&&(y=k,l(f)),g=requestAnimationFrame(m)};return g=requestAnimationFrame(m),()=>{cancelAnimationFrame(g),p==null||p.remove()}},[]),r.jsx("div",{style:{width:"100%",height:340,overflow:"hidden",background:"#101010",padding:"20px 0",boxSizing:"border-box"},children:s.map((h,p)=>{const g=o.has(p);return r.jsx("div",{"aria-current":g||void 0,style:{font:"18px monospace",lineHeight:"22px",whiteSpace:"pre",padding:"0 10px",color:g?"var(--nice-info, #00aaff)":"var(--nice-overlay-light-90, #e2e8f0)",background:g?"color-mix(in srgb, var(--nice-info, #00aaff) 16%, transparent)":void 0},children:h||" "},p)})})}const Cp=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),ti=e=>{(!isFinite(e)||e<0)&&(e=0);const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`},ea={border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},jp=({isPlaying:e,index:t,count:n,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek: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:[ti(a)," / ",ti(s)]})]}),r.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("button",{onClick:o,disabled:t<=0,title:p("playerControls.prev","Prev"),"aria-label":p("playerControls.previousTrack","Previous track"),style:ea,children:r.jsx(F.NtdSkipBack,{size:16})}),r.jsx("button",{onClick:c,title:e?p("playerControls.pause","Pause"):p("playerControls.play","Play"),"aria-label":e?p("playerControls.pause","Pause"):p("playerControls.play","Play"),style:ea,children:e?r.jsx(F.NtdPause,{size:16}):r.jsx(F.NtdPlay,{size:16})}),r.jsx("button",{onClick:l,disabled:t>=n-1,title:p("playerControls.next","Next"),"aria-label":p("playerControls.nextTrack","Next track"),style:ea,children:r.jsx(F.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(F.NtdVolume,{size:16}),r.jsx("input",{type:"range",min:0,max:1,step:.01,value:i,"aria-label":p("playerControls.volume","Volume"),onChange:g=>h(parseFloat(g.target.value))})]})]})]})},Mp=d.memo(jp);function Rp(e,t,n,a,s){const o=Math.max(1,Math.floor(a.length/48)),l=t/48;for(let c=0;c<48;c++){const 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 Np(e,t,n,a,s,i){if(!i.current){const p=[];for(let y=0;y<24;y++)p.push({ang:y/24*Math.PI*2,phase:Math.random()*Math.PI*2,baseR:Math.min(t,n)*.22+Math.random()*30});i.current={nodes:p}}const o=i.current,l=t/2,c=n/2,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 Tp(e,t,n,a,s,i){i.current||(i.current={items:[]});const o=i.current;Math.random()<.06+a*.25&&o.items.push({x:Math.random()*t,y:Math.random()*n,r:8+Math.random()*24,life:1,hue:(s+Math.random()*120)%360});const l=[];for(const c of o.items){c.r+=2+a*14,c.life*=.975-a*.02,c.life>.04&&l.push(c);const 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 Pp="var(--nice-text-muted, #94a3b8)",Ep=({height:e,coverUrl:t,title:n,subtitle:a,label:s})=>r.jsx("div",{style:{textAlign:"center",color:"var(--nice-text-secondary, #e2e8f0)"},children:t?r.jsx("img",{alt:"cover",src:t,style:{height:e-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsx("div",{style:{fontSize:18,fontWeight:600},children:n??"—"}),r.jsx("div",{style:{marginTop:8,fontSize:12,color:Pp},children:s??a??"—"})]})});function tn(e,t){return e+Math.random()*(t-e)}function $p(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:tn(t*.25,t*.75),y:n-tn(4,14),r:tn(1,3),vx:tn(-.15,.15),vy:-tn(.6,1.8)-s*1.2,life:tn(.8,1.6)});e.save(),e.globalCompositeOperation="lighter";for(let p=l.embers.length-1;p>=0;p--){const g=l.embers[p];if(g.x+=g.vx,g.y+=g.vy,g.vy-=.01,g.life-=.015+s*.02,g.life<=0||g.y<-10){l.embers.splice(p,1);continue}const y=e.createRadialGradient(g.x,g.y,0,g.x,g.y,g.r*3);y.addColorStop(0,`hsla(${(i+25)%360},100%,65%,.9)`),y.addColorStop(1,`hsla(${(i+25)%360},100%,65%,0)`),e.fillStyle=y,e.beginPath(),e.arc(g.x,g.y,g.r*3,0,Math.PI*2),e.fill()}e.restore(),e.fillStyle="rgba(60,36,22,.9)",e.fillRect(t*.2,n-10,t*.6,6),l.t+=.02+s*.08}function Ap(e,t,n,a,s){const i=t/2,o=n/2,l=Math.min(t,n)*.28,c=96,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 Ip(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 Lp(e){const n=Array.from(new Set(e.filter(Boolean))).map(a=>new Promise(s=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>s(i),i.onerror=()=>s(i),i.src=a}));return Promise.all(n)}async function _p(e,t,n,a,s){e.current||(e.current={sprites:[],loadedUrls:[],ready:!1});const i=e.current,o=t.join("|")!==i.loadedUrls.join("|");if(!i.ready||o){const l=await Lp(t.length?t:[]);i.loadedUrls=t,i.sprites=[],i.ready=!0;const c=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 zp(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,k=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,k*.7,v*.7,0,0,Math.PI*2),e.fill(),e.restore(),m.img&&m.img.width?e.drawImage(m.img,b-k/2,f-v/2,k,v):(e.save(),e.fillStyle=`hsl(${(s+180)%360}, 40%, 55%)`,e.fillRect(b-k/2,f-v/2,k,v),e.restore())}}function wn(e,t){return e+Math.random()*(t-e)}function Dp(e,t,n,a,s,i){i.current||(i.current={blobs:Array.from({length:7},(u,h)=>({x:wn(t*.2,t*.8),y:wn(n*.2,n*.8),r:wn(Math.min(t,n)*.05,Math.min(t,n)*.12),vx:wn(-.6,.6),vy:wn(-.6,.6),hue:(s+h*10)%360}))});const o=i.current,l=.6+a*2.2;e.save(),e.globalCompositeOperation="lighter";for(const c of o.blobs){c.x+=c.vx*l,c.y+=c.vy*l,c.vy-=.01-a*.015,c.x<c.r&&(c.x=c.r,c.vx=Math.abs(c.vx)),c.x>t-c.r&&(c.x=t-c.r,c.vx=-Math.abs(c.vx)),c.y<c.r&&(c.y=c.r,c.vy=Math.abs(c.vy)),c.y>n-c.r&&(c.y=n-c.r,c.vy=-Math.abs(c.vy));const 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=ke.resolveCssColor("var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",e.canvas),e.lineWidth=2,e.strokeRect(1,1,t-2,n-2)}function Fp(e,t,n,a,s,i){i.current||(i.current={tris:[]});const o=i.current,l=6;for(;o.tris.length<l;)o.tris.push({a:Math.random()*Math.PI*2,r:30+Math.random()*Math.min(t,n)*.35,dr:(Math.random()*.6+.2)*(Math.random()<.5?-1:1)});const c=t/2,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 Op(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,k=g+Math.sin(f*2)*6*m,v=o+Math.cos(f)*k,w=l+Math.sin(f)*k;e.fillStyle=`hsla(${(s+h*30+b*6)%360}, 90%, ${55+m*30}%, ${.6+m*.3})`,e.beginPath(),e.arc(v,w,2+m*4,0,Math.PI*2),e.fill()}}}function Bp(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 Gp(e,t,n,a,s,i){const o=t/2,l=n/2,c=2+Math.floor(a*14);for(let h=0;h<c;h++){const p=Math.random()*Math.PI*2,g=.5+Math.random()*(2.5+a*4);i.current.push({x:o,y:l,vx:Math.cos(p)*g,vy:Math.sin(p)*g,life:0,max:40+Math.random()*60,hue:(s+Math.random()*60)%360})}e.fillStyle="rgba(2,6,23,0.2)",e.fillRect(0,0,t,n);const 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 Wp(e,t,n,a,s,i){e.fillStyle="rgba(10,16,28,0.25)",e.fillRect(0,0,t,n);const o=t/2,l=n/2,c=Math.min(t,n)*(.38+s*.12),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 k=m/x*f,v=(Math.sin(a*3+p*.8+f)*.6+Math.cos(a*2+p+f*.7))*(8+24*s),w=k,R=v;e.lineTo(R,w)}e.globalCompositeOperation="lighter";const b=(i+p*(240/h))%360;e.strokeStyle=`hsla(${b}, 90%, ${60+s*20}%, ${.35+s*.4})`,e.lineWidth=2+s*2,e.stroke(),e.restore()}e.beginPath(),e.arc(o,l,c*(.98+.02*Math.sin(a*2)),0,Math.PI*2),e.strokeStyle=`hsla(${(i+40)%360},90%,70%,${.25+s*.25})`,e.lineWidth=1.5,e.stroke(),e.globalCompositeOperation="source-over"}function Vp(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,k=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(k,v),e.stroke()}e.fillStyle=ke.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 Up(e,t,n,a,s,i){const o=t/2,l=n/2,c=Math.min(t,n)*.5,u=ni(a,0,Math.floor(a.length*.1))/255,h=ni(a,Math.floor(a.length*.6),a.length)/255;i.current+=.01+h*.03;const p=24;for(let g=0;g<p;g++){const y=i.current+g/p*Math.PI*2,m=(.35+u*.55)*c,x=o+Math.cos(y)*m,b=l+Math.sin(y)*m,f=e.createRadialGradient(o,l,0,o,l,m),k=g/p*360+s;f.addColorStop(0,`hsla(${k},85%,65%,0.0)`),f.addColorStop(1,`hsla(${k},85%,65%,0.9)`),e.strokeStyle=f,e.lineWidth=6+h*8,e.beginPath(),e.moveTo(o,l),e.lineTo(x,b),e.stroke()}e.fillStyle="rgba(2,6,23,0.25)",e.fillRect(0,0,t,n)}function ni(e,t,n){let a=0,s=0;for(let i=t;i<n;i++)a+=e[i],s++;return s?a/s:0}function qp(e,t,n,a,s,i){e.fillStyle="rgba(10,16,28,0.35)",e.fillRect(0,0,t,n);const o=n/2,l=Math.max(8,18-s*10),c=n*.35*(.6+s*.7),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=ke.resolveCssColor("var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.canvas),e.lineWidth=6,e.beginPath(),e.moveTo(0,o-l),e.lineTo(t,o-l),e.stroke(),e.beginPath(),e.moveTo(0,o+l),e.lineTo(t,o+l),e.stroke(),e.globalCompositeOperation="source-over"}function Hp(e,t,n,a,s,i){const o=t/2,l=n/2,c=5,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 Kp(e,t,n,a,s){const i=Math.min(a.length,256),o=Math.max(1,Math.floor(a.length/i)),l=t/i;for(let c=0;c<i;c++){const 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 Yp(e,t,n,a){e.current||(e.current={stars:[],ready:!1});const s=e.current;if(!s.ready||s.stars.length!==t){const i=[];for(let o=0;o<t;o++){const l={x:(Math.random()-.5)*n,y:(Math.random()-.5)*a,z:Math.random()*800+100,pz:0};i.push(l)}s.stars=i,s.ready=!0}}function Zp(e,t,n,a,s,i){const o=i.current,l=t/2,c=n/2,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 Xp(e,t,n,a){e.lineWidth=2,e.strokeStyle=ke.resolveCssColor("var(--nice-primary-light, #c7d2fe)",e.canvas),e.beginPath();const s=t/a.length;for(let i=0;i<a.length;i++){const o=(a[i]-128)/128,l=i*s,c=n/2+o*(n*.45);i===0?e.moveTo(l,c):e.lineTo(l,c)}e.stroke()}const Qp=({active:e,onClick:t,title:n,children:a})=>r.jsx("button",{type:"button",onClick:t,title:n,"aria-pressed":e,style:{padding:"4px 8px",borderRadius:6,fontSize:12,border:`1px solid ${e?"var(--nice-info, #6366f1)":"var(--nice-border-color, #334155)"}`,background:e?"var(--nice-accent-tint-12, rgba(99,102,241,.12))":"var(--nice-overlay-60, rgba(15,23,42,.6))",color:e?"var(--nice-color-white, #e2e8f0)":"var(--nice-color-white, #cbd5e1)",cursor:"pointer",whiteSpace:"nowrap",lineHeight:1.2},children:a}),ml=({modes:e=[],active:t,setActive:n,rows:a=2})=>{const{t:s}=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(Qp,{active:t===o,onClick:()=>n(o),title:`${s("visualizer.mode","Mode")}: ${o}`,children:o},o))})})};function Jp(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 ef=({vu:e,hide:t})=>{if(t)return null;const n=12,a=Math.round(e*n);return r.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px 8px",borderRadius:8,border:"1px solid var(--nice-border-color, #334155)",backdropFilter:"blur(2px)",pointerEvents:"none",zIndex:9998},children:Array.from({length:n}).map((s,i)=>{const o=120*(i/n);return r.jsx("div",{style:{width:6,height:18,borderRadius:2,background:i<a?`hsl(${o}, 80%, 50%)`:"var(--nice-text, #1f2937)"}},i)})})},tf="var(--player-bg, #0f172a)";function nf(e,t){const n=e.length;for(let a=0;a<n;a++){const s=a/n,i=.55*Math.exp(-Math.pow((s-(.12+.08*Math.sin(t*.7)))*7,2))+.45*Math.exp(-Math.pow((s-(.4+.15*Math.sin(t*1.1+1)))*9,2))+.3*(1-s)*(.55+.45*Math.sin(t*2+a*.06));e[a]=Math.max(0,Math.min(255,Math.floor(i*255)))}}function rf(e,t){const n=e.length;for(let a=0;a<n;a++){const s=a/n*Math.PI*2,i=Math.sin(s*3+t*3)*.5+Math.sin(s*7+t*2)*.28;e[a]=Math.max(0,Math.min(255,Math.floor(128+i*110)))}}const gl=({kind:e,audioRef:t,width:n="100%",height:a=360,coverUrl:s,title:i,subtitle:o,label:l,defaultMode:c="cover",storageKey: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 W=x.includes(c)?c:x[0];try{const C=localStorage.getItem(u);if(!C)return W;const $=JSON.parse(C);return x.includes($)?$:W}catch{return W}},[x,c,u]),[f,k]=Jp(u,b),v=d.useRef(null),w=d.useRef(null),R=d.useRef(null),M=d.useRef(null),j=d.useRef(null),T=d.useRef(null),P=d.useRef(0),A=d.useRef(0),I=d.useRef([]),[L,N]=d.useState(0),_=d.useRef(null),ee=d.useRef(null),Y=d.useRef(null),O=d.useRef(null),U=d.useRef(null),V=d.useRef(null),K=d.useRef(null),G=f!=="cover"&&f!=="video";return d.useEffect(()=>{var z;if(e==="youtube"||(w.current&&(cancelAnimationFrame(w.current),w.current=null),!G))return;Yt();const W=qn(),C=t.current;if(!C&&!y)return;if(C&&!R.current)try{R.current=W.createMediaElementSource(C)}catch{}if(C&&!M.current){const Z=W.createAnalyser();Z.fftSize=2048,Z.smoothingTimeConstant=.85,M.current=Z;try{(z=R.current)==null||z.connect(Z)}catch{}try{Z.connect(W.destination)}catch{}}const $=M.current;j.current=new Uint8Array($?$.frequencyBinCount:1024),T.current=new Uint8Array($?$.fftSize:2048);const S=()=>{const Z=v.current,E=Math.max(1,Math.floor(window.devicePixelRatio||1));Z.width=Math.floor(Z.clientWidth*E),Z.height=Math.floor(Z.clientHeight*E);const q=Z.getContext("2d");q==null||q.setTransform(1,0,0,1,0,0),q==null||q.scale(E,E)};S();const B=()=>S();window.addEventListener("resize",B),Yp(Y,220,v.current.width,v.current.height);const H=async()=>{const Z=v.current;if(!Z)return;const E=Z.getContext("2d");if(!E)return;const q=Math.max(1,Math.floor(window.devicePixelRatio||1)),X=Z.width/q,re=Z.height/q,oe=performance.now()*.001,se=f==="waveform"||f==="rift";$&&(se?$.getByteTimeDomainData(T.current):$.getByteFrequencyData(j.current)),y&&(nf(j.current,oe),rf(T.current,oe));let D=0;const J=se?T.current:j.current;for(let ae=0;ae<J.length;ae++){const ce=se?(J[ae]-128)/128:J[ae]/255;D+=ce*ce}if(D=Math.sqrt(D/J.length),N(Math.min(1,D)),E.clearRect(0,0,X,re),f==="spectrum")Kp(E,X,re,j.current,P.current);else if(f==="bars")Rp(E,X,re,j.current,P.current);else if(f==="waveform")Xp(E,X,re,T.current);else if(f==="palette"){const ae=(P.current+D*120)%360;Bp(E,X,re,j.current,ae)}else if(f==="radial")Vp(E,X,re,j.current,P.current);else if(f==="rays")Up(E,X,re,j.current,P.current,A);else if(f==="particles")Gp(E,X,re,D,P.current,I);else if(f==="rings")Hp(E,X,re,j.current,D,P.current);else if(f==="grid"){const ae=(P.current+D*160)%360;Ip(E,X,re,j.current,ae)}else if(f==="imageTornado"){const ae=p!=null&&p.length?p:s?[s]:[];await _p(_,ae,g,X,re);const ce=(P.current+D*100)%360;zp(E,X,re,D,ce,_)}else if(f==="colorRipples"){const ae=(P.current+D*120)%360;Tp(E,X,re,D,ae,ee)}else if(f==="starfield"){const ae=(P.current+60)%360;Zp(E,X,re,D,ae,Y)}else if(f==="orbitals"){const ae=(P.current+D*180)%360;Op(E,X,re,j.current,ae,A)}else if(f==="eqcircle"){const ae=(P.current+120)%360;Ap(E,X,re,j.current,ae)}else if(f==="triangles"){const ae=(P.current+40)%360;Fp(E,X,re,D,ae,O)}else if(f==="blob"){const ae=(P.current+90)%360;Np(E,X,re,D,ae,U)}else if(f==="plasma"){const ae=(P.current+D*200)%360;Wp(E,X,re,oe,D,ae)}else if(f==="rift")qp(E,X,re,T.current,D,oe);else if(f==="lavaLamp"){const ae=(P.current+D*80)%360;Dp(E,X,re,D,ae,V)}else if(f==="cozyFire"){const ae=(P.current+D*140)%360;$p(E,X,re,j.current,D,ae,K)}P.current=(P.current+.4)%360,w.current=requestAnimationFrame(H)};return w.current=requestAnimationFrame(H),()=>{window.removeEventListener("resize",B),w.current&&cancelAnimationFrame(w.current)}},[G,e,t,f,p,g,s,y]),r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none",background:f==="cover"?"transparent":tf},children:f==="cover"?r.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:r.jsx(Ep,{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(ml,{modes:x,active:f,setActive:k,rows:2}),r.jsx(ef,{vu:L,hide:e==="youtube"})]})]})},af=({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"&&Cp(p)){const w=()=>{v.src=p,v.load(),t&&v.play().catch(()=>{})};if(v.canPlayType("application/vnd.apple.mpegurl")){w();return}(async()=>{const M=(await import("hls.js")).default;if(M.isSupported()){const j=JSON.parse(m),T=new M({xhrSetup:P=>{if(y&&(P.withCredentials=!0),j)for(const[A,I]of Object.entries(j))P.setRequestHeader(A,String(I))}});o.current=T,T.loadSource(p),T.attachMedia(v),T.on(M.Events.MANIFEST_PARSED,()=>t&&v.play().catch(()=>{}))}else w()})()}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",k=`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(Pa,{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(gl,{kind:(a==null?void 0:a.kind)==="hls"?"hls":(a==null?void 0:a.kind)??"audio",audioRef:i,hlsRef:o,height:e,coverUrl:n==null?void 0:n.coverUrl,title:n==null?void 0:n.title,subtitle:n==null?void 0:n.artist,label:(a==null?void 0:a.label)??`${(a==null?void 0:a.codec)??""} ${(a==null?void 0:a.quality)??""}`.trim(),defaultMode:f,storageKey:k},`vis-${k}`)]})},sf=({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 w=y.getCurrentTime();s(w)},100);return()=>clearInterval(v)}},[y,s]),d.useEffect(()=>{const v=()=>{if(x.current){const w=x.current.clientWidth,R=Math.round(w*(9/16));f({width:w,height:R})}};return v(),window.addEventListener("resize",v),()=>window.removeEventListener("resize",v)},[]);const k=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:k,children:o("youtubePlayer.search","Search")})]}),p&&r.jsxs("div",{children:[r.jsx(Pa,{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(F.NtdPlay,{size:14})," ",o("youtubePlayer.play","Play")]}),r.jsxs("button",{onClick:()=>y==null?void 0:y.pauseVideo(),children:[r.jsx(F.NtdPause,{size:14})," ",o("youtubePlayer.pause","Pause")]})]})]})]})},ri=e=>({name:e,dirs:new Map,files:[]}),of=e=>(e??[]).map(t=>t instanceof File?{file:t}:t),lf=e=>e.replace(/\\/g,"/"),cf=e=>{const t=ri("/");for(const n of e){const a=lf(n.path??n.file.name).split("/").filter(Boolean);if(a.length<=1){t.files.push({file:n.file,path:a[0]??n.file.name});continue}let s=t;for(let i=0;i<a.length-1;i++){const o=a[i];s.dirs.has(o)||s.dirs.set(o,ri(o)),s=s.dirs.get(o)}s.files.push({file:n.file,path:a[a.length-1]??n.file.name})}return t},ya=e=>e.slice().sort((t,n)=>(t.path??t.file.name).localeCompare(n.path??n.file.name)),df={tidal:F.NtdWave,spotify:F.NtdMusic,youtube:F.NtdPlay},va=({q:e,setQ:t,t:n})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[r.jsx("div",{style:{flex:1},children:r.jsx(ie.NiceTextInput,{value:e,onChange:t,placeholder:n("libraryExplorer.searchPlaceholder","Search…"),size:"sm"})}),e&&r.jsx(ie.NiceButton,{variant:"ghost",size:"sm",onClick:()=>t(""),children:r.jsx(F.NtdClose,{size:14})})]}),ba=({files:e,t,onOpenInEditor:n,onPlayFile:a})=>e.length?r.jsx("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:r.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[r.jsx("thead",{children:r.jsxs("tr",{style:{color:"var(--nice-text-muted, #94a3b8)",textAlign:"left"},children:[r.jsx("th",{style:{padding:"8px 12px",fontWeight:600},children:t("libraryExplorer.colFile","File")}),r.jsx("th",{style:{padding:"8px 12px",fontWeight:600},children:t("libraryExplorer.colType","Type")}),r.jsx("th",{style:{padding:"8px 12px",fontWeight:600,width:200},children:t("libraryExplorer.colActions","Actions")})]})}),r.jsx("tbody",{children:e.map(s=>{const i=s.path??s.file.name;return r.jsxs("tr",{style:{borderTop:"1px solid var(--nice-border, #1e293b)"},children:[r.jsx("td",{style:{padding:"6px 12px",maxWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),r.jsx("td",{style:{padding:"6px 12px",color:"var(--nice-text-muted, #94a3b8)"},children:s.file.type||"—"}),r.jsxs("td",{style:{padding:"6px 12px",display:"flex",gap:6},children:[n&&r.jsxs(ie.NiceButton,{variant:"outline",size:"sm",onClick:()=>n(s.file),children:[r.jsx(F.NtdEdit,{size:13})," ",t("libraryExplorer.openInEditor","Edit")]}),a&&r.jsxs(ie.NiceButton,{variant:"primary",size:"sm",onClick:()=>a(s.file),children:[r.jsx(F.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]})]},i)})})]})}):r.jsx("div",{style:{fontSize:13,color:"var(--nice-text-muted, #94a3b8)",padding:12},children:t("libraryExplorer.noFiles","No files")}),yl=({streams:e,t,onPlayStream:n})=>e.length?r.jsxs("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:[r.jsx("div",{style:{padding:"8px 12px",fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:t("libraryExplorer.streaming","Streaming")}),r.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:e.map(a=>r.jsxs("li",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,borderTop:"1px solid var(--nice-border, #1e293b)",padding:"8px 12px"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.title}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",display:"flex",alignItems:"center",gap:4},children:[d.createElement(df[a.provider],{size:12})," ",a.provider.toUpperCase(),a.artist?` • ${a.artist}`:""]})]}),n&&r.jsxs(ie.NiceButton,{variant:"primary",size:"sm",onClick:()=>n(a),children:[r.jsx(F.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]},`${a.provider}:${a.id}`))})]}):null,ta=({name:e,enabled:t})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 8px",fontSize:13},children:[r.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:t?"var(--nice-success, #10b981)":"var(--nice-border, #d1d5db)"}}),r.jsx("span",{style:{color:t?"inherit":"var(--nice-text-muted, #94a3b8)"},children:e})]}),uf=({variant:e="full",files:t=[],streams:n=[],enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,t:c,style:u,id:h,accessMode:p,"data-testid":g})=>{const{t:y}=xe(),m=c??y,[x,b]=d.useState(""),f=d.useMemo(()=>of(t),[t]),k=d.useCallback(R=>{const M=x.trim().toLowerCase();return!M||R.toLowerCase().includes(M)},[x]),v=d.useMemo(()=>ya(f).filter(R=>k(`${R.path??R.file.name} ${R.file.type||""}`)),[f,k]),w=d.useMemo(()=>n.filter(R=>k(`${R.title} ${R.artist??""} ${R.provider}`)),[n,k]);return p==="hidden"?null:e==="minimal"?r.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...u},id:h,"data-testid":g,children:[r.jsx(va,{q:x,setQ:b,t:m}),r.jsx(ba,{files:v,t:m,onOpenInEditor:s,onPlayFile:i}),r.jsx(yl,{streams:w,t:m,onPlayStream:o})]}):e==="onlyFiles"?r.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...u},id:h,"data-testid":g,children:[r.jsx(va,{q:x,setQ:b,t:m}),r.jsx(ba,{files:v,t:m,onOpenInEditor:s,onPlayFile:i})]}):r.jsx(hf,{q:x,setQ:b,normFiles:f,filteredStreams:w,enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,style:u,id:h,"data-testid":g,t:m})},hf=({q:e,setQ:t,normFiles:n,filteredStreams:a,enableProviders:s,onOpenInEditor:i,onPlayFile:o,onPlayStream:l,className:c,style:u,id:h,"data-testid":p,t:g})=>{const y=d.useMemo(()=>cf(n),[n]),[m,x]=d.useState({}),[b,f]=d.useState("/"),k=M=>x(j=>({...j,[M]:!j[M]})),v=(M,j)=>{const T=j==="/"?`/${M.name}`:`${j}${M.name}/`,P=j==="/"&&M.name==="/",A=m[T]??P,I=Array.from(M.dirs.keys()).sort();return r.jsxs("div",{children:[!P&&r.jsxs("button",{type:"button",onClick:()=>{k(T),f(T)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"4px 8px",border:"none",borderRadius:6,cursor:"pointer",textAlign:"left",background:b===T?"var(--nice-accent-tint-20, rgba(99,102,241,0.2))":"transparent",color:"var(--nice-text, inherit)"},children:[r.jsx("span",{style:{display:"inline-flex"},children:A?r.jsx(F.NtdFolderOpen,{size:14}):r.jsx(F.NtdFolder,{size:14})}),r.jsx("span",{style:{fontSize:13},children:M.name})]}),(P||A)&&r.jsx("div",{style:{paddingLeft:P?0:16},children:I.map(L=>v(M.dirs.get(L),T))})]},T)},w=d.useMemo(()=>{let M;if(b==="/")M=ya(n);else{const j=b.replace(/^\//,"").split("/").filter(Boolean);let T=y;for(const P of j){const A=T.dirs.get(P);if(!A)return[];T=A}M=ya(T.files)}return e?M.filter(j=>(j.path??j.file.name).toLowerCase().includes(e.toLowerCase())):M},[b,y,n,e]),R={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(ta,{name:"Tidal",enabled:R.tidal}),r.jsx(ta,{name:"Spotify",enabled:R.spotify}),r.jsx(ta,{name:"YouTube",enabled:R.youtube})]})]}),r.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[r.jsx(va,{q:e,setQ:t,t:g}),r.jsx(ba,{files:w,t:g,onOpenInEditor:i,onPlayFile:o}),(R.tidal||R.spotify||R.youtube)&&r.jsx(yl,{streams:a.filter(M=>R[M.provider]),t:g,onPlayStream:l})]})]})},pf=({kind:e,color:t})=>{const n={width:14,height:14,viewBox:"0 0 24 24",fill:t,"aria-hidden":!0};switch(e){case"youtube":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M23 7.2s-.2-1.6-.9-2.3c-.8-.9-1.7-.9-2.1-1C16.9 3.5 12 3.5 12 3.5s-4.9 0-8 .4c-.4.1-1.3.1-2.1 1C1.2 5.6 1 7.2 1 7.2S.8 9.1.8 11v1.8c0 1.9.2 3.8.2 3.8s.2 1.6.9 2.3c.8.9 1.9.9 2.4 1 1.7.2 7.7.4 7.7.4s4.9 0 8-.4c.4-.1 1.3-.1 2.1-1 .7-.7.9-2.3.9-2.3s.2-1.9.2-3.8V11c0-1.9-.2-3.8-.2-3.8zM9.7 14.6V8.2l6.3 3.2-6.3 3.2z"})});case"spotify":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.59 14.42c-.18.3-.57.4-.87.21-2.39-1.46-5.4-1.79-8.95-.98-.34.08-.68-.13-.76-.47-.08-.34.13-.68.47-.76 3.88-.89 7.21-.5 9.89 1.13.31.19.4.58.22.87zm1.23-2.72c-.23.37-.71.49-1.08.26-2.74-1.69-6.92-2.18-10.16-1.19-.41.13-.85-.11-.97-.52-.13-.41.11-.85.52-.97 3.7-1.12 8.31-.58 11.45 1.34.37.23.49.71.24 1.08zm.11-2.84C14.55 8.84 9.5 8.66 6.43 9.6c-.49.15-1.01-.13-1.16-.62-.15-.49.13-1.01.62-1.16 3.52-1.07 9.1-.86 12.69 1.27.43.26.57.82.31 1.25-.26.43-.82.57-1.25.31z"})});case"tidal":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 2L8 6l4 4 4-4-4-4zM4 6L0 10l4 4 4-4-4-4zm16 0l-4 4 4 4 4-4-4-4zm-8 8l-4 4 4 4 4-4-4-4z"})});case"hls":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M2 12h2v6H2v-6zm4-4h2v10H6V8zm4-4h2v14h-2V4zm4 4h2v10h-2V8zm4 4h2v6h-2v-6z"})});case"audio":default:return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"})})}},Qa=({data:e,display:t,callbacks:n,state:a})=>{const{id:s,index:i,artist:o,title:l,version:c,lp:u,sourcesAvailable:h=[]}=e,{allowVersion:p=!0,dragHandleProps:g}=t,{onChange:y,onRemove:m,onMoveUp:x,onMoveDown:b,onChangeLp:f,onSelectSource:k}=n,{readOnly:v=!1,canMoveUp:w=!0,canMoveDown:R=!0,activeSource:M}=a,{t:j}=xe(),T=d.useRef(null);d.useEffect(()=>{!o&&T.current&&T.current.focus()},[o]);const P=N=>{if(!v&&N.key==="Enter"){const _=N.target.closest("div.gpi-row"),ee=_==null?void 0:_.querySelectorAll("input[data-role='field']");if(!ee||ee.length===0)return;const Y=Array.from(ee).indexOf(N.target),O=ee[Y+1]??ee[0];O==null||O.focus()}},A=N=>{const _=h.includes(N),ee=M===N,Y={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid var(--nice-border, #e5e7eb)",background:ee?"var(--nice-selected-bg, #eef2ff)":"var(--nice-bg, #fff)",opacity:_?1:.35,cursor:_&&k&&!v?"pointer":"default",transition:"transform .05s ease"},O=N==="youtube"?"var(--nice-danger, #ff0000)":N==="spotify"?"var(--nice-success, #1db954)":N==="tidal"?"var(--nice-text, #111827)":N==="hls"?"var(--nice-accent, #7c3aed)":"var(--nice-text, #374151)",U=N==="youtube"?"YouTube":N==="spotify"?"Spotify":N==="tidal"?"TIDAL":N==="hls"?"HLS":j("playlistItem.audio","Audio"),V=j("playlistItem.sourceLabel","Source")+": "+U+(ee?` ${j("playlistItem.sourceSelected","(selected)")}`:""),K=()=>{!_||!k||v||k(N)};return r.jsx("button",{type:"button",title:U,onClick:K,disabled:!_||v,style:Y,"aria-pressed":ee,"aria-label":V,children:r.jsx(pf,{kind:N,color:O})},N)},I=["youtube","tidal","spotify","hls","audio"],L=typeof u=="number"?u:i+1;return r.jsxs("div",{className:"gpi-row",role:"group","aria-label":j("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:N=>f==null?void 0:f(Number(N.target.value)),disabled:v||!f,"aria-label":j("playlistItem.lp","Lp"),title:j("playlistItem.positionOnList","Position in the list"),style:ff}),r.jsx("input",{ref:T,"data-role":"field",type:"text",value:o,onChange:N=>y({artist:N.target.value}),placeholder:j("playlistItem.artist","Artist"),onKeyDown:P,disabled:v,"aria-label":j("playlistItem.artist","Artist"),className:"gpi-input",style:na}),r.jsx("input",{"data-role":"field",type:"text",value:l,onChange:N=>y({title:N.target.value}),placeholder:j("playlistItem.title","Title"),onKeyDown:P,disabled:v,"aria-label":j("playlistItem.title","Title"),className:"gpi-input",style:na}),p&&r.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:N=>y({version:N.target.value||void 0}),placeholder:j("playlistItem.versionOptional","Version (optional)"),onKeyDown:P,disabled:v,"aria-label":j("playlistItem.version","Version"),className:"gpi-input",style:na}),r.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":j("playlistItem.availableSources","Available sources"),children:I.map(A)}),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":j("playlistItem.dragReorder","Drag to reorder"),title:j("playlistItem.dragReorder","Drag to reorder"),style:tr,children:r.jsx(F.NtdMenu,{size:14})}),r.jsx("button",{type:"button",onClick:x,disabled:!w||v,"aria-label":j("playlistItem.moveUp","Move up"),title:j("playlistItem.moveUp","Move up"),style:tr,children:r.jsx(F.NtdArrowUp,{size:14})}),r.jsx("button",{type:"button",onClick:b,disabled:!R||v,"aria-label":j("playlistItem.moveDown","Move down"),title:j("playlistItem.moveDown","Move down"),style:tr,children:r.jsx(F.NtdArrowDown,{size:14})}),r.jsx("button",{type:"button",onClick:m,disabled:v,"aria-label":j("common.delete","Delete"),title:j("common.delete","Delete"),style:{...tr,color:"var(--nice-color-danger, #b91c1c)"},children:r.jsx(F.NtdClose,{size:14})})]})]})},ff={width:48,border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 6px",fontSize:14,textAlign:"center"},na={width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 10px",fontSize:14},tr={border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg, #fff)",padding:"6px 8px",borderRadius:6,cursor:"pointer"},xa=()=>Math.random().toString(36).slice(2,10),nr=e=>(e??[]).map(t=>({id:xa(),...t})),mf=e=>e.map(({id:t,...n})=>n),gf=null,yf=e=>{const t=e.trim();if(!t)return null;const n=t.split(/\s[-–—]\s/);if(n.length<2){const o=t.split(/[;|]/).map(l=>l.trim());return o.length>=2?{artist:o[0],title:o[1],version:o[2]||void 0}:null}const a=n[0].trim(),s=n.slice(1).join(" - ").trim(),i=s.match(/^(.*?)\s*[([](.+?)[)\]]\s*$/);if(i){const o=i[1].trim(),l=i[2].trim();return{artist:a,title:o,version:l||void 0}}return{artist:a,title:s,version:void 0}},vf=({value:e,defaultValue:t,onChange:n,allowVersion:a=!0,maxItems:s,addButtonLabel:i,emptyState:o=gf,readOnly:l=!1,autoFocusNewItem:c=!0,enableBulkPaste:u=!0})=>{const{t:h}=xe(),p=e!==void 0,[g,y]=d.useState(()=>nr(e||t)),[m,x]=d.useState(""),b=d.useRef(null),[f,k]=d.useState(null);d.useEffect(()=>{p&&y(nr(e))},[p,JSON.stringify(e)]);const v=d.useCallback(V=>{n==null||n(mf(V))},[n]),w=d.useCallback(V=>{if(p){const K=V(nr(e));v(K)}else y(K=>{const G=V(K);return v(G),G})},[v,p,e]),R=s?g.length<s:!0,M=d.useCallback(()=>{!R||l||w(V=>[...V,{id:xa(),artist:"",title:"",version:void 0}])},[R,l,w]),j=d.useCallback((V,K)=>{w(G=>G.map(W=>W.id===V?{...W,...K}:W))},[w]),T=d.useCallback(V=>{l||w(K=>K.filter(G=>G.id!==V))},[l,w]),P=d.useCallback((V,K)=>{w(G=>{const W=G.findIndex(B=>B.id===V);if(W<0)return G;const C=W+K;if(C<0||C>=G.length)return G;const $=[...G],[S]=$.splice(W,1);return $.splice(C,0,S),$})},[w]),A=d.useCallback((V,K)=>{w(G=>{const W=G.findIndex(B=>B.id===V);if(W<0)return G;const C=Math.max(0,Math.min(G.length-1,K-1));if(W===C)return G;const $=[...G],[S]=$.splice(W,1);return $.splice(C,0,S),$})},[w]),I=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",k(V))},N=V=>()=>k(K=>K===V?null:K),_=V=>K=>{if(l)return;K.preventDefault();const G=b.current??K.dataTransfer.getData("text/plain");k(null),b.current=null,!(!G||G===V)&&w(W=>{const C=W.findIndex(H=>H.id===G),$=W.findIndex(H=>H.id===V);if(C<0||$<0||C===$)return W;const S=[...W],[B]=S.splice(C,1);return S.splice($,0,B),S})},ee=()=>{b.current=null,k(null)},Y=d.useCallback(()=>{if(!u||l)return;const K=m.split(/\r?\n/).map(G=>G.trim()).filter(Boolean).map(yf).filter(G=>!!G);K.length!==0&&(w(G=>{const W=(s??1/0)-G.length,C=K.slice(0,Math.max(0,W)).map($=>({id:xa(),...$}));return[...G,...C]}),x(""))},[u,l,m,s,w]);d.useEffect(()=>{},[g.length,c]);const O=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.")}),U=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:!R||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":U,children:["+ ",U]})})]}),g.length===0?r.jsx("div",{className:"gp-empty",children:O}):r.jsx("ol",{className:"gp-list",style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:8},children:g.map((V,K)=>{const G=f===V.id;return r.jsx("li",{draggable:!l,onDragStart:I(V.id),onDragOver:L(V.id),onDragLeave:N(V.id),onDrop:_(V.id),onDragEnd:ee,style:{border:G?"2px dashed var(--nice-info, #6366f1)":"2px solid transparent",borderRadius:8,padding:G?4:0},children:r.jsx(Qa,{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:I(V.id)}},callbacks:{onChange:W=>j(V.id,W),onRemove:()=>T(V.id),onMoveUp:()=>P(V.id,-1),onMoveDown:()=>P(V.id,1),onChangeLp:W=>A(V.id,W)},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:te,disabled:!g.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")})]})]})]})})]})},yl={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},lf=Object.keys(yl),Sa=({icon:e,size:t=14})=>{if(!e)return null;const n=yl[e];return n?r.jsx(n,{size:t}):r.jsx("span",{children:e})},ai=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #f59e0b)","var(--nice-warning, #eab308)","var(--nice-success, #84cc16)","var(--nice-success, #22c55e)","var(--nice-info, #14b8a6)","var(--nice-info, #06b6d4)","var(--nice-primary, #3b82f6)","var(--nice-info, #6366f1)","var(--nice-accent, #8b5cf6)","var(--nice-accent, #a855f7)","var(--nice-color-accent-pink, #d946ef)","var(--nice-color-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)","var(--nice-text-muted, #78716c)","var(--nice-text-secondary, #64748b)","var(--nice-text, #000000)"],rr=lf,cf=({tags:e,onCreateTag:t,onUpdateTag:n,onDeleteTag:a,selectedTracks:s,onAssignTag:i,onUnassignTag:l})=>{const{t:o}=Te(),[c,d]=u.useState(null),[h,f]=u.useState(""),[p,y]=u.useState(ai[8]),[g,x]=u.useState(rr[0]),[v,m]=u.useState(!1),[S,b]=u.useState(null),[w,N]=u.useState(""),[R,P]=u.useState(""),[j,M]=u.useState(""),I=u.useCallback(z=>{d(z.id),N(z.name),P(z.color),M(z.icon||rr[0])},[]),T=u.useCallback(()=>{c&&w.trim()&&(n(c,w.trim(),R,j),d(null))},[c,w,R,j,n]),E=u.useCallback(()=>{h.trim()&&(t(h.trim(),p,g),f(""),m(!1))},[h,p,g,t]),_=u.useCallback(z=>{S===z?(a(z),b(null)):(b(z),setTimeout(()=>b(null),3e3))},[S,a]),D=s&&s.length>0,q=z=>!s||s.length===0?!1:s.every(U=>U.tags.includes(z)),te=z=>!s||s.length===0?!1:s.some(U=>U.tags.includes(z))&&!q(z);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:o("playlistManager.tagManager","Tag manager")}),r.jsx("div",{style:{flex:1}}),r.jsxs("button",{onClick:()=>m(!v),style:{background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"4px 10px",fontSize:"0.72rem",cursor:"pointer"},children:["+ ",o("playlistManager.newTag","New tag")]})]}),r.jsxs("div",{style:{padding:12},children:[v&&r.jsxs("div",{style:{border:"1px solid var(--nice-border-color, #d1d5db)",borderRadius:8,padding:10,marginBottom:12,background:"var(--nice-color-surface, #f9fafb)"},children:[r.jsxs("div",{style:{display:"flex",gap:6,marginBottom:8},children:[r.jsx("input",{type:"text",value:h,onChange:z=>f(z.target.value),placeholder:o("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:z=>z.key==="Enter"&&E()}),r.jsx("button",{onClick:E,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":o("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:o("playlistManager.color","Color")}),r.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:ai.map(z=>r.jsx("div",{onClick:()=>y(z),style:{width:20,height:20,borderRadius:"50%",background:z,cursor:"pointer",border:p===z?"3px solid var(--nice-color-accent, #3b82f6)":"2px solid transparent",boxSizing:"border-box"}},z))})]}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:o("playlistManager.icon","Icon")}),r.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:rr.map(z=>r.jsx("div",{onClick:()=>x(z),style:{width:26,height:26,borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"0.85rem",background:g===z?"var(--nice-accent-tint-10, #eff6ff)":"transparent",border:g===z?"1px solid var(--nice-color-accent, #3b82f6)":"1px solid transparent"},children:r.jsx(Sa,{icon:z,size:16})},z))})]})]}),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:o("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:o("playlistManager.noTags","No tags yet")}):r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.map(z=>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===z.id?"var(--nice-color-surface, #f9fafb)":"transparent"},children:c===z.id?r.jsxs(r.Fragment,{children:[r.jsx("select",{value:j,onChange:U=>M(U.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:rr.map(U=>r.jsx("option",{value:U,children:U},U))}),r.jsx("input",{type:"color",value:R,onChange:U=>P(U.target.value),style:{width:24,height:24,border:"none",cursor:"pointer",padding:0}}),r.jsx("input",{type:"text",value:w,onChange:U=>N(U.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:U=>U.key==="Enter"&&T()}),r.jsx("button",{onClick:T,style:ar("var(--nice-color-accent, #3b82f6)"),"aria-label":o("common.save","Save"),children:r.jsx(B.NtdCheck,{size:14})}),r.jsx("button",{onClick:()=>d(null),style:ar("var(--nice-text-secondary, #9ca3af)"),"aria-label":o("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:`${z.color}18`,color:z.color,fontWeight:600,fontSize:"0.78rem"},children:[r.jsx(Sa,{icon:z.icon,size:12}),z.name]}),D&&i&&l&&r.jsx("input",{type:"checkbox",checked:q(z.id),ref:U=>{U&&(U.indeterminate=te(z.id))},onChange:()=>{const U=s.map(Z=>Z.id);q(z.id)?l(U,z.id):i(U,z.id)},style:{cursor:"pointer"}}),r.jsx("div",{style:{flex:1}}),r.jsx("button",{onClick:()=>I(z),style:ar("var(--nice-text-secondary, #9ca3af)"),title:o("playlistManager.editTag","Edit tag"),"aria-label":o("playlistManager.editTag","Edit tag"),children:r.jsx(B.NtdEdit,{size:14})}),r.jsx("button",{onClick:()=>_(z.id),style:ar(S===z.id?"var(--nice-color-error, #ef4444)":"var(--nice-text-secondary, #9ca3af)"),title:S===z.id?o("playlistManager.confirmDelete","Click again to delete"):o("playlistManager.deleteTag","Delete tag"),"aria-label":S===z.id?o("playlistManager.confirmDelete","Click again to delete"):o("playlistManager.deleteTag","Delete tag"),children:r.jsx(B.NtdTrash,{size:14})})]})},z.id))})]})]})},ar=e=>({background:"none",border:"none",cursor:"pointer",fontSize:"0.82rem",color:e,padding:"2px 4px"});var Ja=(e=>(e.Static="static",e.Dynamic="dynamic",e))(Ja||{}),vl=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(vl||{}),bl=(e=>(e.Left="left",e.Right="right",e))(bl||{}),lt=(e=>(e.Artist="artist",e.Title="title",e.Album="album",e.Genre="genre",e.Year="year",e.Duration="duration",e.Rating="rating",e.PlayCount="playCount",e.Tag="tag",e.Source="source",e.AddedDate="addedDate",e))(lt||{}),ct=(e=>(e.Equals="eq",e.NotEquals="neq",e.Contains="contains",e.NotContains="notContains",e.StartsWith="startsWith",e.GreaterThan="gt",e.LessThan="lt",e.Between="between",e.In="in",e.NotIn="notIn",e))(ct||{}),xl=(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))(xl||{}),dn=(e=>(e.Asc="asc",e.Desc="desc",e))(dn||{}),wt=(e=>(e.Library="library",e.Spotify="spotify",e.Tidal="tidal",e.YouTube="youtube",e.MusicBrainz="musicbrainz",e.Import="import",e.Manual="manual",e))(wt||{});const df="_editor_qz5p3_5",uf="_heading_qz5p3_19",hf="_hint_qz5p3_35",pf="_group_qz5p3_49",ff="_groupOr_qz5p3_61",mf="_groupShaded_qz5p3_67",gf="_groupHeader_qz5p3_73",yf="_groupHint_qz5p3_87",vf="_groupActions_qz5p3_95",bf="_rule_qz5p3_107",xf="_value_qz5p3_121",Sf="_value2_qz5p3_127",wf="_dash_qz5p3_133",kf="_limit_qz5p3_141",Cf="_limitInput_qz5p3_159",it={editor:df,heading:uf,hint:hf,group:pf,groupOr:ff,groupShaded:mf,groupHeader:gf,groupHint:yf,groupActions:vf,rule:bf,value:xf,value2:Sf,dash:wf,limit:kf,limitInput:Cf},jf=[{value:lt.Artist,label:"Artist"},{value:lt.Title,label:"Title"},{value:lt.Album,label:"Album"},{value:lt.Genre,label:"Genre"},{value:lt.Year,label:"Year"},{value:lt.Duration,label:"Duration (s)"},{value:lt.Rating,label:"Rating"},{value:lt.PlayCount,label:"Play Count"},{value:lt.Tag,label:"Tag"},{value:lt.Source,label:"Source"},{value:lt.AddedDate,label:"Added Date"}],Mf=[{value:ct.Equals,label:"="},{value:ct.NotEquals,label:"≠"},{value:ct.Contains,label:"contains"},{value:ct.NotContains,label:"not contains"},{value:ct.StartsWith,label:"starts with"},{value:ct.GreaterThan,label:">"},{value:ct.LessThan,label:"<"},{value:ct.Between,label:"between"},{value:ct.In,label:"in"},{value:ct.NotIn,label:"not in"}];function Rf(e){return"logic"in e&&"rules"in e}function wa(){return{id:we.createId(),field:lt.Artist,operator:ct.Contains,value:""}}function Sl(){return{id:we.createId(),logic:"and",rules:[wa()]}}const Nf=({rule:e,onChange:t,onRemove:n})=>{const{t:a}=Te();return r.jsxs("div",{className:it.rule,children:[r.jsx(se.NiceSelect,{size:"sm",controlWidth:150,"aria-label":a("playlistManager.ruleField","Field"),value:e.field,onChange:s=>t({...e,field:$t(s)}),options:jf.map(s=>({value:s.value,label:a(`playlistManager.field.${s.value}`,s.label)}))}),r.jsx(se.NiceSelect,{size:"sm",controlWidth:150,"aria-label":a("playlistManager.ruleOperator","Operator"),value:e.operator,onChange:s=>t({...e,operator:$t(s)}),options:Mf.map(s=>({value:s.value,label:a(`playlistManager.op.${s.value}`,s.label)}))}),r.jsx(se.NiceTextInput,{size:"sm",className:it.value,"aria-label":a("playlistManager.ruleValue","Value"),placeholder:a("playlistManager.ruleValue","Value"),value:e.value,onChange:s=>t({...e,value:s})}),e.operator===ct.Between&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:it.dash,"aria-hidden":"true",children:"–"}),r.jsx(se.NiceTextInput,{size:"sm",className:it.value2,"aria-label":a("playlistManager.ruleValue2","Value 2"),placeholder:a("playlistManager.ruleValue2","Value 2"),value:e.value2??"",onChange:s=>t({...e,value2:s})})]}),r.jsx(se.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})]})},wl=({group:e,onChange:t,onRemove:n,depth:a=0})=>{const{t:s}=Te(),i=u.useCallback((f,p)=>{const y=[...e.rules];y[f]=p,t({...e,rules:y})},[e,t]),l=u.useCallback(f=>{const p=e.rules.filter((y,g)=>g!==f);t({...e,rules:p.length>0?p:[wa()]})},[e,t]),o=u.useCallback(()=>{t({...e,rules:[...e.rules,wa()]})},[e,t]),c=u.useCallback(()=>{t({...e,rules:[...e.rules,Sl()]})},[e,t]),d=u.useCallback(()=>{t({...e,logic:e.logic==="and"?"or":"and"})},[e,t]),h=e.logic==="and";return r.jsxs("div",{className:`${it.group} ${h?"":it.groupOr} ${a%2===0?it.groupShaded:""}`,children:[r.jsxs("div",{className:it.groupHeader,children:[r.jsx(se.NiceButton,{size:"sm",variant:h?"primary":"warning",onClick:d,title:s("playlistManager.toggleLogic","Toggle AND/OR"),children:h?s("playlistManager.logicAnd","AND"):s("playlistManager.logicOr","OR")}),r.jsx("span",{className:it.groupHint,children:h?s("playlistManager.matchAllRules","Match all of these rules"):s("playlistManager.matchAnyRule","Match any of these rules")}),r.jsxs("div",{className:it.groupActions,children:[r.jsx(se.NiceButton,{size:"sm",variant:"outline",leftIcon:r.jsx(B.NtdPlus,{size:14}),onClick:o,title:s("playlistManager.addRuleHint","Add rule"),children:s("playlistManager.addRule","Rule")}),a<3&&r.jsx(se.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(se.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((f,p)=>Rf(f)?r.jsx(wl,{group:f,onChange:y=>i(p,y),onRemove:()=>l(p),depth:a+1},f.id):r.jsx(Nf,{rule:f,onChange:y=>i(p,y),onRemove:()=>l(p)},f.id))]})},Tf=({rules:e,onChange:t,limit:n,onLimitChange:a})=>{const{t:s}=Te(),[i]=u.useState(Sl),l=e??i;return r.jsxs("div",{className:it.editor,children:[r.jsxs("h6",{className:it.heading,children:[r.jsx(B.NtdRepeat,{size:14})," ",s("playlistManager.dynamicRules","Dynamic Playlist Rules")]}),r.jsx("p",{className:it.hint,children:s("playlistManager.dynamicRulesHint","Tracks matching these rules will automatically be included in the playlist.")}),r.jsx(wl,{group:l,onChange:t}),a&&r.jsx("div",{className:it.limit,children:r.jsx(se.NiceNumberInput,{size:"sm",className:it.limitInput,label:s("playlistManager.maxTracksLabel","Max tracks"),min:1,step:1,value:n??null,onChange:o=>a(o===null||o<=0?void 0:Math.round(o)),helperText:s("playlistManager.leaveEmptyForAllHint","Leave empty for unlimited")})})]})},si=e=>{if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`},$f={spotify:"var(--source-spotify, #1db954)",tidal:"var(--source-tidal, #000000)",youtube:"var(--source-youtube, #ff0000)",musicbrainz:"var(--source-musicbrainz, #ba478f)"},Pf=({source:e})=>{if(e==="import")return r.jsx(B.NtdDownload,{size:12});if(e==="manual")return r.jsx(B.NtdEdit,{size:12});const t=$f[e];return t?r.jsx(B.NtdCircle,{size:10,style:{color:t}}):r.jsx(B.NtdMusic,{size:12})},kl=({tracks:e,tags:t,selectedTrackIds:n,onSelectionChange:a,onPlay:s,onRemove:i,onReorder:l,onTagTracks:o,onRateTracks:c,sortField:d,sortDir:h,onSortChange:f,filterText:p,onFilterChange:y,compact:g=!1,draggable:x=!1,onDragStart:v,dropTarget:m=!1,onDrop:S})=>{const{t:b}=Te(),[w,N]=u.useState(null),[R,P]=u.useState(null),j=u.useRef(null),M=u.useMemo(()=>{let C=e??[];if(p.trim()){const $=p.toLowerCase();C=C.filter(k=>{var W,A;return k.title.toLowerCase().includes($)||k.artist.toLowerCase().includes($)||((W=k.album)==null?void 0:W.toLowerCase().includes($))||((A=k.genre)==null?void 0:A.toLowerCase().includes($))})}return[...C].sort(($,k)=>{const W=h==="asc"?1:-1;switch(d){case"title":return W*$.title.localeCompare(k.title);case"artist":return W*$.artist.localeCompare(k.artist);case"album":return W*($.album??"").localeCompare(k.album??"");case"duration":return W*(($.duration??0)-(k.duration??0));case"year":return W*(($.year??0)-(k.year??0));case"rating":return W*(($.rating??0)-(k.rating??0));case"addedDate":return W*($.addedAt??"").localeCompare(k.addedAt??"");case"custom":return W*(($.customOrder??0)-(k.customOrder??0));default:return 0}})},[e,p,d,h]),I=u.useCallback((C,$)=>{const k=M[C];if(k){if($.ctrlKey||$.metaKey){const W=new Set(n);W.has(k.id)?W.delete(k.id):W.add(k.id),a(W)}else if($.shiftKey&&j.current!==null){const W=Math.min(j.current,C),A=Math.max(j.current,C),L=new Set(n);for(let G=W;G<=A;G++)L.add(M[G].id);a(L)}else a(new Set([k.id]));j.current=C}},[M,n,a]),T=u.useCallback(()=>{n.size===M.length?a(new Set):a(new Set(M.map(C=>C.id)))},[M,n,a]),E=({field:C,label:$,width:k})=>{const W=d===C;return r.jsxs("div",{style:{width:k,flex:k?void 0:1,cursor:"pointer",userSelect:"none",fontWeight:W?700:500,fontSize:"0.72rem",textTransform:"uppercase",letterSpacing:"0.04em",opacity:W?1:.6,display:"flex",alignItems:"center",gap:4},onClick:()=>{W?f(C,h===dn.Asc?dn.Desc:dn.Asc):f(C,dn.Asc)},children:[$,W&&(h==="asc"?r.jsx(B.NtdArrowUp,{size:10}):r.jsx(B.NtdArrowDown,{size:10}))]})},_=u.useCallback((C,$)=>{const k=n.has(C.id)?Array.from(n):[C.id];$.dataTransfer.setData("trackIds",JSON.stringify(k)),$.dataTransfer.effectAllowed="move",v==null||v(k,$)},[n,v]),D=u.useCallback((C,$)=>{$.preventDefault(),$.dataTransfer.dropEffect="move",N(C)},[]),q=u.useCallback((C,$)=>{$.preventDefault(),N(null);try{const k=$.dataTransfer.getData("trackIds");if(k&&l){const W=JSON.parse(k),A=M.filter(F=>!W.includes(F.id)),L=M.filter(F=>W.includes(F.id)),G=Math.min(C,A.length);A.splice(G,0,...L),l(A.map(F=>F.id))}}catch{}},[M,l]),te=u.useCallback(C=>{C.preventDefault(),N(null),S==null||S(C)},[S]),z=u.useMemo(()=>new Map(t.map(C=>[C.id,C])),[t]),U=C=>C.replace(/[^a-z0-9_-]/gi,"-"),Z=g?36:48,ae={display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",color:"var(--nice-text-secondary, #6b7280)"},Y=(C,$)=>({display:"flex",alignItems:"center",gap:8,padding:g?"4px 12px":"6px 12px",height:Z,cursor:"pointer",background:$?"var(--nice-color-accent-light, #dbeafe)":C?"var(--nice-selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--nice-border-light, #f3f4f6)",transition:"background 0.1s"}),O=M.length>0&&n.size===M.length;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:m?C=>{C.preventDefault(),C.dataTransfer.dropEffect="copy"}:void 0,onDrop:m?te: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:p,onChange:C=>y(C.target.value),placeholder:b("playlistManager.filterTracks","Filter tracks..."),style:{flex:1,fontSize:"0.82rem",padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",background:"var(--nice-input-bg, #f9fafb)",color:"var(--nice-text-primary, #1f2937)"}}),r.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[M.length,"/",(e??[]).length]}),n.size>0&&i&&r.jsxs("button",{style:{fontSize:"0.72rem",padding:"4px 8px",borderRadius:4,border:"1px solid var(--nice-color-error, #ef4444)",background:"transparent",color:"var(--nice-color-error, #ef4444)",cursor:"pointer"},onClick:()=>i(Array.from(n)),"aria-label":b("playlistManager.removeSelected","Remove selected"),children:[r.jsx(B.NtdTrash,{size:12})," ",n.size]})]}),r.jsxs("div",{style:ae,children:[r.jsx("div",{style:{width:28},children:r.jsx("input",{type:"checkbox",checked:O,onChange:T,style:{cursor:"pointer"}})}),r.jsx("div",{style:{width:20},children:"#"}),!g&&r.jsx("div",{style:{width:44}}),r.jsx(E,{field:"title",label:b("playlistManager.colTitle","Title")}),r.jsx(E,{field:"artist",label:b("playlistManager.colArtist","Artist")}),!g&&r.jsx(E,{field:"album",label:b("playlistManager.colAlbum","Album")}),r.jsx(E,{field:"duration",label:b("playlistManager.colDuration","Duration"),width:60}),!g&&r.jsx(E,{field:"year",label:b("playlistManager.colYear","Year"),width:50}),r.jsx("div",{style:{width:30}})," ",!g&&r.jsx("div",{style:{width:60}})," ",r.jsx("div",{style:{width:24}})," "]}),r.jsxs("div",{style:{flex:1,overflow:"auto"},children:[M.length===0&&r.jsx("div",{style:{padding:24,textAlign:"center",opacity:.4,fontSize:"0.85rem"},children:e.length===0?b("playlistManager.emptyPlaylist","This playlist is empty"):b("playlistManager.noMatchingTracks","No tracks match the filter")}),M.map((C,$)=>{const k=n.has(C.id),W=w===$;return r.jsxs("div",{style:Y(k,W),onClick:A=>I($,A),onDoubleClick:()=>s==null?void 0:s(C),draggable:x,onDragStart:A=>_(C,A),onDragOver:A=>D($,A),onDrop:A=>q($,A),onDragLeave:()=>N(null),children:[r.jsx("div",{style:{width:28},children:r.jsx("input",{type:"checkbox",checked:k,onChange:()=>{const A=new Set(n);k?A.delete(C.id):A.add(C.id),a(A)},onClick:A=>A.stopPropagation(),style:{cursor:"pointer"}})}),r.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:$+1}),!g&&r.jsx("div",{style:{width:44,height:36,flexShrink:0},children:C.coverUrl?r.jsx("img",{src:C.coverUrl,alt:C.title||b("common.coverArt","Cover art"),style:{width:36,height:36,borderRadius:4,objectFit:"cover"},loading:"lazy"}):r.jsx("div",{style:{width:36,height:36,borderRadius:4,background:"var(--nice-color-surface, #f3f4f6)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.9rem"},children:r.jsx(B.NtdMusic,{size:16})})}),r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",fontWeight:500},children:C.title}),r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",opacity:.7},children:C.artist}),!g&&r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",opacity:.5},children:C.album}),r.jsx("div",{style:{width:60,fontSize:"0.78rem",opacity:.5,textAlign:"right"},children:si(C.duration)}),!g&&r.jsx("div",{style:{width:50,fontSize:"0.72rem",opacity:.4,textAlign:"center"},children:C.year||""}),r.jsx("div",{style:{width:30,textAlign:"center",fontSize:"0.75rem"},title:C.source,children:r.jsx(Pf,{source:C.source})}),!g&&r.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[C.tags.slice(0,2).map(A=>{const L=z.get(A);if(!L)return null;const G=`--tag-${U(A)}`;return r.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${G}-bg, ${L.color}22)`,color:`var(${G}, ${L.color})`,whiteSpace:"nowrap"},children:L.name},A)}),C.tags.length>2&&r.jsxs("span",{style:{fontSize:"0.6rem",opacity:.4},children:["+",C.tags.length-2]})]}),r.jsxs("div",{style:{width:24,display:"flex",alignItems:"center"},children:[r.jsx("button",{style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:2,opacity:.5,position:"relative"},onClick:A=>{A.stopPropagation(),P(R===C.id?null:C.id)},title:b("playlistManager.morActions","More actions"),"aria-label":b("playlistManager.morActions","More actions"),children:r.jsx(B.NtdTag,{size:12})}),R===C.id&&t.length>0&&r.jsxs("div",{style:{position:"absolute",right:12,marginTop:4,background:"var(--nice-bg-elevated, #fff)",border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:8,padding:8,zIndex:100,boxShadow:"0 4px 12px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",minWidth:140},children:[r.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:b("playlistManager.assignTag","Assign tag")}),t.map(A=>{const L=C.tags.includes(A.id);return r.jsxs("div",{style:{padding:"4px 8px",borderRadius:4,cursor:"pointer",fontSize:"0.78rem",display:"flex",alignItems:"center",gap:6,background:L?`var(--tag-${U(A.id)}-bg, ${A.color}22)`:"transparent"},onClick:G=>{G.stopPropagation();const F=n.size>0?Array.from(n):[C.id];L||o==null||o(F,[A.id]),P(null)},children:[r.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:`var(--tag-${U(A.id)}, ${A.color})`,flexShrink:0}}),r.jsx("span",{children:A.name}),L&&r.jsx(B.NtdCheck,{size:12,style:{marginLeft:"auto"}})]},A.id)})]})]})]},C.id)})]}),r.jsxs("div",{style:{padding:"6px 12px",borderTop:"1px solid var(--nice-border-color, #e5e7eb)",fontSize:"0.72rem",opacity:.5,display:"flex",gap:16},children:[r.jsxs("span",{children:[M.length," ",b("playlistManager.tracks","tracks")]}),r.jsx("span",{children:si(M.reduce((C,$)=>C+($.duration??0),0))}),n.size>0&&r.jsxs("span",{children:[n.size," ",b("playlistManager.selected","selected")]})]})]})},ii=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),Af=({playlists:e=[],tags:t=[],onCopyTracks:n=()=>{},onMoveTracks:a=()=>{},onRemoveTracks:s=()=>{},onReorderTracks:i=()=>{},onPlay:l=()=>{},onTagTracks:o=()=>{},initialLeftId:c,initialRightId:d})=>{const{t:h}=Te(),[f,p]=u.useState(()=>ii(c??null)),[y,g]=u.useState(()=>ii(d??null)),[x,v]=u.useState("left"),[m,S]=u.useState(null),[b,w]=u.useState(50),[N,R]=u.useState(!1),P=u.useMemo(()=>e.find(O=>O.id===f.playlistId),[e,f.playlistId]),j=u.useMemo(()=>e.find(O=>O.id===y.playlistId),[e,y.playlistId]),M=u.useCallback((O,C)=>{O==="left"?p($=>({...$,...C})):g($=>({...$,...C}))},[]),I=u.useCallback(O=>O==="left"?f:y,[f,y]),T=O=>O==="left"?"right":"left",E=u.useCallback(O=>{const C=I(O),$=I(T(O));!C.playlistId||!$.playlistId||C.selectedTrackIds.size===0||(n(C.playlistId,$.playlistId,Array.from(C.selectedTrackIds)),M(O,{selectedTrackIds:new Set}))},[I,n,M]),_=u.useCallback(O=>{const C=I(O),$=I(T(O));!C.playlistId||!$.playlistId||C.selectedTrackIds.size===0||(a(C.playlistId,$.playlistId,Array.from(C.selectedTrackIds)),M(O,{selectedTrackIds:new Set}))},[I,a,M]),D=u.useCallback(O=>{const C=I(O);!C.playlistId||C.selectedTrackIds.size===0||S({operation:"copy",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[I]),q=u.useCallback(O=>{const C=I(O);!C.playlistId||C.selectedTrackIds.size===0||S({operation:"cut",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[I]),te=u.useCallback(O=>{const C=I(O);!m||!C.playlistId||(m.operation==="copy"?n(m.sourcePlaylistId,C.playlistId,m.trackIds):a(m.sourcePlaylistId,C.playlistId,m.trackIds),S(null))},[m,I,n,a]),z=u.useCallback(O=>{O.key==="Tab"&&!O.shiftKey&&(O.preventDefault(),v(C=>T(C))),(O.ctrlKey||O.metaKey)&&O.key==="c"&&D(x),(O.ctrlKey||O.metaKey)&&O.key==="x"&&q(x),(O.ctrlKey||O.metaKey)&&O.key==="v"&&te(x)},[x,D,q,te]),U=u.useCallback(()=>R(!0),[]),Z=u.useCallback(O=>{if(!N)return;const C=O.currentTarget.getBoundingClientRect(),$=(O.clientX-C.left)/C.width*100;w(Math.max(20,Math.min(80,$)))},[N]),ae=u.useCallback(()=>R(!1),[]),Y=O=>{const C=I(O),$=O==="left"?P:j,k=x===O,A=!!I(T(O)).playlistId;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",border:k?"2px solid var(--nice-color-accent, #3b82f6)":"2px solid transparent",borderRadius:8,overflow:"hidden",background:"var(--nice-bg-elevated, #fff)"},onClick:()=>v(O),children:[r.jsx("div",{style:{padding:"8px 12px",background:k?"var(--nice-color-accent, #3b82f6)":"var(--nice-color-surface, #f3f4f6)",color:k?"var(--nice-text-on-accent, #fff)":"var(--nice-text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:r.jsxs("select",{value:C.playlistId??"",onChange:L=>M(O,{playlistId:L.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:k?"var(--nice-overlay-light-20, #ffffff30)":"var(--nice-input-bg, #fff)",color:k?"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(L=>r.jsxs("option",{value:L.id,children:[L.name," (",L.trackCount,")"]},L.id))]})}),r.jsxs("div",{style:{display:"flex",gap:4,padding:"4px 8px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",flexWrap:"wrap"},children:[r.jsxs("button",{style:ra(!1),onClick:()=>E(O),disabled:!C.playlistId||!A||C.selectedTrackIds.size===0,title:h("playlistManager.copyToOther","Copy to the other playlist"),children:[O==="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:ra(!1),onClick:()=>_(O),disabled:!C.playlistId||!A||C.selectedTrackIds.size===0,title:h("playlistManager.moveToOther","Move to the other playlist"),children:[O==="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}}),m&&r.jsxs("button",{style:ra(!0),onClick:()=>te(O),disabled:!C.playlistId,children:[r.jsx(B.NtdClipboard,{size:12})," ",h("playlistManager.paste","Paste")," (",m.trackIds.length,")"]})]}),$?r.jsx(kl,{tracks:$.tracks,tags:t,selectedTrackIds:C.selectedTrackIds,onSelectionChange:L=>M(O,{selectedTrackIds:L}),onPlay:l,onRemove:L=>s($.id,L),onReorder:L=>i($.id,L),onTagTracks:o,sortField:C.sortField,sortDir:C.sortDir,onSortChange:(L,G)=>M(O,{sortField:L,sortDir:G}),filterText:C.filterText,onFilterChange:L=>M(O,{filterText:L}),compact:!0,draggable:!0}):r.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",opacity:.3,fontSize:"0.85rem"},children:h("playlistManager.selectPlaylistPrompt","Select a playlist to see its tracks")})]})};return r.jsxs("div",{style:{display:"flex",height:"100%",userSelect:N?"none":"auto"},onKeyDown:z,onMouseMove:Z,onMouseUp:ae,tabIndex:0,children:[r.jsx("div",{style:{width:`${b}%`,minWidth:200},children:Y("left")}),r.jsx("div",{style:{width:6,cursor:"col-resize",background:N?"var(--nice-color-accent, #3b82f6)":"var(--nice-border-color, #e5e7eb)",transition:N?"none":"background 0.15s",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseDown:U,children:r.jsx("div",{style:{width:2,height:40,borderRadius:1,background:N?"var(--nice-color-accent, #3b82f6)":"var(--nice-bg-tertiary, #9ca3af)"}})}),r.jsx("div",{style:{flex:1,minWidth:200},children:Y("right")})]})},ra=e=>({background:e?"var(--nice-color-accent, #3b82f6)":"transparent",color:e?"var(--nice-text-on-accent, #fff)":"var(--nice-text-secondary, #6b7280)",border:e?"none":"1px solid var(--nice-border-color, #d1d5db)",borderRadius:6,padding:"3px 8px",fontSize:"0.72rem",cursor:"pointer",whiteSpace:"nowrap"}),Cl="av:local-playlists";function Ef(){try{const e=localStorage.getItem(Cl);return e?JSON.parse(e):[]}catch{return[]}}function If(e){const t=JSON.stringify(e);try{localStorage.setItem(Cl,t)}catch{}}function es(){const[e,t]=u.useState(()=>Ef()),n=u.useRef(!1);return u.useEffect(()=>{n.current=!0},[]),u.useEffect(()=>{If(e)},[e]),u.useMemo(()=>({list:()=>e,get:s=>e.find(i=>i.id===s),create:s=>{const i=new Date().toISOString(),l={id:we.createId(),name:s,items:[],updatedAt:i};return t(o=>[l,...o]),l},rename:(s,i)=>t(l=>l.map(o=>o.id===s?{...o,name:i,updatedAt:new Date().toISOString()}:o)),remove:s=>t(i=>i.filter(l=>l.id!==s)),replaceItems:(s,i)=>t(l=>l.map(o=>o.id===s?{...o,items:i,updatedAt:new Date().toISOString()}:o)),addItems:(s,i)=>t(l=>l.map(o=>o.id===s?{...o,items:[...o.items,...i],updatedAt:new Date().toISOString()}:o))}),[e])}const Lf=ot.scoped("PlaylistList"),zf={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,background:"var(--nice-bg, #fff)"},Df={...zf,padding:"8px 10px",cursor:"pointer"},jl={border:"1px solid var(--nice-border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg, #fff)",cursor:"pointer"},_f={...jl,background:"var(--nice-color-primary, #4f46e5)",borderColor:"var(--nice-color-primary, #4f46e5)",color:"var(--nice-text-on-primary, #fff)"},ts=({selectedId:e,onSelect:t,onCreateRemote:n})=>{const{t:a}=Te(),s=es(),[i,l]=u.useState(""),o=u.useMemo(()=>s.list(),[s]);return r.jsxs("div",{style:{display:"grid",gap:10},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("input",{placeholder:a("playlistList.playlistName","Playlist name..."),value:i,onChange:c=>l(c.target.value),style:{flex:1,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px"},"aria-label":"Playlist name"}),r.jsxs("button",{type:"button",disabled:!i.trim(),style:i.trim()?_f:{...jl,cursor:"not-allowed",color:"var(--nice-text-muted, #9ca3af)",background:"var(--nice-bg-tertiary, #f3f4f6)"},onClick:async()=>{const c=s.create(i.trim());if(l(""),n)try{await n({platform:"tidal",name:c.name,songs:c.items})}catch(d){Lf.error("Remote playlist create failed:",d)}t==null||t(c)},children:["+ ",a("common.add","Add")]})]}),r.jsxs("div",{style:{display:"grid",gap:6},children:[o.map(c=>{const d=c.id===e;return r.jsxs("button",{onClick:()=>t==null?void 0:t(c),style:{...Df,background:d?"var(--nice-selected-bg, #eef2ff)":"var(--nice-bg, #fff)"},children:[r.jsx("div",{style:{fontWeight:600},children:c.name}),r.jsxs("div",{style:{color:"var(--nice-text-dim, #64748b)",fontSize:12},children:[c.items.length+" "+a("playlistList.songs","songs")," ","• ",new Date(c.updatedAt).toLocaleString()]})]},c.id)}),!o.length&&r.jsx("div",{style:{color:"var(--nice-text-muted, #6b7280)"},children:a("playlistList.emptyState","No playlists. Add the first one ↑")})]})]})},Ff=ot.scoped("PlaylistBrowser"),oi={display:"grid",gap:12},li=e=>({artist:(e.artists??[]).join(", "),title:e.title}),Of=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:n,tracks:a,view:s,onSelect:i,onPlay:l})=>{var v;const{t:o}=Te(),c=es(),[d,h]=u.useState(null),[f,p]=u.useState(""),[,y]=u.useState([]),g=d==null?void 0:d.id,x=(m,S)=>{if("addItems"in c){c.addItems(m.id,S);const w=c.list().find(N=>N.id===m.id)||m;h(w);return}const b=c;if("update"in c&&typeof b.update=="function"){const w=Array.from([...m.items||[],...S]);b.update({...m,items:w});const N=c.list().find(R=>R.id===m.id)||{...m,items:w};h(N);return}Ff.warn("useLocalPlaylists: missing addItems/update method — update hook implementation.")};return r.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(min(200px, 100%), 320px) 1fr",gap:16},children:[r.jsxs("div",{style:oi,children:[r.jsx("h3",{style:{margin:0},children:o("playlistBrowser.playlists","Playlists")}),r.jsx(ts,{selectedId:g,onSelect:h}),d&&r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:[o("playlistBrowser.selected","Selected"),": ",r.jsx("strong",{children:d.name})," ·"," ",((v=d.items)==null?void 0:v.length)??0," ",o("playlistBrowser.tracks","tracks")]})]}),r.jsxs("div",{style:oi,children:[r.jsx("h3",{style:{margin:0},children:o("playlistBrowser.library","Library")}),r.jsxs("div",{children:[e==null?void 0:e({placeholder:o("playlistBrowser.searchAndAdd","Search and add to playlist..."),onSelect:m=>{d&&x(d,[li(m)])}}),r.jsx("input",{placeholder:o("playlistBrowser.fullSearch","Full search (Enter does not add, full list below)"),value:f,onChange:m=>p(m.target.value),style:{width:"100%",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px",marginTop:10}})]}),t==null?void 0:t({query:f,onSelect:m=>{d&&x(d,[li(m)])}}),n==null?void 0:n({onPlayNow:m=>y(m),onAddToQueue:m=>y(S=>[...S,...m]),onAddDescriptors:m=>d&&x(d,m)})]})]})};var Yt=(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))(Yt||{});const Ml=(e,t=null)=>e.filter(n=>n.parentId===t).sort((n,a)=>n.sortOrder-a.sortOrder).map(n=>({...n,children:Ml(e,n.id)})),Bf={[Yt.Spotify]:{label:"Spotify",color:"var(--source-spotify, #1DB954)",bg:"var(--source-spotify-bg, #1DB95418)"},[Yt.Tidal]:{label:"Tidal",color:"var(--source-tidal, #000000)",bg:"var(--source-tidal-bg, #00000010)"},[Yt.YouTube]:{label:"YouTube",color:"var(--source-youtube, #FF0000)",bg:"var(--source-youtube-bg, #FF000010)"}},Gf=({folders:e,playlists:t,tags:n,services:a,activeFolderId:s,activePlaylistId:i,onSelectFolder:l,onSelectPlaylist:o,onCreateFolder:c,onRenameFolder:d,onDeleteFolder:h,onCreatePlaylist:f,onConnectService:p,onDisconnectService:y,onDragPlaylistToFolder:g,collapsed:x=!1,onToggleCollapse:v})=>{const{t:m}=Te(),[S,b]=u.useState(new Set),[w,N]=u.useState(!1),[R,P]=u.useState(""),[j,M]=u.useState(null),[I,T]=u.useState(!1),[E,_]=u.useState(""),[D,q]=u.useState("static"),[te,z]=u.useState(null),[U,Z]=u.useState(""),[ae,Y]=u.useState(null),[O,C]=u.useState(!1),$=u.useMemo(()=>Ml(e),[e]),k=u.useCallback(J=>{b(ue=>{const me=new Set(ue);return me.has(J)?me.delete(J):me.add(J),me})},[]),W=u.useCallback(()=>{R.trim()&&(c(R.trim(),j),P(""),N(!1))},[R,j,c]),A=u.useCallback(()=>{E.trim()&&(f(E.trim(),D,s),_(""),T(!1))},[E,D,s,f]),L=u.useCallback(J=>{U.trim()&&(d(J,U.trim()),z(null),Z(""))},[U,d]),G=u.useCallback((J,ue)=>{J.preventDefault(),J.dataTransfer.dropEffect="move",Y(ue)},[]),F=u.useCallback((J,ue)=>{J.preventDefault();const me=J.dataTransfer.getData("playlistId");me&&g&&g(me,ue),Y(null)},[g]),V=u.useCallback(()=>Y(null),[]),Q=u.useCallback(J=>t.filter(ue=>(ue.folderId??null)===J),[t]),le={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)"},ne=(J,ue=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:ue?"var(--nice-color-accent-light, #dbeafe)":J?"var(--nice-color-accent, #3b82f6)":"transparent",color:J?"var(--btn-text, #fff)":"var(--nice-text-primary, #1f2937)",transition:"background 0.15s",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),K={background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:"2px 6px",borderRadius:4,color:"var(--nice-text-secondary, #6b7280)"},H={fontSize:"0.8rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",background:"var(--nice-input-bg, #fff)",color:"var(--nice-text-primary, #1f2937)",width:"100%"},ie=(J,ue)=>{var Me,$e;const me=S.has(J.id),Se=s===J.id,de=ae===J.id,xe=Q(J.id);return r.jsxs("div",{children:[r.jsxs("div",{style:{...ne(Se,de),paddingLeft:12+ue*16},onClick:()=>{l(J.id),J.children&&J.children.length>0&&k(J.id)},onDragOver:je=>G(je,J.id),onDrop:je=>F(je,J.id),onDragLeave:V,children:[r.jsx("span",{style:{width:14,textAlign:"center",flexShrink:0,fontSize:"0.7rem"},children:(((Me=J.children)==null?void 0:Me.length)||0)>0||xe.length>0?me?r.jsx(B.NtdChevronDown,{size:10}):r.jsx(B.NtdChevronRight,{size:10}):null}),te===J.id?r.jsx("input",{value:U,onChange:je=>Z(je.target.value),onKeyDown:je=>{je.key==="Enter"&&L(J.id),je.key==="Escape"&&z(null)},onBlur:()=>L(J.id),autoFocus:!0,style:{...H,flex:1},onClick:je=>je.stopPropagation()}):r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{display:"inline-flex"},children:J.icon??r.jsx(B.NtdFolder,{size:14})}),r.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:J.name}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:xe.length}),r.jsx("button",{style:K,onClick:je=>{je.stopPropagation(),z(J.id),Z(J.name)},title:m("common.rename","Rename"),"aria-label":m("common.rename","Rename"),children:r.jsx(B.NtdEdit,{size:12})}),r.jsx("button",{style:{...K,color:"var(--nice-color-error, #ef4444)"},onClick:je=>{je.stopPropagation(),h(J.id)},title:m("common.delete","Delete"),"aria-label":m("common.delete","Delete"),children:r.jsx(B.NtdTrash,{size:12})})]})]}),me&&r.jsxs(r.Fragment,{children:[xe.map(je=>re(je,ue+1)),($e=J.children)==null?void 0:$e.map(je=>ie(je,ue+1))]})]},J.id)},re=(J,ue)=>{const me=i===J.id;return r.jsxs("div",{style:{...ne(me),paddingLeft:12+ue*16+22},onClick:()=>o(J.id),draggable:!0,onDragStart:Se=>{Se.dataTransfer.setData("playlistId",J.id),Se.dataTransfer.effectAllowed="move"},children:[r.jsx("span",{style:{display:"inline-flex"},children:J.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:J.name}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:J.trackCount})]},J.id)};if(x)return r.jsx("div",{style:le,children:r.jsx("button",{style:{...K,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:v,title:m("playlistManager.expandSidebar","Expand sidebar"),"aria-label":m("playlistManager.expandSidebar","Expand sidebar"),children:r.jsx(B.NtdChevronRight,{size:16})})});const he=Q(null);return r.jsxs("div",{style:le,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})," ",m("playlistManager.title","Playlists")]}),r.jsx("button",{style:K,onClick:v,title:m("playlistManager.collapseSidebar","Collapse sidebar"),"aria-label":m("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:{...K,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:6,padding:"4px 10px"},onClick:()=>T(!0),children:["+ ",m("playlistManager.newPlaylist","New playlist")]}),r.jsxs("button",{style:{...K,border:"1px solid var(--nice-border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{N(!0),M(s)},children:[r.jsx(B.NtdFolder,{size:12})," ",m("playlistManager.newFolder","New folder")]})]}),I&&r.jsxs("div",{style:{...oe,display:"flex",flexDirection:"column",gap:6},children:[r.jsx("input",{value:E,onChange:J=>_(J.target.value),placeholder:m("playlistManager.playlistName","Playlist name"),style:H,autoFocus:!0,onKeyDown:J=>{J.key==="Enter"&&A(),J.key==="Escape"&&T(!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:()=>q("static")}),m("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:()=>q("dynamic")}),r.jsx(B.NtdLightning,{size:12})," ",m("playlistManager.dynamic","Dynamic")]}),r.jsx("div",{style:{flex:1}}),r.jsx("button",{style:{...K,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:A,"aria-label":"Confirm create playlist",children:r.jsx(B.NtdCheck,{size:12})}),r.jsx("button",{style:K,onClick:()=>T(!1),"aria-label":"Cancel create playlist",children:r.jsx(B.NtdClose,{size:12})})]})]}),w&&r.jsxs("div",{style:{...oe,display:"flex",gap:6},children:[r.jsx("input",{value:R,onChange:J=>P(J.target.value),placeholder:m("playlistManager.folderName","Folder name"),style:{...H,flex:1},autoFocus:!0,onKeyDown:J=>{J.key==="Enter"&&W(),J.key==="Escape"&&N(!1)}}),r.jsx("button",{style:{...K,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:W,"aria-label":"Confirm create folder",children:r.jsx(B.NtdCheck,{size:12})}),r.jsx("button",{style:K,onClick:()=>N(!1),"aria-label":"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",{style:ne(s===null&&i===null,ae==="__root__"),onClick:()=>l(null),onDragOver:J=>G(J,null),onDrop:J=>F(J,null),onDragLeave:V,children:[r.jsx(B.NtdHome,{size:14}),r.jsx("span",{style:{flex:1},children:m("playlistManager.allPlaylists","All playlists")}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:t.length})]}),he.map(J=>re(J,0)),$.map(J=>ie(J,0))]}),n.length>0&&r.jsxs("div",{style:oe,children:[r.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:m("playlistManager.tags","Tags")}),r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:n.map(J=>r.jsxs("span",{style:{fontSize:"0.7rem",padding:"2px 8px",borderRadius:12,background:J.color+"22",color:J.color,border:`1px solid ${J.color}44`,cursor:"pointer"},children:[r.jsx(Sa,{icon:J.icon,size:10}),J.icon?" ":"",J.name]},J.id))})]}),r.jsxs("div",{style:oe,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",cursor:"pointer",fontSize:"0.7rem",fontWeight:600,opacity:.6},onClick:()=>C(!O),children:[r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.NtdLink,{size:12})," ",m("playlistManager.services","Services")]}),O?r.jsx(B.NtdChevronUp,{size:12}):r.jsx(B.NtdChevronDown,{size:12})]}),O&&r.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[Yt.Spotify,Yt.Tidal,Yt.YouTube].map(J=>{const ue=Bf[J],me=a.find(Se=>Se.platform===J);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:ue.color}}),r.jsx("span",{style:{flex:1},children:ue.label}),me!=null&&me.connected?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{fontSize:"0.65rem",opacity:.6},children:me.username??m("playlistManager.connected","Connected")}),r.jsx("button",{style:{...K,color:"var(--nice-danger, #ef4444)"},onClick:()=>y(J),"aria-label":m("playlistManager.disconnect","Disconnect"),children:r.jsx(B.NtdClose,{size:12})})]}):r.jsx("button",{style:{...K,background:ue.color,color:"var(--nice-color-white, #fff)",borderRadius:4,padding:"2px 8px"},onClick:()=>p(J),children:m("playlistManager.connect","Connect")})]},J)})})]})]})},Wf=({playlist:e,tags:t,onPlay:n,selectedTrackIds:a,onSelectionChange:s})=>{const{t:i}=Te(),l=u.useCallback(o=>{const c=new Set(a);c.has(o)?c.delete(o):c.add(o),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(o=>{const c=a.has(o.id);return r.jsxs("div",{onClick:()=>l(o.id),onDoubleClick:()=>n(o),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:o.title}),r.jsx("div",{style:{fontSize:"0.68rem",opacity:.5,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:o.artist})]},o.id)})})},Uf=u.memo(Wf),ci=e=>e.replace(/[^a-z0-9_-]/gi,"-"),di={background:"none",border:"none",cursor:"pointer",fontSize:"0.78rem",padding:"2px 4px",opacity:.4},Vf=({playlists:e,folders:t,tags:n,activeFolderId:a,onSelectPlaylist:s,onDeletePlaylist:i,onDuplicatePlaylist:l})=>{const{t:o}=Te(),c=u.useMemo(()=>a?e.filter(d=>d.folderId===a):e,[e,a]);return c.length===0?r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:60,opacity:.4},children:[r.jsx("span",{style:{marginBottom:12,display:"inline-flex"},children:r.jsx(B.NtdMusic,{size:40})}),r.jsx("span",{style:{fontSize:"0.85rem"},children:o("playlistManager.emptyState","No playlists yet")})]}):r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))",gap:12},children:c.map(d=>{var f;const h=t.find(p=>p.id===d.folderId);return r.jsxs("div",{onClick:()=>s(d.id),style:{border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:12,padding:16,cursor:"pointer",background:"var(--nice-bg-elevated, #fff)",transition:"box-shadow 0.15s, transform 0.15s"},onMouseEnter:p=>{p.currentTarget.style.boxShadow="0 4px 12px var(--nice-overlay-8, rgba(0, 0, 0, 0.08))",p.currentTarget.style.transform="translateY(-1px)"},onMouseLeave:p=>{p.currentTarget.style.boxShadow="none",p.currentTarget.style.transform="none"},children:[r.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:8,background:"linear-gradient(135deg, var(--playlist-cover-bg1, #6366f140), var(--playlist-cover-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"2.5rem",marginBottom:10},children:d.type===Ja.Dynamic?r.jsx(B.NtdLightning,{size:40}):r.jsx(B.NtdMusic,{size:40})}),r.jsx("div",{style:{fontWeight:600,fontSize:"0.85rem",marginBottom:2},children:d.name}),r.jsxs("div",{style:{fontSize:"0.72rem",opacity:.5},children:[d.trackCount," ",o("playlistManager.tracks","tracks"),h&&r.jsxs(r.Fragment,{children:[" — ",r.jsx(B.NtdFolder,{size:11})," ",h.name]})]}),((f=d.tags)==null?void 0:f.length)>0&&r.jsx("div",{style:{display:"flex",gap:4,marginTop:6,flexWrap:"wrap"},children:d.tags.slice(0,3).map(p=>{const y=n.find(g=>g.id===p);return y?r.jsx("span",{style:{padding:"1px 8px",borderRadius:12,background:`var(--tag-${ci(p)}-bg, ${y.color}18)`,color:`var(--tag-${ci(p)}, ${y.color})`,fontSize:"0.65rem",fontWeight:500},children:y.name},p):null})}),r.jsxs("div",{style:{display:"flex",gap:4,marginTop:8},children:[r.jsx("button",{onClick:p=>{p.stopPropagation(),l(d.id)},style:di,title:o("playlistManager.duplicate","Duplicate"),"aria-label":o("playlistManager.duplicate","Duplicate"),children:r.jsx(B.NtdCopy,{size:14})}),r.jsx("button",{onClick:p=>{p.stopPropagation(),i(d.id)},style:di,title:o("playlistManager.delete","Delete"),"aria-label":o("playlistManager.delete","Delete"),children:r.jsx(B.NtdTrash,{size:14})})]})]},d.id)})})},qf=u.memo(Vf),ui=[{value:wt.Library,label:"Library",hex:"var(--nice-info, #6366f1)",css:"var(--source-library, #6366f1)",cssBg:"var(--source-library-bg, #6366f118)"},{value:wt.Spotify,label:"Spotify",hex:"var(--nice-success, #1db954)",css:"var(--source-spotify, #1db954)",cssBg:"var(--source-spotify-bg, #1db95418)"},{value:wt.Tidal,label:"Tidal",hex:"var(--nice-text, #000000)",css:"var(--source-tidal, #000000)",cssBg:"var(--source-tidal-bg, #00000018)"},{value:wt.YouTube,label:"YouTube",hex:"var(--nice-danger, #ff0000)",css:"var(--source-youtube, #ff0000)",cssBg:"var(--source-youtube-bg, #ff000018)"},{value:wt.MusicBrainz,label:"MusicBrainz",hex:"#ba478f",css:"var(--source-musicbrainz, #ba478f)",cssBg:"var(--source-musicbrainz-bg, #ba478f18)"}],Hf=({onSearch:e,results:t,isSearching:n,onAddToPlaylist:a,onPlayPreview:s})=>{const{t:i}=Te(),[l,o]=u.useState(""),[c,d]=u.useState(new Set([wt.Library,wt.Spotify,wt.Tidal,wt.YouTube])),[h,f]=u.useState(new Set),[p,y]=u.useState(!1),g=u.useRef(null),x=u.useCallback(P=>{d(j=>{const M=new Set(j);return M.has(P)?M.delete(P):M.add(P),M})},[]),v=u.useCallback(P=>{o(P),g.current&&clearTimeout(g.current),P.trim().length>=2&&(g.current=setTimeout(()=>{e(P.trim(),Array.from(c))},350))},[c,e]),m=u.useCallback(P=>{P.preventDefault(),l.trim().length>=2&&e(l.trim(),Array.from(c))},[l,c,e]),S=u.useCallback(P=>{f(j=>{const M=new Set(j);return M.has(P)?M.delete(P):M.add(P),M})},[]),b=u.useCallback(()=>{h.size===t.length?f(new Set):f(new Set(t.map(P=>P.id)))},[h,t]),w=u.useCallback(()=>{const P=t.filter(j=>h.has(j.id));P.length>0&&(a(P),f(new Set))},[t,h,a]),N=P=>{if(!P)return"--:--";const j=Math.floor(P/60),M=P%60;return`${j}:${M.toString().padStart(2,"0")}`},R=P=>{const j=ui.find(M=>M.value===P);return r.jsx(B.NtdCircle,{size:10,style:{color:j?j.css:"var(--nice-text-secondary, #6b7280)"}})};return r.jsxs("div",{style:{border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:10,background:"var(--nice-bg-elevated, #fff)",overflow:"hidden"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 12px",gap:8,cursor:"pointer",background:"var(--nice-color-surface, #f9fafb)"},onClick:()=>y(!p),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:p?r.jsx(B.NtdChevronUp,{size:12}):r.jsx(B.NtdChevronDown,{size:12})})]}),p&&r.jsxs("div",{style:{padding:"0 12px 12px"},children:[r.jsx("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap"},children:ui.map(P=>{const j=c.has(P.value);return r.jsxs("button",{onClick:()=>x(P.value),style:{padding:"4px 10px",borderRadius:20,border:j?`2px solid ${P.css}`:"1px solid var(--nice-border-color, #d1d5db)",background:j?P.cssBg:"transparent",color:j?P.css:"var(--nice-text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:j?600:400,transition:"all 0.15s"},children:[r.jsx(B.NtdCircle,{size:8,style:{color:P.css}})," ",P.label]},P.value)})}),r.jsxs("form",{onSubmit:m,style:{display:"flex",gap:6,marginBottom:8},children:[r.jsx("input",{type:"text",value:l,onChange:P=>v(P.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:l.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:l.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:b}),i("playlistManager.selectAll","Select all")]}),r.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[t.length," ",i("playlistManager.results","results")]}),r.jsx("div",{style:{flex:1}}),h.size>0&&r.jsxs("button",{onClick:w,style:{padding:"3px 10px",borderRadius:6,border:"none",background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.72rem",cursor:"pointer"},children:[r.jsx(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(P=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:"1px solid var(--nice-border-color, #f3f4f6)",background:h.has(P.id)?"var(--nice-accent-tint-10, #eff6ff)":"transparent",cursor:"pointer",fontSize:"0.78rem"},onClick:()=>S(P.id),children:[r.jsx("input",{type:"checkbox",checked:h.has(P.id),readOnly:!0}),R(P.source),P.imageUrl&&r.jsx("img",{src:P.imageUrl,alt:P.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:P.title}),r.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[P.artist,P.album?` — ${P.album}`:""]})]}),r.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:N(P.duration)}),s&&r.jsx("button",{onClick:j=>{j.stopPropagation(),s(P)},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})})]},P.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&&l.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")})]})]})},Kf=[{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)"}],Yf={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},Zf={display:"flex",justifyContent:"space-between",alignItems:"center"},Xf={display:"flex",gap:4,marginBottom:8},Ln={padding:"8px 20px",borderRadius:6,border:"none",background:"var(--nice-color-accent, #6366f1)",color:"var(--nice-text-on-primary, #fff)",cursor:"pointer",fontWeight:600},sr={...Ln,background:"transparent",color:"var(--nice-text-primary, #334155)",border:"1px solid var(--nice-border, #e2e8f0)"},hi={padding:12,borderRadius:8,border:"1px solid var(--nice-border, #e2e8f0)",cursor:"pointer",transition:"border-color 0.15s"},Rl=["connect","browse","tracks","options","importing","done"];function Qf(e){return Rl.indexOf(e)}function Jf(e){if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const e0=({connections:e=[],onConnect:t=()=>{},onDisconnect:n=()=>{},onFetchPlaylists:a=async()=>[],onFetchTracks:s=async()=>[],onImport:i=async()=>({playlistName:"",imported:0,skipped:0,failed:0,failedTracks:[]}),onClose:l=()=>{},targetFolders:o,sources:c})=>{const{t:d}=Te(),[h,f]=u.useState("connect"),[p,y]=u.useState(null),[g,x]=u.useState([]),[v,m]=u.useState(null),[S,b]=u.useState([]),[w,N]=u.useState(new Set),[R,P]=u.useState(!1),[j,M]=u.useState(null),[I,T]=u.useState(null),[E,_]=u.useState(null),[D,q]=u.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[te,z]=u.useState(""),U=u.useMemo(()=>new Set(e.filter(K=>K.connected).map(K=>K.platform)),[e]),Z=u.useCallback(K=>e.find(H=>H.platform===K),[e]),ae=u.useCallback(K=>{if(y(K),K===99){f("tracks"),z(""),b([]),P(!1);return}U.has(K)?(f("browse"),P(!0),_(null),a(K).then(H=>{x(H),P(!1)}).catch(H=>{_(String(H)),P(!1)})):t(K)},[U,t,a]),Y=u.useCallback(K=>{m(K),f("tracks"),P(!0),_(null),s(K).then(H=>{b(H),N(new Set(H.map(ie=>ie.externalId))),P(!1)}).catch(H=>{_(String(H)),P(!1)})},[s]),O=u.useCallback(K=>{N(H=>{const ie=new Set(H);return ie.has(K)?ie.delete(K):ie.add(K),ie})},[]),C=u.useCallback(()=>{N(K=>K.size===S.length?new Set:new Set(S.map(H=>H.externalId)))},[S]),$=u.useCallback(async()=>{if(!v)return;const K=S.filter(H=>w.has(H.externalId));if(K.length!==0){f("importing"),M({total:K.length,imported:0,skipped:0,failed:0}),_(null);try{const H=await i(v,K,D),ie=H&&typeof H=="object"&&"imported"in H?H:{playlistName:v.name,imported:K.length,skipped:0,failed:0,failedTracks:[]};T(ie),f("done")}catch(H){_(String(H)),f("options")}}},[v,S,w,D,i]),k=h!=="connect"&&h!=="importing"&&h!=="done",W=u.useCallback(()=>{switch(h){case"browse":f("connect");break;case"tracks":f("browse");break;case"options":f("tracks");break}},[h]),A=()=>r.jsx("div",{style:Xf,children:Rl.map((K,H)=>r.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:H<=Qf(h)?"var(--nice-color-accent, #6366f1)":"var(--nice-border, #e2e8f0)",transition:"background 0.2s"}},K))}),L=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[r.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.selectPlatform","Select a music platform to import from")}),Kf.map(K=>{const H=Z(K.value),ie=U.has(K.value);return r.jsxs("div",{style:{...hi,display:"flex",alignItems:"center",gap:12,borderColor:ie?K.color:void 0},onClick:()=>ae(K.value),role:"button",tabIndex:0,onKeyDown:re=>re.key==="Enter"&&ae(K.value),children:[r.jsx("span",{style:{color:K.color,display:"inline-flex"},"aria-hidden":"true",children:K.icon}),r.jsxs("div",{style:{flex:1},children:[r.jsx("strong",{children:K.label}),(H==null?void 0:H.username)&&r.jsx("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:H.username})]}),ie?r.jsxs("span",{style:{color:K.color,fontSize:12,fontWeight:600},children:[d("importWizard.connected","Connected")," ",r.jsx(B.NtdCheck,{size:12})]}):r.jsx("span",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.clickToConnect","Click to connect")})]},K.value)})]}),G=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[r.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.selectPlaylist","Select a playlist to import")}),R?r.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.loading","Loading playlists…")}):r.jsxs("div",{style:{display:"grid",gap:8,maxHeight:320,overflowY:"auto"},children:[g.map(K=>r.jsxs("div",{style:{...hi,display:"flex",alignItems:"center",gap:12},onClick:()=>Y(K),role:"button",tabIndex:0,onKeyDown:H=>H.key==="Enter"&&Y(K),children:[K.coverUrl&&r.jsx("img",{src:K.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:K.name}),K.description&&r.jsx("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:K.description})]}),r.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)",whiteSpace:"nowrap"},children:[K.trackCount," ",d("importWizard.tracks","tracks")]})]},K.id)),g.length===0&&r.jsx("div",{style:{textAlign:"center",padding:24,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.noPlaylists","No playlists found")})]})]}),F=u.useCallback(K=>{const ie=K.split(`
|
|
69
|
-
`).map(
|
|
68
|
+
OR: Artist;Title;Version`),rows:3,style:{width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:8,fontFamily:"inherit"}}),r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:6},children:[r.jsx("div",{style:{color:"var(--nice-text-secondary, #6b7280)",fontSize:12},children:h("genericPlaylist.bulkPasteHint","Each line will be added as a separate song.")}),r.jsx("button",{type:"button",onClick:Y,disabled:!m.trim(),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},children:h("genericPlaylist.addFromList","Add from list")})]})]})]})})]})},vl={music:F.NtdMusic,microphone:F.NtdMicrophone,volume:F.NtdVolume,wave:F.NtdWave,megaphone:F.NtdMegaphone,star:F.NtdStar,heart:F.NtdHeart,lightning:F.NtdLightning,sparkle:F.NtdSparkle,moon:F.NtdMoon,sun:F.NtdSun,mountain:F.NtdMountain,trophy:F.NtdTrophy,crown:F.NtdCrown,target:F.NtdTarget,pin:F.NtdPin},bf=Object.keys(vl),Sa=({icon:e,size:t=14})=>{if(!e)return null;const n=vl[e];return n?r.jsx(n,{size:t}):r.jsx("span",{children:e})},ai=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #f59e0b)","var(--nice-warning, #eab308)","var(--nice-success, #84cc16)","var(--nice-success, #22c55e)","var(--nice-info, #14b8a6)","var(--nice-info, #06b6d4)","var(--nice-primary, #3b82f6)","var(--nice-info, #6366f1)","var(--nice-accent, #8b5cf6)","var(--nice-accent, #a855f7)","var(--nice-color-accent-pink, #d946ef)","var(--nice-color-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)","var(--nice-text-muted, #78716c)","var(--nice-text-secondary, #64748b)","var(--nice-text, #000000)"],rr=bf,xf=({tags:e,onCreateTag:t,onUpdateTag:n,onDeleteTag:a,selectedTracks:s,onAssignTag:i,onUnassignTag:o})=>{const{t:l}=xe(),[c,u]=d.useState(null),[h,p]=d.useState(""),[g,y]=d.useState(ai[8]),[m,x]=d.useState(rr[0]),[b,f]=d.useState(!1),[k,v]=d.useState(null),[w,R]=d.useState(""),[M,j]=d.useState(""),[T,P]=d.useState(""),A=d.useCallback(O=>{u(O.id),R(O.name),j(O.color),P(O.icon||rr[0])},[]),I=d.useCallback(()=>{c&&w.trim()&&(n(c,w.trim(),M,T),u(null))},[c,w,M,T,n]),L=d.useCallback(()=>{h.trim()&&(t(h.trim(),g,m),p(""),f(!1))},[h,g,m,t]),N=d.useCallback(O=>{k===O?(a(O),v(null)):(v(O),setTimeout(()=>v(null),3e3))},[k,a]),_=s&&s.length>0,ee=O=>!s||s.length===0?!1:s.every(U=>U.tags.includes(O)),Y=O=>!s||s.length===0?!1:s.some(U=>U.tags.includes(O))&&!ee(O);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(F.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:O=>p(O.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:O=>O.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(F.NtdCheck,{size:14})})]}),r.jsxs("div",{style:{marginBottom:6},children:[r.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.color","Color")}),r.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:ai.map(O=>r.jsx("div",{onClick:()=>y(O),style:{width:20,height:20,borderRadius:"50%",background:O,cursor:"pointer",border:g===O?"3px solid var(--nice-color-accent, #3b82f6)":"2px solid transparent",boxSizing:"border-box"}},O))})]}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.icon","Icon")}),r.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:rr.map(O=>r.jsx("div",{onClick:()=>x(O),style:{width:26,height:26,borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"0.85rem",background:m===O?"var(--nice-accent-tint-10, #eff6ff)":"transparent",border:m===O?"1px solid var(--nice-color-accent, #3b82f6)":"1px solid transparent"},children:r.jsx(Sa,{icon:O,size:16})},O))})]})]}),_&&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(O=>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===O.id?"var(--nice-color-surface, #f9fafb)":"transparent"},children:c===O.id?r.jsxs(r.Fragment,{children:[r.jsx("select",{value:T,onChange:U=>P(U.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:rr.map(U=>r.jsx("option",{value:U,children:U},U))}),r.jsx("input",{type:"color",value:M,onChange:U=>j(U.target.value),style:{width:24,height:24,border:"none",cursor:"pointer",padding:0}}),r.jsx("input",{type:"text",value:w,onChange:U=>R(U.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:U=>U.key==="Enter"&&I()}),r.jsx("button",{onClick:I,style:ar("var(--nice-color-accent, #3b82f6)"),"aria-label":l("common.save","Save"),children:r.jsx(F.NtdCheck,{size:14})}),r.jsx("button",{onClick:()=>u(null),style:ar("var(--nice-text-secondary, #9ca3af)"),"aria-label":l("common.cancel","Cancel"),children:r.jsx(F.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:`${O.color}18`,color:O.color,fontWeight:600,fontSize:"0.78rem"},children:[r.jsx(Sa,{icon:O.icon,size:12}),O.name]}),_&&i&&o&&r.jsx("input",{type:"checkbox",checked:ee(O.id),ref:U=>{U&&(U.indeterminate=Y(O.id))},onChange:()=>{const U=s.map(V=>V.id);ee(O.id)?o(U,O.id):i(U,O.id)},style:{cursor:"pointer"}}),r.jsx("div",{style:{flex:1}}),r.jsx("button",{onClick:()=>A(O),style:ar("var(--nice-text-secondary, #9ca3af)"),title:l("playlistManager.editTag","Edit tag"),"aria-label":l("playlistManager.editTag","Edit tag"),children:r.jsx(F.NtdEdit,{size:14})}),r.jsx("button",{onClick:()=>N(O.id),style:ar(k===O.id?"var(--nice-color-error, #ef4444)":"var(--nice-text-secondary, #9ca3af)"),title:k===O.id?l("playlistManager.confirmDelete","Click again to delete"):l("playlistManager.deleteTag","Delete tag"),"aria-label":k===O.id?l("playlistManager.confirmDelete","Click again to delete"):l("playlistManager.deleteTag","Delete tag"),children:r.jsx(F.NtdTrash,{size:14})})]})},O.id))})]})]})},ar=e=>({background:"none",border:"none",cursor:"pointer",fontSize:"0.82rem",color:e,padding:"2px 4px"});var Ja=(e=>(e.Static="static",e.Dynamic="dynamic",e))(Ja||{}),bl=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(bl||{}),xl=(e=>(e.Left="left",e.Right="right",e))(xl||{}),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||{}),Sl=(e=>(e.Title="title",e.Artist="artist",e.Album="album",e.Duration="duration",e.AddedDate="addedDate",e.Year="year",e.Rating="rating",e.Custom="custom",e))(Sl||{}),dn=(e=>(e.Asc="asc",e.Desc="desc",e))(dn||{}),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 Sf="_editor_qz5p3_5",kf="_heading_qz5p3_19",wf="_hint_qz5p3_35",Cf="_group_qz5p3_49",jf="_groupOr_qz5p3_61",Mf="_groupShaded_qz5p3_67",Rf="_groupHeader_qz5p3_73",Nf="_groupHint_qz5p3_87",Tf="_groupActions_qz5p3_95",Pf="_rule_qz5p3_107",Ef="_value_qz5p3_121",$f="_value2_qz5p3_127",Af="_dash_qz5p3_133",If="_limit_qz5p3_141",Lf="_limitInput_qz5p3_159",at={editor:Sf,heading:kf,hint:wf,group:Cf,groupOr:jf,groupShaded:Mf,groupHeader:Rf,groupHint:Nf,groupActions:Tf,rule:Pf,value:Ef,value2:$f,dash:Af,limit:If,limitInput:Lf},_f=[{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"}],zf=[{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 Df(e){return"logic"in e&&"rules"in e}function ka(){return{id:ke.createId(),field:ot.Artist,operator:lt.Contains,value:""}}function kl(){return{id:ke.createId(),logic:"and",rules:[ka()]}}const Ff=({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:_f.map(s=>({value:s.value,label:a(`playlistManager.field.${s.value}`,s.label)}))}),r.jsx(ie.NiceSelect,{size:"sm",controlWidth:150,"aria-label":a("playlistManager.ruleOperator","Operator"),value:e.operator,onChange:s=>t({...e,operator:Tt(s)}),options:zf.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(F.NtdClose,{size:14}),ariaLabel:a("playlistManager.removeRule","Remove rule"),title:a("playlistManager.removeRule","Remove rule"),onClick:n,children:null})]})},wl=({group:e,onChange:t,onRemove:n,depth:a=0})=>{const{t:s}=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:[ka()]})},[e,t]),l=d.useCallback(()=>{t({...e,rules:[...e.rules,ka()]})},[e,t]),c=d.useCallback(()=>{t({...e,rules:[...e.rules,kl()]})},[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(F.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(F.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(F.NtdClose,{size:14}),ariaLabel:s("playlistManager.removeGroup","Remove group"),title:s("playlistManager.removeGroup","Remove group"),onClick:n,children:null})]})]}),e.rules.map((p,g)=>Df(p)?r.jsx(wl,{group:p,onChange:y=>i(g,y),onRemove:()=>o(g),depth:a+1},p.id):r.jsx(Ff,{rule:p,onChange:y=>i(g,y),onRemove:()=>o(g)},p.id))]})},Of=({rules:e,onChange:t,limit:n,onLimitChange:a})=>{const{t:s}=xe(),[i]=d.useState(kl),o=e??i;return r.jsxs("div",{className:at.editor,children:[r.jsxs("h6",{className:at.heading,children:[r.jsx(F.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(wl,{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")})})]})},si=e=>{if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`},Bf={spotify:"var(--source-spotify, #1db954)",tidal:"var(--source-tidal, #000000)",youtube:"var(--source-youtube, #ff0000)",musicbrainz:"var(--source-musicbrainz, #ba478f)"},Gf=({source:e})=>{if(e==="import")return r.jsx(F.NtdDownload,{size:12});if(e==="manual")return r.jsx(F.NtdEdit,{size:12});const t=Bf[e];return t?r.jsx(F.NtdCircle,{size:10,style:{color:t}}):r.jsx(F.NtdMusic,{size:12})},Cl=({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:k})=>{const{t:v}=xe(),[w,R]=d.useState(null),[M,j]=d.useState(null),T=d.useRef(null),P=d.useMemo(()=>{let C=e??[];if(g.trim()){const $=g.toLowerCase();C=C.filter(S=>{var B,H;return S.title.toLowerCase().includes($)||S.artist.toLowerCase().includes($)||((B=S.album)==null?void 0:B.toLowerCase().includes($))||((H=S.genre)==null?void 0:H.toLowerCase().includes($))})}return[...C].sort(($,S)=>{const B=h==="asc"?1:-1;switch(u){case"title":return B*$.title.localeCompare(S.title);case"artist":return B*$.artist.localeCompare(S.artist);case"album":return B*($.album??"").localeCompare(S.album??"");case"duration":return B*(($.duration??0)-(S.duration??0));case"year":return B*(($.year??0)-(S.year??0));case"rating":return B*(($.rating??0)-(S.rating??0));case"addedDate":return B*($.addedAt??"").localeCompare(S.addedAt??"");case"custom":return B*(($.customOrder??0)-(S.customOrder??0));default:return 0}})},[e,g,u,h]),A=d.useCallback((C,$)=>{const S=P[C];if(S){if($.ctrlKey||$.metaKey){const B=new Set(n);B.has(S.id)?B.delete(S.id):B.add(S.id),a(B)}else if($.shiftKey&&T.current!==null){const B=Math.min(T.current,C),H=Math.max(T.current,C),z=new Set(n);for(let Z=B;Z<=H;Z++)z.add(P[Z].id);a(z)}else a(new Set([S.id]));T.current=C}},[P,n,a]),I=d.useCallback(()=>{n.size===P.length?a(new Set):a(new Set(P.map(C=>C.id)))},[P,n,a]),L=({field:C,label:$,width:S})=>{const B=u===C;return r.jsxs("div",{style:{width:S,flex:S?void 0:1,cursor:"pointer",userSelect:"none",fontWeight:B?700:500,fontSize:"0.72rem",textTransform:"uppercase",letterSpacing:"0.04em",opacity:B?1:.6,display:"flex",alignItems:"center",gap:4},onClick:()=>{B?p(C,h===dn.Asc?dn.Desc:dn.Asc):p(C,dn.Asc)},children:[$,B&&(h==="asc"?r.jsx(F.NtdArrowUp,{size:10}):r.jsx(F.NtdArrowDown,{size:10}))]})},N=d.useCallback((C,$)=>{const S=n.has(C.id)?Array.from(n):[C.id];$.dataTransfer.setData("trackIds",JSON.stringify(S)),$.dataTransfer.effectAllowed="move",b==null||b(S,$)},[n,b]),_=d.useCallback((C,$)=>{$.preventDefault(),$.dataTransfer.dropEffect="move",R(C)},[]),ee=d.useCallback((C,$)=>{$.preventDefault(),R(null);try{const S=$.dataTransfer.getData("trackIds");if(S&&o){const B=JSON.parse(S),H=P.filter(E=>!B.includes(E.id)),z=P.filter(E=>B.includes(E.id)),Z=Math.min(C,H.length);H.splice(Z,0,...z),o(H.map(E=>E.id))}}catch{}},[P,o]),Y=d.useCallback(C=>{C.preventDefault(),R(null),k==null||k(C)},[k]),O=d.useMemo(()=>new Map(t.map(C=>[C.id,C])),[t]),U=C=>C.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)"},G=(C,$)=>({display:"flex",alignItems:"center",gap:8,padding:m?"4px 12px":"6px 12px",height:V,cursor:"pointer",background:$?"var(--nice-color-accent-light, #dbeafe)":C?"var(--nice-selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--nice-border-light, #f3f4f6)",transition:"background 0.1s"}),W=P.length>0&&n.size===P.length;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:f?C=>{C.preventDefault(),C.dataTransfer.dropEffect="copy"}:void 0,onDrop:f?Y:void 0,children:[r.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",display:"flex",gap:8,alignItems:"center"},children:[r.jsx("input",{type:"text",value:g,onChange:C=>y(C.target.value),placeholder: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(F.NtdTrash,{size:12})," ",n.size]})]}),r.jsxs("div",{style:K,children:[r.jsx("div",{style:{width:28},children:r.jsx("input",{type:"checkbox",checked:W,onChange:I,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((C,$)=>{const S=n.has(C.id),B=w===$;return r.jsxs("div",{style:G(S,B),onClick:H=>A($,H),onDoubleClick:()=>s==null?void 0:s(C),draggable:x,onDragStart:H=>N(C,H),onDragOver:H=>_($,H),onDrop:H=>ee($,H),onDragLeave:()=>R(null),children:[r.jsx("div",{style:{width:28},children:r.jsx("input",{type:"checkbox",checked:S,onChange:()=>{const H=new Set(n);S?H.delete(C.id):H.add(C.id),a(H)},onClick:H=>H.stopPropagation(),style:{cursor:"pointer"}})}),r.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:$+1}),!m&&r.jsx("div",{style:{width:44,height:36,flexShrink:0},children:C.coverUrl?r.jsx("img",{src:C.coverUrl,alt:C.title||v("common.coverArt","Cover art"),style:{width:36,height:36,borderRadius:4,objectFit:"cover"},loading:"lazy"}):r.jsx("div",{style:{width:36,height:36,borderRadius:4,background:"var(--nice-color-surface, #f3f4f6)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.9rem"},children:r.jsx(F.NtdMusic,{size:16})})}),r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",fontWeight:500},children:C.title}),r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",opacity:.7},children:C.artist}),!m&&r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",opacity:.5},children:C.album}),r.jsx("div",{style:{width:60,fontSize:"0.78rem",opacity:.5,textAlign:"right"},children:si(C.duration)}),!m&&r.jsx("div",{style:{width:50,fontSize:"0.72rem",opacity:.4,textAlign:"center"},children:C.year||""}),r.jsx("div",{style:{width:30,textAlign:"center",fontSize:"0.75rem"},title:C.source,children:r.jsx(Gf,{source:C.source})}),!m&&r.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[C.tags.slice(0,2).map(H=>{const z=O.get(H);if(!z)return null;const Z=`--tag-${U(H)}`;return r.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${Z}-bg, ${z.color}22)`,color:`var(${Z}, ${z.color})`,whiteSpace:"nowrap"},children:z.name},H)}),C.tags.length>2&&r.jsxs("span",{style:{fontSize:"0.6rem",opacity:.4},children:["+",C.tags.length-2]})]}),r.jsxs("div",{style:{width:24,display:"flex",alignItems:"center"},children:[r.jsx("button",{style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:2,opacity:.5,position:"relative"},onClick:H=>{H.stopPropagation(),j(M===C.id?null:C.id)},title:v("playlistManager.morActions","More actions"),"aria-label":v("playlistManager.morActions","More actions"),children:r.jsx(F.NtdTag,{size:12})}),M===C.id&&t.length>0&&r.jsxs("div",{style:{position:"absolute",right:12,marginTop:4,background:"var(--nice-bg-elevated, #fff)",border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:8,padding:8,zIndex:100,boxShadow:"0 4px 12px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",minWidth:140},children:[r.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:v("playlistManager.assignTag","Assign tag")}),t.map(H=>{const z=C.tags.includes(H.id);return r.jsxs("div",{style:{padding:"4px 8px",borderRadius:4,cursor:"pointer",fontSize:"0.78rem",display:"flex",alignItems:"center",gap:6,background:z?`var(--tag-${U(H.id)}-bg, ${H.color}22)`:"transparent"},onClick:Z=>{Z.stopPropagation();const E=n.size>0?Array.from(n):[C.id];z||l==null||l(E,[H.id]),j(null)},children:[r.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:`var(--tag-${U(H.id)}, ${H.color})`,flexShrink:0}}),r.jsx("span",{children:H.name}),z&&r.jsx(F.NtdCheck,{size:12,style:{marginLeft:"auto"}})]},H.id)})]})]})]},C.id)})]}),r.jsxs("div",{style:{padding:"6px 12px",borderTop:"1px solid var(--nice-border-color, #e5e7eb)",fontSize:"0.72rem",opacity:.5,display:"flex",gap:16},children:[r.jsxs("span",{children:[P.length," ",v("playlistManager.tracks","tracks")]}),r.jsx("span",{children:si(P.reduce((C,$)=>C+($.duration??0),0))}),n.size>0&&r.jsxs("span",{children:[n.size," ",v("playlistManager.selected","selected")]})]})]})},ii=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),Wf=({playlists:e=[],tags:t=[],onCopyTracks:n=()=>{},onMoveTracks:a=()=>{},onRemoveTracks:s=()=>{},onReorderTracks:i=()=>{},onPlay:o=()=>{},onTagTracks:l=()=>{},initialLeftId:c,initialRightId:u})=>{const{t:h}=xe(),[p,g]=d.useState(()=>ii(c??null)),[y,m]=d.useState(()=>ii(u??null)),[x,b]=d.useState("left"),[f,k]=d.useState(null),[v,w]=d.useState(50),[R,M]=d.useState(!1),j=d.useMemo(()=>e.find(W=>W.id===p.playlistId),[e,p.playlistId]),T=d.useMemo(()=>e.find(W=>W.id===y.playlistId),[e,y.playlistId]),P=d.useCallback((W,C)=>{W==="left"?g($=>({...$,...C})):m($=>({...$,...C}))},[]),A=d.useCallback(W=>W==="left"?p:y,[p,y]),I=W=>W==="left"?"right":"left",L=d.useCallback(W=>{const C=A(W),$=A(I(W));!C.playlistId||!$.playlistId||C.selectedTrackIds.size===0||(n(C.playlistId,$.playlistId,Array.from(C.selectedTrackIds)),P(W,{selectedTrackIds:new Set}))},[A,n,P]),N=d.useCallback(W=>{const C=A(W),$=A(I(W));!C.playlistId||!$.playlistId||C.selectedTrackIds.size===0||(a(C.playlistId,$.playlistId,Array.from(C.selectedTrackIds)),P(W,{selectedTrackIds:new Set}))},[A,a,P]),_=d.useCallback(W=>{const C=A(W);!C.playlistId||C.selectedTrackIds.size===0||k({operation:"copy",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[A]),ee=d.useCallback(W=>{const C=A(W);!C.playlistId||C.selectedTrackIds.size===0||k({operation:"cut",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[A]),Y=d.useCallback(W=>{const C=A(W);!f||!C.playlistId||(f.operation==="copy"?n(f.sourcePlaylistId,C.playlistId,f.trackIds):a(f.sourcePlaylistId,C.playlistId,f.trackIds),k(null))},[f,A,n,a]),O=d.useCallback(W=>{W.key==="Tab"&&!W.shiftKey&&(W.preventDefault(),b(C=>I(C))),(W.ctrlKey||W.metaKey)&&W.key==="c"&&_(x),(W.ctrlKey||W.metaKey)&&W.key==="x"&&ee(x),(W.ctrlKey||W.metaKey)&&W.key==="v"&&Y(x)},[x,_,ee,Y]),U=d.useCallback(()=>M(!0),[]),V=d.useCallback(W=>{if(!R)return;const C=W.currentTarget.getBoundingClientRect(),$=(W.clientX-C.left)/C.width*100;w(Math.max(20,Math.min(80,$)))},[R]),K=d.useCallback(()=>M(!1),[]),G=W=>{const C=A(W),$=W==="left"?j:T,S=x===W,H=!!A(I(W)).playlistId;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",border:S?"2px solid var(--nice-color-accent, #3b82f6)":"2px solid transparent",borderRadius:8,overflow:"hidden",background:"var(--nice-bg-elevated, #fff)"},onClick:()=>b(W),children:[r.jsx("div",{style:{padding:"8px 12px",background:S?"var(--nice-color-accent, #3b82f6)":"var(--nice-color-surface, #f3f4f6)",color:S?"var(--nice-text-on-accent, #fff)":"var(--nice-text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:r.jsxs("select",{value:C.playlistId??"",onChange:z=>P(W,{playlistId:z.target.value||null,selectedTrackIds:new Set}),style:{flex:1,fontSize:"0.82rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",background:S?"var(--nice-overlay-light-20, #ffffff30)":"var(--nice-input-bg, #fff)",color:S?"var(--nice-text-on-accent, #fff)":"var(--nice-text-primary, #1f2937)"},children:[r.jsx("option",{value:"",children:h("playlistManager.selectPlaylist","Select a playlist")}),e.map(z=>r.jsxs("option",{value:z.id,children:[z.name," (",z.trackCount,")"]},z.id))]})}),r.jsxs("div",{style:{display:"flex",gap:4,padding:"4px 8px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",flexWrap:"wrap"},children:[r.jsxs("button",{style:ra(!1),onClick:()=>L(W),disabled:!C.playlistId||!H||C.selectedTrackIds.size===0,title:h("playlistManager.copyToOther","Copy to the other playlist"),children:[W==="left"?r.jsxs(r.Fragment,{children:[r.jsx(F.NtdCopy,{size:12}),r.jsx(F.NtdChevronRight,{size:12})]}):r.jsxs(r.Fragment,{children:[r.jsx(F.NtdChevronLeft,{size:12}),r.jsx(F.NtdCopy,{size:12})]})," ",h("playlistManager.copy","Copy")]}),r.jsxs("button",{style:ra(!1),onClick:()=>N(W),disabled:!C.playlistId||!H||C.selectedTrackIds.size===0,title:h("playlistManager.moveToOther","Move to the other playlist"),children:[W==="left"?r.jsxs(r.Fragment,{children:[r.jsx(F.NtdMove,{size:12}),r.jsx(F.NtdChevronRight,{size:12})]}):r.jsxs(r.Fragment,{children:[r.jsx(F.NtdChevronLeft,{size:12}),r.jsx(F.NtdMove,{size:12})]})," ",h("playlistManager.move","Move")]}),r.jsx("div",{style:{flex:1}}),f&&r.jsxs("button",{style:ra(!0),onClick:()=>Y(W),disabled:!C.playlistId,children:[r.jsx(F.NtdClipboard,{size:12})," ",h("playlistManager.paste","Paste")," (",f.trackIds.length,")"]})]}),$?r.jsx(Cl,{tracks:$.tracks,tags:t,selectedTrackIds:C.selectedTrackIds,onSelectionChange:z=>P(W,{selectedTrackIds:z}),onPlay:o,onRemove:z=>s($.id,z),onReorder:z=>i($.id,z),onTagTracks:l,sortField:C.sortField,sortDir:C.sortDir,onSortChange:(z,Z)=>P(W,{sortField:z,sortDir:Z}),filterText:C.filterText,onFilterChange:z=>P(W,{filterText:z}),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:R?"none":"auto"},onKeyDown:O,onMouseMove:V,onMouseUp:K,tabIndex:0,children:[r.jsx("div",{style:{width:`${v}%`,minWidth:200},children:G("left")}),r.jsx("div",{style:{width:6,cursor:"col-resize",background:R?"var(--nice-color-accent, #3b82f6)":"var(--nice-border-color, #e5e7eb)",transition:R?"none":"background 0.15s",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseDown:U,children:r.jsx("div",{style:{width:2,height:40,borderRadius:1,background:R?"var(--nice-color-accent, #3b82f6)":"var(--nice-bg-tertiary, #9ca3af)"}})}),r.jsx("div",{style:{flex:1,minWidth:200},children:G("right")})]})},ra=e=>({background:e?"var(--nice-color-accent, #3b82f6)":"transparent",color:e?"var(--nice-text-on-accent, #fff)":"var(--nice-text-secondary, #6b7280)",border:e?"none":"1px solid var(--nice-border-color, #d1d5db)",borderRadius:6,padding:"3px 8px",fontSize:"0.72rem",cursor:"pointer",whiteSpace:"nowrap"}),jl="av:local-playlists";function Vf(){try{const e=localStorage.getItem(jl);return e?JSON.parse(e):[]}catch{return[]}}function Uf(e){const t=JSON.stringify(e);try{localStorage.setItem(jl,t)}catch{}}function es(){const[e,t]=d.useState(()=>Vf()),n=d.useRef(!1);return d.useEffect(()=>{n.current=!0},[]),d.useEffect(()=>{Uf(e)},[e]),d.useMemo(()=>({list:()=>e,get:s=>e.find(i=>i.id===s),create:s=>{const i=new Date().toISOString(),o={id:ke.createId(),name:s,items:[],updatedAt:i};return t(l=>[o,...l]),o},rename:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,name:i,updatedAt:new Date().toISOString()}:l)),remove:s=>t(i=>i.filter(o=>o.id!==s)),replaceItems:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,items:i,updatedAt:new Date().toISOString()}:l)),addItems:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,items:[...l.items,...i],updatedAt:new Date().toISOString()}:l))}),[e])}const qf=st.scoped("PlaylistList"),Hf={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,background:"var(--nice-bg, #fff)"},Kf=(function(){return{...Hf,padding:"8px 10px",cursor:"pointer"}})(),Ml={border:"1px solid var(--nice-border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg, #fff)",cursor:"pointer"},Yf=(function(){return{...Ml,background:"var(--nice-color-primary, #4f46e5)",borderColor:"var(--nice-color-primary, #4f46e5)",color:"var(--nice-text-on-primary, #fff)"}})(),ts=({selectedId:e,onSelect:t,onCreateRemote:n})=>{const{t:a}=xe(),s=es(),[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()?Yf:{...Ml,cursor:"not-allowed",color:"var(--nice-text-muted, #9ca3af)",background:"var(--nice-bg-tertiary, #f3f4f6)"},onClick:async()=>{const c=s.create(i.trim());if(o(""),n)try{await n({platform:"tidal",name:c.name,songs:c.items})}catch(u){qf.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:{...Kf,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 ↑")})]})]})},Zf=st.scoped("PlaylistBrowser"),oi={display:"grid",gap:12},li=e=>({artist:(e.artists??[]).join(", "),title:e.title}),Xf=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:n,tracks:a,view:s,onSelect:i,onPlay:o})=>{var b;const{t:l}=xe(),c=es(),[u,h]=d.useState(null),[p,g]=d.useState(""),[,y]=d.useState([]),m=u==null?void 0:u.id,x=(f,k)=>{if("addItems"in c){c.addItems(f.id,k);const w=c.list().find(R=>R.id===f.id)||f;h(w);return}const v=c;if("update"in c&&typeof v.update=="function"){const w=Array.from([...f.items||[],...k]);v.update({...f,items:w});const R=c.list().find(M=>M.id===f.id)||{...f,items:w};h(R);return}Zf.warn("useLocalPlaylists: missing addItems/update method — update hook implementation.")};return r.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(min(200px, 100%), 320px) 1fr",gap:16},children:[r.jsxs("div",{style:oi,children:[r.jsx("h3",{style:{margin:0},children:l("playlistBrowser.playlists","Playlists")}),r.jsx(ts,{selectedId:m,onSelect:h}),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:oi,children:[r.jsx("h3",{style:{margin:0},children:l("playlistBrowser.library","Library")}),r.jsxs("div",{children:[e==null?void 0:e({placeholder:l("playlistBrowser.searchAndAdd","Search and add to playlist..."),onSelect:f=>{u&&x(u,[li(f)])}}),r.jsx("input",{placeholder:l("playlistBrowser.fullSearch","Full search (Enter does not add, full list below)"),value:p,onChange:f=>g(f.target.value),style:{width:"100%",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px",marginTop:10}})]}),t==null?void 0:t({query:p,onSelect:f=>{u&&x(u,[li(f)])}}),n==null?void 0:n({onPlayNow:f=>y(f),onAddToQueue:f=>y(k=>[...k,...f]),onAddDescriptors:f=>u&&x(u,f)})]})]})};var Kt=(e=>(e[e.None=0]="None",e[e.Spotify=1]="Spotify",e[e.Tidal=2]="Tidal",e[e.YouTube=4]="YouTube",e[e.All=7]="All",e))(Kt||{});const Rl=(e,t=null)=>e.filter(n=>n.parentId===t).sort((n,a)=>n.sortOrder-a.sortOrder).map(n=>({...n,children:Rl(e,n.id)})),Qf={[Kt.Spotify]:{label:"Spotify",color:"var(--source-spotify, #1DB954)",bg:"var(--source-spotify-bg, #1DB95418)"},[Kt.Tidal]:{label:"Tidal",color:"var(--source-tidal, #000000)",bg:"var(--source-tidal-bg, #00000010)"},[Kt.YouTube]:{label:"YouTube",color:"var(--source-youtube, #FF0000)",bg:"var(--source-youtube-bg, #FF000010)"}},Jf=({folders:e,playlists:t,tags:n,services:a,activeFolderId:s,activePlaylistId:i,onSelectFolder:o,onSelectPlaylist:l,onCreateFolder:c,onRenameFolder:u,onDeleteFolder:h,onCreatePlaylist:p,onConnectService:g,onDisconnectService:y,onDragPlaylistToFolder:m,collapsed:x=!1,onToggleCollapse:b})=>{const{t:f}=xe(),[k,v]=d.useState(new Set),[w,R]=d.useState(!1),[M,j]=d.useState(""),[T,P]=d.useState(null),[A,I]=d.useState(!1),[L,N]=d.useState(""),[_,ee]=d.useState("static"),[Y,O]=d.useState(null),[U,V]=d.useState(""),[K,G]=d.useState(null),[W,C]=d.useState(!1),$=d.useMemo(()=>Rl(e),[e]),S=d.useCallback(ne=>{v(pe=>{const fe=new Set(pe);return fe.has(ne)?fe.delete(ne):fe.add(ne),fe})},[]),B=d.useCallback(()=>{M.trim()&&(c(M.trim(),T),j(""),R(!1))},[M,T,c]),H=d.useCallback(()=>{L.trim()&&(p(L.trim(),_,s),N(""),I(!1))},[L,_,s,p]),z=d.useCallback(ne=>{U.trim()&&(u(ne,U.trim()),O(null),V(""))},[U,u]),Z=d.useCallback((ne,pe)=>{ne.preventDefault(),ne.dataTransfer.dropEffect="move",G(pe)},[]),E=d.useCallback((ne,pe)=>{ne.preventDefault();const fe=ne.dataTransfer.getData("playlistId");fe&&m&&m(fe,pe),G(null)},[m]),q=d.useCallback(()=>G(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"}),D={background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:"2px 6px",borderRadius:4,color:"var(--nice-text-secondary, #6b7280)"},J={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,Ne;const fe=k.has(ne.id),me=s===ne.id,he=K===ne.id,we=X(ne.id);return r.jsxs("div",{children:[r.jsxs("div",{style:{...se(me,he),paddingLeft:12+pe*16},onClick:()=>{o(ne.id),ne.children&&ne.children.length>0&&S(ne.id)},onDragOver:Ee=>Z(Ee,ne.id),onDrop:Ee=>E(Ee,ne.id),onDragLeave:q,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(F.NtdChevronDown,{size:10}):r.jsx(F.NtdChevronRight,{size:10}):null}),Y===ne.id?r.jsx("input",{value:U,onChange:Ee=>V(Ee.target.value),onKeyDown:Ee=>{Ee.key==="Enter"&&z(ne.id),Ee.key==="Escape"&&O(null)},onBlur:()=>z(ne.id),autoFocus:!0,style:{...J,flex:1},onClick:Ee=>Ee.stopPropagation()}):r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{display:"inline-flex"},children:ne.icon??r.jsx(F.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:D,onClick:Ee=>{Ee.stopPropagation(),O(ne.id),V(ne.name)},title:f("common.rename","Rename"),"aria-label":f("common.rename","Rename"),children:r.jsx(F.NtdEdit,{size:12})}),r.jsx("button",{style:{...D,color:"var(--nice-color-error, #ef4444)"},onClick:Ee=>{Ee.stopPropagation(),h(ne.id)},title:f("common.delete","Delete"),"aria-label":f("common.delete","Delete"),children:r.jsx(F.NtdTrash,{size:12})})]})]}),fe&&r.jsxs(r.Fragment,{children:[we.map(Ee=>ce(Ee,pe+1)),(Ne=ne.children)==null?void 0:Ne.map(Ee=>ae(Ee,pe+1))]})]},ne.id)},ce=(ne,pe)=>{const fe=i===ne.id;return r.jsxs("div",{style:{...se(fe),paddingLeft:12+pe*16+22},onClick:()=>l(ne.id),draggable:!0,onDragStart:me=>{me.dataTransfer.setData("playlistId",ne.id),me.dataTransfer.effectAllowed="move"},children:[r.jsx("span",{style:{display:"inline-flex"},children:ne.type==="dynamic"?r.jsx(F.NtdLightning,{size:12}):r.jsx(F.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:{...D,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(F.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(F.NtdMusic,{size:14})," ",f("playlistManager.title","Playlists")]}),r.jsx("button",{style:D,onClick:b,title:f("playlistManager.collapseSidebar","Collapse sidebar"),"aria-label":f("playlistManager.collapseSidebar","Collapse sidebar"),children:r.jsx(F.NtdChevronLeft,{size:16})})]}),r.jsxs("div",{style:{...oe,display:"flex",gap:4,flexWrap:"wrap"},children:[r.jsxs("button",{style:{...D,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:6,padding:"4px 10px"},onClick:()=>I(!0),children:["+ ",f("playlistManager.newPlaylist","New playlist")]}),r.jsxs("button",{style:{...D,border:"1px solid var(--nice-border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{R(!0),P(s)},children:[r.jsx(F.NtdFolder,{size:12})," ",f("playlistManager.newFolder","New folder")]})]}),A&&r.jsxs("div",{style:{...oe,display:"flex",flexDirection:"column",gap:6},children:[r.jsx("input",{value:L,onChange:ne=>N(ne.target.value),placeholder:f("playlistManager.playlistName","Playlist name"),style:J,autoFocus:!0,onKeyDown:ne=>{ne.key==="Enter"&&H(),ne.key==="Escape"&&I(!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:_==="static",onChange:()=>ee("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:_==="dynamic",onChange:()=>ee("dynamic")}),r.jsx(F.NtdLightning,{size:12})," ",f("playlistManager.dynamic","Dynamic")]}),r.jsx("div",{style:{flex:1}}),r.jsx("button",{style:{...D,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:H,"aria-label":f("playlistManager.confirmCreatePlaylist","Confirm create playlist"),children:r.jsx(F.NtdCheck,{size:12})}),r.jsx("button",{style:D,onClick:()=>I(!1),"aria-label":f("playlistManager.cancelCreatePlaylist","Cancel create playlist"),children:r.jsx(F.NtdClose,{size:12})})]})]}),w&&r.jsxs("div",{style:{...oe,display:"flex",gap:6},children:[r.jsx("input",{value:M,onChange:ne=>j(ne.target.value),placeholder:f("playlistManager.folderName","Folder name"),style:{...J,flex:1},autoFocus:!0,onKeyDown:ne=>{ne.key==="Enter"&&B(),ne.key==="Escape"&&R(!1)}}),r.jsx("button",{style:{...D,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:B,"aria-label":f("playlistManager.confirmCreateFolder","Confirm create folder"),children:r.jsx(F.NtdCheck,{size:12})}),r.jsx("button",{style:D,onClick:()=>R(!1),"aria-label":f("playlistManager.cancelCreateFolder","Cancel create folder"),children:r.jsx(F.NtdClose,{size:12})})]}),r.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[r.jsxs("div",{style:se(s===null&&i===null,K==="__root__"),onClick:()=>o(null),onDragOver:ne=>Z(ne,null),onDrop:ne=>E(ne,null),onDragLeave:q,children:[r.jsx(F.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)),$.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(Sa,{icon:ne.icon,size:10}),ne.icon?" ":"",ne.name]},ne.id))})]}),r.jsxs("div",{style:oe,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",cursor:"pointer",fontSize:"0.7rem",fontWeight:600,opacity:.6},onClick:()=>C(!W),children:[r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(F.NtdLink,{size:12})," ",f("playlistManager.services","Services")]}),W?r.jsx(F.NtdChevronUp,{size:12}):r.jsx(F.NtdChevronDown,{size:12})]}),W&&r.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[Kt.Spotify,Kt.Tidal,Kt.YouTube].map(ne=>{const pe=Qf[ne],fe=a.find(me=>me.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(F.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:{...D,color:"var(--nice-danger, #ef4444)"},onClick:()=>y(ne),"aria-label":f("playlistManager.disconnect","Disconnect"),children:r.jsx(F.NtdClose,{size:12})})]}):r.jsx("button",{style:{...D,background:pe.color,color:"var(--nice-color-white, #fff)",borderRadius:4,padding:"2px 8px"},onClick:()=>g(ne),children:f("playlistManager.connect","Connect")})]},ne)})})]})]})},em=({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(F.NtdMusic,{size:32})}),r.jsx("span",{style:{fontSize:"0.82rem"},children:i("playlistManager.emptyPlaylist","This playlist is empty")})]}):r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(160px, 1fr))",gap:10},children:e.tracks.map(l=>{const c=a.has(l.id);return r.jsxs("div",{onClick:()=>o(l.id),onDoubleClick:()=>n(l),style:{border:c?"2px solid var(--nice-color-accent, #3b82f6)":"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:10,padding:10,cursor:"pointer",background:c?"var(--nice-accent-tint-10, #eff6ff)":"var(--nice-bg-elevated, #fff)",transition:"all 0.12s"},children:[r.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:6,background:"linear-gradient(135deg, var(--playlist-track-bg1, #6366f140), var(--playlist-track-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"1.5rem",marginBottom:6},children:r.jsx(F.NtdMusic,{size:24})}),r.jsx("div",{style:{fontWeight:500,fontSize:"0.78rem",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.title}),r.jsx("div",{style:{fontSize:"0.68rem",opacity:.5,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.artist})]},l.id)})})},tm=d.memo(em),ci=e=>e.replace(/[^a-z0-9_-]/gi,"-"),di={background:"none",border:"none",cursor:"pointer",fontSize:"0.78rem",padding:"2px 4px",opacity:.4},nm=({playlists:e,folders:t,tags:n,activeFolderId:a,onSelectPlaylist:s,onDeletePlaylist:i,onDuplicatePlaylist:o})=>{const{t:l}=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(F.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",{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===Ja.Dynamic?r.jsx(F.NtdLightning,{size:40}):r.jsx(F.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(F.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-${ci(g)}-bg, ${y.color}18)`,color:`var(--tag-${ci(g)}, ${y.color})`,fontSize:"0.65rem",fontWeight:500},children:y.name},g):null})}),r.jsxs("div",{style:{display:"flex",gap:4,marginTop:8},children:[r.jsx("button",{onClick:g=>{g.stopPropagation(),o(u.id)},style:di,title:l("playlistManager.duplicate","Duplicate"),"aria-label":l("playlistManager.duplicate","Duplicate"),children:r.jsx(F.NtdCopy,{size:14})}),r.jsx("button",{onClick:g=>{g.stopPropagation(),i(u.id)},style:di,title:l("playlistManager.delete","Delete"),"aria-label":l("playlistManager.delete","Delete"),children:r.jsx(F.NtdTrash,{size:14})})]})]},u.id)})})},rm=d.memo(nm),ui=[{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)"}],am=({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(j=>{u(T=>{const P=new Set(T);return P.has(j)?P.delete(j):P.add(j),P})},[]),b=d.useCallback(j=>{l(j),m.current&&clearTimeout(m.current),j.trim().length>=2&&(m.current=setTimeout(()=>{e(j.trim(),Array.from(c))},350))},[c,e]),f=d.useCallback(j=>{j.preventDefault(),o.trim().length>=2&&e(o.trim(),Array.from(c))},[o,c,e]),k=d.useCallback(j=>{p(T=>{const P=new Set(T);return P.has(j)?P.delete(j):P.add(j),P})},[]),v=d.useCallback(()=>{h.size===t.length?p(new Set):p(new Set(t.map(j=>j.id)))},[h,t]),w=d.useCallback(()=>{const j=t.filter(T=>h.has(T.id));j.length>0&&(a(j),p(new Set))},[t,h,a]),R=j=>{if(!j)return"--:--";const T=Math.floor(j/60),P=j%60;return`${T}:${P.toString().padStart(2,"0")}`},M=j=>{const T=ui.find(P=>P.value===j);return r.jsx(F.NtdCircle,{size:10,style:{color:T?T.css:"var(--nice-text-secondary, #6b7280)"}})};return r.jsxs("div",{style:{border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:10,background:"var(--nice-bg-elevated, #fff)",overflow:"hidden"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 12px",gap:8,cursor:"pointer",background:"var(--nice-color-surface, #f9fafb)"},onClick:()=>y(!g),children:[r.jsx(F.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(F.NtdChevronUp,{size:12}):r.jsx(F.NtdChevronDown,{size:12})})]}),g&&r.jsxs("div",{style:{padding:"0 12px 12px"},children:[r.jsx("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap"},children:ui.map(j=>{const T=c.has(j.value);return r.jsxs("button",{onClick:()=>x(j.value),style:{padding:"4px 10px",borderRadius:20,border:T?`2px solid ${j.css}`:"1px solid var(--nice-border-color, #d1d5db)",background:T?j.cssBg:"transparent",color:T?j.css:"var(--nice-text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:T?600:400,transition:"all 0.15s"},children:[r.jsx(F.NtdCircle,{size:8,style:{color:j.css}})," ",j.label]},j.value)})}),r.jsxs("form",{onSubmit:f,style:{display:"flex",gap:6,marginBottom:8},children:[r.jsx("input",{type:"text",value:o,onChange:j=>b(j.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(F.NtdClock,{size:14}):r.jsx(F.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:w,style:{padding:"3px 10px",borderRadius:6,border:"none",background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.72rem",cursor:"pointer"},children:[r.jsx(F.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(j=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:"1px solid var(--nice-border-color, #f3f4f6)",background:h.has(j.id)?"var(--nice-accent-tint-10, #eff6ff)":"transparent",cursor:"pointer",fontSize:"0.78rem"},onClick:()=>k(j.id),children:[r.jsx("input",{type:"checkbox",checked:h.has(j.id),readOnly:!0}),M(j.source),j.imageUrl&&r.jsx("img",{src:j.imageUrl,alt:j.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:j.title}),r.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[j.artist,j.album?` — ${j.album}`:""]})]}),r.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:R(j.duration)}),s&&r.jsx("button",{onClick:T=>{T.stopPropagation(),s(j)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem"},title:i("playlistManager.preview","Preview"),"aria-label":i("playlistManager.preview","Preview"),children:r.jsx(F.NtdPlay,{size:14})})]},j.id))})]}),n&&r.jsxs("div",{style:{textAlign:"center",padding:20,opacity:.5,fontSize:"0.82rem"},children:[r.jsx(F.NtdClock,{size:14})," ",i("playlistManager.searching","Searching"),"..."]}),!n&&o.trim().length>=2&&t.length===0&&r.jsx("div",{style:{textAlign:"center",padding:20,opacity:.4,fontSize:"0.82rem"},children:i("playlistManager.noResults","No results")})]})]})},sm=[{value:1,label:"Spotify",icon:r.jsx(F.NtdMusic,{size:16}),color:"var(--source-spotify, #1db954)"},{value:2,label:"Tidal",icon:r.jsx(F.NtdMusic,{size:16}),color:"var(--source-tidal, #000000)"},{value:3,label:"Apple Music",icon:r.jsx(F.NtdMusic,{size:16}),color:"var(--source-apple, #fa243c)"},{value:4,label:"YouTube",icon:r.jsx(F.NtdMusic,{size:16}),color:"var(--source-youtube, #ff0000)"},{value:99,label:"Manual Paste",icon:r.jsx(F.NtdMusic,{size:16}),color:"var(--source-manual, #6366f1)"}],im={display:"flex",flexDirection:"column",gap:16,padding:24,borderRadius:12,background:"var(--nice-bg-primary, #ffffff)",border:"1px solid var(--nice-border, #e2e8f0)",maxWidth:640,minHeight:400},om={display:"flex",justifyContent:"space-between",alignItems:"center"},lm={display:"flex",gap:4,marginBottom:8},Ln={padding:"8px 20px",borderRadius:6,border:"none",background:"var(--nice-color-accent, #6366f1)",color:"var(--nice-text-on-primary, #fff)",cursor:"pointer",fontWeight:600},sr=(function(){return{...Ln,background:"transparent",color:"var(--nice-text-primary, #334155)",border:"1px solid var(--nice-border, #e2e8f0)"}})(),hi={padding:12,borderRadius:8,border:"1px solid var(--nice-border, #e2e8f0)",cursor:"pointer",transition:"border-color 0.15s"},Nl=["connect","browse","tracks","options","importing","done"];function cm(e){return Nl.indexOf(e)}function dm(e){if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const um=({connections:e=[],onConnect:t=()=>{},onDisconnect:n=()=>{},onFetchPlaylists:a=async()=>[],onFetchTracks:s=async()=>[],onImport:i=async()=>({playlistName:"",imported:0,skipped:0,failed:0,failedTracks:[]}),onClose:o=()=>{},targetFolders:l,sources:c})=>{const{t:u}=xe(),[h,p]=d.useState("connect"),[g,y]=d.useState(null),[m,x]=d.useState([]),[b,f]=d.useState(null),[k,v]=d.useState([]),[w,R]=d.useState(new Set),[M,j]=d.useState(!1),[T,P]=d.useState(null),[A,I]=d.useState(null),[L,N]=d.useState(null),[_,ee]=d.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[Y,O]=d.useState(""),U=d.useMemo(()=>new Set(e.filter(D=>D.connected).map(D=>D.platform)),[e]),V=d.useCallback(D=>e.find(J=>J.platform===D),[e]),K=d.useCallback(D=>{if(y(D),D===99){p("tracks"),O(""),v([]),j(!1);return}U.has(D)?(p("browse"),j(!0),N(null),a(D).then(J=>{x(J),j(!1)}).catch(J=>{N(String(J)),j(!1)})):t(D)},[U,t,a]),G=d.useCallback(D=>{f(D),p("tracks"),j(!0),N(null),s(D).then(J=>{v(J),R(new Set(J.map(ae=>ae.externalId))),j(!1)}).catch(J=>{N(String(J)),j(!1)})},[s]),W=d.useCallback(D=>{R(J=>{const ae=new Set(J);return ae.has(D)?ae.delete(D):ae.add(D),ae})},[]),C=d.useCallback(()=>{R(D=>D.size===k.length?new Set:new Set(k.map(J=>J.externalId)))},[k]),$=d.useCallback(async()=>{if(!b)return;const D=k.filter(J=>w.has(J.externalId));if(D.length!==0){p("importing"),P({total:D.length,imported:0,skipped:0,failed:0}),N(null);try{const J=await i(b,D,_),ae=J&&typeof J=="object"&&"imported"in J?J:{playlistName:b.name,imported:D.length,skipped:0,failed:0,failedTracks:[]};I(ae),p("done")}catch(J){N(String(J)),p("options")}}},[b,k,w,_,i]),S=h!=="connect"&&h!=="importing"&&h!=="done",B=d.useCallback(()=>{switch(h){case"browse":p("connect");break;case"tracks":p("browse");break;case"options":p("tracks");break}},[h]),H=()=>r.jsx("div",{style:lm,children:Nl.map((D,J)=>r.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:J<=cm(h)?"var(--nice-color-accent, #6366f1)":"var(--nice-border, #e2e8f0)",transition:"background 0.2s"}},D))}),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")}),sm.map(D=>{const J=V(D.value),ae=U.has(D.value);return r.jsxs("div",{style:{...hi,display:"flex",alignItems:"center",gap:12,borderColor:ae?D.color:void 0},onClick:()=>K(D.value),role:"button",tabIndex:0,onKeyDown:ce=>ce.key==="Enter"&&K(D.value),children:[r.jsx("span",{style:{color:D.color,display:"inline-flex"},"aria-hidden":"true",children:D.icon}),r.jsxs("div",{style:{flex:1},children:[r.jsx("strong",{children:D.label}),(J==null?void 0:J.username)&&r.jsx("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:J.username})]}),ae?r.jsxs("span",{style:{color:D.color,fontSize:12,fontWeight:600},children:[u("importWizard.connected","Connected")," ",r.jsx(F.NtdCheck,{size:12})]}):r.jsx("span",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.clickToConnect","Click to connect")})]},D.value)})]}),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.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(D=>r.jsxs("div",{style:{...hi,display:"flex",alignItems:"center",gap:12},onClick:()=>G(D),role:"button",tabIndex:0,onKeyDown:J=>J.key==="Enter"&&G(D),children:[D.coverUrl&&r.jsx("img",{src:D.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:D.name}),D.description&&r.jsx("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:D.description})]}),r.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)",whiteSpace:"nowrap"},children:[D.trackCount," ",u("importWizard.tracks","tracks")]})]},D.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")})]})]}),E=d.useCallback(D=>{const ae=D.split(`
|
|
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),R(new Set(ae.map(ce=>ce.externalId)))},[]),q=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[g===99&&k.length===0&&r.jsxs("div",{style:{display:"grid",gap:8},children:[r.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:u("importWizard.pasteInstructions",'Paste your track list below (one track per line). Use "Artist - Title" format for best results.')}),r.jsx("textarea",{value:Y,onChange:D=>O(D.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:{...Ln,opacity:te.trim().length===0?.5:1},disabled:te.trim().length===0,onClick:()=>F(te),type:"button",children:d("importWizard.parseTracks","Parse Tracks")})]}),(p!==99||S.length>0)&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[r.jsxs("p",{style:{margin:0,fontWeight:600},children:[v==null?void 0:v.name," — ",w.size,"/",S.length," ",d("importWizard.selected","selected")]}),r.jsx("button",{style:sr,onClick:C,type:"button",children:w.size===S.length?d("importWizard.deselectAll","Deselect All"):d("importWizard.selectAll","Select All")})]}),R?r.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.loadingTracks","Loading tracks…")}):r.jsx("div",{style:{maxHeight:320,overflowY:"auto"},children:r.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[r.jsx("thead",{children:r.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-border, #e2e8f0)",textAlign:"left"},children:[r.jsx("th",{style:{padding:"4px 8px",width:32}}),r.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.title","Title")}),r.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.artist","Artist")}),r.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.album","Album")}),r.jsx("th",{style:{padding:"4px 8px",textAlign:"right"},children:d("importWizard.duration","Duration")})]})}),r.jsx("tbody",{children:S.map(K=>{const H=w.has(K.externalId);return r.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-border, #e2e8f0)",opacity:H?1:.5,cursor:"pointer"},onClick:()=>O(K.externalId),children:[r.jsx("td",{style:{padding:"6px 8px"},children:r.jsx("input",{type:"checkbox",checked:H,readOnly:!0})}),r.jsx("td",{style:{padding:"6px 8px",fontWeight:500},children:K.title}),r.jsx("td",{style:{padding:"6px 8px",color:"var(--nice-text-dim, #64748b)"},children:K.artist}),r.jsx("td",{style:{padding:"6px 8px",color:"var(--nice-text-dim, #64748b)"},children:K.album??"—"}),r.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--nice-text-dim, #64748b)"},children:Jf(K.duration)})]},K.externalId)})})]})}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:r.jsxs("button",{style:{...Ln,opacity:w.size===0?.5:1},disabled:w.size===0,onClick:()=>f("options"),type:"button",children:[d("importWizard.next","Next")," ",r.jsx(B.NtdArrowRight,{size:12})]})})]})]}),Q=()=>r.jsxs("div",{style:{display:"grid",gap:16},children:[r.jsx("p",{style:{margin:0,fontWeight:600},children:d("importWizard.importOptions","Import options")}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:D.mergeTags,onChange:K=>q(H=>({...H,mergeTags:K.target.checked}))}),d("importWizard.mergeTags","Merge tags from source playlist")]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:D.mergeFolders,onChange:K=>q(H=>({...H,mergeFolders:K.target.checked}))}),d("importWizard.mergeFolders","Merge into existing folder structure")]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:D.overwriteExisting,onChange:K=>q(H=>({...H,overwriteExisting:K.target.checked}))}),d("importWizard.overwrite","Overwrite existing tracks (match by ISRC)")]}),o&&o.length>0&&r.jsxs("div",{style:{display:"grid",gap:4},children:[r.jsx("label",{style:{fontSize:13,fontWeight:500},children:d("importWizard.targetFolder","Target folder")}),r.jsxs("select",{style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #e2e8f0)"},value:D.targetFolderId??"",onChange:K=>q(H=>({...H,targetFolderId:K.target.value||void 0})),children:[r.jsx("option",{value:"",children:d("importWizard.root","— Root —")}),o.map(K=>r.jsx("option",{value:K.id,children:K.name},K.id))]})]}),r.jsx("div",{style:{marginTop:8,padding:12,borderRadius:8,background:"var(--nice-info-bg, #eff6ff)",fontSize:13},children:d("importWizard.summary",`Ready to import ${w.size} tracks from "${(v==null?void 0:v.name)??""}"`)}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[r.jsxs("button",{style:sr,onClick:W,type:"button",children:[r.jsx(B.NtdArrowLeft,{size:12})," ",d("importWizard.back","Back")]}),r.jsx("button",{style:Ln,onClick:$,type:"button",children:d("importWizard.startImport","Start Import")})]})]}),le=()=>{const K=j?Math.round(j.imported/j.total*100):0;return r.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[r.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:d("importWizard.importing","Importing…")}),r.jsx("div",{style:{height:8,borderRadius:4,background:"var(--nice-border, #e2e8f0)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${K}%`,background:"var(--nice-color-accent, #6366f1)",borderRadius:4,transition:"width 0.3s"}})}),j&&r.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-dim, #64748b)"},children:[j.imported," / ",j.total," ",d("importWizard.tracks","tracks"),j.currentTrack&&r.jsxs("div",{style:{marginTop:4},children:[r.jsx(B.NtdMusic,{size:12})," ",j.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:d("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})," ",d("importWizard.imported","imported")]}),I.skipped>0&&r.jsxs("div",{style:{color:"var(--nice-color-warning, #f59e0b)"},children:[I.skipped," ",d("importWizard.skipped","skipped (duplicates)")]}),I.failed>0&&r.jsxs("div",{style:{color:"var(--nice-color-error, #ef4444)"},children:[I.failed," ",d("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:d("importWizard.showFailed","Show failed tracks")}),r.jsx("ul",{style:{marginTop:4,paddingLeft:20},children:I.failedTracks.map((K,H)=>r.jsx("li",{children:K},H))})]})]}),r.jsx("button",{style:Ln,onClick:l,type:"button",children:d("importWizard.close","Done")})]}),ne={connect:d("importWizard.stepConnect","Connect"),browse:d("importWizard.stepBrowse","Browse"),tracks:d("importWizard.stepTracks","Select Tracks"),options:d("importWizard.stepOptions","Options"),importing:d("importWizard.stepImporting","Importing"),done:d("importWizard.stepDone","Done")};return r.jsxs("div",{style:Yf,children:[A(),r.jsxs("div",{style:Zf,children:[r.jsxs("h2",{style:{margin:0,fontSize:18},children:[d("importWizard.title","Import Playlist")," — ",ne[h]]}),k&&r.jsxs("button",{style:sr,onClick:W,type:"button",children:[r.jsx(B.NtdArrowLeft,{size:12})," ",d("importWizard.back","Back")]}),h==="connect"&&r.jsx("button",{style:sr,onClick:l,type:"button","aria-label":d("importWizard.close","Close"),title:d("importWizard.close","Close"),children:r.jsx(B.NtdClose,{size:14})})]}),E&&r.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--nice-error-bg, #fef2f2)",color:"var(--nice-color-error, #ef4444)",fontSize:13},children:E}),h==="connect"&&L(),h==="browse"&&G(),h==="tracks"&&V(),h==="options"&&Q(),h==="importing"&&le(),h==="done"&&oe()]})},t0=[{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}],n0="concert-harp",ns=Object.fromEntries(t0.map(e=>[e.id,e])),r0="nice2dev-note-sound-set";function Nl(){try{const e=localStorage.getItem(r0);if(e&&ns[e])return e}catch{}return n0}const Ir=["quarter","eighth","sixteenth","beamed"];function Tl(e,t,n){const a=n*.2,s=n*.15,i=Math.max(1,n*.07),l=n*.72,o=n*.34,c=new Path2D,d=h=>{c.moveTo(h+a,o),c.ellipse(h,o,a,s,-.4,0,Math.PI*2),c.rect(h+a-i,o-l,i,l)};if(t==="beamed"){const h=-n*.24,f=n*.24;d(h),d(f),c.rect(h+a-i,o-l,f-h+i,n*.12)}else{const h=-a*.5;d(h);const f=t==="eighth"?1:t==="sixteenth"?2:0,p=h+a;for(let y=0;y<f;y++){const g=o-l+y*n*.2;c.moveTo(p,g),c.quadraticCurveTo(p+n*.32,g+n*.14,p+n*.18,g+n*.42),c.quadraticCurveTo(p+n*.2,g+n*.22,p,g+n*.14),c.closePath()}}e.stroke(c),e.fill(c)}function pi(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function $l(e){if(!e)return null;const t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle=e;const n=t.fillStyle;if(n.startsWith("#")){const s=parseInt(n.slice(1),16);return{r:s>>16&255,g:s>>8&255,b:s&255}}const a=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return a?{r:+a[1],g:+a[2],b:+a[3]}:null}function aa(e,t){const n=$l(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function a0(e){const t=$l(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function Pl(){const e=pi("--text-primary")||we.resolveCssColor("var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))"),t=pi("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",s=a0(e)<.45;return{base:aa(e,.92),staffLine:aa(e,.22),outline:we.resolveCssColor(s?"var(--nice-overlay-light-75, rgba(255, 255, 255, 0.75))":"var(--nice-overlay-55, rgba(0, 0, 0, 0.55))"),accents:[aa(t,.95)],isDark:n,notesDark:s}}const Gr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),Al=46,kt=5,mr=4,s0=(Al-(kt-1)*mr)/2,i0=6,o0=18,l0=110,c0=50,Wr=Gr?c0:l0,d0=Gr?4:2,u0=Gr?2:4,fi=Gr?1:0,h0=180,mi=2.8,gi=40,p0=14,yi=1.2,f0=16,sa=[64,67,71,74,77],ln=64,zn=77;function m0(e){const t=Math.max(0,Math.min(kt-1,e)),n=Math.floor(t),a=Math.min(n+1,kt-1),s=t-n;return Math.round(sa[n]+(sa[a]-sa[n])*s)}function g0(e){return(Math.max(ln-1*(zn-ln)/(kt-1),Math.min(zn+1*(zn-ln)/(kt-1),e))-ln)/(zn-ln)*(kt-1)}const vi=2.5,bi=.72,y0=.55,Dn=new Map;let gr=null;async function v0(e){const t=e??Nl(),n=ns[t];if(!n||!n.dir){Dn.clear(),gr=t;return}if(gr===t&&Dn.size>0)return;Dn.clear(),gr=t;const a=qn(),s=[];for(let i=ln;i<=zn;i++)s.push(fetch(`/assets/soundfonts/notes/${n.dir}/note-${i}.mp3`).then(l=>l.arrayBuffer()).then(l=>a.decodeAudioData(l)).then(l=>{Dn.set(i,l)}).catch(()=>{}));await Promise.all(s)}function xi(e){const t=Dn.get(e);if(!t)return;const n=qn(),a=n.createBufferSource();a.buffer=t;const s=n.createGain();s.gain.value=.7,a.connect(s).connect(n.destination),a.start()}function b0(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 x0(e){const t=b0(42),n=[];for(let a=0;a<e;a++){const i=t()<.15?0:-1;n.push({x:t(),lineIdx:t()*(kt+1)-.5,shape:Ir[Math.floor(t()*Ir.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:i})}return n.sort((a,s)=>a.x-s.x),n}const ht=x0(Wr),Cn=new Float32Array(Wr),ir=new Float32Array(Wr),_n=new Float32Array(Wr);let ka=!1;const S0=(kt-1)/2;function w0(){if(!ka){ka=!0;for(let e=0;e<ht.length;e++)_n[e]=ht[e].lineIdx}}let Ca=[],Si="";function k0(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function C0(e){const t=k0(e);t===Si&&Ca.length===ht.length||(Si=t,Ca=ht.map(n=>{const a=Math.ceil(n.size*1.6),s=a*2,i=document.createElement("canvas");i.width=s,i.height=s;const l=i.getContext("2d");return l.translate(a,a),l.rotate(n.rot*Math.PI/180),l.lineWidth=1.8,l.strokeStyle=e.outline,l.fillStyle=n.colorIdx<0?e.base:e.accents[n.colorIdx%e.accents.length],Tl(l,n.shape,n.size*1.3),{canvas:i,ox:a,oy:a}}))}function j0({pitchMidiRef:e}={}){const t=u.useRef(null),n=u.useRef(0),a=u.useRef(0),s=u.useRef(0),i=u.useRef(null),l=u.useRef(0),o=u.useRef(0),c=u.useRef(null),d=u.useRef(null),h=u.useRef(!1),f=u.useCallback((x,v,m)=>{const S=s0+x*mr,b=v/m*Math.PI*2;return S+Math.sin(b)*i0},[]),p=u.useCallback(x=>{const v=t.current;if(!v)return;if(o.current++,fi>0&&o.current%(fi+1)!==0){s.current=x,n.current=requestAnimationFrame(p);return}const m=v.getContext("2d");if(!m)return;const S=Math.min(window.devicePixelRatio||1,u0),b=v.getBoundingClientRect(),w=b.width,N=b.height;(v.width!==Math.round(w*S)||v.height!==Math.round(N*S))&&(v.width=Math.round(w*S),v.height=Math.round(N*S),m.setTransform(S,0,0,S,0,0));const R=s.current?(x-s.current)/1e3:0;s.current=x,a.current=(a.current+o0*R)%w,m.clearRect(0,0,w,N),l.current++,(!i.current||l.current%60===0)&&(i.current=Pl());const P=i.current;C0(P),m.strokeStyle=P.staffLine,m.lineWidth=.7;for(let T=0;T<kt;T++){m.beginPath();for(let E=0;E<=w;E+=d0){const _=f(T,E,w);E===0?m.moveTo(E,_):m.lineTo(E,_)}m.stroke()}const j=a.current,M=(e==null?void 0:e.current)??null;if(M!==null){w0();const T=g0(M),E=vi*R;for(let _=0;_<ht.length;_++){const q=(ht[_].lineIdx-S0)*y0,z=T*bi+(T+q)*(1-bi)-_n[_];_n[_]+=z>0?Math.min(E,z):Math.max(-E,z)}}else if(ka){const T=vi*.4*R;for(let E=0;E<ht.length;E++){const D=ht[E].lineIdx-_n[E];_n[E]+=D>0?Math.min(T,D):Math.max(-T,D)}}const I=c.current;I&&(I.timer-=R,I.timer<=0&&(c.current=null));for(let T=0;T<ht.length;T++){const E=ht[T];if(ir[T]>0){ir[T]-=R;const q=Math.max(0,ir[T]/mi);Cn[T]+=h0*q*R,Cn[T]>w&&(Cn[T]-=w)}const _=Ca[T];if(!_)continue;const D=E.lineIdx;for(let q=0;q<2;q++){let z=((E.x*w-j-Cn[T]+q*w)%w+w)%w;const U=f(Math.max(0,Math.min(kt-1,Math.round(D))),z,w),Z=(D-Math.round(D))*mr;let ae=U+Z;if(I&&I.timer>0){const Y=z-I.x,O=ae-I.y,C=Math.sqrt(Y*Y+O*O);if(C<gi&&C>.1){const $=I.timer/yi,k=p0*(1-C/gi)*$;z+=Y/C*k,ae+=O/C*k}}m.drawImage(_.canvas,z-_.ox,ae-_.oy)}}n.current=requestAnimationFrame(p)},[f]),y=u.useCallback(x=>{const v=t.current;if(!v)return;const m=v.getBoundingClientRect(),S=x.clientX-m.left,b=x.clientY-m.top,w=m.width,N=a.current;let R=1/0,P=-1;for(let j=0;j<ht.length;j++){const M=ht[j],T=((M.x*w-N-Cn[j])%w+w)%w,E=f(Math.max(0,Math.min(kt-1,Math.round(M.lineIdx))),T,w),_=(M.lineIdx-Math.round(M.lineIdx))*mr,D=E+_,q=T-S,te=D-b,z=q*q+te*te;z<R&&(R=z,P=j)}if(P>=0&&Math.sqrt(R)<f0){ir[P]=mi;const j=ht[P],M=m0(j.lineIdx);try{Zt();const I=Nl(),T=ns[I];T!=null&&T.dir&&(gr!==I||!h.current?(h.current=!0,v0(I).then(()=>xi(M))):xi(M))}catch{}}c.current={x:S,y:b,timer:yi}},[f]),g=u.useCallback(x=>{const v=t.current;if(!v)return;const m=v.getBoundingClientRect(),S=x.clientX-m.left,b=x.clientY-m.top;d.current={x:S,y:b},c.current&&c.current.timer>0&&(c.current.x=S,c.current.y=b)},[]);return u.useEffect(()=>(n.current=requestAnimationFrame(p),()=>cancelAnimationFrame(n.current)),[p]),r.jsx("canvas",{ref:t,"aria-hidden":"true",role:"img","aria-label":"Note river animation canvas",onClick:y,onMouseMove:g,style:{display:"block",width:"100%",height:Al,marginBottom:5,cursor:"pointer",background:"transparent"}})}const M0=14,R0=.9,N0=320,T0=160,$0=6,wi=8,P0=14;function A0(){const e=u.useRef(null),t=u.useRef([]),n=u.useRef(0),a=u.useRef(0),s=u.useRef([]),i=u.useRef(null),l=u.useRef(0),o=u.useCallback((d,h)=>{for(let f=0;f<M0;f++){const p=Math.random()*Math.PI*2,y=T0*(.4+Math.random()*.6),g=R0*(.6+Math.random()*.4),x=Math.random()<.15?0:-1;t.current.push({x:d,y:h,vx:Math.cos(p)*y,vy:Math.sin(p)*y-60,rot:Math.random()*Math.PI*2,vr:(Math.random()-.5)*$0*2,size:wi+Math.random()*(P0-wi),shape:Ir[Math.floor(Math.random()*Ir.length)],life:g,maxLife:g,colorIdx:x})}},[]),c=u.useCallback(d=>{const h=e.current;if(!h){n.current=requestAnimationFrame(c);return}const f=h.getContext("2d");if(!f){n.current=requestAnimationFrame(c);return}const p=window.devicePixelRatio||1,y=window.innerWidth,g=window.innerHeight;(h.width!==Math.round(y*p)||h.height!==Math.round(g*p))&&(h.width=Math.round(y*p),h.height=Math.round(g*p),h.style.width=`${y}px`,h.style.height=`${g}px`,f.setTransform(p,0,0,p,0,0));const x=a.current?Math.min((d-a.current)/1e3,.05):0;a.current=d,f.clearRect(0,0,y,g),l.current++,(!i.current||l.current%60===0)&&(i.current=Pl());const v=i.current;if(navigator.getGamepads){const S=navigator.getGamepads();for(let b=0;b<S.length;b++){const w=S[b];if(w)for(let N=0;N<w.buttons.length;N++){const R=b*100+N,P=w.buttons[N].pressed;P&&!s.current[R]&&o(y/2,g/2),s.current[R]=P}}}const m=[];for(const S of t.current){if(S.life-=x,S.life<=0)continue;S.vy+=N0*x,S.x+=S.vx*x,S.y+=S.vy*x,S.rot+=S.vr*x;const b=Math.max(0,S.life/S.maxLife),w=.5+.5*b;f.save(),f.globalAlpha=b,f.translate(S.x,S.y),f.rotate(S.rot),f.lineWidth=1.4,f.strokeStyle=v.notesDark?`rgba(255,255,255,${b*.8})`:`rgba(0,0,0,${b*.55})`;const N=S.colorIdx<0?v.base:v.accents[S.colorIdx%v.accents.length];f.fillStyle=N.replace(/[\d.]+\)$/,`${b})`),Tl(f,S.shape,S.size*w*1.3),f.restore(),m.push(S)}t.current=m,n.current=requestAnimationFrame(c)},[o]);return u.useEffect(()=>{const d=f=>{o(f.clientX,f.clientY)},h=f=>{if(f.key!=="Enter")return;const p=document.activeElement;if(p){const y=p.getBoundingClientRect();o(y.left+y.width/2,y.top+y.height/2)}else o(window.innerWidth/2,window.innerHeight/2)};return window.addEventListener("click",d,!0),window.addEventListener("keydown",h,!0),n.current=requestAnimationFrame(c),()=>{window.removeEventListener("click",d,!0),window.removeEventListener("keydown",h,!0),cancelAnimationFrame(n.current)}},[c,o]),r.jsx("canvas",{ref:e,"aria-hidden":"true",role:"img","aria-label":"Note particles animation canvas",style:{position:"fixed",inset:0,zIndex:99999,pointerEvents:"none"}})}const yr={type:"gain",enabled:!0,mix:1,gain:0},Fn={type:"compressor",enabled:!0,mix:1,threshold:-24,ratio:4,attack:10,release:100,knee:6,makeupGain:0},On={type:"reverb",enabled:!0,mix:.3,decay:2,preDelay:10,damping:.5,roomSize:.5},Bn={type:"delay",enabled:!0,mix:.3,time:250,feedback:.4,pingPong:!1,highCut:8e3},vr={type:"chorus",enabled:!0,mix:.5,rate:1.5,depth:.5,delay:7,voices:3},br={type:"eq",enabled:!0,mix:1,bands:[{frequency:60,gain:0,q:1,type:"lowshelf"},{frequency:250,gain:0,q:1,type:"peaking"},{frequency:1e3,gain:0,q:1,type:"peaking"},{frequency:4e3,gain:0,q:1,type:"peaking"},{frequency:12e3,gain:0,q:1,type:"highshelf"}]},xr={type:"filter",enabled:!0,mix:1,filterType:"lowpass",frequency:1e3,q:1,gain:0},Sr={type:"distortion",enabled:!0,mix:.5,drive:.5,tone:.5,curve:"soft"},wr={type:"tremolo",enabled:!0,mix:1,rate:5,depth:.5,waveform:"sine"},kr={type:"phaser",enabled:!0,mix:.5,rate:.5,depth:.5,feedback:.5,stages:4,frequency:1e3},E0={gain:{unity:{...yr,gain:0},boost:{...yr,gain:6},cut:{...yr,gain:-6}},compressor:{gentle:{...Fn,threshold:-20,ratio:2,attack:30,release:200},moderate:{...Fn,threshold:-24,ratio:4,attack:10,release:100},aggressive:{...Fn,threshold:-30,ratio:8,attack:1,release:50},limiter:{...Fn,threshold:-3,ratio:20,attack:.1,release:100}},reverb:{small_room:{...On,decay:.5,roomSize:.2,damping:.7},large_hall:{...On,decay:3,roomSize:.8,damping:.3},plate:{...On,decay:1.5,roomSize:.5,damping:.4},cathedral:{...On,decay:5,roomSize:.9,damping:.2,mix:.4}},delay:{slapback:{...Bn,time:80,feedback:.1,mix:.3},quarter_note:{...Bn,time:500,feedback:.4,mix:.3},dotted_eighth:{...Bn,time:375,feedback:.5,mix:.3},long_ambient:{...Bn,time:750,feedback:.6,highCut:3e3,mix:.4}},chorus:{subtle:{...vr,rate:.5,depth:.2,voices:2,mix:.3},vintage:{...vr,rate:1,depth:.4,voices:2,delay:10,mix:.4},ensemble:{...vr,rate:2,depth:.6,voices:4,mix:.5}},eq:{vocal_presence:{...br,bands:[{frequency:80,gain:-3,q:1,type:"highpass"},{frequency:250,gain:-2,q:1,type:"peaking"},{frequency:3e3,gain:3,q:1.5,type:"peaking"},{frequency:8e3,gain:2,q:1,type:"highshelf"}]},bass_boost:{...br,bands:[{frequency:60,gain:6,q:1,type:"lowshelf"},{frequency:200,gain:2,q:1,type:"peaking"}]},brightness:{...br,bands:[{frequency:4e3,gain:3,q:1,type:"peaking"},{frequency:1e4,gain:4,q:1,type:"highshelf"}]}},filter:{low_pass_warm:{...xr,filterType:"lowpass",frequency:2e3,q:.7},high_pass_clean:{...xr,filterType:"highpass",frequency:100,q:.7},telephone:{...xr,filterType:"bandpass",frequency:1500,q:2}},distortion:{overdrive:{...Sr,drive:.3,tone:.6,curve:"soft",mix:.7},crunch:{...Sr,drive:.5,tone:.5,curve:"tube",mix:.8},fuzz:{...Sr,drive:.8,tone:.4,curve:"fuzz",mix:1}},tremolo:{slow:{...wr,rate:3,depth:.4,waveform:"sine"},fast:{...wr,rate:8,depth:.6,waveform:"sine"},choppy:{...wr,rate:6,depth:.9,waveform:"square"}},phaser:{subtle:{...kr,rate:.3,depth:.3,feedback:.3,stages:4},jet:{...kr,rate:.1,depth:.8,feedback:.7,stages:8},rotary:{...kr,rate:1,depth:.5,feedback:.4,stages:6}}};function ki(e){return Math.pow(10,e/20)}function I0(e,t,n,a){const s=e.sampleRate,i=Math.floor(s*t),l=e.createBuffer(2,i,s);for(let o=0;o<2;o++){const c=l.getChannelData(o);for(let d=0;d<i;d++){const h=d/s,f=Math.exp(-h/n),p=1-a*(d/i);c[d]=(Math.random()*2-1)*f*p}}return l}function L0(e,t){const a=new Float32Array(44100),s=Math.PI/180;for(let i=0;i<44100;i++){const l=i*2/44100-1;switch(t){case"soft":a[i]=(3+e*10)*l*20*s/(Math.PI+e*10*Math.abs(l));break;case"hard":a[i]=Math.tanh(l*(1+e*5));break;case"fuzz":a[i]=Math.sign(l)*Math.pow(Math.abs(l),1/(1+e*3));break;case"tube":l>=0?a[i]=1-Math.pow(1-l,1+e*2):a[i]=-(1-Math.pow(1+l,1+e*2));break}}return a}class z0{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(o=>o.id===t);if(!a)return!1;const s={...a.params,...n},i=this.effects.indexOf(a);for(const o of a.nodes)o.disconnect();const l=this.createEffectInstance(t,s);return this.effects[i]=l,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,l;switch(n.type){case"gain":{const o=a.createGain();o.gain.value=ki(n.gain),s.push(o),i=l=o;break}case"compressor":{const o=a.createDynamicsCompressor();o.threshold.value=n.threshold,o.ratio.value=n.ratio,o.attack.value=n.attack/1e3,o.release.value=n.release/1e3,o.knee.value=n.knee;const c=a.createGain();c.gain.value=ki(n.makeupGain),o.connect(c),s.push(o,c),i=o,l=c;break}case"reverb":{const o=a.createConvolver();o.buffer=I0(a,n.decay,n.decay,n.damping);const c=a.createGain(),d=a.createGain(),h=a.createGain(),f=a.createGain();c.gain.value=n.mix,d.gain.value=1-n.mix,h.connect(o),h.connect(d),o.connect(c),c.connect(f),d.connect(f),s.push(h,o,c,d,f),i=h,l=f;break}case"delay":{const o=a.createDelay(5);o.delayTime.value=n.time/1e3;const c=a.createGain();c.gain.value=n.feedback;const d=a.createBiquadFilter();d.type="lowpass",d.frequency.value=n.highCut;const h=a.createGain(),f=a.createGain(),p=a.createGain(),y=a.createGain();h.gain.value=n.mix,f.gain.value=1-n.mix,p.connect(o),p.connect(f),o.connect(d),d.connect(c),c.connect(o),d.connect(h),h.connect(y),f.connect(y),s.push(p,o,d,c,h,f,y),i=p,l=y;break}case"eq":{const o=[];let c=null;for(const d of n.bands){const h=a.createBiquadFilter();h.type=d.type,h.frequency.value=d.frequency,h.Q.value=d.q,h.gain.value=d.gain,c&&c.connect(h),c=h,o.push(h)}s.push(...o),i=o[0]||a.createGain(),l=o[o.length-1]||i;break}case"filter":{const o=a.createBiquadFilter();o.type=n.filterType,o.frequency.value=n.frequency,o.Q.value=n.q,o.gain.value=n.gain,s.push(o),i=l=o;break}case"distortion":{const o=a.createWaveShaper();o.curve=L0(n.drive,n.curve),o.oversample="4x";const c=a.createBiquadFilter();c.type="lowpass",c.frequency.value=1e3+n.tone*1e4;const d=a.createGain(),h=a.createGain(),f=a.createGain(),p=a.createGain();d.gain.value=n.mix,h.gain.value=1-n.mix,f.connect(o),f.connect(h),o.connect(c),c.connect(d),d.connect(p),h.connect(p),s.push(f,o,c,d,h,p),i=f,l=p;break}case"tremolo":{const o=a.createOscillator();o.type=n.waveform,o.frequency.value=n.rate;const c=a.createGain();c.gain.value=n.depth*.5;const d=a.createGain();d.gain.value=1-n.depth*.5,o.connect(c),c.connect(d.gain),o.start(),s.push(o,c,d),i=l=d;break}case"phaser":{const o=[],c=a.createOscillator();c.type="sine",c.frequency.value=n.rate;const d=a.createGain();d.gain.value=n.depth*n.frequency;let h=null;for(let x=0;x<n.stages;x++){const v=a.createBiquadFilter();v.type="allpass",v.frequency.value=n.frequency,v.Q.value=.5,c.connect(d),d.connect(v.frequency),h&&h.connect(v),h=v,o.push(v)}const f=a.createGain(),p=a.createGain(),y=a.createGain(),g=a.createGain();f.gain.value=n.mix,p.gain.value=1-n.mix,y.connect(o[0]),y.connect(p),o[o.length-1].connect(f),f.connect(g),p.connect(g),c.start(),s.push(c,d,...o,f,p,y,g),i=y,l=g;break}default:throw new Error(`Unknown effect type: ${n.type}`)}return{id:t,params:n,nodes:s,input:i,output:l}}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 El={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})},Il={gain:"Gain",compressor:"Compressor",reverb:"Reverb",delay:"Delay",chorus:"Chorus",eq:"EQ",filter:"Filter",distortion:"Distortion",tremolo:"Tremolo",phaser:"Phaser"},D0={gain:yr,compressor:Fn,reverb:On,delay:Bn,chorus:vr,eq:br,filter:xr,distortion:Sr,tremolo:wr,phaser:kr},_0=["gain","compressor","reverb","delay","chorus","eq","filter","distortion","tremolo","phaser"],Le=({value:e,min:t,max:n,step:a=1,label:s,unit:i="",onChange:l,disabled:o})=>{const c=u.useRef(null),[d,h]=u.useState(!1),f=u.useRef(0),p=u.useRef(e),y=u.useCallback(x=>{o||(x.preventDefault(),h(!0),f.current=x.clientY,p.current=e)},[o,e]);u.useEffect(()=>{if(!d)return;const x=m=>{const S=f.current-m.clientY,b=n-t,N=S/200*b,R=Math.min(n,Math.max(t,p.current+N));l(a<1?R:Math.round(R/a)*a)},v=()=>{h(!1)};return document.addEventListener("mousemove",x),document.addEventListener("mouseup",v),()=>{document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",v)}},[d,t,n,a,l]);const g=(e-t)/(n-t)*270-135;return r.jsxs("div",{className:`nice-fx-knob ${o?"nice-fx-knob--disabled":""}`,ref:c,children:[r.jsx("div",{className:`nice-fx-knob__dial ${d?"nice-fx-knob__dial--active":""}`,onMouseDown:y,style:{transform:`rotate(${g}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 F0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:l,showPresets:o,compact:c}){return r.jsx(Ct,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:l,showPresets:o,compact:c,children:r.jsx(Le,{value:e.gain,min:-60,max:12,step:.1,label:"Gain",unit:"dB",onChange:d=>t({...e,gain:d}),disabled:!e.enabled})})}function O0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:l,showPresets:o,compact:c}){return r.jsx(Ct,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:l,showPresets:o,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(Le,{value:e.threshold,min:-60,max:0,label:"Threshold",unit:"dB",onChange:d=>t({...e,threshold:d}),disabled:!e.enabled}),r.jsx(Le,{value:e.ratio,min:1,max:20,label:"Ratio",onChange:d=>t({...e,ratio:d}),disabled:!e.enabled}),r.jsx(Le,{value:e.attack,min:.1,max:200,label:"Attack",unit:"ms",onChange:d=>t({...e,attack:d}),disabled:!e.enabled}),r.jsx(Le,{value:e.release,min:10,max:1e3,label:"Release",unit:"ms",onChange:d=>t({...e,release:d}),disabled:!e.enabled}),!c&&r.jsxs(r.Fragment,{children:[r.jsx(Le,{value:e.knee,min:0,max:40,label:"Knee",unit:"dB",onChange:d=>t({...e,knee:d}),disabled:!e.enabled}),r.jsx(Le,{value:e.makeupGain,min:0,max:24,label:"Makeup",unit:"dB",onChange:d=>t({...e,makeupGain:d}),disabled:!e.enabled})]})]})})}function B0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:l,showPresets:o,compact:c}){return r.jsx(Ct,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:l,showPresets:o,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(Le,{value:e.decay,min:.1,max:10,step:.1,label:"Decay",unit:"s",onChange:d=>t({...e,decay:d}),disabled:!e.enabled}),r.jsx(Le,{value:e.damping,min:0,max:1,step:.01,label:"Damping",onChange:d=>t({...e,damping:d}),disabled:!e.enabled}),r.jsx(Le,{value:e.roomSize,min:0,max:1,step:.01,label:"Room",onChange:d=>t({...e,roomSize:d}),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:d=>t({...e,mix:d}),disabled:!e.enabled})]})})}function G0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:l,showPresets:o,compact:c}){return r.jsx(Ct,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:l,showPresets:o,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(Le,{value:e.time,min:0,max:2e3,label:"Time",unit:"ms",onChange:d=>t({...e,time:d}),disabled:!e.enabled}),r.jsx(Le,{value:e.feedback,min:0,max:1,step:.01,label:"Feedback",onChange:d=>t({...e,feedback:d}),disabled:!e.enabled}),r.jsx(Le,{value:e.highCut,min:200,max:2e4,label:"HiCut",unit:"Hz",onChange:d=>t({...e,highCut:d}),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:d=>t({...e,mix:d}),disabled:!e.enabled})]})})}function W0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:l,showPresets:o,compact:c}){return r.jsx(Ct,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:l,showPresets:o,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(Le,{value:e.drive,min:0,max:1,step:.01,label:"Drive",onChange:d=>t({...e,drive:d}),disabled:!e.enabled}),r.jsx(Le,{value:e.tone,min:0,max:1,step:.01,label:"Tone",onChange:d=>t({...e,tone:d}),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:d=>t({...e,mix:d}),disabled:!e.enabled})]})})}function Ct({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:l,showPresets:o,compact:c,children:d}){const[h,f]=u.useState(!1);return r.jsxs("div",{className:`nice-fx-card ${e.enabled?"":"nice-fx-card--disabled"} ${i?"nice-fx-card--drop-target":""} ${c?"nice-fx-card--compact":""}`,draggable:!0,onDragStart:a,onDragEnd:s,children:[r.jsxs("div",{className:"nice-fx-card__header",children:[r.jsx("span",{className:"nice-fx-card__icon",children:El[e.type]}),r.jsx("span",{className:"nice-fx-card__title",children:Il[e.type]}),r.jsx("button",{type:"button",className:`nice-fx-card__toggle ${e.enabled?"nice-fx-card__toggle--active":""}`,onClick:()=>t({...e,enabled:!e.enabled}),title:e.enabled?"Disable":"Enable","aria-pressed":e.enabled,children:r.jsx("span",{className:"nice-fx-card__toggle-dot","aria-hidden":"true"})}),o&&Object.keys(l).length>0&&r.jsxs("div",{className:"nice-fx-card__presets",children:[r.jsx("button",{type:"button",className:"nice-fx-card__preset-btn",onClick:()=>f(!h),"aria-label":"Presets",children:r.jsx(B.NtdChevronDown,{size:12})}),h&&r.jsx("div",{className:"nice-fx-card__preset-menu",children:Object.entries(l).map(([p,y])=>r.jsx("button",{type:"button",className:"nice-fx-card__preset-item",onClick:()=>{t({...y,enabled:e.enabled}),f(!1)},children:p.replace(/_/g," ")},p))})]}),r.jsx("button",{type:"button",className:"nice-fx-card__remove",onClick:n,title:"Remove",children:"×"})]}),r.jsx("div",{className:"nice-fx-card__body",children:d})]})}function U0({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:l,showPresets:o,compact:c}){return r.jsx(Ct,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:l,showPresets:o,compact:c,children:r.jsx("div",{className:"nice-fx-card__generic",children:r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:d=>t({...e,mix:d}),disabled:!e.enabled})})})}function V0({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,l)=>t({...e,params:{...a,[i]:l}});return r.jsx(Ct,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.rate??1.5,min:.1,max:10,step:.1,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),r.jsx(Le,{value:a.depth??.5,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),r.jsx(Le,{value:a.feedback??.3,min:0,max:.95,step:.01,label:"Feedback",onChange:i=>s("feedback",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function q0({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,l)=>t({...e,params:{...a,[i]:l}});return r.jsx(Ct,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.low??0,min:-12,max:12,step:.5,label:"Low",onChange:i=>s("low",i),disabled:!e.enabled}),r.jsx(Le,{value:a.mid??0,min:-12,max:12,step:.5,label:"Mid",onChange:i=>s("mid",i),disabled:!e.enabled}),r.jsx(Le,{value:a.high??0,min:-12,max:12,step:.5,label:"High",onChange:i=>s("high",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function H0({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,l)=>t({...e,params:{...a,[i]:l}});return r.jsx(Ct,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.frequency??1e3,min:20,max:2e4,step:1,label:"Freq",onChange:i=>s("frequency",i),disabled:!e.enabled}),r.jsx(Le,{value:a.Q??1,min:.1,max:20,step:.1,label:"Q",onChange:i=>s("Q",i),disabled:!e.enabled}),r.jsx(Le,{value:a.gain??0,min:-24,max:24,step:.5,label:"Gain",onChange:i=>s("gain",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function K0({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,l)=>t({...e,params:{...a,[i]:l}});return r.jsx(Ct,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.rate??5,min:.1,max:20,step:.1,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),r.jsx(Le,{value:a.depth??.5,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function Y0({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,l)=>t({...e,params:{...a,[i]:l}});return r.jsx(Ct,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.rate??.5,min:.01,max:8,step:.01,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),r.jsx(Le,{value:a.depth??.7,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),r.jsx(Le,{value:a.feedback??.5,min:0,max:.95,step:.01,label:"Feedback",onChange:i=>s("feedback",i),disabled:!e.enabled}),r.jsx(Le,{value:a.stages??4,min:2,max:12,step:2,label:"Stages",onChange:i=>s("stages",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}const Z0=({audioContext:e,chain:t,effects:n,onChange:a,onChainUpdate:s,maxEffects:i=10,availableEffects:l=_0,showPresets:o=!0,compact:c=!1,className:d=""})=>{const[h,f]=u.useState((n==null?void 0:n.map(j=>j.params))||[]),[p,y]=u.useState({isDragging:!1,dragIndex:-1,dropIndex:-1}),[g,x]=u.useState(!1),v=u.useMemo(()=>t||(e?new z0(e):null),[e,t]),m=u.useCallback((j,M)=>{const I=[...h];I[j]=M,f(I),a==null||a(I),v&&(s==null||s(v))},[h,a,v,s]),S=u.useCallback(j=>{if(h.length>=i)return;const M={...D0[j]},I=[...h,M];f(I),a==null||a(I),x(!1)},[h,i,a]),b=u.useCallback(j=>{const M=h.filter((I,T)=>T!==j);f(M),a==null||a(M)},[h,a]),w=u.useCallback(j=>{y({isDragging:!0,dragIndex:j,dropIndex:-1})},[]),N=u.useCallback(()=>{if(p.dragIndex!==-1&&p.dropIndex!==-1&&p.dragIndex!==p.dropIndex){const j=[...h],[M]=j.splice(p.dragIndex,1);j.splice(p.dropIndex,0,M),f(j),a==null||a(j)}y({isDragging:!1,dragIndex:-1,dropIndex:-1})},[p,h,a]),R=u.useCallback((j,M)=>{j.preventDefault(),p.isDragging&&y(I=>({...I,dropIndex:M}))},[p.isDragging]),P=(j,M)=>{const I={onRemove:()=>b(M),onDragStart:()=>w(M),onDragEnd:N,isDragTarget:p.dropIndex===M,presets:E0[j.type]||{},showPresets:o,compact:c};switch(j.type){case"gain":return r.jsx(F0,{effect:j,onChange:T=>m(M,T),...I},M);case"compressor":return r.jsx(O0,{effect:j,onChange:T=>m(M,T),...I},M);case"reverb":return r.jsx(B0,{effect:j,onChange:T=>m(M,T),...I},M);case"delay":return r.jsx(G0,{effect:j,onChange:T=>m(M,T),...I},M);case"distortion":return r.jsx(W0,{effect:j,onChange:T=>m(M,T),...I},M);case"chorus":return r.jsx(V0,{effect:j,onChange:T=>m(M,T),...I},M);case"eq":return r.jsx(q0,{effect:j,onChange:T=>m(M,T),...I},M);case"filter":return r.jsx(H0,{effect:j,onChange:T=>m(M,T),...I},M);case"tremolo":return r.jsx(K0,{effect:j,onChange:T=>m(M,T),...I},M);case"phaser":return r.jsx(Y0,{effect:j,onChange:T=>m(M,T),...I},M);default:return r.jsx(U0,{effect:j,onChange:T=>m(M,T),...I},M)}};return r.jsxs("div",{className:`nice-fx-rack ${c?"nice-fx-rack--compact":""} ${d}`,children:[r.jsxs("div",{className:"nice-fx-rack__header",children:[r.jsx("h3",{className:"nice-fx-rack__title",children:"Effects Chain"}),r.jsxs("span",{className:"nice-fx-rack__count",children:[h.length,"/",i]})]}),r.jsx("div",{className:"nice-fx-rack__chain",children:h.length===0?r.jsx("div",{className:"nice-fx-rack__empty",children:"No effects. Click + to add."}):h.map((j,M)=>r.jsxs("div",{className:"nice-fx-rack__slot",onDragOver:I=>R(I,M),children:[P(j,M),M<h.length-1&&r.jsx("div",{className:"nice-fx-rack__connector","aria-hidden":"true",children:r.jsx(B.NtdArrowRight,{size:14})})]},M))}),h.length<i&&r.jsxs("div",{className:"nice-fx-rack__add",children:[r.jsx("button",{type:"button",className:"nice-fx-rack__add-btn",onClick:()=>x(!g),children:"+ Add Effect"}),g&&r.jsx("div",{className:"nice-fx-rack__add-menu",children:l.map(j=>r.jsxs("button",{type:"button",className:"nice-fx-rack__add-item",onClick:()=>S(j),children:[r.jsx("span",{className:"nice-fx-rack__add-icon",children:El[j]}),r.jsx("span",{className:"nice-fx-rack__add-label",children:Il[j]})]},j))})]})]})},Ll=[{type:"chipmunk",enabled:!1,intensity:60,label:"Chipmunk",icon:"sparkle"},{type:"helium",enabled:!1,intensity:80,label:"Helium",icon:"sparkle"},{type:"deep",enabled:!1,intensity:50,label:"Deep Voice",icon:"music"},{type:"demon",enabled:!1,intensity:70,label:"Demon",icon:"skull"},{type:"robot",enabled:!1,intensity:50,label:"Robot",icon:"robot"},{type:"alien",enabled:!1,intensity:60,label:"Alien",icon:"ghost"},{type:"echo",enabled:!1,intensity:50,label:"Echo",icon:"mountain"},{type:"cave",enabled:!1,intensity:60,label:"Cave",icon:"mountain"},{type:"reverb",enabled:!1,intensity:50,label:"Reverb",icon:"wave"},{type:"chorus",enabled:!1,intensity:50,label:"Chorus",icon:"music"},{type:"flanger",enabled:!1,intensity:50,label:"Flanger",icon:"wave"},{type:"distortion",enabled:!1,intensity:40,label:"Distortion",icon:"lightning"},{type:"telephone",enabled:!1,intensity:80,label:"Telephone",icon:"phone"},{type:"megaphone",enabled:!1,intensity:60,label:"Megaphone",icon:"megaphone"},{type:"radio",enabled:!1,intensity:70,label:"AM Radio",icon:"wave"},{type:"underwater",enabled:!1,intensity:50,label:"Underwater",icon:"wave"},{type:"whisper",enabled:!1,intensity:60,label:"Whisper",icon:"volume-mute"},{type:"tremolo",enabled:!1,intensity:50,label:"Tremolo",icon:"wave"},{type:"autotune",enabled:!1,intensity:60,label:"Auto-Tune",icon:"microphone"},{type:"vocoder",enabled:!1,intensity:50,label:"Vocoder",icon:"volume"}];function Ci(e,t,n){const a=e.sampleRate,s=Math.round(a*t),i=e.createBuffer(2,s,a);for(let l=0;l<2;l++){const o=i.getChannelData(l);for(let c=0;c<s;c++)o[c]=(Math.random()*2-1)*Math.pow(1-c/s,n)}return i}function or(e){const t=Math.max(1,e),n=44100,a=new Float32Array(n),s=Math.PI/180;for(let i=0;i<n;i++){const l=i*2/n-1;a[i]=(3+t)*l*20*s/(Math.PI+t*Math.abs(l))}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,l;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{(l=this.mediaStream)==null||l.getTracks().forEach(o=>o.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 l=t.createGain();l.gain.value=.7+a*.3;const o=t.createGain();o.gain.value=1-a*.5;const c=t.createDelay(1),d=t.createDelay(1),h=t.createOscillator(),f=t.createOscillator(),p=t.createGain(),y=t.createGain(),g=n-1,x=Math.abs(g)*5+2,v=Math.abs(g)*.015;h.type="sawtooth",h.frequency.value=x,p.gain.value=v,h.connect(p),p.connect(c.delayTime),c.delayTime.value=.02,f.type="sawtooth",f.frequency.value=x,y.gain.value=v,f.connect(y),y.connect(d.delayTime),d.delayTime.value=.02+v;const m=t.createGain();m.gain.value=.5;const S=t.createGain();return S.gain.value=.5,s.connect(c),s.connect(d),c.connect(m),d.connect(S),m.connect(l),S.connect(l),s.connect(o),l.connect(i),o.connect(i),h.start(),f.start(),{type:"chipmunk",nodes:[s,c,d,h,f,p,y,m,S,l,o,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 l=t.createGain();l.gain.value=1-n*.6;const o=t.createOscillator();o.type="square",o.frequency.value=50+n*200;const c=t.createGain();return c.gain.value=0,o.connect(c.gain),a.connect(c),c.connect(i),a.connect(l),i.connect(s),l.connect(s),o.start(),{type:"robot",nodes:[a,o,c,i,l,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 l=t.createGain();l.gain.value=0,i.connect(l.gain),a.connect(l);const o=t.createDelay(.1);o.delayTime.value=.005;const c=t.createOscillator();c.type="sine",c.frequency.value=3+n*10;const d=t.createGain();d.gain.value=.004,c.connect(d),d.connect(o.delayTime),l.connect(o),o.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,l,o,c,d,h,s],input:a,output:s}}buildDelay(t,n,a,s){const i=t.createGain(),l=t.createGain(),o=t.createDelay(2);o.delayTime.value=n;const c=t.createGain();c.gain.value=Math.min(.85,a);const d=t.createGain();d.gain.value=.5+s*.5;const h=t.createGain();return h.gain.value=1,i.connect(o),o.connect(c),c.connect(o),o.connect(d),i.connect(h),d.connect(l),h.connect(l),{type:"echo",nodes:[i,o,c,d,h,l],input:i,output:l}}buildCave(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(2);i.delayTime.value=.2+n*.3;const l=t.createDelay(2);l.delayTime.value=.35+n*.25;const o=t.createDelay(2);o.delayTime.value=.55+n*.3;const c=t.createGain();c.gain.value=.5;const d=t.createGain();d.gain.value=.35;const h=t.createGain();h.gain.value=.25;const f=t.createConvolver();f.buffer=Ci(t,2+n*3,3);const p=t.createGain();p.gain.value=.3+n*.3,a.connect(i),i.connect(c),c.connect(i),a.connect(l),l.connect(d),d.connect(l),a.connect(o),o.connect(h),h.connect(o),i.connect(p),l.connect(p),o.connect(p),a.connect(f),f.connect(p);const y=t.createGain();return y.gain.value=.7,a.connect(y),y.connect(s),p.connect(s),{type:"cave",nodes:[a,i,l,o,c,d,h,f,p,y,s],input:a,output:s}}buildReverb(t,n,a,s){const i=t.createGain(),l=t.createGain(),o=t.createConvolver();o.buffer=Ci(t,n,a);const c=t.createGain();c.gain.value=.4+s*.5;const d=t.createGain();return d.gain.value=1,i.connect(o),o.connect(c),i.connect(d),c.connect(l),d.connect(l),{type:"reverb",nodes:[i,o,c,d,l],input:i,output:l}}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}],l=[a,s],o=t.createGain();o.gain.value=.7,a.connect(o),o.connect(s),l.push(o);for(const c of i){const d=t.createDelay(.1);d.delayTime.value=c.delayMs/1e3;const h=t.createOscillator();h.type="sine",h.frequency.value=c.lfoFreq;const f=t.createGain();f.gain.value=c.depth*(.5+n),h.connect(f),f.connect(d.delayTime);const p=t.createGain();p.gain.value=.3+n*.2,a.connect(d),d.connect(p),p.connect(s),h.start(),l.push(d,h,f,p)}return{type:"chorus",nodes:l,input:a,output:s}}buildFlanger(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.02);i.delayTime.value=.005;const l=t.createOscillator();l.type="sine",l.frequency.value=.2+n*2;const o=t.createGain();o.gain.value=.003+n*.002,l.connect(o),o.connect(i.delayTime);const c=t.createGain();c.gain.value=.5+n*.35;const d=t.createGain();d.gain.value=.5+n*.3;const h=t.createGain();return h.gain.value=1,a.connect(i),i.connect(c),c.connect(i),i.connect(d),a.connect(h),d.connect(s),h.connect(s),l.start(),{type:"flanger",nodes:[a,i,l,o,c,d,h,s],input:a,output:s}}buildDistortion(t,n,a){const s=t.createGain(),i=t.createGain(),l=t.createWaveShaper();l.curve=or(n),l.oversample="4x";const o=t.createGain();o.gain.value=.6+a*.4;const c=t.createGain();return c.gain.value=1-a*.4,s.connect(l),l.connect(o),s.connect(c),o.connect(i),c.connect(i),{type:"distortion",nodes:[s,l,o,c,i],input:s,output:i}}buildBandpass(t,n,a,s){const i=t.createGain(),l=t.createGain(),o=t.createBiquadFilter();o.type="highpass",o.frequency.value=n,o.Q.value=.7;const c=t.createBiquadFilter();return c.type="lowpass",c.frequency.value=a,c.Q.value=.7,i.connect(o),o.connect(c),c.connect(l),{type:"telephone",nodes:[i,o,c,l],input:i,output:l}}buildMegaphone(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500;const l=t.createBiquadFilter();l.type="lowpass",l.frequency.value=4e3;const o=t.createWaveShaper();o.curve=or(15+n*30),o.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(l),l.connect(o),o.connect(c),c.connect(s),{type:"megaphone",nodes:[a,i,l,o,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 l=t.createBiquadFilter();l.type="lowpass",l.frequency.value=3e3-n*500;const o=t.createBiquadFilter();o.type="peaking",o.frequency.value=1500,o.gain.value=8,o.Q.value=2;const c=t.createWaveShaper();return c.curve=or(10),a.connect(i),i.connect(l),l.connect(o),o.connect(c),c.connect(s),{type:"radio",nodes:[a,i,l,o,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 l=t.createOscillator();l.type="sine",l.frequency.value=.5+n*2;const o=t.createGain();o.gain.value=100+n*200,l.connect(o),o.connect(i.frequency);const c=t.createGain();c.gain.value=.7+n*.3;const d=t.createGain();return d.gain.value=.3-n*.2,a.connect(i),i.connect(c),a.connect(d),c.connect(s),d.connect(s),l.start(),{type:"underwater",nodes:[a,i,l,o,c,d,s],input:a,output:s}}buildWhisper(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500+n*500,i.Q.value=.5;const l=t.createWaveShaper(),o=new Float32Array(256);for(let d=0;d<256;d++){const h=d/255*2-1;o[d]=Math.sign(h)*Math.pow(Math.abs(h),.3+n*.5)}l.curve=o;const c=t.createBiquadFilter();return c.type="highshelf",c.frequency.value=3e3,c.gain.value=6+n*6,a.connect(i),i.connect(l),l.connect(c),c.connect(s),{type:"whisper",nodes:[a,i,l,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 l=t.createOscillator();l.type="sawtooth",l.frequency.value=2+n*3;const o=t.createGain();o.gain.value=.02+n*.015,l.connect(o),o.connect(i.delayTime);const c=t.createWaveShaper();c.curve=or(20+n*50),c.oversample="2x";const d=t.createBiquadFilter();d.type="lowshelf",d.frequency.value=200,d.gain.value=8+n*8;const h=t.createGain();h.gain.value=.7+n*.3;const f=t.createGain();return f.gain.value=.3,a.connect(i),i.connect(c),c.connect(d),d.connect(h),a.connect(f),h.connect(s),f.connect(s),l.start(),{type:"demon",nodes:[a,i,l,o,c,d,h,f,s],input:a,output:s}}buildTremolo(t,n){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=1;const l=t.createOscillator();l.type="sine",l.frequency.value=3+n*12;const o=t.createGain();return o.gain.value=.3+n*.5,l.connect(o),o.connect(i.gain),a.connect(i),i.connect(s),l.start(),{type:"tremolo",nodes:[a,i,l,o,s],input:a,output:s}}buildAutotune(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.05);i.delayTime.value=.005;const l=t.createOscillator();l.type="sine",l.frequency.value=6+n*8;const o=t.createGain();o.gain.value=.002+n*.002,l.connect(o),o.connect(i.delayTime);const c=[],d=[261.6,293.7,329.6,349.2,392,440,493.9,523.3],h=t.createGain();h.gain.value=.15;for(const y of d){const g=t.createBiquadFilter();g.type="peaking",g.frequency.value=y,g.Q.value=8+n*15,g.gain.value=4+n*8,a.connect(g),g.connect(h),c.push(g)}const f=t.createGain();f.gain.value=.7;const p=t.createGain();return p.gain.value=.5+n*.3,a.connect(i),i.connect(p),h.connect(p),a.connect(f),p.connect(s),f.connect(s),l.start(),{type:"autotune",nodes:[a,i,l,o,...c,h,p,f,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 l=t.createGain();l.gain.value=0;const o=8,c=[a,s,i,l],d=t.createGain();d.gain.value=.5+n*.5,c.push(d);for(let f=0;f<o;f++){const p=200*Math.pow(2,f*.5),y=t.createBiquadFilter();y.type="bandpass",y.frequency.value=p,y.Q.value=4;const g=t.createBiquadFilter();g.type="bandpass",g.frequency.value=p,g.Q.value=4;const x=t.createGain();x.gain.value=0,a.connect(y),y.connect(x.gain),i.connect(g),g.connect(x),x.connect(d),c.push(y,g,x)}d.connect(s);const h=t.createGain();return h.gain.value=.3-n*.2,a.connect(h),h.connect(s),c.push(h),i.start(),{type:"vocoder",nodes:c,input:a,output:s}}}const X0={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},Q0=({deviceId:e,mediaStream:t,compact:n=!1,t:a,className:s,style:i,id:l,accessMode:o,"data-testid":c})=>{const{t:d}=Te(),h=a??d,f=u.useRef(null),[p,y]=u.useState(!1),[g,x]=u.useState(()=>Ll.map(z=>({...z}))),[v,m]=u.useState(!0),[S,b]=u.useState(80),[w,N]=u.useState(100),[R,P]=u.useState(0),j=u.useRef(0),M=u.useCallback(()=>{const z=()=>{var U;(U=f.current)!=null&&U.isStarted&&(P(f.current.getLevel()),j.current=requestAnimationFrame(z))};j.current=requestAnimationFrame(z)},[]),I=u.useCallback(()=>{j.current&&cancelAnimationFrame(j.current)},[]),T=u.useCallback(async()=>{const z=new zl;f.current=z;try{t?await z.startWithStream(t):await z.start(e),z.setMonitoring(v),z.setVolume(S/100),z.setInputGain(w/100);for(const U of g)U.enabled&&z.addEffect(U.type,U.intensity);y(!0),M()}catch(U){typeof console<"u"&&console.warn("[VocalEffectsRack] start error",U)}},[e,t,v,S,w,g,M]),E=u.useCallback(()=>{var z;I(),(z=f.current)==null||z.stop(),f.current=null,y(!1),P(0)},[I]);u.useEffect(()=>()=>{var z;I(),(z=f.current)==null||z.stop(),f.current=null},[I]);const _=u.useCallback(z=>{x(U=>U.map(Z=>{var Y;if(Z.type!==z)return Z;const ae={...Z,enabled:!Z.enabled};return(Y=f.current)!=null&&Y.isStarted&&(ae.enabled?f.current.addEffect(z,ae.intensity):f.current.removeEffect(z)),ae}))},[]),D=u.useCallback((z,U)=>{x(Z=>Z.map(ae=>{var Y;return ae.type!==z?ae:(ae.enabled&&((Y=f.current)!=null&&Y.isStarted)&&f.current.updateIntensity(z,U),{...ae,intensity:U})}))},[]);u.useEffect(()=>{var z;(z=f.current)==null||z.setVolume(S/100)},[S]),u.useEffect(()=>{var z;(z=f.current)==null||z.setInputGain(w/100)},[w]),u.useEffect(()=>{var z;(z=f.current)==null||z.setMonitoring(v)},[v]);const q=u.useCallback(()=>{var z;(z=f.current)==null||z.clearAllEffects(),x(U=>U.map(Z=>({...Z,enabled:!1})))},[]),te=g.filter(z=>z.enabled).length;return o==="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:l,"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:[te>0&&r.jsxs(se.NiceBadge,{variant:"primary",children:[te," ",h("vocalEffects.active","active")]}),p?r.jsx(se.NiceButton,{variant:"danger",size:"sm",onClick:E,children:h("vocalEffects.stop","Stop")}):r.jsx(se.NiceButton,{variant:"primary",size:"sm",onClick:T,children:h("vocalEffects.start","Start mic")})]})]}),r.jsxs("div",{style:{display:"flex",gap:16,alignItems:"center",marginBottom:16,flexWrap:"wrap"},children:[r.jsx(se.NiceToggle,{checked:v,onChange:m,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(se.NiceSlider,{value:S,onChange:b,min:0,max:200})}),r.jsxs("span",{style:{minWidth:36,fontSize:12},children:[S,"%"]})]}),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(se.NiceSlider,{value:w,onChange:N,min:0,max:300})}),r.jsxs("span",{style:{minWidth:36,fontSize:12},children:[w,"%"]})]}),p&&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,R*300)}%`,background:R>.5?"var(--nice-danger, #ef4444)":R>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})}),te>0&&r.jsx(se.NiceButton,{variant:"ghost",size:"sm",onClick:q,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:g.map(z=>r.jsxs("div",{style:{border:z.enabled?"2px solid var(--nice-accent, #3b82f6)":"1px solid var(--nice-border, #e2e8f0)",borderRadius:10,padding:n?"6px 8px":"10px 12px",background:z.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:()=>_(z.type),style:{display:"flex",alignItems:"center",gap:6,width:"100%",marginBottom:z.enabled?6:0,background:"transparent",border:"none",cursor:"pointer",color:"inherit",textAlign:"left"},children:[(()=>{const U=X0[z.icon]??B.NtdMusic;return r.jsx(U,{size:n?18:22})})(),r.jsx("span",{style:{fontSize:n?12:14,fontWeight:z.enabled?700:500,color:z.enabled?"var(--nice-accent, #3b82f6)":"inherit"},children:z.label})]}),z.enabled&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},onClick:U=>U.stopPropagation(),children:[r.jsx("div",{style:{flex:1},children:r.jsx(se.NiceSlider,{value:z.intensity,onChange:U=>D(z.type,U),min:0,max:100})}),r.jsx("span",{style:{fontSize:11,minWidth:24,color:"var(--nice-text-muted, #64748b)"},children:z.intensity})]})]},z.type))}),r.jsx("div",{style:{marginTop:12,fontSize:12,color:"var(--nice-text-muted, #94a3b8)",textAlign:"center"},children:h("vocalEffects.hint","Click effects to toggle. Multiple effects can be active at once — adjust intensity with the slider.")})]})},Dl={algorithm:"pitchy",gain:1,rmsThreshold:.02,pitchThreshold:.6,smoothingWindow:3,hysteresisFrames:2,useHanning:!1,offsetMs:0},J0=[{value:"pitchy",label:"Pitchy (fast)"},{value:"autocorrelation",label:"Autocorrelation"},{value:"librosa",label:"Librosa (server)"},{value:"crepe",label:"CREPE (AI, server)"}],em=({deviceId:e,onDeviceChange:t,settings:n,onSettingsChange:a,audioInputs:s,algorithms:i=J0,showLevelMeter:l=!0,onCalibrate:o,compact:c=!1,t:d})=>{const{t:h}=Te(),f=d??h,p=u.useMemo(()=>({...Dl,...n}),[n]),y=T=>a==null?void 0:a({...p,...T}),[g,x]=u.useState([]);u.useEffect(()=>{var _,D,q;if(s||!((_=navigator.mediaDevices)!=null&&_.enumerateDevices))return;let T=!1;const E=()=>navigator.mediaDevices.enumerateDevices().then(te=>!T&&x(te.filter(z=>z.kind==="audioinput"))).catch(()=>{});return E(),(q=(D=navigator.mediaDevices).addEventListener)==null||q.call(D,"devicechange",E),()=>{var te,z;T=!0,(z=(te=navigator.mediaDevices).removeEventListener)==null||z.call(te,"devicechange",E)}},[s]);const v=s??g,m=u.useMemo(()=>v.map((T,E)=>({value:T.deviceId,label:T.label||`${f("audioInput.microphone","Microphone")} ${E+1}`})),[v,f]),[S,b]=u.useState(!1),[w,N]=u.useState(0),R=u.useRef(null),P=()=>{const T=R.current;T&&(cancelAnimationFrame(T.raf),T.stream.getTracks().forEach(E=>E.stop()),T.ctx.close().catch(()=>{}),R.current=null),b(!1),N(0)},j=async()=>{try{const T=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0}}),E=new AudioContext,_=E.createMediaStreamSource(T),D=E.createAnalyser();D.fftSize=1024,_.connect(D);const q=new Float32Array(D.fftSize),te=()=>{D.getFloatTimeDomainData(q);let z=0;for(let U=0;U<q.length;U++)z+=q[U]*q[U];N(Math.sqrt(z/q.length)*(p.gain||1)),R.current.raf=requestAnimationFrame(te)};R.current={ctx:E,stream:T,raf:requestAnimationFrame(te)},b(!0)}catch{}};u.useEffect(()=>()=>P(),[]);const M={fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:4,display:"block"},I=(T,E,_)=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[r.jsx("span",{style:{flex:"0 0 120px",fontSize:13},children:T}),r.jsx("div",{style:{flex:1},children:E}),r.jsx("span",{style:{flex:"0 0 48px",textAlign:"right",fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:_})]});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:{...M,display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(B.NtdMicrophone,{size:13})," ",f("audioInput.device","Microphone")]}),r.jsx(se.NiceSelect,{options:m,value:e??"",onChange:T=>t==null?void 0:t(typeof T=="string"?T:T[0]),placeholder:f("audioInput.selectDevice","Select microphone"),size:"sm"})]}),r.jsxs("div",{style:{flex:"1 1 200px",minWidth:160},children:[r.jsx("label",{style:M,children:f("audioInput.algorithm","Pitch algorithm")}),r.jsx(se.NiceSelect,{options:i,value:p.algorithm,onChange:T=>y({algorithm:typeof T=="string"?T:T[0]}),size:"sm"})]})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[I(f("audioInput.gain","Gain"),r.jsx(se.NiceSlider,{value:Math.round(p.gain*100),onChange:T=>y({gain:T/100}),min:0,max:300}),`${Math.round(p.gain*100)}%`),I(f("audioInput.rmsThreshold","RMS gate"),r.jsx(se.NiceSlider,{value:Math.round(p.rmsThreshold*1e3),onChange:T=>y({rmsThreshold:T/1e3}),min:0,max:200}),p.rmsThreshold.toFixed(3)),I(f("audioInput.pitchThreshold","Pitch clarity"),r.jsx(se.NiceSlider,{value:Math.round(p.pitchThreshold*100),onChange:T=>y({pitchThreshold:T/100}),min:0,max:100}),p.pitchThreshold.toFixed(2)),!c&&I(f("audioInput.smoothing","Smoothing"),r.jsx(se.NiceSlider,{value:p.smoothingWindow,onChange:T=>y({smoothingWindow:T}),min:0,max:12}),`${p.smoothingWindow}`),!c&&I(f("audioInput.hysteresis","Hysteresis"),r.jsx(se.NiceSlider,{value:p.hysteresisFrames,onChange:T=>y({hysteresisFrames:T}),min:0,max:12}),`${p.hysteresisFrames}`),!c&&I(f("audioInput.offset","Latency"),r.jsx(se.NiceSlider,{value:p.offsetMs,onChange:T=>y({offsetMs:T}),min:-200,max:500}),`${p.offsetMs}ms`)]}),r.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap"},children:[r.jsx(se.NiceToggle,{checked:p.useHanning,onChange:T=>y({useHanning:T}),label:f("audioInput.hanning","Hanning window")}),l&&r.jsxs(r.Fragment,{children:[r.jsx(se.NiceButton,{variant:S?"danger":"secondary",size:"sm",onClick:S?P:j,children:S?f("audioInput.stopTest","Stop test"):f("audioInput.testMic","Test mic")}),r.jsx("div",{style:{width:100,height:8,borderRadius:4,background:"var(--nice-bg-tertiary)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${Math.min(100,w*300)}%`,background:w>.5?"var(--nice-danger, #ef4444)":w>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})})]}),o&&e&&r.jsxs(se.NiceButton,{variant:"ghost",size:"sm",onClick:()=>o(e),children:[r.jsx(B.NtdSettings,{size:14})," ",f("audioInput.calibrate","Calibrate latency")]})]})]})};class _l{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),l=this.audioContext.createOscillator(),o=this.audioContext.createGain();l.type=s,l.frequency.value=i;const c=n/127*.8;o.gain.value=c,l.connect(o),o.connect(this.masterGain);const d=this.audioContext.currentTime;return o.gain.setValueAtTime(0,d),o.gain.linearRampToValueAtTime(c,d+.01),o.gain.exponentialRampToValueAtTime(c*.7,d+.1),o.gain.setValueAtTime(c*.7,d+a-.05),o.gain.exponentialRampToValueAtTime(.001,d+a),l.start(d),l.stop(d+a),l.onended=()=>{o.disconnect(),l.disconnect()},{osc:l,gain:o}}scheduleNote(t,n,a,s=100,i="sine"){const l=this.midiToFreq(t),o=this.audioContext.createOscillator(),c=this.audioContext.createGain();o.type=i,o.frequency.value=l;const d=s/127*.8;o.connect(c),c.connect(this.masterGain);const h=n;return c.gain.setValueAtTime(0,h),c.gain.linearRampToValueAtTime(d,h+.01),c.gain.exponentialRampToValueAtTime(d*.7,h+.1),c.gain.setValueAtTime(d*.7,h+a-.05),c.gain.exponentialRampToValueAtTime(.001,h+a),o.start(h),o.stop(h+a),o.onended=()=>{c.disconnect(),o.disconnect()},{osc:o,gain:c}}setVolume(t){this.masterGain.gain.value=Math.max(0,Math.min(1,t))}stopAll(){this.activeNotes.forEach(({osc:t,gain:n})=>{try{t.stop(),n.disconnect(),t.disconnect()}catch{}}),this.activeNotes.clear()}dispose(){this.stopAll(),this.masterGain.disconnect()}}const ji=ot.scoped("AudioPlaybackEngine");class tm{constructor(){this.audioContext=null,this.masterGain=null,this.masterFilter=null,this.clips=new Map,this.scheduledSources=new Map,this.midiTracks=new Map,this.synths=new Map,this.isPlaying=!1,this.startTimeOffset=0,this.audioContextStartTime=0,this.currentTime=0,this.loopRegion={start:0,end:0,enabled:!1},this.bpm=120,this.duration=0,this.initAudioContext()}setMidiCCEvents(t,n){const a=this.midiTracks.get(t);a&&(a.ccEvents=n)}getMidiCCEvents(t){const n=this.midiTracks.get(t);return(n==null?void 0:n.ccEvents)||[]}addMidiCCEvent(t,n){const a=this.midiTracks.get(t);a&&(a.ccEvents||(a.ccEvents=[]),a.ccEvents.push(n))}removeMidiCCEvent(t,n){const a=this.midiTracks.get(t);a&&a.ccEvents&&(a.ccEvents=a.ccEvents.filter(s=>s.id!==n))}initAudioContext(){try{this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.masterGain=this.audioContext.createGain(),this.masterFilter=this.audioContext.createBiquadFilter(),this.masterFilter.type="peaking",this.masterFilter.frequency.value=1200,this.masterFilter.Q.value=.7,this.masterFilter.gain.value=0,this.masterGain.connect(this.masterFilter),this.masterFilter.connect(this.audioContext.destination),this.masterGain.gain.value=.8,this.audioContext.state==="suspended"&&this.audioContext.resume()}catch(t){ji.error("Failed to initialize AudioContext:",t)}}createEffectNode(t){if(!this.audioContext||t.bypass)return null;try{switch(t.type){case"eq3":{const n=this.audioContext.createBiquadFilter(),a=this.audioContext.createBiquadFilter(),s=this.audioContext.createBiquadFilter();return n.type="lowshelf",n.frequency.value=t.params.lowFreq||250,n.gain.value=t.params.lowGain||0,a.type="peaking",a.frequency.value=1e3,a.Q.value=1,a.gain.value=t.params.midGain||0,s.type="highshelf",s.frequency.value=t.params.highFreq||4e3,s.gain.value=t.params.highGain||0,n.connect(a),a.connect(s),{input:n,output:s}}case"compressor":{const n=this.audioContext.createDynamicsCompressor();return n.threshold.value=t.params.threshold||-24,n.ratio.value=t.params.ratio||4,n.attack.value=t.params.attack||.003,n.release.value=t.params.release||.25,n.knee.value=t.params.knee||30,n}case"delay":{const n=this.audioContext.createDelay(5);n.delayTime.value=t.params.time||.25;const a=this.audioContext.createGain();a.gain.value=t.params.feedback||.3;const s=this.audioContext.createGain();s.gain.value=t.params.mix||.3;const i=this.audioContext.createGain();return i.gain.value=1-(t.params.mix||.3),n.connect(a),a.connect(n),n.connect(s),{input:n,output:s,dry:i,connect:function(l){s.connect(l),i.connect(l)}}}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 o=0;o<2;o++){const c=s.getChannelData(o);for(let d=0;d<a;d++)c[d]=(Math.random()*2-1)*Math.pow(1-d/a,2)}n.buffer=s;const i=this.audioContext.createGain();i.gain.value=t.params.mix||.3;const l=this.audioContext.createGain();return l.gain.value=1-(t.params.mix||.3),n.connect(i),{input:n,output:i,dry:l,connect:function(o){i.connect(o),l.connect(o)}}}case"distortion":{const n=this.audioContext.createWaveShaper(),a=t.params.amount||20,s=44100,i=new Float32Array(s),l=Math.PI/180;for(let d=0;d<s;d++){const h=d*2/s-1;i[d]=(3+a)*h*20*l/(Math.PI+a*Math.abs(h))}n.curve=i,n.oversample="4x";const o=this.audioContext.createGain();o.gain.value=t.params.mix||.5;const c=this.audioContext.createGain();return c.gain.value=1-(t.params.mix||.5),n.connect(o),{input:n,output:o,dry:c,connect:function(d){o.connect(d),c.connect(d)}}}default:return null}}catch(n){return ji.error("Failed to create effect node:",t.type,n),null}}addClip(t){this.clips.set(t.id,t),this.updateDuration()}removeClip(t){this.clips.delete(t),this.stopClip(t),this.updateDuration()}updateClip(t,n){const a=this.clips.get(t);a&&(Object.assign(a,n),this.updateDuration())}getClipsByLayer(t){return Array.from(this.clips.values()).filter(n=>n.layerId===t)}setMidiTrack(t,n,a="sine",s=.5){if(this.midiTracks.set(t,{layerId:t,notes:n,instrument:a,volume:s}),!this.synths.has(t)&&this.audioContext&&this.masterGain){const i=new _l(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 l=s;if(t.effectChain&&t.effectChain.length>0)for(const h of t.effectChain){const f=this.createEffectNode(h);if(f)if("input"in f&&"output"in f){const p=f;l.connect(p.input),l=p.output,"dry"in f&&s.connect(p.dry)}else l.connect(f),l=f}l.connect(i),i.connect(this.masterGain);const o=t.startTime,c=Math.max(0,this.currentTime-o),d=this.audioContext.currentTime+(o-this.currentTime);d>=this.audioContext.currentTime&&(a.start(d,t.offset+c,t.duration-c),this.scheduledSources.set(t.id,a),a.onended=()=>{this.scheduledSources.delete(t.id)})})}stopClip(t){const n=this.scheduledSources.get(t);if(n){try{n.stop()}catch{}this.scheduledSources.delete(t)}}stopAllSources(){this.scheduledSources.forEach(t=>{try{t.stop()}catch{}}),this.scheduledSources.clear(),this.synths.forEach(t=>t.stopAll())}scheduleMidiNotes(){this.audioContext&&this.midiTracks.forEach(t=>{const n=this.synths.get(t.layerId);if(n&&(t.notes.forEach(a=>{if(a.start+a.duration<=this.currentTime)return;const i=Math.max(0,this.currentTime-a.start),l=this.audioContext.currentTime+(a.start-this.currentTime);l>=this.audioContext.currentTime&&n.scheduleNote(a.pitch,l,a.duration-i,a.velocity,t.instrument)}),t.ccEvents&&Array.isArray(t.ccEvents)&&t.ccEvents.length>0)){const a=[...t.ccEvents].sort((l,o)=>l.time-o.time);let i=a[0];for(let l=1;l<a.length;++l){const o=a[l],c=i.time,d=o.time,h=i.value,f=o.value,p=i.handleType||"linear",y=Math.max(2,Math.ceil((d-c)*20));for(let g=0;g<=y;++g){const x=g/y;let v=h;if(p==="linear")v=h+(f-h)*x;else if(p==="step")v=x<1?h:f;else if(p==="exp"){const w=Math.max(h/127,.001),N=Math.max(f/127,.001);v=w*Math.pow(N/w,x)*127}const m=c+(d-c)*x,S=this.audioContext.currentTime+(m-this.currentTime);S>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(o.cc,v,S)}i=o}}})}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 nm=[{name:"Grand Piano",waveform:"sawtooth",attack:.02,sustain:.7,release:1.2,eq:{C:2,D:1,E:1,F:0,G:0,A:-1,B:-2,C2:-3},category:"Keyboard"},{name:"Electric Piano",waveform:"triangle",attack:.03,sustain:.8,release:1,eq:{C:0,D:1,E:2,F:3,G:1,A:-1,B:-2,C2:-2},category:"Keyboard"},{name:"Harpsichord",waveform:"square",attack:.01,sustain:.5,release:.6,eq:{C:-1,D:-1,E:0,F:2,G:3,A:1,B:0,C2:-1},category:"Keyboard"},{name:"Violin",waveform:"triangle",attack:.3,sustain:1,release:1.5,eq:{C:3,D:2,E:2,F:1,G:-1,A:-2,B:-3,C2:-3},category:"String"},{name:"Acoustic Guitar",waveform:"sawtooth",attack:.2,sustain:.6,release:.9,eq:{C:-1,D:-2,E:0,F:1,G:3,A:2,B:0,C2:-2},category:"String"},{name:"Electric Guitar",waveform:"square",attack:.05,sustain:.7,release:1.2,eq:{C:-2,D:1,E:2,F:2,G:1,A:0,B:-1,C2:-3},category:"String"},{name:"Kick Drum",waveform:"sine",attack:.005,sustain:.1,release:.2,eq:{C:5,D:3,E:0,F:-3,G:-5,A:-7,B:-9,C2:-10},category:"Percussion"},{name:"Snare Drum",waveform:"triangle",attack:.01,sustain:.2,release:.3,eq:{C:-2,D:-1,E:1,F:2,G:3,A:2,B:0,C2:-2},category:"Percussion"},{name:"Hi-Hat",waveform:"square",attack:.002,sustain:.05,release:.1,eq:{C:-5,D:-3,E:0,F:2,G:5,A:7,B:9,C2:10},category:"Percussion"},{name:"Acoustic Bass",waveform:"sine",attack:.08,sustain:.8,release:1.2,eq:{C:4,D:3,E:2,F:1,G:0,A:-1,B:-2,C2:-3},category:"Bass"},{name:"Electric Bass",waveform:"square",attack:.05,sustain:.9,release:1.3,eq:{C:3,D:2,E:1,F:0,G:-1,A:-2,B:-3,C2:-4},category:"Bass"},{name:"Trumpet",waveform:"sawtooth",attack:.1,sustain:.9,release:1.5,eq:{C:2,D:3,E:4,F:5,G:3,A:1,B:-1,C2:-3},category:"Brass"},{name:"Trombone",waveform:"triangle",attack:.2,sustain:1,release:1.7,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-2,C2:-4},category:"Brass"},{name:"Saxophone",waveform:"sawtooth",attack:.15,sustain:.8,release:1.3,eq:{C:2,D:3,E:4,F:3,G:1,A:-1,B:-2,C2:-3},category:"Woodwind"},{name:"Clarinet",waveform:"triangle",attack:.18,sustain:.9,release:1.6,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-1,C2:-2},category:"Woodwind"},{name:"Saw Synth",waveform:"sawtooth",attack:.05,sustain:.9,release:1.2,eq:{C:2,D:3,E:4,F:3,G:2,A:0,B:-1,C2:-2},category:"Synth"},{name:"Square Lead",waveform:"square",attack:.04,sustain:.85,release:1.1,eq:{C:2,D:3,E:4,F:3,G:1,A:0,B:-1,C2:-3},category:"Synth"}];function Ur(e={}){const{channelFilter:t,sysex:n=!1,onEvent:a,inputNameIncludes:s,onInputsChanged:i}=e,[l,o]=u.useState(null),[c,d]=u.useState(!1),[h,f]=u.useState([]),p=u.useRef(null),y=u.useCallback((g,x)=>{const v=g.data??new Uint8Array(0),m=v[0]??0,S=v[1]??0,b=v[2]??0,w=g.timeStamp,N=m&240,R=m&15,P=x.id,j=x.name??"MIDI Input",M=t===void 0||t===R;if((N===144||N===128)&&M){const I=N===144&&b>0;return{type:I?"noteon":"noteoff",note:S,velocity:I?b:0,channel:R,ts:w,deviceId:P,deviceName:j}}return N===176&&M?{type:"cc",controller:S,value:b,channel:R,ts:w,deviceId:P,deviceName:j}:N===208&&M?{type:"aftertouch",pressure:S,channel:R,ts:w,deviceId:P,deviceName:j}:N===224&&M?{type:"pitchbend",value:(S|b<<7)-8192,channel:R,ts:w,deviceId:P,deviceName:j}:N===192&&M?{type:"program",program:S,channel:R,ts:w,deviceId:P,deviceName:j}:{type:"unknown",status:m,data1:S,data2:b,channel:R,ts:w,deviceId:P,deviceName:j}},[t]);return u.useEffect(()=>{if(!("requestMIDIAccess"in navigator)){o(!1);return}o(!0);let g=!1;return navigator.requestMIDIAccess({sysex:n}).then(x=>{if(g)return;p.current=x,d(!0);const v=()=>{const m=Array.from(x.inputs.values()),S=s?m.filter(b=>(b.name||"").toUpperCase().includes(s.toUpperCase())):m;f(S),i==null||i(S),m.forEach(b=>b.onmidimessage=null),S.forEach(b=>{b.onmidimessage=w=>a==null?void 0:a(y(w,b))})};v(),x.onstatechange=()=>v()}),()=>{g=!0;const x=p.current;x&&(x.inputs.forEach(v=>v.onmidimessage=null),x.onstatechange=null)}},[s,a,i,y,n]),{supported:l,granted:c,inputs:h}}const rs="nice2dev.midiLearn";function rm(){try{const e=localStorage.getItem(rs);return e?JSON.parse(e):{}}catch{return{}}}function Mi(e){const t={};for(const n of e)t[n.id]={id:n.id,type:n.type,number:n.number,channel:n.channel,min:n.min,max:n.max};localStorage.setItem(rs,JSON.stringify(t))}function am(e){const{parameters:t,onParameterChange:n}=e,[a,s]=u.useState(()=>{const b=rm();return t.map(w=>{const N=b[w.id];return{id:w.id,paramName:w.name,type:(N==null?void 0:N.type)??"cc",number:N==null?void 0:N.number,channel:N==null?void 0:N.channel,min:(N==null?void 0:N.min)??w.min??0,max:(N==null?void 0:N.max)??w.max??127,value:0}})}),[i,l]=u.useState({learning:!1,targetId:null}),[o,c]=u.useState(null),d=u.useRef(a);d.current=a;const h=u.useRef(n);h.current=n;const f=u.useRef(i);f.current=i;const p=u.useCallback(b=>{var N;c(b);const w=f.current;if(w.learning&&w.targetId){if(!d.current.find(j=>j.id===w.targetId))return;let P={};switch(b.type){case"cc":P={type:"cc",number:b.controller,channel:b.channel};break;case"noteon":P={type:"note",number:b.note,channel:b.channel};break;case"pitchbend":P={type:"pitchbend",channel:b.channel};break;case"aftertouch":P={type:"aftertouch",channel:b.channel};break;default:return}s(j=>{const M=j.map(I=>I.id===w.targetId?{...I,...P}:I);return Mi(M),M}),l({learning:!1,targetId:null});return}for(const R of d.current){if(R.number===void 0&&R.type!=="pitchbend"&&R.type!=="aftertouch"||R.channel!==void 0&&b.channel!==R.channel)continue;let P=null,j=127;if(R.type==="cc"&&b.type==="cc"&&b.controller===R.number?P=b.value:R.type==="note"&&b.type==="noteon"&&b.note===R.number?P=b.velocity:R.type==="pitchbend"&&b.type==="pitchbend"?(P=b.value+8192,j=16383):R.type==="aftertouch"&&b.type==="aftertouch"&&(P=b.pressure),P!==null){const M=P/j,I=R.min+M*(R.max-R.min);s(T=>T.map(E=>E.id===R.id?{...E,value:M}:E)),(N=h.current)==null||N.call(h,R.id,I,M)}}},[]),{supported:y,granted:g}=Ur({onEvent:p}),x=u.useCallback(b=>{l({learning:!0,targetId:b})},[]),v=u.useCallback(()=>{l({learning:!1,targetId:null})},[]),m=u.useCallback(b=>{s(w=>{const N=w.map(R=>R.id===b?{...R,type:"cc",number:void 0,channel:void 0}:R);return Mi(N),N})},[]),S=u.useCallback(()=>{s(b=>{const w=b.map(N=>({...N,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(rs),w})},[]);return{bindings:a,startLearn:x,cancelLearn:v,removeBinding:m,clearAll:S,learnState:i,midiSupported:y,midiGranted:g,lastEvent:o}}const sm={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function im(e={}){const{lowerZone:t=sm,onNoteExpression:n,onNoteOn:a,onNoteOff:s}=e,[i,l]=u.useState([]),o=u.useRef(new Map),c=u.useRef(n);c.current=n;const d=u.useRef(a);d.current=a;const h=u.useRef(s);h.current=s;const f=u.useRef(new Set(t.memberChannels));u.useEffect(()=>{f.current=new Set(t.memberChannels)},[t.memberChannels]);const p=u.useCallback(x=>{var m,S,b,w,N;if(!f.current.has(x.channel??-1))return;const v=`${x.channel}`;switch(x.type){case"noteon":{const R={note:x.note,channel:x.channel,velocity:x.velocity,pitchBend:0,pressure:0,slide:0,lastUpdate:x.ts};o.current.set(v,R),l(Array.from(o.current.values())),(m=d.current)==null||m.call(d,R);break}case"noteoff":{o.current.delete(v),l(Array.from(o.current.values())),(S=h.current)==null||S.call(h,x.channel,x.note);break}case"pitchbend":{const R=o.current.get(v);R&&(R.pitchBend=x.value,R.lastUpdate=x.ts,(b=c.current)==null||b.call(c,R),l(Array.from(o.current.values())));break}case"aftertouch":{const R=o.current.get(v);R&&(R.pressure=x.pressure,R.lastUpdate=x.ts,(w=c.current)==null||w.call(c,R),l(Array.from(o.current.values())));break}case"cc":{if(x.controller===74){const R=o.current.get(v);R&&(R.slide=x.value,R.lastUpdate=x.ts,(N=c.current)==null||N.call(c,R),l(Array.from(o.current.values())))}break}}},[]),{supported:y,granted:g}=Ur({onEvent:p,sysex:!1});return{activeNotes:i,midiSupported:y,midiGranted:g}}const om={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 lm(e={},t=om){const[n,a]=u.useState(()=>{const y=localStorage.getItem("oxygen25.layout");return y?JSON.parse(y):t}),[s,i]=u.useState([]),l=u.useRef({mode:"idle"}),o=u.useCallback(y=>{a(g=>{const x={...g,...y};return localStorage.setItem("oxygen25.layout",JSON.stringify(x)),x})},[]),c=u.useCallback(y=>{var v,m,S,b,w,N,R,P,j;const g=y.deviceName||"MIDI";i(M=>M.includes(g)?M:[...M,g]);const x=l.current;if(x.mode!=="idle"){if(x.mode==="knob"&&y.type==="cc"){const M=x.index;o({knobs:n.knobs.map(I=>I.index===M?{...I,cc:y.controller}:I)}),l.current={mode:"idle"};return}if(x.mode==="fader"&&y.type==="cc"){o({fader:{cc:y.controller,label:"Fader"}}),l.current={mode:"idle"};return}if(x.mode==="pad"&&y.type==="noteon"){const M=n.pads.slice();M[x.padIdx]={...M[x.padIdx],note:y.note},o({pads:M}),l.current={mode:"idle"};return}if(x.mode==="transport"&&y.type==="cc"){const M={...n.transport};M[x.action]=y.controller,o({transport:M}),l.current={mode:"idle"};return}}switch(y.type){case"noteon":{n.pads.findIndex(I=>I.note===y.note)>=0?(v=e.onPad)==null||v.call(e,{note:y.note,velocity:y.velocity,ts:y.ts,device:g}):(m=e.onKey)==null||m.call(e,{note:y.note,velocity:y.velocity,ts:y.ts,device:g});break}case"cc":{if(n.fader&&y.controller===n.fader.cc){(S=e.onFader)==null||S.call(e,{cc:y.controller,value:y.value,ts:y.ts,device:g});break}const M=n.knobs.find(T=>T.cc===y.controller);if(M){(b=e.onKnob)==null||b.call(e,{index:M.index,cc:y.controller,value:y.value,ts:y.ts,device:g});break}const I=Object.keys(n.transport).find(T=>n.transport[T]===y.controller);if(I){(w=e.onTransport)==null||w.call(e,{action:I,value:y.value,ts:y.ts,device:g});break}(N=e.onUnknown)==null||N.call(e,y);break}case"pitchbend":(R=e.onPitchBend)==null||R.call(e,{value:y.value,ts:y.ts,device:g});break;case"aftertouch":(P=e.onAftertouch)==null||P.call(e,{pressure:y.pressure,ts:y.ts,device:g});break;default:(j=e.onUnknown)==null||j.call(e,y)}},[o,e,n]),{supported:d,granted:h,inputs:f}=Ur({inputNameIncludes:void 0,onEvent:c,sysex:!1,channelFilter:void 0,onInputsChanged:y=>i(y.map(g=>g.name||"MIDI"))}),p=u.useMemo(()=>({knob:y=>l.current={mode:"knob",index:y},fader:()=>l.current={mode:"fader"},pad:y=>l.current={mode:"pad",padIdx:y},transport:y=>l.current={mode:"transport",action:y},cancel:()=>l.current={mode:"idle"},state:()=>l.current}),[]);return{supported:d,granted:h,inputs:f,layout:n,setLayout:o,learn:p,inputsInfo:s}}const ja={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],mixolydian:[0,2,4,5,7,9,10],pentatonic:[0,2,4,7,9],minorPenta:[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11]},cm=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Ma={pop:[[0,4,7],[5,9,0],[7,11,2],[5,9,0]],rock:[[0,4,7],[5,9,0],[3,7,10],[5,9,0]],jazz:[[0,4,7,11],[2,5,9,0],[5,9,0,4],[0,4,7,11]],blues12:[[0,4,7],[0,4,7],[0,4,7],[0,4,7],[5,9,0],[5,9,0],[0,4,7],[0,4,7],[7,11,2],[5,9,0],[0,4,7],[7,11,2]]},nn=36,jn=38,Nt=42,rn=51,dm=49,Ra={basic:[{step:0,pitch:nn,vel:110},{step:0,pitch:Nt,vel:80},{step:2,pitch:Nt,vel:70},{step:4,pitch:jn,vel:100},{step:4,pitch:Nt,vel:80},{step:6,pitch:Nt,vel:70},{step:8,pitch:nn,vel:100},{step:10,pitch:Nt,vel:70},{step:12,pitch:jn,vel:100},{step:12,pitch:Nt,vel:80},{step:14,pitch:Nt,vel:70}],rock:[{step:0,pitch:nn,vel:120},{step:0,pitch:dm,vel:90},{step:4,pitch:jn,vel:110},{step:4,pitch:Nt,vel:80},{step:8,pitch:nn,vel:110},{step:8,pitch:Nt,vel:80},{step:10,pitch:nn,vel:90},{step:12,pitch:jn,vel:110},{step:12,pitch:Nt,vel:80}],swing:[{step:0,pitch:rn,vel:90},{step:3,pitch:rn,vel:70},{step:4,pitch:rn,vel:80},{step:8,pitch:rn,vel:90},{step:11,pitch:rn,vel:70},{step:12,pitch:rn,vel:80},{step:4,pitch:nn,vel:80},{step:12,pitch:jn,vel:70}]},Fl={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function um(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 Ol=1;const lr=()=>Ol++,Bl=e=>60/e,hm=e=>Bl(e)/4;function ia(e,t,n,a){const s=t.length,i=Math.floor(n/s),l=(n%s+s)%s;return e+t[l]+(a+i)*12}function Gl(e=Fl){Ol=1;const t=e.seed>0?um(e.seed):Math.random,n=ja[e.scale]??ja.pentatonic,a=Ma[e.progression]??Ma.pop,s=Ra[e.drumPattern]??Ra.basic,i=Bl(e.tempo),l=hm(e.tempo),o=Math.max(1,e.bars),c=16,d=[],h=[],f=[],p=[];let y=0;for(let g=0;g<o;g++){const x=g*4*i,v=g%a.length,m=a[v];for(const b of m)f.push({id:lr(),pitch:ia(e.root,n,b,e.octave-1),start:x,duration:4*i-.01,velocity:70+Math.floor(t()*20)});const S=m[0];for(let b=0;b<4;b++){const w=b===2?S+(t()>.5?2:0):S;h.push({id:lr(),pitch:ia(e.root,n,w,e.octave-2),start:x+b*i,duration:i*.9,velocity:80+Math.floor(t()*30)})}for(let b=0;b<c;b++){if(t()>e.density)continue;const w=x+b*l,N=t()>.8?t()>.5?2:-2:t()>.5?1:-1;y=Math.max(-3,Math.min(n.length+3,y+N));const R=1+Math.floor(t()*3);d.push({id:lr(),pitch:ia(e.root,n,y,e.octave),start:w,duration:R*l*.95,velocity:85+Math.floor(t()*30)})}for(const b of s)p.push({id:lr(),pitch:b.pitch,start:x+b.step*l,duration:l*.8,velocity:b.vel+Math.floor(t()*10-5)})}return{melody:d,bass:h,chords:f,drums:p,config:e}}const pm=Object.keys(ja),fm=Object.keys(Ma),mm=Object.keys(Ra),gm=Gl;function Ke(e,t,n){return{cc:e,paramId:n,label:`Knob ${t}`,controlType:"knob",min:0,max:127,inverted:!1}}function Vn(e,t,n){return{cc:e,paramId:n,label:t,controlType:"fader",min:0,max:127,inverted:!1}}function an(e,t,n){return{cc:e,paramId:n,label:t,controlType:"button",min:0,max:127,inverted:!1}}const Wl={id:"oxygen25",name:"M-Audio Oxygen 25 (MkIV)",deviceMatch:"OXYGEN",mappings:[Ke(21,1,"mixer.volume"),Ke(22,2,"mixer.pan"),Ke(23,3,"fx.reverb"),Ke(24,4,"fx.delay"),Ke(25,5,"fx.chorus"),Ke(26,6,"fx.filter"),Ke(27,7,"fx.drive"),Ke(28,8,"fx.eq"),Vn(7,"Master Fader","mixer.master"),an(115,"Play","transport.play"),an(114,"Stop","transport.stop"),an(117,"Record","transport.record"),an(112,"Rewind","transport.rewind"),an(113,"Forward","transport.forward"),an(116,"Loop","transport.loop")]},Ul={id:"mpk-mini",name:"Akai MPK Mini",deviceMatch:"MPK",mappings:[Ke(1,1,"mixer.volume"),Ke(2,2,"mixer.pan"),Ke(3,3,"fx.reverb"),Ke(4,4,"fx.delay"),Ke(5,5,"fx.chorus"),Ke(6,6,"fx.filter"),Ke(7,7,"fx.drive"),Ke(8,8,"fx.eq")]},Vl={id:"minilab",name:"Arturia MiniLab",deviceMatch:"Arturia MiniLab",mappings:[Ke(7,1,"mixer.volume"),Ke(74,2,"mixer.pan"),Ke(71,3,"fx.reverb"),Ke(76,4,"fx.delay"),Ke(77,5,"fx.chorus"),Ke(93,6,"fx.filter"),Ke(73,7,"fx.drive"),Ke(75,8,"fx.eq"),Vn(1,"Mod Wheel","mixer.master")]},ql={id:"launch-control-xl",name:"Novation Launch Control XL",deviceMatch:"Launch Control",mappings:[...Array.from({length:8},(e,t)=>Ke(13+t,t+1,`mixer.send${t+1}`)),...Array.from({length:8},(e,t)=>Vn(77+t,`Fader ${t+1}`,`mixer.track${t+1}`))]},as={id:"generic",name:"Generic MIDI Controller",deviceMatch:"",mappings:[Ke(1,1,"mixer.modWheel"),Vn(7,"Volume","mixer.volume"),Ke(10,2,"mixer.pan"),Vn(11,"Expression","mixer.expression")]},Hl=[Wl,Ul,Vl,ql,as];class ym{constructor(t){this.ccMap=new Map,this.onChange=null,this.profile=t??as,this.rebuildMap()}setProfile(t){this.profile=t,this.rebuildMap()}getProfile(){return this.profile}autoDetect(t){const n=t.toUpperCase(),a=Hl.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,l=a.min+i*(a.max-a.min),o={paramId:a.paramId,label:a.label,rawValue:n,scaledValue:l,normalizedValue:i};return(c=this.onChange)==null||c.call(this,o),o}setMapping(t,n,a,s="knob"){const i={cc:t,paramId:n,label:a,controlType:s,min:0,max:127,inverted:!1},l=this.profile.mappings.findIndex(o=>o.cc===t);l>=0?this.profile.mappings[l]=i:this.profile.mappings.push(i),this.ccMap.set(t,i)}removeMapping(t){this.profile.mappings=this.profile.mappings.filter(n=>n.cc!==t),this.ccMap.delete(t)}getMappings(){return[...this.profile.mappings]}getMapping(t){return this.ccMap.get(t)}exportConfig(){return{...this.profile,mappings:this.profile.mappings.map(t=>({...t}))}}importConfig(t){this.profile={...t,mappings:t.mappings.map(n=>({...n}))},this.rebuildMap()}static createCustomProfile(t,n){return{id:`custom-${t.toLowerCase().replace(/\s+/g,"-")}`,name:t,deviceMatch:"",mappings:n.map(a=>({...a,min:0,max:127,inverted:!1}))}}rebuildMap(){this.ccMap.clear();for(const t of this.profile.mappings)this.ccMap.set(t.cc,t)}}function ss(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function Xt(e="New Pattern",t=16,n=120){return{name:e,length:t,steps:Array.from({length:t},()=>ss()),bpm:n,swing:0,rootNote:60}}function Kl(e,t){const n=e.steps.map((a,s)=>s===t?{...a,active:!a.active}:a);return{...e,steps:n}}function Yl(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 Zl(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 Xl(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 Ql(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 Jl(e,t){const n=e.steps.map((a,s)=>s===t?{...a,slide:!a.slide}:a);return{...e,steps:n}}function ec(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 tc(e){return{...e,steps:[...e.steps].reverse()}}function nc(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 rc(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 ac(e){return{...e,steps:e.steps.map(()=>ss(e.rootNote))}}function is(e,t=4){return 60/e/t}function sc(e,t,n=0,a=4){const s=is(t,a),i=e*s;return e%2===1&&n>0?i+s*n*.5:i}function ic(e){return e.active&&Math.random()<e.probability}function vm(){const e=Xt("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function bm(){const e=Xt("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function xm(){const e=Xt("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 Sm(e=60){const t=Xt("Arp",16,120);return[0,4,7,12,7,4,0,-5,0,3,7,12,7,3,0,-5].forEach((a,s)=>{t.steps[s]={...t.steps[s],active:!0,note:e+a,velocity:90,gate:.5}}),{...t,rootNote:e}}function wm(e=36){const t=Xt("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 km(e){return JSON.stringify(e,null,2)}function Cm(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function jm(e={}){const{onTrigger:t,onLFOOutput:n,initialPattern:a}=e,[s,i]=u.useState(()=>a??Xt()),[l,o]=u.useState(-1),[c,d]=u.useState(!1),[h,f]=u.useState([]),p=u.useRef(s);p.current=s;const y=u.useRef(h);y.current=h;const g=u.useRef(c);g.current=c;const x=u.useRef(t);x.current=t;const v=u.useRef(n);v.current=n;const m=u.useRef(null),S=u.useRef(0),b=u.useRef(0),w=u.useCallback(()=>{var V,Q;if(!g.current)return;const k=p.current,W=S.current%k.length,A=k.steps[W];if(ic(A)){const le=sc(S.current,k.bpm,k.swing);(V=x.current)==null||V.call(x,A,W,le)}const L=(Date.now()-b.current)/1e3;for(let le=0;le<y.current.length;le++){const oe=y.current[le];if(oe.enabled&&oe.targetCC!==void 0){const ne=Ia(oe,L,k.bpm);(Q=v.current)==null||Q.call(v,le,oe.targetCC,ne)}}o(W),S.current++;const G=is(k.bpm)*1e3,F=W%2===0?0:G*k.swing*.5;m.current=setTimeout(w,G+F)},[]),N=u.useCallback(()=>{g.current||(S.current=0,b.current=Date.now(),d(!0),g.current=!0,w())},[w]),R=u.useCallback(()=>{d(!1),g.current=!1,o(-1),m.current&&(clearTimeout(m.current),m.current=null)},[]),P=u.useCallback(()=>{g.current?R():N()},[N,R]);u.useEffect(()=>()=>{m.current&&clearTimeout(m.current)},[]);const j=u.useCallback(k=>i(W=>Kl(W,k)),[]),M=u.useCallback((k,W)=>i(A=>Yl(A,k,W)),[]),I=u.useCallback((k,W)=>i(A=>Zl(A,k,W)),[]),T=u.useCallback((k,W)=>i(A=>Xl(A,k,W)),[]),E=u.useCallback((k,W)=>i(A=>Ql(A,k,W)),[]),_=u.useCallback(k=>i(W=>Jl(W,k)),[]),D=u.useCallback(k=>i(W=>ec(W,k)),[]),q=u.useCallback(()=>i(k=>tc(k)),[]),te=u.useCallback(k=>i(W=>nc(W,k)),[]),z=u.useCallback((k,W)=>i(A=>rc(A,k,W)),[]),U=u.useCallback(()=>i(k=>ac(k)),[]),Z=u.useCallback(k=>i(W=>({...W,bpm:Math.max(20,Math.min(300,k))})),[]),ae=u.useCallback(k=>i(W=>({...W,swing:Math.max(0,Math.min(1,k))})),[]),Y=u.useCallback(k=>{i(W=>{if(W.length===k)return W;const A=Array.from({length:k},(L,G)=>G<W.steps.length?W.steps[G]:{active:!1,note:W.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...W,length:k,steps:A}})},[]),O=u.useCallback(k=>{f(W=>[...W,k??zr()])},[]),C=u.useCallback(k=>{f(W=>W.filter((A,L)=>L!==k))},[]),$=u.useCallback((k,W)=>{f(A=>A.map((L,G)=>G===k?{...L,...W}:L))},[]);return{pattern:s,currentStep:l,playing:c,lfos:h,play:N,stop:R,togglePlayback:P,toggle:j,setNote:M,setVelocity:I,setGate:T,setProbability:E,toggleSlide:_,transpose:D,reverse:q,shift:te,randomizeVel:z,clear:U,setPattern:i,setBpm:Z,setSwing:ae,setLength:Y,addLFO:O,removeLFO:C,updateLFO:$}}function os(e){const t=u.useRef(null),n=u.useRef(new Map),a=u.useRef(1),s=u.useCallback(()=>{if(!t.current){const l=e();l.onmessage=o=>{const{id:c}=o.data,d=n.current.get(c);d&&(n.current.delete(c),d.resolve(o.data))},l.onerror=o=>{console.error("[useWorker] Worker error:",o.message);for(const[c,d]of n.current)d.reject(new Error(`Worker error: ${o.message}`));n.current.clear(),l.terminate(),t.current=null},t.current=l}return t.current},[e]);return u.useEffect(()=>{const l=n.current;return()=>{var o;(o=t.current)==null||o.terminate(),t.current=null;for(const[,c]of l)c.reject(new Error("Worker terminated on unmount"));l.clear()}},[]),u.useCallback((l,o)=>{const c=a.current++,d=s();return new Promise((h,f)=>{n.current.set(c,{resolve:h,reject:f}),d.postMessage({...l,id:c},o??[])})},[s])}function Mm(){const e=os(u.useCallback(()=>new Worker(new URL("/assets/pitchWorker-BgAp5Z97.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:bt&&bt.tagName.toUpperCase()==="SCRIPT"&&bt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return u.useCallback(async(n,a,s=.01)=>(await e({buffer:n,sampleRate:a,rmsThreshold:s})).hz,[e])}function Rm(){const e=os(u.useCallback(()=>new Worker(new URL("/assets/scoringWorker-3JjtDDtu.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:bt&&bt.tagName.toUpperCase()==="SCRIPT"&&bt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return u.useCallback(async(n,a,s)=>(await e({notes:n,points:a,params:s})).result,[e])}const Nm={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function oc(){return`
|
|
71
|
+
Tame Impala - Let It Happen`,rows:10,style:{width:"100%",padding:12,borderRadius:6,border:"1px solid var(--nice-border, #e2e8f0)",fontFamily:"monospace",fontSize:13,resize:"vertical"}}),r.jsx("button",{style:{...Ln,opacity:Y.trim().length===0?.5:1},disabled:Y.trim().length===0,onClick:()=>E(Y),type:"button",children:u("importWizard.parseTracks","Parse Tracks")})]}),(g!==99||k.length>0)&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[r.jsxs("p",{style:{margin:0,fontWeight:600},children:[b==null?void 0:b.name," — ",w.size,"/",k.length," ",u("importWizard.selected","selected")]}),r.jsx("button",{style:sr,onClick:C,type:"button",children:w.size===k.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:k.map(D=>{const J=w.has(D.externalId);return r.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-border, #e2e8f0)",opacity:J?1:.5,cursor:"pointer"},onClick:()=>W(D.externalId),children:[r.jsx("td",{style:{padding:"6px 8px"},children:r.jsx("input",{type:"checkbox",checked:J,readOnly:!0})}),r.jsx("td",{style:{padding:"6px 8px",fontWeight:500},children:D.title}),r.jsx("td",{style:{padding:"6px 8px",color:"var(--nice-text-dim, #64748b)"},children:D.artist}),r.jsx("td",{style:{padding:"6px 8px",color:"var(--nice-text-dim, #64748b)"},children:D.album??"—"}),r.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--nice-text-dim, #64748b)"},children:dm(D.duration)})]},D.externalId)})})]})}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:r.jsxs("button",{style:{...Ln,opacity:w.size===0?.5:1},disabled:w.size===0,onClick:()=>p("options"),type:"button",children:[u("importWizard.next","Next")," ",r.jsx(F.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:_.mergeTags,onChange:D=>ee(J=>({...J,mergeTags:D.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:_.mergeFolders,onChange:D=>ee(J=>({...J,mergeFolders:D.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:_.overwriteExisting,onChange:D=>ee(J=>({...J,overwriteExisting:D.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:_.targetFolderId??"",onChange:D=>ee(J=>({...J,targetFolderId:D.target.value||void 0})),children:[r.jsx("option",{value:"",children:u("importWizard.root","— Root —")}),l.map(D=>r.jsx("option",{value:D.id,children:D.name},D.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(w.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:sr,onClick:B,type:"button",children:[r.jsx(F.NtdArrowLeft,{size:12})," ",u("importWizard.back","Back")]}),r.jsx("button",{style:Ln,onClick:$,type:"button",children:u("importWizard.startImport","Start Import")})]})]}),re=()=>{const D=T?Math.round(T.imported/T.total*100):0;return r.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[r.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:u("importWizard.importing","Importing…")}),r.jsx("div",{style:{height:8,borderRadius:4,background:"var(--nice-border, #e2e8f0)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${D}%`,background:"var(--nice-color-accent, #6366f1)",borderRadius:4,transition:"width 0.3s"}})}),T&&r.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-dim, #64748b)"},children:[T.imported," / ",T.total," ",u("importWizard.tracks","tracks"),T.currentTrack&&r.jsxs("div",{style:{marginTop:4},children:[r.jsx(F.NtdMusic,{size:12})," ",T.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(F.NtdCheck,{size:48})}),r.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:u("importWizard.complete","Import Complete")}),A&&r.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[r.jsxs("div",{children:[r.jsx("strong",{children:A.imported})," ",u("importWizard.imported","imported")]}),A.skipped>0&&r.jsxs("div",{style:{color:"var(--nice-color-warning, #f59e0b)"},children:[A.skipped," ",u("importWizard.skipped","skipped (duplicates)")]}),A.failed>0&&r.jsxs("div",{style:{color:"var(--nice-color-error, #ef4444)"},children:[A.failed," ",u("importWizard.failed","failed")]}),A.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:A.failedTracks.map((D,J)=>r.jsx("li",{children:D},J))})]})]}),r.jsx("button",{style:Ln,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:im,children:[H(),r.jsxs("div",{style:om,children:[r.jsxs("h2",{style:{margin:0,fontSize:18},children:[u("importWizard.title","Import Playlist")," — ",se[h]]}),S&&r.jsxs("button",{style:sr,onClick:B,type:"button",children:[r.jsx(F.NtdArrowLeft,{size:12})," ",u("importWizard.back","Back")]}),h==="connect"&&r.jsx("button",{style:sr,onClick:o,type:"button","aria-label":u("importWizard.close","Close"),title:u("importWizard.close","Close"),children:r.jsx(F.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"&&z(),h==="browse"&&Z(),h==="tracks"&&q(),h==="options"&&X(),h==="importing"&&re(),h==="done"&&oe()]})},hm=[{id:"concert-harp",name:"Concert Harp",description:"Warm concert harp",icon:"music",dir:"concert-harp",attribution:"ConcertHarp SoundFont — source: musical-artifacts.com/artifacts/375"},{id:"celtic-harp",name:"Celtic Harp",description:"Bright celtic harp",icon:"leaf",dir:"celtic-harp"},{id:"triangle",name:"Triangle",description:"Metallic percussion triangle",icon:"triangle",dir:"triangle",attribution:"Triangle SoundFont — source: polyphone.io/en/soundfonts/unpitched-percussion/298-triangle"},{id:"synth",name:"Celesta",description:"Synthesized celesta / music-box",icon:"sparkle",dir:"synth"},{id:"none",name:"Silent",description:"No sound on click",icon:"volumeMute",dir:null}],pm="concert-harp",ns=Object.fromEntries(hm.map(e=>[e.id,e])),fm="nice2dev-note-sound-set";function Tl(){try{const e=localStorage.getItem(fm);if(e&&ns[e])return e}catch{}return pm}const Ir=["quarter","eighth","sixteenth","beamed"];function Pl(e,t,n){const a=n*.2,s=n*.15,i=Math.max(1,n*.07),o=n*.72,l=n*.34,c=new Path2D,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 pi(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function El(e){if(!e)return null;const t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle=e;const n=t.fillStyle;if(n.startsWith("#")){const s=parseInt(n.slice(1),16);return{r:s>>16&255,g:s>>8&255,b:s&255}}const a=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return a?{r:+a[1],g:+a[2],b:+a[3]}:null}function aa(e,t){const n=El(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function mm(e){const t=El(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function $l(){const e=pi("--text-primary")||ke.resolveCssColor("var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))"),t=pi("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",s=mm(e)<.45;return{base:aa(e,.92),staffLine:aa(e,.22),outline:ke.resolveCssColor(s?"var(--nice-overlay-light-75, rgba(255, 255, 255, 0.75))":"var(--nice-overlay-55, rgba(0, 0, 0, 0.55))"),accents:[aa(t,.95)],isDark:n,notesDark:s}}const Gr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),Al=46,St=5,mr=4,gm=(Al-(St-1)*mr)/2,ym=6,vm=18,bm=110,xm=50,Wr=Gr?xm:bm,Sm=Gr?4:2,km=Gr?2:4,fi=Gr?1:0,wm=180,mi=2.8,gi=40,Cm=14,yi=1.2,jm=16,sa=[64,67,71,74,77],ln=64,_n=77;function Mm(e){const t=Math.max(0,Math.min(St-1,e)),n=Math.floor(t),a=Math.min(n+1,St-1),s=t-n;return Math.round(sa[n]+(sa[a]-sa[n])*s)}function Rm(e){return(Math.max(ln-1*(_n-ln)/(St-1),Math.min(_n+1*(_n-ln)/(St-1),e))-ln)/(_n-ln)*(St-1)}const vi=2.5,bi=.72,Nm=.55,zn=new Map;let gr=null;async function Tm(e){const t=e??Tl(),n=ns[t];if(!n||!n.dir){zn.clear(),gr=t;return}if(gr===t&&zn.size>0)return;zn.clear(),gr=t;const a=qn(),s=[];for(let i=ln;i<=_n;i++)s.push(fetch(`/assets/soundfonts/notes/${n.dir}/note-${i}.mp3`).then(o=>o.arrayBuffer()).then(o=>a.decodeAudioData(o)).then(o=>{zn.set(i,o)}).catch(()=>{}));await Promise.all(s)}function xi(e){const t=zn.get(e);if(!t)return;const n=qn(),a=n.createBufferSource();a.buffer=t;const s=n.createGain();s.gain.value=.7,a.connect(s).connect(n.destination),a.start()}function Pm(e){return()=>{e|=0,e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function Em(e){const t=Pm(42),n=[];for(let a=0;a<e;a++){const i=t()<.15?0:-1;n.push({x:t(),lineIdx:t()*(St+1)-.5,shape:Ir[Math.floor(t()*Ir.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:i})}return n.sort((a,s)=>a.x-s.x),n}const ut=Em(Wr),Cn=new Float32Array(Wr),ir=new Float32Array(Wr),Dn=new Float32Array(Wr);let wa=!1;const $m=(St-1)/2;function Am(){if(!wa){wa=!0;for(let e=0;e<ut.length;e++)Dn[e]=ut[e].lineIdx}}let Ca=[],Si="";function Im(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function Lm(e){const t=Im(e);t===Si&&Ca.length===ut.length||(Si=t,Ca=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],Pl(o,n.shape,n.size*1.3),{canvas:i,ox:a,oy:a}}))}function _m({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,k)=>{const v=gm+b*mr,w=f/k*Math.PI*2;return v+Math.sin(w)*ym},[]),y=d.useCallback(b=>{const f=n.current;if(!f)return;if(c.current++,fi>0&&c.current%(fi+1)!==0){i.current=b,a.current=requestAnimationFrame(y);return}const k=f.getContext("2d");if(!k)return;const v=Math.min(window.devicePixelRatio||1,km),w=f.getBoundingClientRect(),R=w.width,M=w.height;(f.width!==Math.round(R*v)||f.height!==Math.round(M*v))&&(f.width=Math.round(R*v),f.height=Math.round(M*v),k.setTransform(v,0,0,v,0,0));const j=i.current?(b-i.current)/1e3:0;i.current=b,s.current=(s.current+vm*j)%R,k.clearRect(0,0,R,M),l.current++,(!o.current||l.current%60===0)&&(o.current=$l());const T=o.current;Lm(T),k.strokeStyle=T.staffLine,k.lineWidth=.7;for(let L=0;L<St;L++){k.beginPath();for(let N=0;N<=R;N+=Sm){const _=g(L,N,R);N===0?k.moveTo(N,_):k.lineTo(N,_)}k.stroke()}const P=s.current,A=(e==null?void 0:e.current)??null;if(A!==null){Am();const L=Rm(A),N=vi*j;for(let _=0;_<ut.length;_++){const Y=(ut[_].lineIdx-$m)*Nm,U=L*bi+(L+Y)*(1-bi)-Dn[_];Dn[_]+=U>0?Math.min(N,U):Math.max(-N,U)}}else if(wa){const L=vi*.4*j;for(let N=0;N<ut.length;N++){const ee=ut[N].lineIdx-Dn[N];Dn[N]+=ee>0?Math.min(L,ee):Math.max(-L,ee)}}const I=u.current;I&&(I.timer-=j,I.timer<=0&&(u.current=null));for(let L=0;L<ut.length;L++){const N=ut[L];if(ir[L]>0){ir[L]-=j;const Y=Math.max(0,ir[L]/mi);Cn[L]+=wm*Y*j,Cn[L]>R&&(Cn[L]-=R)}const _=Ca[L];if(!_)continue;const ee=N.lineIdx;for(let Y=0;Y<2;Y++){let U=((N.x*R-P-Cn[L]+Y*R)%R+R)%R;const V=g(Math.max(0,Math.min(St-1,Math.round(ee))),U,R),K=(ee-Math.round(ee))*mr;let G=V+K;if(I&&I.timer>0){const W=U-I.x,C=G-I.y,$=Math.sqrt(W*W+C*C);if($<gi&&$>.1){const S=I.timer/yi,B=Cm*(1-$/gi)*S;U+=W/$*B,G+=C/$*B}}k.drawImage(_.canvas,U-_.ox,G-_.oy)}}a.current=requestAnimationFrame(y)},[g,e]),m=d.useCallback(b=>{const f=n.current;if(!f)return;const k=f.getBoundingClientRect(),v=b.clientX-k.left,w=b.clientY-k.top,R=k.width,M=s.current;let j=1/0,T=-1;for(let P=0;P<ut.length;P++){const A=ut[P],L=((A.x*R-M-Cn[P])%R+R)%R,N=g(Math.max(0,Math.min(St-1,Math.round(A.lineIdx))),L,R),_=(A.lineIdx-Math.round(A.lineIdx))*mr,ee=N+_,Y=L-v,O=ee-w,U=Y*Y+O*O;U<j&&(j=U,T=P)}if(T>=0&&Math.sqrt(j)<jm){ir[T]=mi;const P=ut[T],A=Mm(P.lineIdx);try{Yt();const I=Tl(),L=ns[I];L!=null&&L.dir&&(gr!==I||!p.current?(p.current=!0,Tm(I).then(()=>xi(A))):xi(A))}catch{}}u.current={x:v,y:w,timer:yi}},[g]),x=d.useCallback(b=>{const f=n.current;if(!f)return;const k=f.getBoundingClientRect(),v=b.clientX-k.left,w=b.clientY-k.top;h.current={x:v,y:w},u.current&&u.current.timer>0&&(u.current.x=v,u.current.y=w)},[]);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:Al,marginBottom:5,cursor:"pointer",background:"transparent"}})}const zm=14,Dm=.9,Fm=320,Om=160,Bm=6,ki=8,Gm=14;function Wm(){const{t:e}=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<zm;g++){const y=Math.random()*Math.PI*2,m=Om*(.4+Math.random()*.6),x=Dm*(.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)*Bm*2,size:ki+Math.random()*(Gm-ki),shape:Ir[Math.floor(Math.random()*Ir.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=$l());const f=o.current;if(navigator.getGamepads){const v=navigator.getGamepads();for(let w=0;w<v.length;w++){const R=v[w];if(R)for(let M=0;M<R.buttons.length;M++){const j=w*100+M,T=R.buttons[M].pressed;T&&!i.current[j]&&c(m/2,x/2),i.current[j]=T}}}const k=[];for(const v of n.current){if(v.life-=b,v.life<=0)continue;v.vy+=Fm*b,v.x+=v.vx*b,v.y+=v.vy*b,v.rot+=v.vr*b;const w=Math.max(0,v.life/v.maxLife),R=.5+.5*w;g.save(),g.globalAlpha=w,g.translate(v.x,v.y),g.rotate(v.rot),g.lineWidth=1.4,g.strokeStyle=f.notesDark?`rgba(255,255,255,${w*.8})`:`rgba(0,0,0,${w*.55})`;const M=v.colorIdx<0?f.base:f.accents[v.colorIdx%f.accents.length];g.fillStyle=M.replace(/[\d.]+\)$/,`${w})`),Pl(g,v.shape,v.size*R*1.3),g.restore(),k.push(v)}n.current=k,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 yr={type:"gain",enabled:!0,mix:1,gain:0},Fn={type:"compressor",enabled:!0,mix:1,threshold:-24,ratio:4,attack:10,release:100,knee:6,makeupGain:0},On={type:"reverb",enabled:!0,mix:.3,decay:2,preDelay:10,damping:.5,roomSize:.5},Bn={type:"delay",enabled:!0,mix:.3,time:250,feedback:.4,pingPong:!1,highCut:8e3},vr={type:"chorus",enabled:!0,mix:.5,rate:1.5,depth:.5,delay:7,voices:3},br={type:"eq",enabled:!0,mix:1,bands:[{frequency:60,gain:0,q:1,type:"lowshelf"},{frequency:250,gain:0,q:1,type:"peaking"},{frequency:1e3,gain:0,q:1,type:"peaking"},{frequency:4e3,gain:0,q:1,type:"peaking"},{frequency:12e3,gain:0,q:1,type:"highshelf"}]},xr={type:"filter",enabled:!0,mix:1,filterType:"lowpass",frequency:1e3,q:1,gain:0},Sr={type:"distortion",enabled:!0,mix:.5,drive:.5,tone:.5,curve:"soft"},kr={type:"tremolo",enabled:!0,mix:1,rate:5,depth:.5,waveform:"sine"},wr={type:"phaser",enabled:!0,mix:.5,rate:.5,depth:.5,feedback:.5,stages:4,frequency:1e3},Vm=(function(){return{gain:{unity:{...yr,gain:0},boost:{...yr,gain:6},cut:{...yr,gain:-6}},compressor:{gentle:{...Fn,threshold:-20,ratio:2,attack:30,release:200},moderate:{...Fn,threshold:-24,ratio:4,attack:10,release:100},aggressive:{...Fn,threshold:-30,ratio:8,attack:1,release:50},limiter:{...Fn,threshold:-3,ratio:20,attack:.1,release:100}},reverb:{small_room:{...On,decay:.5,roomSize:.2,damping:.7},large_hall:{...On,decay:3,roomSize:.8,damping:.3},plate:{...On,decay:1.5,roomSize:.5,damping:.4},cathedral:{...On,decay:5,roomSize:.9,damping:.2,mix:.4}},delay:{slapback:{...Bn,time:80,feedback:.1,mix:.3},quarter_note:{...Bn,time:500,feedback:.4,mix:.3},dotted_eighth:{...Bn,time:375,feedback:.5,mix:.3},long_ambient:{...Bn,time:750,feedback:.6,highCut:3e3,mix:.4}},chorus:{subtle:{...vr,rate:.5,depth:.2,voices:2,mix:.3},vintage:{...vr,rate:1,depth:.4,voices:2,delay:10,mix:.4},ensemble:{...vr,rate:2,depth:.6,voices:4,mix:.5}},eq:{vocal_presence:{...br,bands:[{frequency:80,gain:-3,q:1,type:"highpass"},{frequency:250,gain:-2,q:1,type:"peaking"},{frequency:3e3,gain:3,q:1.5,type:"peaking"},{frequency:8e3,gain:2,q:1,type:"highshelf"}]},bass_boost:{...br,bands:[{frequency:60,gain:6,q:1,type:"lowshelf"},{frequency:200,gain:2,q:1,type:"peaking"}]},brightness:{...br,bands:[{frequency:4e3,gain:3,q:1,type:"peaking"},{frequency:1e4,gain:4,q:1,type:"highshelf"}]}},filter:{low_pass_warm:{...xr,filterType:"lowpass",frequency:2e3,q:.7},high_pass_clean:{...xr,filterType:"highpass",frequency:100,q:.7},telephone:{...xr,filterType:"bandpass",frequency:1500,q:2}},distortion:{overdrive:{...Sr,drive:.3,tone:.6,curve:"soft",mix:.7},crunch:{...Sr,drive:.5,tone:.5,curve:"tube",mix:.8},fuzz:{...Sr,drive:.8,tone:.4,curve:"fuzz",mix:1}},tremolo:{slow:{...kr,rate:3,depth:.4,waveform:"sine"},fast:{...kr,rate:8,depth:.6,waveform:"sine"},choppy:{...kr,rate:6,depth:.9,waveform:"square"}},phaser:{subtle:{...wr,rate:.3,depth:.3,feedback:.3,stages:4},jet:{...wr,rate:.1,depth:.8,feedback:.7,stages:8},rotary:{...wr,rate:1,depth:.5,feedback:.4,stages:6}}}})();function wi(e){return Math.pow(10,e/20)}function Um(e,t,n,a){const s=e.sampleRate,i=Math.floor(s*t),o=e.createBuffer(2,i,s);for(let l=0;l<2;l++){const c=o.getChannelData(l);for(let 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 qm(e,t){const a=new Float32Array(44100),s=Math.PI/180;for(let i=0;i<44100;i++){const o=i*2/44100-1;switch(t){case"soft":a[i]=(3+e*10)*o*20*s/(Math.PI+e*10*Math.abs(o));break;case"hard":a[i]=Math.tanh(o*(1+e*5));break;case"fuzz":a[i]=Math.sign(o)*Math.pow(Math.abs(o),1/(1+e*3));break;case"tube":o>=0?a[i]=1-Math.pow(1-o,1+e*2):a[i]=-(1-Math.pow(1+o,1+e*2));break}}return a}class Hm{constructor(t){this.effects=[],this.bypass=!1,this.audioContext=t,this.inputNode=t.createGain(),this.outputNode=t.createGain(),this.inputNode.connect(this.outputNode)}get input(){return this.inputNode}get output(){return this.outputNode}addEffect(t,n){const a=`effect_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=this.createEffectInstance(a,t);return n!==void 0&&n>=0&&n<this.effects.length?this.effects.splice(n,0,s):this.effects.push(s),this.reconnectChain(),a}removeEffect(t){const n=this.effects.findIndex(s=>s.id===t);if(n===-1)return!1;const a=this.effects[n];for(const s of a.nodes)s.disconnect();return this.effects.splice(n,1),this.reconnectChain(),!0}updateEffect(t,n){const a=this.effects.find(l=>l.id===t);if(!a)return!1;const s={...a.params,...n},i=this.effects.indexOf(a);for(const l of a.nodes)l.disconnect();const o=this.createEffectInstance(t,s);return this.effects[i]=o,this.reconnectChain(),!0}reorderEffects(t,n){if(t<0||t>=this.effects.length||n<0||n>=this.effects.length)return!1;const[a]=this.effects.splice(t,1);return this.effects.splice(n,0,a),this.reconnectChain(),!0}setBypass(t){this.bypass=t,this.reconnectChain()}getEffects(){return[...this.effects]}clear(){for(const t of this.effects)for(const n of t.nodes)n.disconnect();this.effects=[],this.reconnectChain()}createEffectInstance(t,n){const{audioContext:a}=this,s=[];let i,o;switch(n.type){case"gain":{const l=a.createGain();l.gain.value=wi(n.gain),s.push(l),i=o=l;break}case"compressor":{const l=a.createDynamicsCompressor();l.threshold.value=n.threshold,l.ratio.value=n.ratio,l.attack.value=n.attack/1e3,l.release.value=n.release/1e3,l.knee.value=n.knee;const c=a.createGain();c.gain.value=wi(n.makeupGain),l.connect(c),s.push(l,c),i=l,o=c;break}case"reverb":{const l=a.createConvolver();l.buffer=Um(a,n.decay,n.decay,n.damping);const c=a.createGain(),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=qm(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 Il={gain:r.jsx(F.NtdVolume,{size:16}),compressor:r.jsx(F.NtdSettings,{size:16}),reverb:r.jsx(F.NtdMountain,{size:16}),delay:r.jsx(F.NtdStopwatch,{size:16}),chorus:r.jsx(F.NtdSparkle,{size:16}),eq:r.jsx(F.NtdBarChart,{size:16}),filter:r.jsx(F.NtdFilter,{size:16}),distortion:r.jsx(F.NtdLightning,{size:16}),tremolo:r.jsx(F.NtdWave,{size:16}),phaser:r.jsx(F.NtdMagicWand,{size:16})},Ll={gain:"Gain",compressor:"Compressor",reverb:"Reverb",delay:"Delay",chorus:"Chorus",eq:"EQ",filter:"Filter",distortion:"Distortion",tremolo:"Tremolo",phaser:"Phaser"},Km={gain:yr,compressor:Fn,reverb:On,delay:Bn,chorus:vr,eq:br,filter:xr,distortion:Sr,tremolo:kr,phaser:wr},Ym=["gain","compressor","reverb","delay","chorus","eq","filter","distortion","tremolo","phaser"],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 k=p.current-f.clientY,v=n-t,R=k/200*v,M=Math.min(n,Math.max(t,g.current+R));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 Zm({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 Xm({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 Qm({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 Jm({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 e0({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:Il[e.type]}),r.jsx("span",{className:"nice-fx-card__title",children:Ll[e.type]}),r.jsx("button",{type:"button",className:`nice-fx-card__toggle ${e.enabled?"nice-fx-card__toggle--active":""}`,onClick:()=>t({...e,enabled:!e.enabled}),title:e.enabled?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(F.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(ke.NiceIcon,{name:"close",size:14})})]}),r.jsx("div",{className:"nice-fx-card__body",children:u})]})}function t0({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 n0({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 r0({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 a0({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 s0({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 i0({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 o0=({audioContext:e,chain:t,effects:n,onChange:a,onChainUpdate:s,maxEffects:i=10,availableEffects:o=Ym,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 Hm(e):null),[e,t]),k=d.useCallback((P,A)=>{const I=[...p];I[P]=A,g(I),a==null||a(I),f&&(s==null||s(f))},[p,a,f,s]),v=d.useCallback(P=>{if(p.length>=i)return;const A={...Km[P]},I=[...p,A];g(I),a==null||a(I),b(!1)},[p,i,a]),w=d.useCallback(P=>{const A=p.filter((I,L)=>L!==P);g(A),a==null||a(A)},[p,a]),R=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],[A]=P.splice(y.dragIndex,1);P.splice(y.dropIndex,0,A),g(P),a==null||a(P)}m({isDragging:!1,dragIndex:-1,dropIndex:-1})},[y,p,a]),j=d.useCallback((P,A)=>{P.preventDefault(),y.isDragging&&m(I=>({...I,dropIndex:A}))},[y.isDragging]),T=(P,A)=>{const I={onRemove:()=>w(A),onDragStart:()=>R(A),onDragEnd:M,isDragTarget:y.dropIndex===A,presets:Vm[P.type]||{},showPresets:l,compact:c};switch(P.type){case"gain":return r.jsx(Zm,{effect:P,onChange:L=>k(A,L),...I},A);case"compressor":return r.jsx(Xm,{effect:P,onChange:L=>k(A,L),...I},A);case"reverb":return r.jsx(Qm,{effect:P,onChange:L=>k(A,L),...I},A);case"delay":return r.jsx(Jm,{effect:P,onChange:L=>k(A,L),...I},A);case"distortion":return r.jsx(e0,{effect:P,onChange:L=>k(A,L),...I},A);case"chorus":return r.jsx(n0,{effect:P,onChange:L=>k(A,L),...I},A);case"eq":return r.jsx(r0,{effect:P,onChange:L=>k(A,L),...I},A);case"filter":return r.jsx(a0,{effect:P,onChange:L=>k(A,L),...I},A);case"tremolo":return r.jsx(s0,{effect:P,onChange:L=>k(A,L),...I},A);case"phaser":return r.jsx(i0,{effect:P,onChange:L=>k(A,L),...I},A);default:return r.jsx(t0,{effect:P,onChange:L=>k(A,L),...I},A)}};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,A)=>r.jsxs("div",{className:"nice-fx-rack__slot",onDragOver:I=>j(I,A),children:[T(P,A),A<p.length-1&&r.jsx("div",{className:"nice-fx-rack__connector","aria-hidden":"true",children:r.jsx(F.NtdArrowRight,{size:14})})]},A))}),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:Il[P]}),r.jsx("span",{className:"nice-fx-rack__add-label",children:Ll[P]})]},P))})]})]})},_l=[{type:"chipmunk",enabled:!1,intensity:60,label:"Chipmunk",icon:"sparkle"},{type:"helium",enabled:!1,intensity:80,label:"Helium",icon:"sparkle"},{type:"deep",enabled:!1,intensity:50,label:"Deep Voice",icon:"music"},{type:"demon",enabled:!1,intensity:70,label:"Demon",icon:"skull"},{type:"robot",enabled:!1,intensity:50,label:"Robot",icon:"robot"},{type:"alien",enabled:!1,intensity:60,label:"Alien",icon:"ghost"},{type:"echo",enabled:!1,intensity:50,label:"Echo",icon:"mountain"},{type:"cave",enabled:!1,intensity:60,label:"Cave",icon:"mountain"},{type:"reverb",enabled:!1,intensity:50,label:"Reverb",icon:"wave"},{type:"chorus",enabled:!1,intensity:50,label:"Chorus",icon:"music"},{type:"flanger",enabled:!1,intensity:50,label:"Flanger",icon:"wave"},{type:"distortion",enabled:!1,intensity:40,label:"Distortion",icon:"lightning"},{type:"telephone",enabled:!1,intensity:80,label:"Telephone",icon:"phone"},{type:"megaphone",enabled:!1,intensity:60,label:"Megaphone",icon:"megaphone"},{type:"radio",enabled:!1,intensity:70,label:"AM Radio",icon:"wave"},{type:"underwater",enabled:!1,intensity:50,label:"Underwater",icon:"wave"},{type:"whisper",enabled:!1,intensity:60,label:"Whisper",icon:"volume-mute"},{type:"tremolo",enabled:!1,intensity:50,label:"Tremolo",icon:"wave"},{type:"autotune",enabled:!1,intensity:60,label:"Auto-Tune",icon:"microphone"},{type:"vocoder",enabled:!1,intensity:50,label:"Vocoder",icon:"volume"}];function Ci(e,t,n){const a=e.sampleRate,s=Math.round(a*t),i=e.createBuffer(2,s,a);for(let o=0;o<2;o++){const l=i.getChannelData(o);for(let c=0;c<s;c++)l[c]=(Math.random()*2-1)*Math.pow(1-c/s,n)}return i}function or(e){const t=Math.max(1,e),n=44100,a=new Float32Array(n),s=Math.PI/180;for(let i=0;i<n;i++){const o=i*2/n-1;a[i]=(3+t)*o*20*s/(Math.PI+t*Math.abs(o))}return a}class zl{constructor(){this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.activeEffects=new Map,this.effectOrder=[],this.monitoring=!0,this._volume=1,this._inputVolume=1,this.started=!1,this.externalStream=!1,this.analyser=null}get isStarted(){return this.started}get context(){return this.audioCtx}get activeEffectTypes(){return[...this.effectOrder]}async start(t){this.started||(this.audioCtx=new AudioContext,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),this.sourceNode=this.audioCtx.createMediaStreamSource(this.mediaStream),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}async startWithStream(t){this.started||(this.externalStream=!0,this.audioCtx=new AudioContext,this.mediaStream=t,this.sourceNode=this.audioCtx.createMediaStreamSource(t),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}stop(){var t,n,a,s,i,o;this.clearAllEffects();try{(t=this.analyser)==null||t.disconnect()}catch{}try{(n=this.outputGain)==null||n.disconnect()}catch{}try{(a=this.inputGain)==null||a.disconnect()}catch{}try{(s=this.sourceNode)==null||s.disconnect()}catch{}try{(i=this.audioCtx)==null||i.close()}catch{}if(!this.externalStream)try{(o=this.mediaStream)==null||o.getTracks().forEach(l=>l.stop())}catch{}this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.analyser=null,this.started=!1}setMonitoring(t){this.monitoring=t,this.outputGain&&(this.outputGain.gain.value=t?this._volume:0)}setVolume(t){this._volume=Math.max(0,Math.min(2,t)),this.outputGain&&this.monitoring&&(this.outputGain.gain.value=this._volume)}setInputGain(t){this._inputVolume=Math.max(0,Math.min(3,t)),this.inputGain&&(this.inputGain.gain.value=this._inputVolume)}getLevel(){if(!this.analyser)return 0;const t=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(t);let n=0;for(let a=0;a<t.length;a++){const s=(t[a]-128)/128;n+=s*s}return Math.sqrt(n/t.length)}addEffect(t,n=50){if(!this.audioCtx||!this.inputGain||!this.outputGain||this.activeEffects.has(t))return;const a=this.buildEffectChain(t,n);a&&(this.activeEffects.set(t,a),this.effectOrder.push(t),this.reconnectChain())}removeEffect(t){const n=this.activeEffects.get(t);if(n){for(const a of n.nodes)try{a.disconnect()}catch{}this.activeEffects.delete(t),this.effectOrder=this.effectOrder.filter(a=>a!==t),this.reconnectChain()}}toggleEffect(t,n=50){return this.activeEffects.has(t)?(this.removeEffect(t),!1):(this.addEffect(t,n),!0)}updateIntensity(t,n){this.activeEffects.has(t)&&(this.removeEffect(t),this.addEffect(t,n))}clearAllEffects(){for(const[t]of this.activeEffects){const n=this.activeEffects.get(t);if(n)for(const a of n.nodes)try{a.disconnect()}catch{}}this.activeEffects.clear(),this.effectOrder=[],this.reconnectChain()}reconnectChain(){if(!this.inputGain||!this.outputGain)return;try{this.inputGain.disconnect()}catch{}for(const[,n]of this.activeEffects)try{n.output.disconnect()}catch{}if(this.effectOrder.length===0){this.inputGain.connect(this.outputGain);return}let t=this.inputGain;for(const n of this.effectOrder){const a=this.activeEffects.get(n);a&&(t.connect(a.input),t=a.output)}t.connect(this.outputGain)}buildEffectChain(t,n){const a=this.audioCtx,s=n/100;switch(t){case"chipmunk":return this.buildPitchShift(a,1+s*.8,s);case"helium":return this.buildPitchShift(a,1.5+s*1,s);case"deep":return this.buildPitchShift(a,1/(1+s*.5),s);case"demon":return this.buildDemon(a,s);case"robot":return this.buildRobot(a,s);case"alien":return this.buildAlien(a,s);case"echo":return this.buildDelay(a,.15+s*.35,.3+s*.4,s);case"cave":return this.buildCave(a,s);case"reverb":return this.buildReverb(a,1.5+s*3,2+s*4,s);case"chorus":return this.buildChorus(a,s);case"flanger":return this.buildFlanger(a,s);case"distortion":return this.buildDistortion(a,20+s*100,s);case"telephone":return this.buildBandpass(a,400,3500,s);case"megaphone":return this.buildMegaphone(a,s);case"radio":return this.buildRadio(a,s);case"underwater":return this.buildUnderwater(a,s);case"whisper":return this.buildWhisper(a,s);case"tremolo":return this.buildTremolo(a,s);case"autotune":return this.buildAutotune(a,s);case"vocoder":return this.buildVocoder(a,s);default:return null}}buildPitchShift(t,n,a){const s=t.createGain();s.gain.value=1;const i=t.createGain();i.gain.value=1;const o=t.createGain();o.gain.value=.7+a*.3;const l=t.createGain();l.gain.value=1-a*.5;const c=t.createDelay(1),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 k=t.createGain();return k.gain.value=.5,s.connect(c),s.connect(u),c.connect(f),u.connect(k),f.connect(o),k.connect(o),s.connect(l),o.connect(i),l.connect(i),h.start(),p.start(),{type:"chipmunk",nodes:[s,c,u,h,p,g,y,f,k,o,l,i],input:s,output:i}}buildRobot(t,n){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=.6+n*.4;const o=t.createGain();o.gain.value=1-n*.6;const l=t.createOscillator();l.type="square",l.frequency.value=50+n*200;const c=t.createGain();return c.gain.value=0,l.connect(c.gain),a.connect(c),c.connect(i),a.connect(o),i.connect(s),o.connect(s),l.start(),{type:"robot",nodes:[a,l,c,i,o,s],input:a,output:s}}buildAlien(t,n){const a=t.createGain(),s=t.createGain(),i=t.createOscillator();i.type="sine",i.frequency.value=300+n*700;const o=t.createGain();o.gain.value=0,i.connect(o.gain),a.connect(o);const l=t.createDelay(.1);l.delayTime.value=.005;const c=t.createOscillator();c.type="sine",c.frequency.value=3+n*10;const 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=Ci(t,2+n*3,3);const g=t.createGain();g.gain.value=.3+n*.3,a.connect(i),i.connect(c),c.connect(i),a.connect(o),o.connect(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=Ci(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=or(n),o.oversample="4x";const l=t.createGain();l.gain.value=.6+a*.4;const c=t.createGain();return c.gain.value=1-a*.4,s.connect(o),o.connect(l),s.connect(c),l.connect(i),c.connect(i),{type:"distortion",nodes:[s,o,l,c,i],input:s,output:i}}buildBandpass(t,n,a,s){const i=t.createGain(),o=t.createGain(),l=t.createBiquadFilter();l.type="highpass",l.frequency.value=n,l.Q.value=.7;const c=t.createBiquadFilter();return c.type="lowpass",c.frequency.value=a,c.Q.value=.7,i.connect(l),l.connect(c),c.connect(o),{type:"telephone",nodes:[i,l,c,o],input:i,output:o}}buildMegaphone(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500;const o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=4e3;const l=t.createWaveShaper();l.curve=or(15+n*30),l.oversample="2x";const c=t.createBiquadFilter();return c.type="peaking",c.frequency.value=2e3,c.gain.value=6+n*6,c.Q.value=1,a.connect(i),i.connect(o),o.connect(l),l.connect(c),c.connect(s),{type:"megaphone",nodes:[a,i,o,l,c,s],input:a,output:s}}buildRadio(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=300+n*200;const o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=3e3-n*500;const l=t.createBiquadFilter();l.type="peaking",l.frequency.value=1500,l.gain.value=8,l.Q.value=2;const c=t.createWaveShaper();return c.curve=or(10),a.connect(i),i.connect(o),o.connect(l),l.connect(c),c.connect(s),{type:"radio",nodes:[a,i,o,l,c,s],input:a,output:s}}buildUnderwater(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="lowpass",i.frequency.value=300+(1-n)*400,i.Q.value=5+n*10;const o=t.createOscillator();o.type="sine",o.frequency.value=.5+n*2;const l=t.createGain();l.gain.value=100+n*200,o.connect(l),l.connect(i.frequency);const c=t.createGain();c.gain.value=.7+n*.3;const 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=or(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 l0={sparkle:F.NtdSparkle,music:F.NtdMusic,skull:F.NtdSkull,robot:F.NtdRobot,ghost:F.NtdGhost,mountain:F.NtdMountain,wave:F.NtdWave,lightning:F.NtdLightning,phone:F.NtdPhone,megaphone:F.NtdMegaphone,"volume-mute":F.NtdVolumeMute,microphone:F.NtdMicrophone,volume:F.NtdVolume},c0=({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(()=>_l.map(O=>({...O}))),[b,f]=d.useState(!0),[k,v]=d.useState(80),[w,R]=d.useState(100),[M,j]=d.useState(0),T=d.useRef(0),P=d.useCallback(()=>{const O=()=>{var U;(U=p.current)!=null&&U.isStarted&&(j(p.current.getLevel()),T.current=requestAnimationFrame(O))};T.current=requestAnimationFrame(O)},[]),A=d.useCallback(()=>{T.current&&cancelAnimationFrame(T.current)},[]),I=d.useCallback(async()=>{const O=new zl;p.current=O;try{t?await O.startWithStream(t):await O.start(e),O.setMonitoring(b),O.setVolume(k/100),O.setInputGain(w/100);for(const U of m)U.enabled&&O.addEffect(U.type,U.intensity);y(!0),P()}catch(U){typeof console<"u"&&console.warn("[VocalEffectsRack] start error",U)}},[e,t,b,k,w,m,P]),L=d.useCallback(()=>{var O;A(),(O=p.current)==null||O.stop(),p.current=null,y(!1),j(0)},[A]);d.useEffect(()=>()=>{var O;A(),(O=p.current)==null||O.stop(),p.current=null},[A]);const N=d.useCallback(O=>{x(U=>U.map(V=>{var G;if(V.type!==O)return V;const K={...V,enabled:!V.enabled};return(G=p.current)!=null&&G.isStarted&&(K.enabled?p.current.addEffect(O,K.intensity):p.current.removeEffect(O)),K}))},[]),_=d.useCallback((O,U)=>{x(V=>V.map(K=>{var G;return K.type!==O?K:(K.enabled&&((G=p.current)!=null&&G.isStarted)&&p.current.updateIntensity(O,U),{...K,intensity:U})}))},[]);d.useEffect(()=>{var O;(O=p.current)==null||O.setVolume(k/100)},[k]),d.useEffect(()=>{var O;(O=p.current)==null||O.setInputGain(w/100)},[w]),d.useEffect(()=>{var O;(O=p.current)==null||O.setMonitoring(b)},[b]);const ee=d.useCallback(()=>{var O;(O=p.current)==null||O.clearAllEffects(),x(U=>U.map(V=>({...V,enabled:!1})))},[]),Y=m.filter(O=>O.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(F.NtdMicrophone,{size:n?16:20})," ",h("vocalEffects.title","Vocal effects")]}),r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[Y>0&&r.jsxs(ie.NiceBadge,{variant:"primary",children:[Y," ",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:I,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(F.NtdVolume,{size:14})," ",h("vocalEffects.monitor","Monitor")]})}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[h("vocalEffects.volume","Vol"),r.jsx("div",{style:{width:100},children:r.jsx(ie.NiceSlider,{value:k,onChange:v,min:0,max:200})}),r.jsxs("span",{style:{minWidth:36,fontSize:12},children:[k,"%"]})]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[h("vocalEffects.gain","Gain"),r.jsx("div",{style:{width:100},children:r.jsx(ie.NiceSlider,{value:w,onChange:R,min:0,max:300})}),r.jsxs("span",{style:{minWidth:36,fontSize:12},children:[w,"%"]})]}),g&&r.jsx("div",{style:{width:80,height:8,borderRadius:4,background:"var(--nice-bg-tertiary)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${Math.min(100,M*300)}%`,background:M>.5?"var(--nice-danger, #ef4444)":M>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})}),Y>0&&r.jsx(ie.NiceButton,{variant:"ghost",size:"sm",onClick:ee,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(O=>r.jsxs("div",{style:{border:O.enabled?"2px solid var(--nice-accent, #3b82f6)":"1px solid var(--nice-border, #e2e8f0)",borderRadius:10,padding:n?"6px 8px":"10px 12px",background:O.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:()=>N(O.type),style:{display:"flex",alignItems:"center",gap:6,width:"100%",marginBottom:O.enabled?6:0,background:"transparent",border:"none",cursor:"pointer",color:"inherit",textAlign:"left"},children:[(()=>{const U=l0[O.icon]??F.NtdMusic;return r.jsx(U,{size:n?18:22})})(),r.jsx("span",{style:{fontSize:n?12:14,fontWeight:O.enabled?700:500,color:O.enabled?"var(--nice-accent, #3b82f6)":"inherit"},children:O.label})]}),O.enabled&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},onClick:U=>U.stopPropagation(),onKeyDown:U=>{U.key!=="Escape"&&U.stopPropagation()},children:[r.jsx("div",{style:{flex:1},children:r.jsx(ie.NiceSlider,{value:O.intensity,onChange:U=>_(O.type,U),min:0,max:100})}),r.jsx("span",{style:{fontSize:11,minWidth:24,color:"var(--nice-text-muted, #64748b)"},children:O.intensity})]})]},O.type))}),r.jsx("div",{style:{marginTop:12,fontSize:12,color:"var(--nice-text-muted, #94a3b8)",textAlign:"center"},children:h("vocalEffects.hint","Click effects to toggle. Multiple effects can be active at once — adjust intensity with the slider.")})]})},Dl={algorithm:"pitchy",gain:1,rmsThreshold:.02,pitchThreshold:.6,smoothingWindow:3,hysteresisFrames:2,useHanning:!1,offsetMs:0},d0=[{value:"pitchy",label:"Pitchy (fast)"},{value:"autocorrelation",label:"Autocorrelation"},{value:"librosa",label:"Librosa (server)"},{value:"crepe",label:"CREPE (AI, server)"}],u0=({deviceId:e,onDeviceChange:t,settings:n,onSettingsChange:a,audioInputs:s,algorithms:i=d0,showLevelMeter:o=!0,onCalibrate:l,compact:c=!1,t:u})=>{const{t:h}=xe(),p=u??h,g=d.useMemo(()=>({...Dl,...n}),[n]),y=I=>a==null?void 0:a({...g,...I}),[m,x]=d.useState([]);d.useEffect(()=>{var N,_,ee;if(s||!((N=navigator.mediaDevices)!=null&&N.enumerateDevices))return;let I=!1;const L=()=>navigator.mediaDevices.enumerateDevices().then(Y=>!I&&x(Y.filter(O=>O.kind==="audioinput"))).catch(()=>{});return L(),(ee=(_=navigator.mediaDevices).addEventListener)==null||ee.call(_,"devicechange",L),()=>{var Y,O;I=!0,(O=(Y=navigator.mediaDevices).removeEventListener)==null||O.call(Y,"devicechange",L)}},[s]);const b=s??m,f=d.useMemo(()=>b.map((I,L)=>({value:I.deviceId,label:I.label||`${p("audioInput.microphone","Microphone")} ${L+1}`})),[b,p]),[k,v]=d.useState(!1),[w,R]=d.useState(0),M=d.useRef(null),j=()=>{const I=M.current;I&&(cancelAnimationFrame(I.raf),I.stream.getTracks().forEach(L=>L.stop()),I.ctx.close().catch(()=>{}),M.current=null),v(!1),R(0)},T=async()=>{try{const I=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0}}),L=new AudioContext,N=L.createMediaStreamSource(I),_=L.createAnalyser();_.fftSize=1024,N.connect(_);const ee=new Float32Array(_.fftSize),Y=()=>{_.getFloatTimeDomainData(ee);let O=0;for(let U=0;U<ee.length;U++)O+=ee[U]*ee[U];R(Math.sqrt(O/ee.length)*(g.gain||1)),M.current.raf=requestAnimationFrame(Y)};M.current={ctx:L,stream:I,raf:requestAnimationFrame(Y)},v(!0)}catch{}};d.useEffect(()=>()=>j(),[]);const P={fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:4,display:"block"},A=(I,L,N)=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[r.jsx("span",{style:{flex:"0 0 120px",fontSize:13},children:I}),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:N})]});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(F.NtdMicrophone,{size:13})," ",p("audioInput.device","Microphone")]}),r.jsx(ie.NiceSelect,{options:f,value:e??"",onChange:I=>t==null?void 0:t(typeof I=="string"?I:I[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:I=>y({algorithm:typeof I=="string"?I:I[0]}),size:"sm"})]})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[A(p("audioInput.gain","Gain"),r.jsx(ie.NiceSlider,{value:Math.round(g.gain*100),onChange:I=>y({gain:I/100}),min:0,max:300}),`${Math.round(g.gain*100)}%`),A(p("audioInput.rmsThreshold","RMS gate"),r.jsx(ie.NiceSlider,{value:Math.round(g.rmsThreshold*1e3),onChange:I=>y({rmsThreshold:I/1e3}),min:0,max:200}),g.rmsThreshold.toFixed(3)),A(p("audioInput.pitchThreshold","Pitch clarity"),r.jsx(ie.NiceSlider,{value:Math.round(g.pitchThreshold*100),onChange:I=>y({pitchThreshold:I/100}),min:0,max:100}),g.pitchThreshold.toFixed(2)),!c&&A(p("audioInput.smoothing","Smoothing"),r.jsx(ie.NiceSlider,{value:g.smoothingWindow,onChange:I=>y({smoothingWindow:I}),min:0,max:12}),`${g.smoothingWindow}`),!c&&A(p("audioInput.hysteresis","Hysteresis"),r.jsx(ie.NiceSlider,{value:g.hysteresisFrames,onChange:I=>y({hysteresisFrames:I}),min:0,max:12}),`${g.hysteresisFrames}`),!c&&A(p("audioInput.offset","Latency"),r.jsx(ie.NiceSlider,{value:g.offsetMs,onChange:I=>y({offsetMs:I}),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:I=>y({useHanning:I}),label:p("audioInput.hanning","Hanning window")}),o&&r.jsxs(r.Fragment,{children:[r.jsx(ie.NiceButton,{variant:k?"danger":"secondary",size:"sm",onClick:k?j:T,children:k?p("audioInput.stopTest","Stop test"):p("audioInput.testMic","Test mic")}),r.jsx("div",{style:{width:100,height:8,borderRadius:4,background:"var(--nice-bg-tertiary)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${Math.min(100,w*300)}%`,background:w>.5?"var(--nice-danger, #ef4444)":w>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})})]}),l&&e&&r.jsxs(ie.NiceButton,{variant:"ghost",size:"sm",onClick:()=>l(e),children:[r.jsx(F.NtdSettings,{size:14})," ",p("audioInput.calibrate","Calibrate latency")]})]})]})};class Fl{constructor(t,n){this.activeNotes=new Map,this.audioContext=t,this.masterGain=t.createGain(),this.masterGain.gain.value=.3,this.masterGain.connect(n)}applyCC(t,n,a){}midiToFreq(t){return 440*Math.pow(2,(t-69)/12)}playNote(t,n=100,a=1,s="sine"){const i=this.midiToFreq(t),o=this.audioContext.createOscillator(),l=this.audioContext.createGain();o.type=s,o.frequency.value=i;const c=n/127*.8;l.gain.value=c,o.connect(l),l.connect(this.masterGain);const 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 ji=st.scoped("AudioPlaybackEngine");class h0{constructor(){this.audioContext=null,this.masterGain=null,this.masterFilter=null,this.clips=new Map,this.scheduledSources=new Map,this.midiTracks=new Map,this.synths=new Map,this.isPlaying=!1,this.startTimeOffset=0,this.audioContextStartTime=0,this.currentTime=0,this.loopRegion={start:0,end:0,enabled:!1},this.bpm=120,this.duration=0,this.initAudioContext()}setMidiCCEvents(t,n){const a=this.midiTracks.get(t);a&&(a.ccEvents=n)}getMidiCCEvents(t){const n=this.midiTracks.get(t);return(n==null?void 0:n.ccEvents)||[]}addMidiCCEvent(t,n){const a=this.midiTracks.get(t);a&&(a.ccEvents||(a.ccEvents=[]),a.ccEvents.push(n))}removeMidiCCEvent(t,n){const a=this.midiTracks.get(t);a&&a.ccEvents&&(a.ccEvents=a.ccEvents.filter(s=>s.id!==n))}initAudioContext(){try{this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.masterGain=this.audioContext.createGain(),this.masterFilter=this.audioContext.createBiquadFilter(),this.masterFilter.type="peaking",this.masterFilter.frequency.value=1200,this.masterFilter.Q.value=.7,this.masterFilter.gain.value=0,this.masterGain.connect(this.masterFilter),this.masterFilter.connect(this.audioContext.destination),this.masterGain.gain.value=.8,this.audioContext.state==="suspended"&&this.audioContext.resume()}catch(t){ji.error("Failed to initialize AudioContext:",t)}}createEffectNode(t){if(!this.audioContext||t.bypass)return null;try{switch(t.type){case"eq3":{const n=this.audioContext.createBiquadFilter(),a=this.audioContext.createBiquadFilter(),s=this.audioContext.createBiquadFilter();return n.type="lowshelf",n.frequency.value=t.params.lowFreq||250,n.gain.value=t.params.lowGain||0,a.type="peaking",a.frequency.value=1e3,a.Q.value=1,a.gain.value=t.params.midGain||0,s.type="highshelf",s.frequency.value=t.params.highFreq||4e3,s.gain.value=t.params.highGain||0,n.connect(a),a.connect(s),{input:n,output:s}}case"compressor":{const n=this.audioContext.createDynamicsCompressor();return n.threshold.value=t.params.threshold||-24,n.ratio.value=t.params.ratio||4,n.attack.value=t.params.attack||.003,n.release.value=t.params.release||.25,n.knee.value=t.params.knee||30,n}case"delay":{const n=this.audioContext.createDelay(5);n.delayTime.value=t.params.time||.25;const a=this.audioContext.createGain();a.gain.value=t.params.feedback||.3;const s=this.audioContext.createGain();s.gain.value=t.params.mix||.3;const i=this.audioContext.createGain();return i.gain.value=1-(t.params.mix||.3),n.connect(a),a.connect(n),n.connect(s),{input:n,output:s,dry:i,connect:function(o){s.connect(o),i.connect(o)}}}case"reverb":{const n=this.audioContext.createConvolver(),a=this.audioContext.sampleRate*(t.params.decay||2),s=this.audioContext.createBuffer(2,a,this.audioContext.sampleRate);for(let l=0;l<2;l++){const c=s.getChannelData(l);for(let 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 ji.error("Failed to create effect node:",t.type,n),null}}addClip(t){this.clips.set(t.id,t),this.updateDuration()}removeClip(t){this.clips.delete(t),this.stopClip(t),this.updateDuration()}updateClip(t,n){const a=this.clips.get(t);a&&(Object.assign(a,n),this.updateDuration())}getClipsByLayer(t){return Array.from(this.clips.values()).filter(n=>n.layerId===t)}setMidiTrack(t,n,a="sine",s=.5){if(this.midiTracks.set(t,{layerId:t,notes:n,instrument:a,volume:s}),!this.synths.has(t)&&this.audioContext&&this.masterGain){const i=new Fl(this.audioContext,this.masterGain);i.setVolume(s),this.synths.set(t,i)}}removeMidiTrack(t){this.midiTracks.delete(t);const n=this.synths.get(t);n&&(n.dispose(),this.synths.delete(t))}updateMidiTrackVolume(t,n){const a=this.midiTracks.get(t);a&&(a.volume=n);const s=this.synths.get(t);s&&s.setVolume(n)}updateDuration(){let t=0;this.clips.forEach(n=>{const a=n.startTime+n.duration;a>t&&(t=a)}),this.duration=t}play(){!this.audioContext||this.isPlaying||(this.audioContext.state==="suspended"&&this.audioContext.resume(),this.isPlaying=!0,this.audioContextStartTime=this.audioContext.currentTime,this.startTimeOffset=this.currentTime,this.scheduleClips(),this.scheduleMidiNotes(),this.startTimeTracking(),this.onPlayStateChange&&this.onPlayStateChange(!0))}pause(){this.isPlaying&&(this.isPlaying=!1,this.stopAllSources(),this.onPlayStateChange&&this.onPlayStateChange(!1))}stop(){this.pause(),this.seek(0)}seek(t){const n=this.isPlaying;n&&this.pause(),this.currentTime=Math.max(0,Math.min(t,this.duration)),this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),n&&this.play()}scheduleClips(){!this.audioContext||!this.masterGain||this.clips.forEach(t=>{if(t.startTime+t.duration<=this.currentTime)return;const a=this.audioContext.createBufferSource();a.buffer=t.buffer,t.stretchFactor&&t.stretchFactor!==1&&(a.playbackRate.value=1/t.stretchFactor);const s=this.audioContext.createGain();s.gain.value=t.volume;const i=this.audioContext.createStereoPanner();i.pan.value=t.pan,a.connect(s);let o=s;if(t.effectChain&&t.effectChain.length>0)for(const h of t.effectChain){const p=this.createEffectNode(h);if(p)if("input"in p&&"output"in p){const g=p;o.connect(g.input),o=g.output,"dry"in p&&s.connect(g.dry)}else o.connect(p),o=p}o.connect(i),i.connect(this.masterGain);const l=t.startTime,c=Math.max(0,this.currentTime-l),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 w=Math.max(h/127,.001),R=Math.max(p/127,.001);b=w*Math.pow(R/w,x)*127}const f=c+(u-c)*x,k=this.audioContext.currentTime+(f-this.currentTime);k>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(l.cc,b,k)}i=l}}})}startTimeTracking(){if(!this.audioContext)return;const t=()=>{if(!this.isPlaying||!this.audioContext)return;const n=this.audioContext.currentTime-this.audioContextStartTime;if(this.currentTime=this.startTimeOffset+n,this.loopRegion.enabled&&this.currentTime>=this.loopRegion.end){this.seek(this.loopRegion.start);return}if(this.currentTime>=this.duration){this.stop();return}this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),requestAnimationFrame(t)};requestAnimationFrame(t)}setLoopRegion(t,n,a){this.loopRegion={start:t,end:n,enabled:a}}setBPM(t){this.bpm=Math.max(20,Math.min(300,t))}getBPM(){return this.bpm}setMasterVolume(t){this.masterGain&&(this.masterGain.gain.value=Math.max(0,Math.min(1,t)))}setMasterFilter(t){this.masterFilter&&(t.type&&(this.masterFilter.type=t.type),t.frequency!=null&&(this.masterFilter.frequency.value=Math.max(20,Math.min(2e4,t.frequency))),t.q!=null&&(this.masterFilter.Q.value=Math.max(.1,Math.min(18,t.q))),t.gain!=null&&"gain"in this.masterFilter&&(this.masterFilter.gain.value=Math.max(-40,Math.min(40,t.gain))))}getCurrentTime(){return this.currentTime}getDuration(){return this.duration}getIsPlaying(){return this.isPlaying}setOnTimeUpdate(t){this.onTimeUpdate=t}setOnPlayStateChange(t){this.onPlayStateChange=t}dispose(){this.stop(),this.audioContext&&this.audioContext.close(),this.clips.clear()}}const p0=[{name:"Grand Piano",waveform:"sawtooth",attack:.02,sustain:.7,release:1.2,eq:{C:2,D:1,E:1,F:0,G:0,A:-1,B:-2,C2:-3},category:"Keyboard"},{name:"Electric Piano",waveform:"triangle",attack:.03,sustain:.8,release:1,eq:{C:0,D:1,E:2,F:3,G:1,A:-1,B:-2,C2:-2},category:"Keyboard"},{name:"Harpsichord",waveform:"square",attack:.01,sustain:.5,release:.6,eq:{C:-1,D:-1,E:0,F:2,G:3,A:1,B:0,C2:-1},category:"Keyboard"},{name:"Violin",waveform:"triangle",attack:.3,sustain:1,release:1.5,eq:{C:3,D:2,E:2,F:1,G:-1,A:-2,B:-3,C2:-3},category:"String"},{name:"Acoustic Guitar",waveform:"sawtooth",attack:.2,sustain:.6,release:.9,eq:{C:-1,D:-2,E:0,F:1,G:3,A:2,B:0,C2:-2},category:"String"},{name:"Electric Guitar",waveform:"square",attack:.05,sustain:.7,release:1.2,eq:{C:-2,D:1,E:2,F:2,G:1,A:0,B:-1,C2:-3},category:"String"},{name:"Kick Drum",waveform:"sine",attack:.005,sustain:.1,release:.2,eq:{C:5,D:3,E:0,F:-3,G:-5,A:-7,B:-9,C2:-10},category:"Percussion"},{name:"Snare Drum",waveform:"triangle",attack:.01,sustain:.2,release:.3,eq:{C:-2,D:-1,E:1,F:2,G:3,A:2,B:0,C2:-2},category:"Percussion"},{name:"Hi-Hat",waveform:"square",attack:.002,sustain:.05,release:.1,eq:{C:-5,D:-3,E:0,F:2,G:5,A:7,B:9,C2:10},category:"Percussion"},{name:"Acoustic Bass",waveform:"sine",attack:.08,sustain:.8,release:1.2,eq:{C:4,D:3,E:2,F:1,G:0,A:-1,B:-2,C2:-3},category:"Bass"},{name:"Electric Bass",waveform:"square",attack:.05,sustain:.9,release:1.3,eq:{C:3,D:2,E:1,F:0,G:-1,A:-2,B:-3,C2:-4},category:"Bass"},{name:"Trumpet",waveform:"sawtooth",attack:.1,sustain:.9,release:1.5,eq:{C:2,D:3,E:4,F:5,G:3,A:1,B:-1,C2:-3},category:"Brass"},{name:"Trombone",waveform:"triangle",attack:.2,sustain:1,release:1.7,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-2,C2:-4},category:"Brass"},{name:"Saxophone",waveform:"sawtooth",attack:.15,sustain:.8,release:1.3,eq:{C:2,D:3,E:4,F:3,G:1,A:-1,B:-2,C2:-3},category:"Woodwind"},{name:"Clarinet",waveform:"triangle",attack:.18,sustain:.9,release:1.6,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-1,C2:-2},category:"Woodwind"},{name:"Saw Synth",waveform:"sawtooth",attack:.05,sustain:.9,release:1.2,eq:{C:2,D:3,E:4,F:3,G:2,A:0,B:-1,C2:-2},category:"Synth"},{name:"Square Lead",waveform:"square",attack:.04,sustain:.85,release:1.1,eq:{C:2,D:3,E:4,F:3,G:1,A:0,B:-1,C2:-3},category:"Synth"}];function Vr(e={}){const{channelFilter:t,sysex:n=!1,onEvent:a,inputNameIncludes:s,onInputsChanged:i}=e,[o,l]=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,k=b[1]??0,v=b[2]??0,w=m.timeStamp,R=f&240,M=f&15,j=x.id,T=x.name??"MIDI Input",P=t===void 0||t===M;if((R===144||R===128)&&P){const A=R===144&&v>0;return{type:A?"noteon":"noteoff",note:k,velocity:A?v:0,channel:M,ts:w,deviceId:j,deviceName:T}}return R===176&&P?{type:"cc",controller:k,value:v,channel:M,ts:w,deviceId:j,deviceName:T}:R===208&&P?{type:"aftertouch",pressure:k,channel:M,ts:w,deviceId:j,deviceName:T}:R===224&&P?{type:"pitchbend",value:(k|v<<7)-8192,channel:M,ts:w,deviceId:j,deviceName:T}:R===192&&P?{type:"program",program:k,channel:M,ts:w,deviceId:j,deviceName:T}:{type:"unknown",status:f,data1:k,data2:v,channel:M,ts:w,deviceId:j,deviceName:T}},[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()),k=s?f.filter(v=>(v.name||"").toUpperCase().includes(s.toUpperCase())):f;p(k),i==null||i(k),f.forEach(v=>v.onmidimessage=null),k.forEach(v=>{v.onmidimessage=w=>a==null?void 0:a(y(w,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 rs="nice2dev.midiLearn";function f0(){try{const e=localStorage.getItem(rs);return e?JSON.parse(e):{}}catch{return{}}}function Mi(e){const t={};for(const n of e)t[n.id]={id:n.id,type:n.type,number:n.number,channel:n.channel,min:n.min,max:n.max};localStorage.setItem(rs,JSON.stringify(t))}function m0(e){const{parameters:t,onParameterChange:n}=e,[a,s]=d.useState(()=>{const v=f0();return t.map(w=>{const R=v[w.id];return{id:w.id,paramName:w.name,type:(R==null?void 0:R.type)??"cc",number:R==null?void 0:R.number,channel:R==null?void 0:R.channel,min:(R==null?void 0:R.min)??w.min??0,max:(R==null?void 0:R.max)??w.max??127,value:0}})}),[i,o]=d.useState({learning:!1,targetId:null}),[l,c]=d.useState(null),u=d.useRef(a);u.current=a;const h=d.useRef(n);h.current=n;const p=d.useRef(i);p.current=i;const g=d.useCallback(v=>{var R;c(v);const w=p.current;if(w.learning&&w.targetId){if(!u.current.find(T=>T.id===w.targetId))return;let j={};switch(v.type){case"cc":j={type:"cc",number:v.controller,channel:v.channel};break;case"noteon":j={type:"note",number:v.note,channel:v.channel};break;case"pitchbend":j={type:"pitchbend",channel:v.channel};break;case"aftertouch":j={type:"aftertouch",channel:v.channel};break;default:return}s(T=>{const P=T.map(A=>A.id===w.targetId?{...A,...j}:A);return Mi(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 j=null,T=127;if(M.type==="cc"&&v.type==="cc"&&v.controller===M.number?j=v.value:M.type==="note"&&v.type==="noteon"&&v.note===M.number?j=v.velocity:M.type==="pitchbend"&&v.type==="pitchbend"?(j=v.value+8192,T=16383):M.type==="aftertouch"&&v.type==="aftertouch"&&(j=v.pressure),j!==null){const P=j/T,A=M.min+P*(M.max-M.min);s(I=>I.map(L=>L.id===M.id?{...L,value:P}:L)),(R=h.current)==null||R.call(h,M.id,A,P)}}},[]),{supported:y,granted:m}=Vr({onEvent:g}),x=d.useCallback(v=>{o({learning:!0,targetId:v})},[]),b=d.useCallback(()=>{o({learning:!1,targetId:null})},[]),f=d.useCallback(v=>{s(w=>{const R=w.map(M=>M.id===v?{...M,type:"cc",number:void 0,channel:void 0}:M);return Mi(R),R})},[]),k=d.useCallback(()=>{s(v=>{const w=v.map(R=>({...R,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(rs),w})},[]);return{bindings:a,startLearn:x,cancelLearn:b,removeBinding:f,clearAll:k,learnState:i,midiSupported:y,midiGranted:m,lastEvent:l}}const g0={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function y0(e={}){const{lowerZone:t=g0,onNoteExpression:n,onNoteOn:a,onNoteOff:s}=e,[i,o]=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,k,v,w,R;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())),(k=h.current)==null||k.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,(w=c.current)==null||w.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,(R=c.current)==null||R.call(c,M),o(Array.from(l.current.values())))}break}}},[]),{supported:y,granted:m}=Vr({onEvent:g,sysex:!1});return{activeNotes:i,midiSupported:y,midiGranted:m}}const v0={name:"M-Audio Oxygen 25 (MKIV)",deviceMatch:"OXYGEN",knobs:[{index:1,cc:21,label:"Knob 1"},{index:2,cc:22,label:"Knob 2"},{index:3,cc:23,label:"Knob 3"},{index:4,cc:24,label:"Knob 4"},{index:5,cc:25,label:"Knob 5"},{index:6,cc:26,label:"Knob 6"},{index:7,cc:27,label:"Knob 7"},{index:8,cc:28,label:"Knob 8"}],fader:{cc:7,label:"Fader (Channel Volume)"},pads:[{note:36,label:"Kick C1"},{note:38,label:"Snare D1"},{note:42,label:"HH Closed F#1"},{note:46,label:"HH Open A#1"},{note:48,label:"Tom1 C2"},{note:45,label:"Tom2 A1"},{note:43,label:"Floor G1"},{note:49,label:"Crash C#2"}],transport:{play:115,stop:114,record:117,rew:112,ff:113,loop:116}};function b0(e={},t=v0){const{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,k,v,w,R,M,j,T,P;const x=m.deviceName||"MIDI";o(A=>A.includes(x)?A:[...A,x]);const b=l.current;if(b.mode!=="idle"){if(b.mode==="knob"&&m.type==="cc"){const A=b.index;c({knobs:a.knobs.map(I=>I.index===A?{...I,cc:m.controller}:I)}),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 A=a.pads.slice();A[b.padIdx]={...A[b.padIdx],note:m.note},c({pads:A}),l.current={mode:"idle"};return}if(b.mode==="transport"&&m.type==="cc"){const A={...a.transport};A[b.action]=m.controller,c({transport:A}),l.current={mode:"idle"};return}}switch(m.type){case"noteon":{a.pads.findIndex(I=>I.note===m.note)>=0?(f=e.onPad)==null||f.call(e,{note:m.note,velocity:m.velocity,ts:m.ts,device:x}):(k=e.onKey)==null||k.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 A=a.knobs.find(L=>L.cc===m.controller);if(A){(w=e.onKnob)==null||w.call(e,{index:A.index,cc:m.controller,value:m.value,ts:m.ts,device:x});break}const I=Object.keys(a.transport).find(L=>a.transport[L]===m.controller);if(I){(R=e.onTransport)==null||R.call(e,{action:I,value:m.value,ts:m.ts,device:x});break}(M=e.onUnknown)==null||M.call(e,m);break}case"pitchbend":(j=e.onPitchBend)==null||j.call(e,{value:m.value,ts:m.ts,device:x});break;case"aftertouch":(T=e.onAftertouch)==null||T.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}=Vr({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 ja={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],mixolydian:[0,2,4,5,7,9,10],pentatonic:[0,2,4,7,9],minorPenta:[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11]},x0=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Ma={pop:[[0,4,7],[5,9,0],[7,11,2],[5,9,0]],rock:[[0,4,7],[5,9,0],[3,7,10],[5,9,0]],jazz:[[0,4,7,11],[2,5,9,0],[5,9,0,4],[0,4,7,11]],blues12:[[0,4,7],[0,4,7],[0,4,7],[0,4,7],[5,9,0],[5,9,0],[0,4,7],[0,4,7],[7,11,2],[5,9,0],[0,4,7],[7,11,2]]},nn=36,jn=38,Rt=42,rn=51,S0=49,Ra={basic:[{step:0,pitch:nn,vel:110},{step:0,pitch:Rt,vel:80},{step:2,pitch:Rt,vel:70},{step:4,pitch:jn,vel:100},{step:4,pitch:Rt,vel:80},{step:6,pitch:Rt,vel:70},{step:8,pitch:nn,vel:100},{step:10,pitch:Rt,vel:70},{step:12,pitch:jn,vel:100},{step:12,pitch:Rt,vel:80},{step:14,pitch:Rt,vel:70}],rock:[{step:0,pitch:nn,vel:120},{step:0,pitch:S0,vel:90},{step:4,pitch:jn,vel:110},{step:4,pitch:Rt,vel:80},{step:8,pitch:nn,vel:110},{step:8,pitch:Rt,vel:80},{step:10,pitch:nn,vel:90},{step:12,pitch:jn,vel:110},{step:12,pitch:Rt,vel:80}],swing:[{step:0,pitch:rn,vel:90},{step:3,pitch:rn,vel:70},{step:4,pitch:rn,vel:80},{step:8,pitch:rn,vel:90},{step:11,pitch:rn,vel:70},{step:12,pitch:rn,vel:80},{step:4,pitch:nn,vel:80},{step:12,pitch:jn,vel:70}]},Ol={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function k0(e){let t=e|0;return()=>{t=t+1831565813|0;let n=Math.imul(t^t>>>15,1|t);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}let Bl=1;const lr=()=>Bl++,Gl=e=>60/e,w0=e=>Gl(e)/4;function ia(e,t,n,a){const s=t.length,i=Math.floor(n/s),o=(n%s+s)%s;return e+t[o]+(a+i)*12}function Wl(e=Ol){Bl=1;const t=e.seed>0?k0(e.seed):Math.random,n=ja[e.scale]??ja.pentatonic,a=Ma[e.progression]??Ma.pop,s=Ra[e.drumPattern]??Ra.basic,i=Gl(e.tempo),o=w0(e.tempo),l=Math.max(1,e.bars),c=16,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:lr(),pitch:ia(e.root,n,v,e.octave-1),start:x,duration:4*i-.01,velocity:70+Math.floor(t()*20)});const k=f[0];for(let v=0;v<4;v++){const w=v===2?k+(t()>.5?2:0):k;h.push({id:lr(),pitch:ia(e.root,n,w,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 w=x+v*o,R=t()>.8?t()>.5?2:-2:t()>.5?1:-1;y=Math.max(-3,Math.min(n.length+3,y+R));const M=1+Math.floor(t()*3);u.push({id:lr(),pitch:ia(e.root,n,y,e.octave),start:w,duration:M*o*.95,velocity:85+Math.floor(t()*30)})}for(const v of s)g.push({id:lr(),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 C0=Object.keys(ja),j0=Object.keys(Ma),M0=Object.keys(Ra),R0=Wl;function qe(e,t,n){return{cc:e,paramId:n,label:`Knob ${t}`,controlType:"knob",min:0,max:127,inverted:!1}}function Un(e,t,n){return{cc:e,paramId:n,label:t,controlType:"fader",min:0,max:127,inverted:!1}}function an(e,t,n){return{cc:e,paramId:n,label:t,controlType:"button",min:0,max:127,inverted:!1}}const Vl={id:"oxygen25",name:"M-Audio Oxygen 25 (MkIV)",deviceMatch:"OXYGEN",mappings:[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"),Un(7,"Master Fader","mixer.master"),an(115,"Play","transport.play"),an(114,"Stop","transport.stop"),an(117,"Record","transport.record"),an(112,"Rewind","transport.rewind"),an(113,"Forward","transport.forward"),an(116,"Loop","transport.loop")]},Ul={id:"mpk-mini",name:"Akai MPK Mini",deviceMatch:"MPK",mappings:[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")]},ql={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"),Un(1,"Mod Wheel","mixer.master")]},Hl=(function(){return{id:"launch-control-xl",name:"Novation Launch Control XL",deviceMatch:"Launch Control",mappings:[...Array.from({length:8},(e,t)=>qe(13+t,t+1,`mixer.send${t+1}`)),...Array.from({length:8},(e,t)=>Un(77+t,`Fader ${t+1}`,`mixer.track${t+1}`))]}})(),as={id:"generic",name:"Generic MIDI Controller",deviceMatch:"",mappings:[qe(1,1,"mixer.modWheel"),Un(7,"Volume","mixer.volume"),qe(10,2,"mixer.pan"),Un(11,"Expression","mixer.expression")]},Kl=[Vl,Ul,ql,Hl,as];class N0{constructor(t){this.ccMap=new Map,this.onChange=null,this.profile=t??as,this.rebuildMap()}setProfile(t){this.profile=t,this.rebuildMap()}getProfile(){return this.profile}autoDetect(t){const n=t.toUpperCase(),a=Kl.find(s=>s.deviceMatch&&n.includes(s.deviceMatch.toUpperCase()));return a?(this.setProfile(a),a):null}onMappedChange(t){this.onChange=t}handleCC(t,n){var c;const a=this.ccMap.get(t);if(!a)return null;const i=(a.inverted?127-n:n)/127,o=a.min+i*(a.max-a.min),l={paramId:a.paramId,label:a.label,rawValue:n,scaledValue:o,normalizedValue:i};return(c=this.onChange)==null||c.call(this,l),l}setMapping(t,n,a,s="knob"){const i={cc:t,paramId:n,label:a,controlType:s,min:0,max:127,inverted:!1},o=this.profile.mappings.findIndex(l=>l.cc===t);o>=0?this.profile.mappings[o]=i:this.profile.mappings.push(i),this.ccMap.set(t,i)}removeMapping(t){this.profile.mappings=this.profile.mappings.filter(n=>n.cc!==t),this.ccMap.delete(t)}getMappings(){return[...this.profile.mappings]}getMapping(t){return this.ccMap.get(t)}exportConfig(){return{...this.profile,mappings:this.profile.mappings.map(t=>({...t}))}}importConfig(t){this.profile={...t,mappings:t.mappings.map(n=>({...n}))},this.rebuildMap()}static createCustomProfile(t,n){return{id:`custom-${t.toLowerCase().replace(/\s+/g,"-")}`,name:t,deviceMatch:"",mappings:n.map(a=>({...a,min:0,max:127,inverted:!1}))}}rebuildMap(){this.ccMap.clear();for(const t of this.profile.mappings)this.ccMap.set(t.cc,t)}}function ss(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function Zt(e="New Pattern",t=16,n=120){return{name:e,length:t,steps:Array.from({length:t},()=>ss()),bpm:n,swing:0,rootNote:60}}function Yl(e,t){const n=e.steps.map((a,s)=>s===t?{...a,active:!a.active}:a);return{...e,steps:n}}function Zl(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,note:Math.max(0,Math.min(127,n))}:s);return{...e,steps:a}}function Xl(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,velocity:Math.max(0,Math.min(127,n))}:s);return{...e,steps:a}}function Ql(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,gate:Math.max(0,Math.min(1,n))}:s);return{...e,steps:a}}function Jl(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,probability:Math.max(0,Math.min(1,n))}:s);return{...e,steps:a}}function ec(e,t){const n=e.steps.map((a,s)=>s===t?{...a,slide:!a.slide}:a);return{...e,steps:n}}function tc(e,t){const n=e.steps.map(a=>a.active?{...a,note:Math.max(0,Math.min(127,a.note+t))}:a);return{...e,steps:n,rootNote:Math.max(0,Math.min(127,e.rootNote+t))}}function nc(e){return{...e,steps:[...e.steps].reverse()}}function rc(e,t){const n=e.steps.length,a=(t%n+n)%n,s=[...e.steps.slice(a),...e.steps.slice(0,a)];return{...e,steps:s}}function ac(e,t=60,n=127){const a=e.steps.map(s=>s.active?{...s,velocity:Math.floor(t+Math.random()*(n-t+1))}:s);return{...e,steps:a}}function sc(e){return{...e,steps:e.steps.map(()=>ss(e.rootNote))}}function is(e,t=4){return 60/e/t}function ic(e,t,n=0,a=4){const s=is(t,a),i=e*s;return e%2===1&&n>0?i+s*n*.5:i}function oc(e){return e.active&&Math.random()<e.probability}function T0(){const e=Zt("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function P0(){const e=Zt("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function E0(){const e=Zt("Hi-Hat",16);for(let t=0;t<16;t+=2)e.steps[t]={...e.steps[t],active:!0,note:42,velocity:80};return e}function $0(e=60){const t=Zt("Arp",16,120);return[0,4,7,12,7,4,0,-5,0,3,7,12,7,3,0,-5].forEach((a,s)=>{t.steps[s]={...t.steps[s],active:!0,note:e+a,velocity:90,gate:.5}}),{...t,rootNote:e}}function A0(e=36){const t=Zt("Bassline",16,120),n=[0,0,7,0,5,5,3,0,0,0,7,12,5,5,3,0],a=[1,0,1,0,1,0,1,1,1,0,1,1,1,0,1,0];return n.forEach((s,i)=>{t.steps[i]={...t.steps[i],active:!!a[i],note:e+s,velocity:100,gate:.7}}),{...t,rootNote:e}}function I0(e){return JSON.stringify(e,null,2)}function L0(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function _0(e={}){const{onTrigger:t,onLFOOutput:n,initialPattern:a}=e,[s,i]=d.useState(()=>a??Zt()),[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),k=d.useRef(0),v=d.useRef(0),w=d.useCallback(()=>{var q,X;if(!m.current)return;const S=g.current,B=k.current%S.length,H=S.steps[B];if(oc(H)){const re=ic(k.current,S.bpm,S.swing);(q=x.current)==null||q.call(x,H,B,re)}const z=(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=Ia(oe,z,S.bpm);(X=b.current)==null||X.call(b,re,oe.targetCC,se)}}l(B),k.current++;const Z=is(S.bpm)*1e3,E=B%2===0?0:Z*S.swing*.5;f.current=setTimeout(w,Z+E)},[]),R=d.useCallback(()=>{m.current||(k.current=0,v.current=Date.now(),u(!0),m.current=!0,w())},[w]),M=d.useCallback(()=>{u(!1),m.current=!1,l(-1),f.current&&(clearTimeout(f.current),f.current=null)},[]),j=d.useCallback(()=>{m.current?M():R()},[R,M]);d.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const T=d.useCallback(S=>i(B=>Yl(B,S)),[]),P=d.useCallback((S,B)=>i(H=>Zl(H,S,B)),[]),A=d.useCallback((S,B)=>i(H=>Xl(H,S,B)),[]),I=d.useCallback((S,B)=>i(H=>Ql(H,S,B)),[]),L=d.useCallback((S,B)=>i(H=>Jl(H,S,B)),[]),N=d.useCallback(S=>i(B=>ec(B,S)),[]),_=d.useCallback(S=>i(B=>tc(B,S)),[]),ee=d.useCallback(()=>i(S=>nc(S)),[]),Y=d.useCallback(S=>i(B=>rc(B,S)),[]),O=d.useCallback((S,B)=>i(H=>ac(H,S,B)),[]),U=d.useCallback(()=>i(S=>sc(S)),[]),V=d.useCallback(S=>i(B=>({...B,bpm:Math.max(20,Math.min(300,S))})),[]),K=d.useCallback(S=>i(B=>({...B,swing:Math.max(0,Math.min(1,S))})),[]),G=d.useCallback(S=>{i(B=>{if(B.length===S)return B;const H=Array.from({length:S},(z,Z)=>Z<B.steps.length?B.steps[Z]:{active:!1,note:B.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...B,length:S,steps:H}})},[]),W=d.useCallback(S=>{p(B=>[...B,S??_r()])},[]),C=d.useCallback(S=>{p(B=>B.filter((H,z)=>z!==S))},[]),$=d.useCallback((S,B)=>{p(H=>H.map((z,Z)=>Z===S?{...z,...B}:z))},[]);return{pattern:s,currentStep:o,playing:c,lfos:h,play:R,stop:M,togglePlayback:j,toggle:T,setNote:P,setVelocity:A,setGate:I,setProbability:L,toggleSlide:N,transpose:_,reverse:ee,shift:Y,randomizeVel:O,clear:U,setPattern:i,setBpm:V,setSwing:K,setLength:G,addLFO:W,removeLFO:C,updateLFO:$}}function os(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 z0(){const e=os(d.useCallback(()=>new Worker(new URL("/assets/pitchWorker-BgAp5Z97.js",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 D0(){const e=os(d.useCallback(()=>new Worker(new URL("/assets/scoringWorker-3JjtDDtu.js",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 F0={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function lc(){return`
|
|
72
72
|
/**
|
|
73
73
|
* NiceAudioProcessor — Main audio analysis processor.
|
|
74
74
|
*/
|
|
@@ -404,7 +404,7 @@ registerProcessor('nice-audio-processor', NiceAudioProcessor);
|
|
|
404
404
|
registerProcessor('nice-gain-processor', NiceGainProcessor);
|
|
405
405
|
registerProcessor('nice-compressor-processor', NiceCompressorProcessor);
|
|
406
406
|
registerProcessor('nice-vocoder-processor', NiceVocoderProcessor);
|
|
407
|
-
`}let Ri=!1,cr=null;async function
|
|
407
|
+
`}let Ri=!1,cr=null;async function cc(e){if(!Ri)return cr||(cr=(async()=>{const t=lc(),n=new Blob([t],{type:"application/javascript"}),a=URL.createObjectURL(n);try{await e.audioWorklet.addModule(a),Ri=!0}finally{URL.revokeObjectURL(a)}})(),cr)}function dc(e,t,n){const a=new AudioWorkletNode(e,"nice-audio-processor",{processorOptions:{...F0,...t}});return n&&(a.port.onmessage=s=>{s.data.type==="analysis"&&n(s.data.payload)}),a}function uc(e,t=1){const n=new AudioWorkletNode(e,"nice-gain-processor");return n.parameters.get("gain").value=t,n}function hc(e,t){const n=new AudioWorkletNode(e,"nice-compressor-processor");return(t==null?void 0:t.threshold)!==void 0&&(n.parameters.get("threshold").value=t.threshold),(t==null?void 0:t.ratio)!==void 0&&(n.parameters.get("ratio").value=t.ratio),(t==null?void 0:t.attack)!==void 0&&(n.parameters.get("attack").value=t.attack),(t==null?void 0:t.release)!==void 0&&(n.parameters.get("release").value=t.release),(t==null?void 0:t.makeupGain)!==void 0&&(n.parameters.get("makeupGain").value=t.makeupGain),n}function pc(e,t){const n=new AudioWorkletNode(e,"nice-vocoder-processor");return(t==null?void 0:t.pitchShift)!==void 0&&(n.parameters.get("pitchShift").value=t.pitchShift),(t==null?void 0:t.formantShift)!==void 0&&(n.parameters.get("formantShift").value=t.formantShift),(t==null?void 0:t.mix)!==void 0&&(n.parameters.get("mix").value=t.mix),n}function O0(e={}){const{enableAnalysis:t=!0,analysisOptions:n,enableGain:a=!1,initialGain:s=1,enableCompressor:i=!1,compressorOptions:o,enableVocoder:l=!1,vocoderOptions:c,onAnalysis: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),k=d.useRef(null),v=d.useRef(null),w=d.useRef(null),R=d.useRef(null),M=d.useRef(null),j=d.useRef(null),T=d.useRef({analysisOptions:n,initialGain:s,compressorOptions:o,vocoderOptions:c});T.current={analysisOptions:n,initialGain:s,compressorOptions:o,vocoderOptions:c};const P=d.useRef(u);P.current=u,d.useEffect(()=>{let Y=!0;return(async()=>{try{const U=T.current,V=new AudioContext;if(b.current=V,await cc(V),!Y){V.close();return}const K=[];if(t){const G=dc(V,U.analysisOptions,W=>{var C;Y&&(x(W),(C=P.current)==null||C.call(P,W))});f.current=G,K.push(G)}if(a){const G=uc(V,U.initialGain);k.current=G,K.push(G)}if(i){const G=hc(V,U.compressorOptions);v.current=G,K.push(G)}if(l){const G=pc(V,U.vocoderOptions);w.current=G,K.push(G)}if(K.length>0){M.current=K[0],j.current=K[K.length-1];for(let G=0;G<K.length-1;G++)K[G].connect(K[G+1])}p(!0)}catch(U){Y&&y(U)}})(),()=>{var U,V,K,G,W;Y=!1,(U=f.current)==null||U.disconnect(),(V=k.current)==null||V.disconnect(),(K=v.current)==null||K.disconnect(),(G=w.current)==null||G.disconnect(),(W=b.current)==null||W.close()}},[t,a,i,l]);const A=d.useCallback(Y=>{R.current&&R.current.disconnect(),R.current=Y,M.current&&Y.connect(M.current)},[]),I=d.useCallback(()=>{R.current&&(R.current.disconnect(),R.current=null)},[]),L=d.useCallback(()=>j.current,[]),N=d.useCallback(Y=>{var U;const O=(U=k.current)==null?void 0:U.parameters.get("gain");O&&(O.value=Math.max(0,Math.min(2,Y)))},[]),_=d.useCallback((Y,O)=>{var V;const U=(V=v.current)==null?void 0:V.parameters.get(Y);U&&(U.value=O)},[]),ee=d.useCallback((Y,O)=>{var V;const U=(V=w.current)==null?void 0:V.parameters.get(Y);U&&(U.value=O)},[]);return{isReady:h,error:g,analysis:m,connectSource:A,disconnectSource:I,getOutputNode:L,setGain:N,setCompressorParam:_,setVocoderParam:ee,audioContext:b.current}}function B0(e,t,n){const i={id:`${t}-${n}-${Date.now()}`,type:n,bypass:!1,params:{eq3:{lowGain:0,midGain:0,highGain:0,lowFreq:250,highFreq:4e3},compressor:{threshold:-24,ratio:4,attack:.003,release:.25,knee:30},delay:{time:.25,feedback:.3,mix:.3},reverb:{decay:2,mix:.3},distortion:{amount:20,mix:.5}}[n]};e(o=>{var l;return{...o,[t]:{...o[t],effectChain:[...((l=o[t])==null?void 0:l.effectChain)||[],i]}}})}function G0(e,t,n){e(a=>{var s,i;return{...a,[t]:{...a[t],effectChain:((i=(s=a[t])==null?void 0:s.effectChain)==null?void 0:i.filter(o=>o.id!==n))||[]}}})}function W0(e,t,n){e(a=>{var s,i;return{...a,[t]:{...a[t],effectChain:((i=(s=a[t])==null?void 0:s.effectChain)==null?void 0:i.map(o=>o.id===n?{...o,bypass:!o.bypass}:o))||[]}}})}function V0(e,t,n,a){e(s=>{var i,o;return{...s,[t]:{...s[t],effectChain:((o=(i=s[t])==null?void 0:i.effectChain)==null?void 0:o.map(l=>l.id===n?{...l,params:{...l.params,...a}}:l))||[]}}})}function U0(e,t,n,a,s,i,o=.5,l=100){const c={id:Date.now()+Math.floor(Math.random()*1e3),pitch:s,start:i,duration:o,velocity:l};t(u=>({...u,[a]:[...u[a]||[],c]})),n({layerId:a,noteId:c.id})}function q0(e,t,n,a){e(s=>({...s,[n]:(s[n]||[]).filter(i=>i.id!==a)})),t(null)}function H0(e,t,n){e(a=>({...a,[n]:[]})),t(null)}function K0(e,t,n){e(a=>({...a,[t]:n}))}function Y0(e,t,n,a,s){const i={id:Date.now()+Math.floor(Math.random()*1e3),cc:n,value:a,time:s};e(o=>({...o,[t]:[...o[t]||[],i]}))}function Z0(e,t,n,a,s,i){e(o=>({...o,[t]:(o[t]||[]).map(l=>l.id===n?{...l,value:a,time:s,handleType:i??l.handleType}:l)}))}function X0(e,t,n){e(a=>({...a,[t]:(a[t]||[]).filter(s=>s.id!==n)}))}function dr(e){if(!e||e<=0)return null;const t=12*Math.log2(e/440)+69;return Math.round(t-12)}function Q0(e){if(e.length===0)return[];const t=[];let n=e[0];for(let a=1;a<e.length;a++){const s=e[a];s.pitch===n.pitch&&Math.abs(s.freq-n.freq)<1?n.duration+=s.duration:(t.push(n),n=s)}return t.push(n),t}function J0(e,t,n=.01){const a=Math.floor(t/50);let s=-1,i=0,o=0;for(let c=0;c<e.length;c++)o+=e[c]*e[c];if(o=Math.sqrt(o/e.length),o<n)return 0;let l=1;for(let c=50;c<a;c++){let 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 eg(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=la.PitchDetector.forFloat32Array(m),k=Math.max(1,Math.floor((g.length-m)/x));let v=0;for(let w=0;w<g.length-m;w+=x){if(a!=null&&a.aborted)throw new Error("aborted");const R=g.slice(w,w+m);if(o)for(let I=0;I<R.length;I++)R[I]*=.5*(1-Math.cos(2*Math.PI*I/(R.length-1)));const[M,j]=f.findPitch(R,y),T=dr(M);let P=0;for(let I=0;I<R.length;I++)P+=R[I]*R[I];P=Math.sqrt(P/R.length);const A=typeof i=="number"?i:.01;T&&M>50&&M<2e3&&j>.7&&P>A&&b.push({start:w/y,duration:m/y,pitch:T,freq:M}),v++,s&&s(v/k)}}else if(t==="crepe"){if(s&&s(.05),!l)throw new Error("CREPE backend callback (postPitch) is required for crepe algorithm");const f=await l(e);if(a!=null&&a.aborted)throw new Error("aborted");const k=Array.isArray(f.track)?f.track:[];k.length>0&&k.forEach((v,w)=>{var M;const R=dr(v.hz);if(R&&v.hz>50&&v.hz<2e3){const j=((M=k[w+1])==null?void 0:M.t)??v.t+.1;b.push({start:v.t,duration:w<k.length-1?j-v.t:.1,pitch:R,freq:v.hz})}}),s&&s(1)}else if(t==="ultrastar-wp"){const f=Math.max(1,Math.floor((g.length-m)/x));let k=0;for(let v=0;v<g.length-m;v+=x){if(a!=null&&a.aborted)throw new Error("aborted");const w=g.slice(v,v+m);if(o)for(let T=0;T<w.length;T++)w[T]*=.5*(1-Math.cos(2*Math.PI*T/(w.length-1)));const M=J0(w,y,typeof i=="number"?i:.01),j=dr(M);j&&M>50&&M<2e3&&b.push({start:v/y,duration:m/y,pitch:j,freq:M}),k++,s&&s(k/f)}}if(t==="librosa"){if(s&&s(.05),!c)throw new Error("Librosa backend callback (postLibrosaPitchTrack) is required for librosa algorithm");const f=await c(e);if(a!=null&&a.aborted)throw new Error("aborted");const k=Array.isArray(f.track)?f.track:[];k.length>0&&k.forEach((v,w)=>{var M;const R=dr(v.hz);if(R&&v.hz>50&&v.hz<2e3){const j=((M=k[w+1])==null?void 0:M.t)??v.t+.1;b.push({start:v.t,duration:w<k.length-1?j-v.t:.1,pitch:R,freq:v.hz})}}),s&&s(1)}return Q0(b)}function tg(e){switch(e){case"pitchy":return`#TITLE:Analyzed Song
|
|
408
408
|
#ARTIST:AI
|
|
409
409
|
#ALGO:Pitchy
|
|
410
410
|
: 0 4 40 Pitchy
|
|
@@ -427,4 +427,4 @@ E`;case"ultrastarws":return`#TITLE:Analyzed Song
|
|
|
427
427
|
E`;default:return`#TITLE:Analyzed Song
|
|
428
428
|
#ARTIST:AI
|
|
429
429
|
: 0 2 40 Test
|
|
430
|
-
E`}}function Vm(e,t){return`${e}:${t}`}function qm(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 Hm(e){return e.length===0?[]:e.flat()}function Km(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const ls=[{id:"mpc-60-tight",name:"MPC 60 Tight",stepsPerBar:16,timingOffsets:[0,.02,0,.01,0,.03,0,.01,0,.02,0,.01,0,.03,0,.01],velocityScales:[1.1,.85,.95,.8,1.05,.85,.9,.8,1.1,.85,.95,.8,1.05,.85,.9,.8],durationScales:[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]},{id:"mpc-60-swing",name:"MPC 60 Swing",stepsPerBar:16,timingOffsets:[0,.06,0,.04,0,.07,0,.04,0,.06,0,.04,0,.07,0,.04],velocityScales:[1.15,.7,.9,.75,1.1,.7,.85,.75,1.15,.7,.9,.75,1.1,.7,.85,.75],durationScales:[1.05,.9,1,.95,1.05,.9,1,.95,1.05,.9,1,.95,1.05,.9,1,.95]},{id:"hip-hop-lazy",name:"Hip-Hop Lazy",stepsPerBar:16,timingOffsets:[0,.04,.01,.05,0,.04,.02,.06,0,.04,.01,.05,0,.04,.02,.06],velocityScales:[1.2,.65,.85,.6,1.1,.65,.8,.6,1.2,.65,.85,.6,1.1,.65,.8,.6],durationScales:[1.1,1,1,.9,1.1,1,1,.9,1.1,1,1,.9,1.1,1,1,.9]},{id:"funk-pocket",name:"Funk Pocket",stepsPerBar:16,timingOffsets:[0,-.01,.03,0,0,-.01,.04,0,0,-.01,.03,0,0,-.01,.04,0],velocityScales:[1.2,.9,.7,1.05,.85,.9,.7,1,1.15,.9,.7,1.05,.85,.9,.7,1],durationScales:[1,.95,1.1,1,1,.95,1.1,1,1,.95,1.1,1,1,.95,1.1,1]},{id:"shuffle-blues",name:"Shuffle / Blues",stepsPerBar:8,timingOffsets:[0,.11,0,.11,0,.11,0,.11],velocityScales:[1.2,.8,1.1,.8,1.2,.8,1.1,.8],durationScales:[1.1,.8,1.1,.8,1.1,.8,1.1,.8]},{id:"reggaeton",name:"Reggaeton",stepsPerBar:16,timingOffsets:[0,0,0,.03,0,0,0,.03,0,0,0,.03,0,0,0,.03],velocityScales:[1.3,.6,.9,1.1,.7,.6,.9,1.1,1.3,.6,.9,1.1,.7,.6,.9,1.1],durationScales:[1,1,1,.9,1,1,1,.9,1,1,1,.9,1,1,1,.9]}];function Ym(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function pc(e,t){return t.amount===0?e:e.map(n=>{const a=n.time/t.grid;if(Math.round(a)%2===1){const l=t.grid*t.amount*.5;return{...n,time:n.time+l}}return{...n}})}function fc(e,t){const n=t.seed!=null?Ym(t.seed):Math.random;return e.map(a=>{const s=(n()-.5)*2*t.timingAmount,i=Math.round((n()-.5)*2*t.velocityAmount),l=(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+l)}})}function mc(e,t,n=1){const a=4/t.stepsPerBar;return e.map(s=>{const i=s.time/a,l=Math.round(i)%t.stepsPerBar,o=t.timingOffsets[l]*a*n,c=1+(t.velocityScales[l]-1)*n,d=1+(t.durationScales[l]-1)*n;return{...s,time:Math.max(0,s.time+o),velocity:Math.max(1,Math.min(127,Math.round(s.velocity*c))),duration:Math.max(.01,s.duration*d)}})}function Zm(e,t){let n=[...e.map(a=>({...a}))];return t.template&&t.grooveStrength>0&&(n=mc(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=pc(n,t.swing)),t.humanize&&(n=fc(n,t.humanize)),n}function Xm(e){return ls.find(t=>t.id===e)}function Qm(){return ls.map(({id:e,name:t})=>({id:e,name:t}))}function gc(e){switch(e){case"1/4":return 1;case"1/8":return .5;case"1/16":return .25;case"1/32":return .125;case"1/4T":return 2/3;case"1/8T":return 1/3;case"1/16T":return 1/6}}function cs(e,t){return gc(e)*60/t}function Na(e,t,n){const a=cs(t,n);return Math.round(e/a)*a}function Jm(e,t){const{value:n,bpm:a,strength:s=1,quantizeStarts:i=!0,quantizeDurations:l=!1}=t,o=cs(n,a);return e.map(c=>{let{start:d,duration:h}=c;if(i){const f=Math.round(d/o)*o;d=d+(f-d)*s}if(l){const f=Math.max(o,Math.round(h/o)*o);h=h+(f-h)*s}return d===c.start&&h===c.duration?c:{...c,start:d,duration:h}})}function eg(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function tg(e,t={}){const{timingRange:n=.02,velocityRange:a=10,seed:s}=t,i=s!=null?eg(s):Math.random;return e.map(l=>{const o=(i()*2-1)*n,c=Math.round((i()*2-1)*a);return{...l,start:Math.max(0,l.start+o),velocity:l.velocity!=null?Math.max(1,Math.min(127,(l.velocity??100)+c)):void 0}})}function ng(){return{start:0,end:0,enabled:!1}}function rg(e,t){return{...e<t?{start:e,end:t}:{start:t,end:e},enabled:!0}}function ag(e,t,n){return{start:Na(e.start,t,n),end:Na(e.end,t,n),enabled:e.enabled}}function sg(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function ig(e,t){if(!t.enabled||t.end<=t.start||e<t.start)return e;if(e>=t.end){const n=t.end-t.start;return t.start+(e-t.start)%n}return e}function Ta(e){return e.length===1?e.toLowerCase():e}function Cr(e){var n,a,s,i;const t=[];return(n=e.modifiers)!=null&&n.ctrl&&t.push("Ctrl"),(a=e.modifiers)!=null&&a.shift&&t.push("Shift"),(s=e.modifiers)!=null&&s.alt&&t.push("Alt"),(i=e.modifiers)!=null&&i.meta&&t.push("Meta"),t.push(Ta(e.key)),t.join("+")}function og(e,t){var o,c,d,h;const n=Ta(e.key)===Ta(t.key),a=!!e.ctrlKey==!!((o=t.modifiers)!=null&&o.ctrl),s=!!e.shiftKey==!!((c=t.modifiers)!=null&&c.shift),i=!!e.altKey==!!((d=t.modifiers)!=null&&d.alt),l=!!e.metaKey==!!((h=t.modifiers)!=null&&h.meta);return n&&a&&s&&i&&l}class yc{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],l=n[s];Cr(i.binding)===Cr(l.binding)&&(i.scope===l.scope||i.scope==="global"||l.scope==="global")&&t.push([i,l])}return t}getGrouped(){const t={};for(const n of this.actions.values())t[n.group]||(t[n.group]=[]),t[n.group].push(n);return t}getAll(){return[...this.actions.values()]}exportConfig(){return[...this.actions.values()].map(t=>({id:t.id,binding:t.binding}))}importConfig(t){for(const n of t)this.rebind(n.id,n.binding)}formatBinding(t){const n=this.actions.get(t);return n?Cr(n.binding):""}handleKeyDown(t){if(!this.enabled)return!1;for(const n of this.actions.values())if(n.enabled&&this.activeScopes.has(n.scope)&&og(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 lg(e={}){const t=new yc,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 cg(e){return Cr(e)}const dg=["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"],ug=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],hg=500*1024*1024,pg=20;function Gt(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function fg(e,t){return!!(e.type&&t.some(n=>e.type.startsWith(n.replace("*","")))||e.type.startsWith("audio/"))}function mg(e,t){const n=Gt(e.name);return n!==""&&t.includes(n)}function ds(e,t={}){const n=t.maxSize??hg,a=t.allowedTypes??dg,s=t.allowedExtensions??ug,i=t.maxFiles??pg,l=[],o=[];for(let c=0;c<e.length;c++){const d=e[c];if(c>=i){o.push({file:d,reason:"limit",message:`Exceeded maximum of ${i} files`});continue}if(d.size>n){o.push({file:d,reason:"size",message:`File exceeds ${Math.round(n/1024/1024)}MB limit`});continue}if(!fg(d,a)&&!mg(d,s)){o.push({file:d,reason:"type",message:`Unsupported file type: ${d.type||Gt(d.name)}`});continue}l.push(d)}return{valid:l,errors:o}}async function vc(e){const t={file:e,name:e.name.replace(/\.[^.]+$/,""),extension:Gt(e.name),sizeBytes:e.size,mimeType:e.type||`audio/${Gt(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 gg(e){let t=0;return{onDragEnter:n=>{var a;n.preventDefault(),n.stopPropagation(),t++,t===1&&((a=e.onDragEnter)==null||a.call(e))},onDragOver:n=>{n.preventDefault(),n.stopPropagation(),(n instanceof DragEvent&&n.dataTransfer||"dataTransfer"in n&&n.dataTransfer)&&(n.dataTransfer.dropEffect="copy")},onDragLeave:n=>{var a;n.preventDefault(),n.stopPropagation(),t--,t===0&&((a=e.onDragLeave)==null||a.call(e))},onDrop:async n=>{var d,h;n.preventDefault(),n.stopPropagation(),t=0,(d=e.onDragLeave)==null||d.call(e);const a="dataTransfer"in n?n.dataTransfer:null;if(!((h=a==null?void 0:a.files)!=null&&h.length))return;const s=Array.from(a.files),{valid:i,errors:l}=ds(s,e.validation),o=[],c=[...l];for(const f of i)if(e.probe)try{o.push(await vc(f))}catch{c.push({file:f,reason:"decode",message:"Failed to decode audio"})}else o.push({file:f,name:f.name.replace(/\.[^.]+$/,""),extension:Gt(f.name),sizeBytes:f.size,mimeType:f.type||`audio/${Gt(f.name)}`});e.onDrop({accepted:o,rejected:c})}}}function yg(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 o;if(!((o=n.files)!=null&&o.length)){t({accepted:[],rejected:[]});return}const a=Array.from(n.files),{valid:s,errors:i}=ds(a,e.validation),l=s.map(c=>({file:c,name:c.name.replace(/\.[^.]+$/,""),extension:Gt(c.name),sizeBytes:c.size,mimeType:c.type||`audio/${Gt(c.name)}`}));t({accepted:l,rejected:i})},n.click()})}var Ot=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(Ot||{}),bc=(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))(bc||{}),xc=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(xc||{});const vg=["var(--nice-success, #4caf50)","var(--nice-primary, #2196f3)","var(--nice-warning, #ff9800)","var(--nice-color-accent-pink, #e91e63)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-success, #8bc34a)","var(--nice-warning, #ffc107)"],Lr=["off","no function","brak"],bg=e=>e.segments.some(t=>t.isOff||Lr.some(n=>t.name.toLowerCase().includes(n))),xg=e=>e.segments.find(t=>t.isOff||Lr.some(n=>t.name.toLowerCase().includes(n))),Sc=e=>Math.floor((e.valueFrom+e.valueTo)/2),Sg=e=>{const t=xg(e);return t?Sc(t):0},wg=(e,t)=>e.segments.find(n=>t>=n.valueFrom&&t<=n.valueTo),Mn=(e,t=0,n=255)=>Math.max(t,Math.min(n,Math.round(e))),Un=({channel:e,value:t,onChange:n,onCommit:a,showDirectionHint:s})=>{const[i,l]=u.useState(Mn(t)),o=u.useMemo(()=>wg(e,i),[e,i]);u.useEffect(()=>l(Mn(t)),[t]);const c=d=>{const h=Mn(d);l(h),n(h),a==null||a(h)};return r.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:6},children:[r.jsxs("strong",{children:[e.channel,". ",e.name]}),s&&o&&r.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:o.name})]}),r.jsx("input",{type:"range",min:0,max:255,value:i,onChange:d=>{const h=Mn(Number(d.target.value));l(h),n(h)},onMouseUp:()=>a==null?void 0:a(i),onTouchEnd:()=>a==null?void 0:a(i),style:{width:"100%"}}),r.jsx("div",{style:{marginTop:6},children:r.jsx("input",{type:"number",min:0,max:255,value:i,onChange:d=>{const h=Mn(Number(d.target.value));l(h),n(h)},onBlur:()=>a==null?void 0:a(i),style:{width:80,padding:6,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:6}})}),bg(e)&&r.jsx("button",{type:"button",onClick:()=>c(Sg(e)),style:{width:"100%",marginTop:8,padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)",cursor:"pointer"},children:"OFF"})]})},us=({channel:e,value:t,onChange:n,onCommit:a})=>{const s=u.useMemo(()=>{const l=[...e.segments];return l.sort((o,c)=>{const d=(o.isOff?-1:0)+(Lr.some(f=>o.name.toLowerCase().includes(f))?-1:0),h=(c.isOff?-1:0)+(Lr.some(f=>c.name.toLowerCase().includes(f))?-1:0);return d!==h?d-h:o.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),l},[e]),i=l=>{const o=Sc(l);n(o),a==null||a(o)};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((l,o)=>{const c=t>=l.valueFrom&&t<=l.valueTo;return r.jsx("button",{type:"button",onClick:()=>i(l),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:`${l.name} [${l.valueFrom}..${l.valueTo}]`,children:l.name},`${l.name}-${o}`)})})]})},hs=e=>{switch(e.channel.type){case Ot.Dimmer:case Ot.DimmerWithOff:return r.jsx(Un,{...e});case Ot.RotationWithOff:case Ot.RotationWithOffAndCcw:return r.jsx(Un,{...e,showDirectionHint:!0});case Ot.Options:return r.jsx(us,{...e});default:return r.jsx(Un,{...e})}},oa=e=>Math.max(0,Math.min(255,Math.round(e))),kg=[{target:".ntd-dmx-editor",titleKey:"tutorial.dmxEditor.intro.title",title:"DMX editor",contentKey:"tutorial.dmxEditor.intro.content",content:"Pick the FTDI device and port, then set each DMX channel’s value with the sliders to control your lighting fixtures live.",placement:"auto"}];function wc({service:e,...t}){return e?r.jsx(Cg,{service:e,...t}):r.jsx("div",{className:t.className,style:t.style,children:r.jsx("small",{children:"Provide a `service` prop (DmxService) to control hardware."})})}function Cg({service:e,pollInterval:t=500,className:n,style:a,tutorial:s}){const[i,l]=u.useState([]),[o,c]=u.useState(null),[d,h]=u.useState(()=>Array(513).fill(0)),[f,p]=u.useState(30),[y,g]=u.useState(0),[x,v]=u.useState(!1),m=u.useRef(null);u.useEffect(()=>{let I=!1;return e.getDevices().then(T=>{I||(l(T),T.length>0&&c(T[0]))}).catch(()=>{}),()=>{I=!0}},[e]),u.useEffect(()=>{if(m.current&&window.clearInterval(m.current),!(t<=0))return m.current=window.setInterval(async()=>{try{const I=await e.getState();Array.isArray(I.frontSnapshot)&&I.frontSnapshot.length>=513&&h(I.frontSnapshot.slice(0,513)),typeof I.fps=="number"&&p(I.fps),typeof I.startCode=="number"&&g(I.startCode)}catch{}},t),()=>{m.current&&window.clearInterval(m.current)}},[e,t]);const S=async()=>{o&&(await e.openPort(o.serialNumber||o.description),v(!0))},b=async()=>{await e.closePort(),v(!1)},w=async()=>{await e.blackout(),h(I=>{const T=[...I];for(let E=1;E<T.length;E++)T[E]=0;return T})},N=()=>e.configure(f,y),R=(I,T)=>{const E=oa(T);h(_=>{const D=[..._];return D[I]=E,D})},P=(I,T)=>e.setChannel(I,oa(T)),j=(o==null?void 0:o.deviceInfo)??null,M=u.useMemo(()=>{var I;return(I=j==null?void 0:j.channels)!=null&&I.length?j.channels:Array.from({length:16},(T,E)=>({channel:E+1,name:`Channel ${E+1}`,type:Ot.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[j]);return r.jsxs("div",{className:`ntd-dmx-editor ${n??""}`,style:{position:"relative",padding:16,display:"grid",gap:16,...a},children:[r.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:r.jsx(we.NiceTutorialButton,{steps:we.resolveTutorial(s,kg)})}),r.jsxs("section",{style:{display:"grid",gap:12,gridTemplateColumns:"1fr auto auto auto",alignItems:"end"},children:[r.jsxs("div",{children:[r.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FTDI Device"}),r.jsx("select",{value:(o==null?void 0:o.serialNumber)||"",onChange:I=>c(i.find(T=>T.serialNumber===I.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"},children:i.map(I=>{var T,E;return r.jsxs("option",{value:I.serialNumber,children:[((T=I.deviceInfo)==null?void 0:T.manufacturer)??""," ",((E=I.deviceInfo)==null?void 0:E.model)??I.description," (",I.serialNumber||I.description,")"]},I.serialNumber||I.description)})}),j&&r.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:["Mode: ",r.jsx("b",{children:j.modeName}),", footprint: ",r.jsx("b",{children:j.footprint})]})]}),r.jsx("button",{onClick:S,disabled:!o||x,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-success, #10b981)",background:"var(--nice-success-bg, #ecfdf5)",cursor:"pointer"},children:"Open port"}),r.jsx("button",{onClick:b,disabled:!x,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-danger, #ef4444)",background:"var(--nice-danger-bg, #fef2f2)",cursor:"pointer"},children:"Close port"}),r.jsx("button",{onClick:w,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-border-color, #4b5563)",background:"var(--nice-bg-secondary, #f3f4f6)",cursor:"pointer"},children:"Blackout"})]}),r.jsxs("section",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(160px, 100%), 1fr))",gap:12,alignItems:"end"},children:[r.jsxs("div",{children:[r.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FPS"}),r.jsx("input",{type:"number",min:10,max:44,value:f,onChange:I=>p(Number(I.target.value)),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),r.jsxs("div",{children:[r.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"Start Code"}),r.jsx("input",{type:"number",min:0,max:255,value:y,onChange:I=>g(oa(Number(I.target.value))),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),r.jsx("div",{children:r.jsx("button",{onClick:N,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-primary, #3b82f6)",background:"var(--nice-primary-bg, #eff6ff)",cursor:"pointer"},children:"Apply configuration"})})]}),r.jsxs("section",{children:[r.jsx("h3",{style:{margin:"8px 0 12px",fontSize:16},children:"Channels"}),r.jsx("div",{style:{display:"grid",gap:12,gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))"},children:M.map(I=>r.jsx(hs,{channel:I,value:d[I.channel]??0,onChange:T=>R(I.channel,T),onCommit:T=>P(I.channel,T)},I.channel))})]})]})}const kc=[{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 Cc{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,kc.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 l=this.fixtures.get(t);if(!l)return;const o=this.profiles.get(l.profileId);if(!o)return;const c=[...l.values];o.channels.forEach((d,h)=>{d.name.toLowerCase().includes("red")?c[h]=n:d.name.toLowerCase().includes("green")?c[h]=a:d.name.toLowerCase().includes("blue")?c[h]=s:d.name.toLowerCase().includes("white")&&(c[h]=i)}),this.setFixtureValues(t,c)}setFixtureDimmer(t,n){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);s&&s.channels.forEach((i,l)=>{i.type==="dimmer"&&(a.values[l]=Math.max(0,Math.min(255,Math.round(n*255))),this.setChannel(a.universe,a.startChannel+l,a.values[l]))})}fadeFixture(t,n,a,s="linear"){return new Promise(i=>{const l=this.fixtures.get(t);if(!l){i();return}const o=[...l.values],c=performance.now(),d=()=>{const h=performance.now()-c,f=Math.min(1,h/a);let p=f;switch(s){case"ease-in":p=f*f;break;case"ease-out":p=1-(1-f)*(1-f);break;case"ease-in-out":p=f<.5?2*f*f:1-Math.pow(-2*f+2,2)/2;break}const y=o.map((g,x)=>{const v=n[x]??g;return Math.round(g+(v-g)*p)});this.setFixtureValues(t,y),f<1?requestAnimationFrame(d):i()};d()})}setOutputCallback(t){this.outputCallback=t}start(){this.running||(this.running=!0,this.intervalId=window.setInterval(()=>{this.sendOutput()},1e3/this.frameRate))}stop(){this.running=!1,this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null)}sendOutput(){this.outputCallback&&this.universes.forEach((t,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 jg=6454,Mg=new Uint8Array([65,114,116,45,78,101,116,0]);function Rg(e,t){const n=new Uint8Array(18+t.length);return n.set(Mg,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 Ng=5568;function Tg(e,t,n,a=100,s="Nice2Dev DMX"){const i=Math.min(t.length,512),l=126+i,o=new Uint8Array(l),c=new DataView(o.buffer);c.setUint16(0,16,!1),c.setUint16(2,0,!1);const d=[65,83,67,45,69,49,46,49,55,0,0,0];for(let g=0;g<d.length;g++)o[4+g]=d[g];const h=l-16;c.setUint16(16,28672|h&4095,!1),c.setUint32(18,4,!1);for(let g=0;g<16;g++)o[22+g]=g+1;const f=l-38;c.setUint16(38,28672|f&4095,!1),c.setUint32(40,2,!1);const p=new TextEncoder().encode(s.slice(0,63));o.set(p,44),o[108]=a,c.setUint16(109,0,!1),o[111]=n&255,o[112]=0,c.setUint16(113,e,!1);const y=i+11;return c.setUint16(115,28672|y&4095,!1),o[117]=2,o[118]=161,c.setUint16(119,0,!1),c.setUint16(121,1,!1),c.setUint16(123,i+1,!1),o[125]=0,o.set(t.slice(0,i),126),o}function $g(e){const t=e>>8&255,n=e&255;return`239.255.${t}.${n}`}class Pg{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 l;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 o of n.channels)o.channel>=1&&o.channel<=512&&(a[o.channel-1]=o.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 o;(o=this.onOutput)==null||o.call(this,this.fadeToValues),this.timer=setTimeout(()=>this.advanceStep(),i)}):((l=this.onOutput)==null||l.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 l=performance.now()-a,o=Math.min(l/t,1);for(let d=0;d<512;d++)s[d]=Math.round(this.fadeFromValues[d]+(this.fadeToValues[d]-this.fadeFromValues[d])*o);(c=this.onOutput)==null||c.call(this,s),o<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 Ag=({engine:e,tracks:t=[],scenes:n=[],duration:a=3e5,currentTime:s=0,bpm:i=120,onTimeChange:l,onCueAdd:o,onCueUpdate:c,onCueDelete:d,onTrackAdd:h,onTrackUpdate:f,onPlay:p,onPause:y,onStop:g,className:x=""})=>{const[v,m]=u.useState(1),[S,b]=u.useState(0),[w,N]=u.useState(!1),[R,P]=u.useState(null),[j,M]=u.useState(null),[I,T]=u.useState(!0),[E,_]=u.useState(1e3),D=u.useRef(null),q=u.useRef(null),te=u.useRef(0),z=u.useMemo(()=>.1*v,[v]),U=u.useCallback(A=>A*z,[z]),Z=u.useCallback(A=>A/z,[z]),ae=u.useCallback(A=>{if(!I)return A;const L=6e4/i;return Math.round(A/L)*L},[I,i]);u.useEffect(()=>{if(w){const A=performance.now(),L=s,G=()=>{const F=performance.now()-A,V=L+F;if(V>=a){N(!1),l==null||l(0),g==null||g();return}Y(V),l==null||l(V),q.current=requestAnimationFrame(G)};q.current=requestAnimationFrame(G),p==null||p()}else q.current!==null&&(cancelAnimationFrame(q.current),q.current=null),y==null||y();return()=>{q.current!==null&&cancelAnimationFrame(q.current)}},[w,s,a,l,p,y,g]);const Y=u.useCallback(A=>{t.forEach(L=>{L.muted||L.cues.forEach(G=>{const F=G.startTime,V=F+G.duration;if(A>=F&&A<V&&te.current<F){const Q=n.find(le=>le.id===G.sceneId);Q&&Q.fixtures.forEach(le=>{G.fadeIn&&G.fadeIn>0?e.fadeFixture(le.fixtureId,le.values,G.fadeIn):e.setFixtureValues(le.fixtureId,le.values)})}if(te.current<V&&A>=V){const Q=n.find(le=>le.id===G.sceneId);Q&&Q.fixtures.forEach(le=>{if(e.getFixture(le.fixtureId)&&G.fadeOut&&G.fadeOut>0){const ne=new Array(le.values.length).fill(0);e.fadeFixture(le.fixtureId,ne,G.fadeOut)}})}})}),te.current=A},[t,n,e]),O=A=>{const L=Math.floor(A/1e3),G=Math.floor(L/60),F=L%60,V=Math.floor(A%1e3/(1e3/30));return`${G}:${F.toString().padStart(2,"0")}:${V.toString().padStart(2,"0")}`},C=u.useCallback(A=>{if(!D.current)return;const L=D.current.getBoundingClientRect(),G=A.clientX-L.left+S,F=ae(Z(G));l==null||l(Math.max(0,Math.min(a,F)))},[S,Z,ae,a,l]),$=u.useCallback((A,L,G)=>{const F=t.find(le=>le.id===L),V=F==null?void 0:F.cues.find(le=>le.id===A);if(!V)return;const Q=ae(Math.max(0,V.startTime+Z(G)));c==null||c({...V,startTime:Q})},[t,Z,ae,c]),k=()=>{const A=6e4/i,L=Math.ceil(a/A),G=[];for(let F=0;F<=L;F++){const V=F*A,Q=U(V),le=F%4===0;G.push(r.jsx("div",{className:`nice-dmx-timeline__beat ${le?"nice-dmx-timeline__beat--measure":""}`,style:{left:Q},children:le&&r.jsx("span",{className:"nice-dmx-timeline__beat-label",children:F/4+1})},F))}return G},W=(A,L)=>{const G=U(A.startTime),F=U(A.duration),V=n.find(Q=>Q.id===A.sceneId);return r.jsxs("div",{className:`nice-dmx-timeline__cue ${R===A.id?"nice-dmx-timeline__cue--selected":""}`,style:{left:G,width:F,backgroundColor:(V==null?void 0:V.color)||L.color||"var(--nice-accent, #8b5cf6)"},onClick:Q=>{Q.stopPropagation(),P(A.id)},draggable:!L.locked,onDragEnd:Q=>{var oe;const le=(oe=Q.target.parentElement)==null?void 0:oe.getBoundingClientRect();le&&$(A.id,L.id,Q.clientX-le.left-G)},children:[r.jsx("span",{className:"nice-dmx-timeline__cue-name",children:A.name||(V==null?void 0:V.name)}),A.fadeIn&&A.fadeIn>0&&r.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--in",style:{width:U(A.fadeIn)}}),A.fadeOut&&A.fadeOut>0&&r.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--out",style:{width:U(A.fadeOut)}})]},A.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:()=>l==null?void 0:l(0),title:"Go to start","aria-label":"Go to start",children:r.jsx(B.NtdSkipBack,{size:14})}),r.jsx("button",{type:"button",onClick:()=>N(!w),title:w?"Pause":"Play","aria-label":w?"Pause":"Play",children:w?r.jsx(B.NtdPause,{size:14}):r.jsx(B.NtdPlay,{size:14})}),r.jsx("button",{type:"button",onClick:()=>{N(!1),l==null||l(0),e.blackout(),g==null||g()},title:"Stop","aria-label":"Stop",children:r.jsx(B.NtdStop,{size:14})})]}),r.jsx("div",{className:"nice-dmx-timeline__time",children:O(s)}),r.jsxs("div",{className:"nice-dmx-timeline__tools",children:[r.jsx("button",{type:"button",className:I?"active":"",onClick:()=>T(!I),title:"Snap to grid","aria-label":"Snap to grid",children:r.jsx(B.NtdGrid,{size:14})}),r.jsx("button",{type:"button",onClick:()=>m(Math.max(.25,v-.25)),title:"Zoom out",children:"−"}),r.jsxs("span",{className:"nice-dmx-timeline__zoom",children:[Math.round(v*100),"%"]}),r.jsx("button",{type:"button",onClick:()=>m(Math.min(4,v+.25)),title:"Zoom in",children:"+"})]}),r.jsxs("div",{className:"nice-dmx-timeline__bpm",children:[r.jsx("label",{children:"BPM:"}),r.jsx("span",{children:i})]}),r.jsx("button",{type:"button",className:"nice-dmx-timeline__blackout",onClick:()=>e.blackout(),title:"Blackout","aria-label":"Blackout",children:r.jsx(B.NtdMoon,{size:14})})]}),r.jsxs("div",{className:"nice-dmx-timeline__content",children:[r.jsxs("div",{className:"nice-dmx-timeline__headers",children:[t.map(A=>r.jsxs("div",{className:`nice-dmx-timeline__header ${j===A.id?"nice-dmx-timeline__header--selected":""}`,onClick:()=>M(A.id),children:[r.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:A.color||"var(--nice-accent, #8b5cf6)"}}),r.jsx("span",{className:"nice-dmx-timeline__track-name",children:A.name}),r.jsxs("div",{className:"nice-dmx-timeline__track-controls",children:[r.jsx("button",{type:"button",className:A.muted?"active":"",onClick:L=>{L.stopPropagation(),f==null||f({...A,muted:!A.muted})},title:"Mute",children:"M"}),r.jsx("button",{type:"button",className:A.locked?"active":"",onClick:L=>{L.stopPropagation(),f==null||f({...A,locked:!A.locked})},title:"Lock","aria-label":"Lock",children:r.jsx(B.NtdLock,{size:14})})]})]},A.id)),r.jsx("button",{type:"button",className:"nice-dmx-timeline__add-track",onClick:()=>{h==null||h({id:`track-${Date.now()}`,name:`Track ${t.length+1}`,fixtureIds:[],cues:[]})},children:"+ Add Track"})]}),r.jsxs("div",{className:"nice-dmx-timeline__tracks",ref:D,onClick:C,onScroll:A=>b(A.currentTarget.scrollLeft),children:[r.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:U(a)},children:k()}),t.map(A=>r.jsx("div",{className:`nice-dmx-timeline__track ${A.muted?"nice-dmx-timeline__track--muted":""}`,style:{width:U(a)},children:A.cues.map(L=>W(L,A))},A.id)),r.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:U(s)}})]})]})]})};function Eg(){const[e]=u.useState(()=>new Cc);return u.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function Ig(e,t,n=120){const[a,s]=u.useState(0),i=u.useRef(0);return u.useEffect(()=>{if(!t)return;const l=60/n,o=()=>{const c=t.currentTime,d=Math.floor(c/l);d!==i.current&&(i.current=d,s(d))};return t.addEventListener("timeupdate",o),()=>t.removeEventListener("timeupdate",o)},[t,n]),{currentBeat:a}}const Lg=[],zg=[{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 jc(){const[e,t]=u.useState(!1),[n,a]=u.useState(.8),[s,i]=u.useState(!1),[l,o]=u.useState(null),[c,d]=u.useState(null),[h,f]=u.useState(null),p=u.useRef(null),y=u.useRef(null),g=u.useRef(null),x=u.useRef(null),v=u.useRef([]),m=u.useRef(null),S=u.useRef(null),b=u.useCallback(()=>{if(y.current)return;const D=new AudioContext;y.current=D;const q=D.createGain();q.gain.value=n,x.current=q;const te=D.createAnalyser();te.fftSize=256,m.current=te,q.connect(te).connect(D.destination)},[]),w=u.useCallback(()=>{const D=p.current,q=y.current,te=x.current;if(!D||!q||!te||g.current)return;const z=q.createMediaElementSource(D);g.current=z,v.current.length>0?(z.connect(v.current[0]),v.current[v.current.length-1].connect(te)):z.connect(te)},[]),N=u.useCallback(()=>{var q;const D=p.current;!D||!S.current||(Zt(),b(),w(),((q=y.current)==null?void 0:q.state)==="suspended"&&y.current.resume(),D.play().catch(te=>d(String(te))))},[b,w]),R=u.useCallback(()=>{var D;(D=p.current)==null||D.pause()},[]),P=u.useCallback(()=>{e?R():N()},[e,N,R]),j=u.useCallback(D=>{const q=Math.max(0,Math.min(1,D));a(q),x.current&&(x.current.gain.value=q),p.current&&(p.current.volume=q)},[]),M=u.useCallback(D=>{S.current=D,d(null),o(null),i(!0),g.current&&(g.current.disconnect(),g.current=null),p.current||(p.current=new Audio,p.current.crossOrigin="anonymous",p.current.addEventListener("playing",()=>{t(!0),i(!1)}),p.current.addEventListener("pause",()=>t(!1)),p.current.addEventListener("waiting",()=>i(!0)),p.current.addEventListener("canplay",()=>i(!1)),p.current.addEventListener("error",()=>d("Failed to load stream"))),p.current.src=D.streamUrl,p.current.load(),o({genre:D.genre,bitrate:D.bitrate})},[]),I=u.useCallback(D=>{y.current||b();const te=y.current;v.current.forEach(U=>U.disconnect());const z=D.bands.map(U=>{const Z=te.createBiquadFilter();return Z.type="peaking",Z.frequency.value=U.frequency,Z.gain.value=U.gain,Z.Q.value=U.Q??1.4,Z});for(let U=0;U<z.length-1;U++)z[U].connect(z[U+1]);v.current=z,g.current&&x.current&&(g.current.disconnect(),g.current.connect(z[0]),z[z.length-1].connect(x.current)),f(D.name)},[b]),T=u.useCallback(()=>{v.current.forEach(D=>D.disconnect()),v.current=[],g.current&&x.current&&(g.current.disconnect(),g.current.connect(x.current)),f(null)},[]);return u.useEffect(()=>()=>{var D,q,te;(D=p.current)==null||D.pause(),p.current=null,v.current.forEach(z=>z.disconnect()),(q=g.current)==null||q.disconnect(),(te=y.current)==null||te.close()},[]),[{isPlaying:e,volume:n,isBuffering:s,metadata:l,error:c,activePreset:h},{play:N,pause:R,toggle:P,setVolume:j,setStation:M,applyEQPreset:I,clearEQ:T}]}function Mc({stations:e,activeStationId:t,onSelect:n,onToggleFavorite:a,className:s}){const{t:i}=Te(),[l,o]=u.useState(""),[c,d]=u.useState(null),[h,f]=u.useState(!1),p=u.useMemo(()=>[...new Set(e.map(g=>g.genre).filter(Boolean))],[e]),y=u.useMemo(()=>e.filter(g=>{var x,v;if(h&&!g.isFavorite||c&&g.genre!==c)return!1;if(l){const m=l.toLowerCase();return g.name.toLowerCase().includes(m)||(((x=g.genre)==null?void 0:x.toLowerCase().includes(m))??!1)||(((v=g.country)==null?void 0:v.toLowerCase().includes(m))??!1)}return!0}),[e,l,c,h]);return r.jsxs("div",{className:`nice-station-browser${s?` ${s}`:""}`,children:[r.jsxs("div",{className:"nice-station-browser__toolbar",children:[r.jsx("input",{type:"text",className:"nice-station-browser__search",placeholder:(i==null?void 0:i("search_stations"))??"Search stations...",value:l,onChange:g=>o(g.target.value)}),r.jsxs("select",{className:"nice-station-browser__genre-filter",value:c??"",onChange:g=>d(g.target.value||null),children:[r.jsx("option",{value:"",children:(i==null?void 0:i("all_genres"))??"All Genres"}),p.map(g=>r.jsx("option",{value:g,children:g},g))]}),r.jsx("button",{className:`nice-station-browser__fav-toggle${h?" nice-station-browser__fav-toggle--active":""}`,onClick:()=>f(!h),title:(i==null?void 0:i("favorites"))??"Favorites","aria-label":(i==null?void 0:i("favorites"))??"Favorites",children:r.jsx(B.NtdStar,{size:14,style:{color:"var(--nice-warning, #facc15)"}})})]}),r.jsxs("div",{className:"nice-station-browser__list",children:[y.map(g=>r.jsxs("div",{className:`nice-station-browser__item${g.id===t?" nice-station-browser__item--active":""}`,onClick:()=>n(g),role:"button",tabIndex:0,onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&n(g)},children:[g.logoUrl&&r.jsx("img",{className:"nice-station-browser__logo",src:g.logoUrl,alt:g.name,loading:"lazy"}),r.jsxs("div",{className:"nice-station-browser__info",children:[r.jsx("span",{className:"nice-station-browser__name",children:g.name}),g.genre&&r.jsx("span",{className:"nice-station-browser__genre",children:g.genre}),g.country&&r.jsx("span",{className:"nice-station-browser__country",children:g.country})]}),g.bitrate&&r.jsxs("span",{className:"nice-station-browser__bitrate",children:[g.bitrate,"kbps"]}),a&&r.jsx("button",{className:`nice-station-browser__fav${g.isFavorite?" nice-station-browser__fav--active":""}`,onClick:x=>{x.stopPropagation(),a(g.id)},"aria-label":(i==null?void 0:i("favorites"))??"Favorites",children:r.jsx(B.NtdStar,{size:14,style:{color:g.isFavorite?"var(--nice-warning, #facc15)":"var(--nice-text-muted)"}})})]},g.id)),y.length===0&&r.jsx("div",{className:"nice-station-browser__empty",children:(i==null?void 0:i("no_stations_found"))??"No stations found"})]})]})}function Dg({stations:e=Lg,initialStationId:t,autoPlay:n=!1,eqPresets:a=zg,onStationChange:s,onPlayingChange:i,onMetadata:l,onToggleFavorite:o,onRecordingStart:c,onRecordingStop:d,showBrowser:h=!0,showEqualizer:f=!1,showVisualizer:p=!1,showMetadataHistory:y=!1,showRecording:g=!1,showSleepTimer:x=!1,className:v,style:m}){var W,A;const{t:S}=Te(),[b,w]=jc(),[N,R]=u.useState(()=>t?e.find(L=>L.id===t)??null:null),[P,j]=u.useState(f),M=u.useRef(null),I=u.useRef(0),[T,E]=u.useState([]),[_,D]=u.useState(!1),q=u.useRef(null),te=u.useRef([]),[z,U]=u.useState(0),Z=u.useRef(null),[ae,Y]=u.useState(0),[O,C]=u.useState(null),$=u.useRef(null);u.useEffect(()=>{i==null||i(b.isPlaying)},[b.isPlaying,i]),u.useEffect(()=>{b.metadata&&(l==null||l(b.metadata),(b.metadata.title||b.metadata.artist)&&E(L=>[{time:new Date,meta:b.metadata},...L.slice(0,49)]))},[b.metadata,l]);const k=u.useCallback(L=>{R(L),w.setStation(L),s==null||s(L),n&&setTimeout(()=>w.play(),100)},[w,s,n]);return u.useEffect(()=>{if(t&&!N){const L=e.find(G=>G.id===t);L&&k(L)}},[t,e]),u.useEffect(()=>{if(!p||!M.current)return;const L=M.current,G=L.getContext("2d");if(!G)return;const F=()=>{I.current=requestAnimationFrame(F),G.clearRect(0,0,L.width,L.height);const V=G.createLinearGradient(0,L.height,0,0);if(V.addColorStop(0,we.resolveCssColor("var(--nice-accent-tint-80, rgba(99, 102, 241, 0.8))",G.canvas)),V.addColorStop(.5,"rgba(168,85,247,0.6)"),V.addColorStop(1,"rgba(236,72,153,0.4)"),!b.isPlaying){const ne=L.width/32;for(let K=0;K<32;K++){const H=4+Math.sin(Date.now()/1e3+K*.3)*3;G.fillStyle=V,G.fillRect(K*ne+1,L.height-H,ne-2,H)}return}const Q=32,le=L.width/Q;for(let oe=0;oe<Q;oe++){const ne=oe/Q,H=(Math.sin(Date.now()/200+oe*.5)*.3+.5)*L.height*(1-ne*.5)*(.5+Math.random()*.5);G.fillStyle=V,G.fillRect(oe*le+1,L.height-H,le-2,H)}};return F(),()=>cancelAnimationFrame(I.current)},[p,b.isPlaying]),u.useCallback(()=>{if(b.isPlaying)try{const G=new AudioContext().createMediaStreamDestination();te.current=[];const F=new MediaRecorder(G.stream,{mimeType:"audio/webm"});F.ondataavailable=V=>{V.data.size>0&&te.current.push(V.data)},F.onstop=()=>{const V=new Blob(te.current,{type:"audio/webm"});d==null||d(V),U(0),Z.current&&window.clearInterval(Z.current)},F.start(1e3),q.current=F,D(!0),U(0),Z.current=window.setInterval(()=>{U(V=>V+1)},1e3),c==null||c()}catch{}},[b.isPlaying,c,d]),u.useCallback(()=>{q.current&&_&&(q.current.stop(),D(!1),Z.current&&window.clearInterval(Z.current))},[_]),u.useCallback(L=>{$.current&&window.clearInterval($.current),Y(L),C(L*60),$.current=window.setInterval(()=>{C(G=>!G||G<=1?($.current&&window.clearInterval($.current),$.current=null,w.pause(),null):G-1)},1e3)},[w]),u.useCallback(()=>{$.current&&window.clearInterval($.current),$.current=null,C(null),Y(0)},[]),u.useEffect(()=>()=>{Z.current&&window.clearInterval(Z.current),$.current&&window.clearInterval($.current),cancelAnimationFrame(I.current)},[]),r.jsxs("div",{className:`nice-radio-player${v?` ${v}`:""}`,style:m,children:[r.jsx("div",{className:"nice-radio-player__now-playing",children:N?r.jsxs(r.Fragment,{children:[N.logoUrl&&r.jsx("img",{className:"nice-radio-player__cover",src:N.logoUrl,alt:N.name}),r.jsxs("div",{className:"nice-radio-player__info",children:[r.jsx("span",{className:"nice-radio-player__station-name",children:N.name}),((W=b.metadata)==null?void 0:W.title)&&r.jsx("span",{className:"nice-radio-player__track",children:b.metadata.artist?`${b.metadata.artist} — ${b.metadata.title}`:b.metadata.title}),((A=b.metadata)==null?void 0:A.genre)&&r.jsx("span",{className:"nice-radio-player__genre",children:b.metadata.genre}),b.isBuffering&&r.jsx("span",{className:"nice-radio-player__buffering",children:(S==null?void 0:S("buffering"))??"Buffering..."})]})]}):r.jsx("div",{className:"nice-radio-player__placeholder",children:(S==null?void 0:S("select_station"))??"Select a station"})}),r.jsxs("div",{className:"nice-radio-player__controls",children:[r.jsx("button",{className:"nice-radio-player__play-btn",onClick:w.toggle,disabled:!N,"aria-label":b.isPlaying?"Pause":"Play",children:b.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:b.volume,onChange:L=>w.setVolume(parseFloat(L.target.value)),className:"nice-radio-player__volume-slider","aria-label":"Volume"})]}),r.jsx("button",{className:`nice-radio-player__eq-btn${P?" nice-radio-player__eq-btn--active":""}`,onClick:()=>j(!P),title:"Equalizer",children:"EQ"})]}),b.error&&r.jsx("div",{className:"nice-radio-player__error",children:b.error}),P&&r.jsx("div",{className:"nice-radio-player__equalizer",children:r.jsxs("div",{className:"nice-radio-player__eq-presets",children:[a.map(L=>r.jsx("button",{className:`nice-radio-player__eq-preset${b.activePreset===L.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>w.applyEQPreset(L),children:L.name},L.name)),b.activePreset&&r.jsx("button",{className:"nice-radio-player__eq-preset",onClick:w.clearEQ,children:(S==null?void 0:S("clear"))??"Clear"})]})}),h&&r.jsx(Mc,{stations:e,activeStationId:N==null?void 0:N.id,onSelect:k})]})}const _g=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],Fg={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class Rc{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??_g,audioConstraints:{...Fg,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 l;const[i]=s.streams;i&&(a.remoteStream=i,(l=this.onRemoteStream)==null||l.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 Og(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function Bg(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function Gg(){return new AudioContext({sampleRate:48e3,latencyHint:"interactive"})}const ps=u.forwardRef(function(t,n){const{mode:a="bars",width:s=300,height:i=100,barCount:l=32,barColor:o="var(--nice-primary, #3b82f6)",backgroundColor:c="transparent",fftSize:d=256,smoothing:h=.8,minDecibels:f=-90,maxDecibels:p=-10,deviceId:y,autoStart:g=!1,onStart:x,onStop:v,onAudioLevel:m,onError:S,className:b,style:w,barBorderRadius:N=2,barGap:R=2,lineWidth:P=2}=t,j=u.useRef(null),M=u.useRef(null),I=u.useRef(null),T=u.useRef(null),E=u.useRef(0),_=u.useRef(null),D=u.useRef(0),[q,te]=u.useState(!1),z=Array.isArray(o)?o.join("|"):o,U=u.useMemo(()=>z.split("|").map(A=>we.resolveCssColor(A,j.current)),[z]),Z=u.useCallback((A,L,G=!0)=>{const F=G?A.createLinearGradient(0,i,0,0):A.createLinearGradient(0,0,s,0);return L.forEach((V,Q)=>{F.addColorStop(Q/(L.length-1),V)}),F},[s,i]),ae=u.useCallback((A,L)=>{const F=(s-(l-1)*R)/l,V=Math.floor(L.length/l),Q=U,le=Q.length>1?Z(A,Q):Q[0];A.fillStyle=le;for(let oe=0;oe<l;oe++){const K=L[oe*V]/255*i,H=oe*(F+R),ie=i-K;N>0?(A.beginPath(),A.roundRect(H,ie,F,K,N),A.fill()):A.fillRect(H,ie,F,K)}},[l,U,R,N,s,i,Z]),Y=u.useCallback((A,L)=>{const G=i/2,V=(s-(l-1)*R)/l,Q=Math.floor(L.length/l),le=U,oe=le.length>1?Z(A,le):le[0];A.fillStyle=oe;for(let ne=0;ne<l;ne++){const H=L[ne*Q]/255*G,ie=ne*(V+R);N>0?(A.beginPath(),A.roundRect(ie,G-H,V,H,N),A.fill(),A.beginPath(),A.roundRect(ie,G,V,H,N),A.fill()):(A.fillRect(ie,G-H,V,H),A.fillRect(ie,G,V,H))}},[l,U,R,N,s,i,Z]),O=u.useCallback((A,L)=>{const G=U;A.strokeStyle=G.length>1?Z(A,G,!1):G[0],A.lineWidth=P,A.lineCap="round",A.lineJoin="round",A.beginPath();const F=s/L.length;let V=0;for(let Q=0;Q<L.length;Q++){const oe=L[Q]/128*i/2;Q===0?A.moveTo(V,oe):A.lineTo(V,oe),V+=F}A.stroke()},[U,P,s,i,Z]),C=u.useCallback((A,L)=>{const G=s/2,F=i/2,V=Math.min(s,i)/3,Q=U;A.strokeStyle=Q.length>1?Z(A,Q):Q[0],A.lineWidth=P;const le=Math.floor(L.length/64),oe=Math.PI*2/64;A.beginPath();for(let ne=0;ne<64;ne++){const K=L[ne*le]/255,H=V+K*V*.5,ie=ne*oe-Math.PI/2,re=G+Math.cos(ie)*H,he=F+Math.sin(ie)*H;ne===0?A.moveTo(re,he):A.lineTo(re,he)}A.closePath(),A.stroke()},[U,P,s,i,Z]),$=u.useCallback(()=>{const A=j.current,L=I.current,G=_.current;if(!A||!L||!G)return;const F=A.getContext("2d");if(!F)return;a==="waveform"?L.getByteTimeDomainData(G):L.getByteFrequencyData(G);let V=0;for(let Q=0;Q<G.length;Q++)V+=G[Q];switch(D.current=V/(G.length*255),m==null||m(D.current),F.clearRect(0,0,s,i),c!=="transparent"&&(F.fillStyle=we.resolveCssColor(c,F.canvas),F.fillRect(0,0,s,i)),a){case"bars":ae(F,G);break;case"mirror-bars":Y(F,G);break;case"waveform":O(F,G);break;case"circle":C(F,G);break}E.current=requestAnimationFrame($)},[a,s,i,c,ae,Y,O,C,m]),k=u.useCallback(async()=>{try{if(q)return;const A=await navigator.mediaDevices.getUserMedia({audio:y?{deviceId:{exact:y}}:!0,video:!1});T.current=A;const L=new AudioContext;M.current=L;const G=L.createMediaStreamSource(A),F=L.createAnalyser();F.fftSize=d,F.smoothingTimeConstant=h,F.minDecibels=f,F.maxDecibels=p,G.connect(F),I.current=F,_.current=new Uint8Array(F.frequencyBinCount),te(!0),x==null||x(),$()}catch(A){S==null||S(A instanceof Error?A:new Error(String(A)))}},[q,y,d,h,f,p,x,S,$]),W=u.useCallback(()=>{cancelAnimationFrame(E.current),T.current&&(T.current.getTracks().forEach(L=>L.stop()),T.current=null),M.current&&(M.current.close(),M.current=null),I.current=null,_.current=null,D.current=0,te(!1),v==null||v();const A=j.current;if(A){const L=A.getContext("2d");L&&(L.clearRect(0,0,s,i),c!=="transparent"&&(L.fillStyle=we.resolveCssColor(c,L.canvas),L.fillRect(0,0,s,i)))}},[s,i,c,v]);return u.useImperativeHandle(n,()=>({start:k,stop:W,isCapturing:()=>q,getAudioLevel:()=>D.current}),[k,W,q]),u.useEffect(()=>(g&&k(),()=>{W()}),[g]),r.jsx("canvas",{ref:j,width:s,height:i,className:b,style:{display:"block",...w},"aria-label":"Audio visualizer"})}),Ni=e=>{switch(e){case"top-left":return{top:16,left:16};case"top-right":return{top:16,right:16};case"bottom-left":return{bottom:16,left:16};case"bottom-right":default:return{bottom:16,right:16}}},Wg={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"},Ug={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))"},Vg={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))"},Nc=u.forwardRef(function(t,n){const{userId:a,userName:s,userAvatarUrl:i,participants:l=[],rtcConfig:o,position:c="bottom-right",expanded:d=!0,onSignalingMessage:h,onMuteToggle:f,onLeave:p,onSpeakingChange:y,speakingThreshold:g=.1,theme:x="auto",className:v,style:m,zIndex:S=1e3}=t,b=u.useRef(null),w=u.useRef(null),N=u.useRef(new Map);u.useRef(new Map);const[R,P]=u.useState(!1),[j,M]=u.useState(!1),[I,T]=u.useState(!1),[E,_]=u.useState(d),q=u.useMemo(()=>x==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":x,[x])==="dark"?Vg:Ug;u.useEffect(()=>{const O=new Rc(a,o);return O.onRemoteStream=(C,$)=>{let k=N.current.get(C);k||(k=new Audio,k.autoplay=!0,N.current.set(C,k)),k.srcObject=$},O.onSignalingMessage=C=>{h==null||h(C)},O.onPeerStateChange=(C,$)=>{$==="connected"&&M(!0)},b.current=O,O.initialize().then(()=>{var C;(C=w.current)==null||C.start()}),()=>{O.disconnect();const C=N.current;C.forEach($=>{$.srcObject=null}),C.clear()}},[a,o,h]);const te=u.useCallback(()=>{var C;const O=!R;P(O),(C=b.current)==null||C.setMuted(O),f==null||f(O)},[R,f]),z=u.useCallback(()=>{var O,C;(O=b.current)==null||O.disconnect(),(C=w.current)==null||C.stop(),M(!1),p==null||p()},[p]),U=u.useCallback(O=>{const C=O>g;C!==I&&(T(C),y==null||y(a,C))},[g,I,a,y]),Z=u.useCallback(async O=>{var C;await((C=b.current)==null?void 0:C.createOffer(O))},[]),ae=u.useCallback(async O=>{var C;await((C=b.current)==null?void 0:C.handleSignalingMessage(O))},[]);u.useImperativeHandle(n,()=>({connectToPeer:Z,handleSignalingMessage:ae,toggleMute:te,isMuted:()=>R,leave:z,getManager:()=>b.current}),[Z,ae,te,R,z]);const Y=({participant:O,isLocal:C,isSpeaking:$})=>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:q.hoverBg,border:`2px solid ${$?q.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:q.text,transition:"border-color 0.15s ease"},children:O.avatarUrl?r.jsx("img",{src:O.avatarUrl,alt:O.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):O.name.charAt(0).toUpperCase()}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsxs("div",{style:{color:q.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[O.name,C&&r.jsx("span",{style:{color:q.textSecondary,fontWeight:400},children:" (You)"})]})}),O.isMuted&&r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:q.mutedIcon,strokeWidth:"2",children:[r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),r.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),r.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),r.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),r.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})]});return E?r.jsxs("div",{className:v,style:{...Wg,...Ni(c),backgroundColor:q.background,border:`1px solid ${q.border}`,zIndex:S,...m},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${q.border}`},children:[r.jsx("span",{style:{color:q.text,fontWeight:600},children:"Voice Chat"}),r.jsx("button",{onClick:()=>_(!1),style:{background:"none",border:"none",cursor:"pointer",padding:4,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:4},"aria-label":"Collapse",children:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:q.textSecondary,strokeWidth:"2",children:[r.jsx("polyline",{points:"4 14 10 14 10 20"}),r.jsx("polyline",{points:"20 10 14 10 14 4"}),r.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),r.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[r.jsx(Y,{participant:{id:a,name:s,avatarUrl:i,isMuted:R},isLocal:!0,isSpeaking:I&&!R}),l.map(O=>r.jsx(Y,{participant:O,isSpeaking:O.isSpeaking},O.id))]}),r.jsx(ps,{ref:w,mode:"bars",width:256,height:32,barCount:24,barColor:R?"var(--nice-text-muted, #9ca3af)":["var(--nice-primary, #3b82f6)","var(--nice-accent, #8b5cf6)"],barGap:3,barBorderRadius:2,autoStart:!1,onAudioLevel:U,style:{borderRadius:4,opacity:R?.5:1}}),r.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[r.jsx("button",{onClick:te,style:{flex:1,padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:R?q.mutedBg:q.activeBg,color:R?q.mutedIcon:q.activeIcon,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":R?"Unmute":"Mute",children:R?r.jsxs(r.Fragment,{children:[r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),r.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),r.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),r.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),r.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Muted"]}):r.jsxs(r.Fragment,{children:[r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[r.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),r.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),r.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),r.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Mic On"]})}),r.jsx("button",{onClick:z,style:{padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:"var(--nice-danger-bg, #fef2f2)",color:"var(--nice-danger-dark, #dc2626)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":"Leave voice chat",children:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[r.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),r.jsx("polyline",{points:"16 17 21 12 16 7"}),r.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]})]}):r.jsx("div",{className:v,style:{position:"fixed",...Ni(c),zIndex:S,...m},children:r.jsxs("button",{onClick:()=>_(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:q.background,boxShadow:"0 4px 12px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":"Expand voice chat",children:[r.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:q.text,strokeWidth:"2",children:[r.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),r.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),r.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),r.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),l.length>0&&r.jsx("span",{style:{position:"absolute",top:-4,right:-4,width:20,height:20,borderRadius:"50%",backgroundColor:q.speakingRing,color:"var(--nice-color-white, #fff)",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:l.length+1})]})})});function qg(e,t){const n={...t,id:`op_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now()},a=e.operations.slice(0,e.undoIndex+1);return a.push(n),{...e,operations:a,undoIndex:a.length-1}}function Hg(e){return e.undoIndex<0?e:{...e,undoIndex:e.undoIndex-1}}function Kg(e){return e.undoIndex>=e.operations.length-1?e:{...e,undoIndex:e.undoIndex+1}}function Yg(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(l=>{const o=Math.round(l.startTick/s)*s,c=l.startTick+(o-l.startTick)*i,d=(Math.random()-.5)*2*t.humanize;return{...l,startTick:Math.max(0,Math.round(c+d))}})}function Zg(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(l=>(l-s+12)%12).sort((l,o)=>l-o);for(const l of a)if(l.intervals.length===i.length&&l.intervals.every((o,c)=>o===i[c])){const o=t[s],c=t[e[0]%12];return{root:o,quality:l.quality,bass:c!==o?c:void 0,symbol:`${o}${l.quality==="maj"?"":l.quality}${c!==o?`/${c}`:""}`,intervals:l.intervals}}}return null}const Tc={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 Xg(e,t,n){const a=Tc[n],s=(e-t+120)%12;let i=a[0],l=999;for(const c of a){const d=Math.min(Math.abs(s-c),12-Math.abs(s-c));d<l&&(l=d,i=c)}const o=Math.floor((e-t)/12);return t+o*12+i}function Qg(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 Jg(e){return e>=95?"S":e>=85?"A":e>=70?"B":e>=55?"C":e>=40?"D":"F"}const ey={"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]}},ty={"Bass Drum":{staffLine:4,noteHead:"normal",stem:"down"},Snare:{staffLine:2,noteHead:"normal",stem:"up"},"Hi-Hat Closed":{staffLine:0,noteHead:"x",stem:"up"},"Hi-Hat Open":{staffLine:0,noteHead:"diamond",stem:"up"},Ride:{staffLine:-1,noteHead:"x",stem:"up"},Crash:{staffLine:-2,noteHead:"x",stem:"up"},"High Tom":{staffLine:1,noteHead:"normal",stem:"up"},"Mid Tom":{staffLine:2,noteHead:"normal",stem:"down"},"Low Tom":{staffLine:3,noteHead:"normal",stem:"down"}};exports.ALL_CAP_STYLES=Wn;exports.ALL_EFFECTS=Ll;exports.ALL_TEXTURES=To;exports.ARTNET_PORT=jg;exports.ASYMMETRIC_CAPS=xo;exports.AudioEffectType=bc;exports.AudioPlaybackEngine=tm;exports.AudioRecorder=La;exports.AutoSavePanel=Li;exports.CONTROLLER_PROFILES=Hl;exports.ChaseRunner=Pg;exports.CollaboratorPermission=xc;exports.DEFAULT_ARP_CONFIG=ua;exports.DEFAULT_AUDIO_INPUT_SETTINGS=Dl;exports.DEFAULT_BAR_FILL=Wt;exports.DEFAULT_CAP_STYLE=wo;exports.DEFAULT_EMPTY_BAR_FILL=_r;exports.DEFAULT_FONT_SETTINGS=Br;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=Fr;exports.DEFAULT_GOLD_FILLED_BAR_FILL=Or;exports.DEFAULT_KARAOKE_SETTINGS=ko;exports.DEFAULT_SEED_CONFIG=Fl;exports.DMXEngine=Cc;exports.DRUM_PATTERN_NAMES=mm;exports.DefaultScoringPresets=_a;exports.DmxChannelControl=hs;exports.DmxChannelType=Ot;exports.DmxEditor=wc;exports.DmxOptionsControl=us;exports.DmxSliderControl=Un;exports.DynamicRuleField=lt;exports.DynamicRuleOperator=ct;exports.EditorTrackProvider=za;exports.EditorUndoManager=bu;exports.FIXTURE_PROFILES=kc;exports.GENERIC_PROFILE=as;exports.GM_DRUM_MAP=ty;exports.GRADIENT_PRESETS=ul;exports.GROOVE_TEMPLATES=ls;exports.GenericPlaylistItem=Qa;exports.KARAOKE_FONT_OPTIONS=rp;exports.KEY_MAPS=Uo;exports.KaraokeFormat=Ya;exports.LANE_COLORS=In;exports.LAUNCH_CONTROL_PROFILE=ql;exports.LAYER_COLORS=vg;exports.MINILAB_PROFILE=Vl;exports.MPK_MINI_PROFILE=Ul;exports.MasterFXPanel=Di;exports.MidiCCMapper=ym;exports.NOTE_NAMES=cm;exports.NiceArpeggiatorPanel=su;exports.NiceAudioEffectsRack=Z0;exports.NiceAudioErrorBoundary=_c;exports.NiceAudioInputPicker=em;exports.NiceAudioPitchAnalyzer=dh;exports.NiceAudioStudio=Od;exports.NiceAudioTimeline=Ii;exports.NiceAutoSavePanel=Li;exports.NiceBarFillEditor=ch;exports.NiceCCAutomationLaneEditor=nu;exports.NiceCCLane=Zc;exports.NiceDMXTimeline=Ag;exports.NiceDmxChannelControl=hs;exports.NiceDmxEditor=wc;exports.NiceDmxOptionsControl=us;exports.NiceDmxSliderControl=Un;exports.NiceDynamicRuleEditor=Tf;exports.NiceEditorTrackProvider=za;exports.NiceGenericPlayer=Ao;exports.NiceGenericPlayerControls=mp;exports.NiceGenericPlayerStage=Hp;exports.NiceGenericPlaylist=of;exports.NiceGenericPlaylistItem=Qa;exports.NiceI18nProvider=Dc;exports.NiceKaraokeEditorManager=cp;exports.NiceKaraokeLyrics=ho;exports.NiceKaraokeManager=Oh;exports.NiceKaraokePhaserRenderer=hp;exports.NiceKaraokeSelectionMode=dl;exports.NiceKaraokeSessionJoin=tp;exports.NiceKaraokeSetupPanel=cl;exports.NiceKaraokeSongBrowser=Hh;exports.NiceKaraokeSummaryOverlay=$o;exports.NiceKaraokeTimeline=Ro;exports.NiceKaraokeUploader=Go;exports.NiceLFOPanel=lu;exports.NiceLatencyCalibrator=Yh;exports.NiceMasterFXPanel=Di;exports.NiceModeSwitcher=fl;exports.NiceMusicLibraryExplorer=Jp;exports.NiceNoteParticles=A0;exports.NiceNoteRiver=j0;exports.NicePadKaraokeOverlay=Wo;exports.NicePianoRoll=Pa;exports.NicePlaylistBrowser=Of;exports.NicePlaylistDualPane=Af;exports.NicePlaylistGridView=Uf;exports.NicePlaylistImportWizard=e0;exports.NicePlaylistList=ts;exports.NicePlaylistOverview=qf;exports.NicePlaylistSearchBar=Hf;exports.NicePlaylistSidebar=Gf;exports.NicePlaylistTagEditor=cf;exports.NicePlaylistTrackList=kl;exports.NiceRadioPlayer=Dg;exports.NiceRecordingOptionsPanel=_i;exports.NiceStageVisualizer=ml;exports.NiceStationBrowser=Mc;exports.NiceStepSequencerPanel=hu;exports.NiceStreamingVisualizer=ps;exports.NiceUndoRedoPanel=zi;exports.NiceVocalEffectsRack=Q0;exports.NiceVocalPerformanceReport=Uh;exports.NiceVoiceChatOverlay=Nc;exports.NiceWaveform=$i;exports.NiceYouTubePlayer=Kp;exports.NiceZoomSnapControls=Aa;exports.OVERLAY_PATTERNS=$r;exports.OXYGEN25_PROFILE=Wl;exports.PLAYER_COLORS=et;exports.PLAYER_COLOR_VARS=ur;exports.PROGRESSION_NAMES=fm;exports.PadNotePlayer=Ko;exports.PaneSide=bl;exports.PianoRoll=Pa;exports.PlaylistList=ts;exports.PlaylistType=Ja;exports.RecordingOptionsPanel=_i;exports.SACN_PORT=Ng;exports.SCALE_INTERVALS=Tc;exports.SCALE_NAMES=pm;exports.SKEW_CAPS=So;exports.STANDARD_TUNINGS=ey;exports.SYMMETRIC_CAPS=Ua;exports.ShortcutManager=yc;exports.SimpleSynth=_l;exports.SortDirection=dn;exports.SortField=xl;exports.StreamingVisualizer=ps;exports.TEXTURE_CATEGORIES=Ha;exports.TrackSource=wt;exports.UndoRedoPanel=zi;exports.ViewMode=vl;exports.VocalEffectsEngine=zl;exports.VoiceChatOverlay=Nc;exports.WebRTCAudioManager=Rc;exports.ZoomSnapControls=Aa;exports.addEffectToLayer=$m;exports.addMidiNote=Im;exports.analyzeAudioFileWithAlgorithm=Wm;exports.applyGroove=Zm;exports.applyGrooveTemplate=mc;exports.applyHumanize=fc;exports.applyKaraokeDisplayVars=Xa;exports.applyMidiTransform=Qg;exports.applySwing=pc;exports.arrow_L=Bt;exports.arrow_R=Tt;exports.autoCorrelate=Lo;exports.bracket_L=Oa;exports.bracket_R=vo;exports.buildArpSequence=ao;exports.buildLanes=Vo;exports.buildNoteDescriptors=Ka;exports.buildPadNoteEvents=Ho;exports.buildSegmentScores=zo;exports.canRedo=Ui;exports.canUndo=Wi;exports.chamfer_L=Mr;exports.chamfer_R=fn;exports.clearMidiNotes=zm;exports.clearPattern=ac;exports.computeGrade=Jg;exports.computeTheoreticalMax=el;exports.computeVocalPerformanceReport=sl;exports.convertBrowserSongToKaraokeSongFile=Th;exports.copyCCEvents=da;exports.createAnalyserNode=cc;exports.createArpPattern=Sm;exports.createArtNetPacket=Rg;exports.createBasslinePattern=wm;exports.createCCHistory=Fi;exports.createCompressorNode=uc;exports.createDefaultLFO=zr;exports.createDefaultShortcuts=lg;exports.createDropZoneHandlers=gg;exports.createEmptyPattern=Xt;exports.createEmptyStep=ss;exports.createGainNode=dc;exports.createHiHatPattern=xm;exports.createKickPattern=vm;exports.createLoopRegion=ng;exports.createSACNPacket=Tg;exports.createSnarePattern=bm;exports.createVocoderNode=hc;exports.createVoiceChatAudioContext=Gg;exports.cutCCEvents=qi;exports.deleteCCEventsInRange=Hi;exports.deserializeLFO=Qd;exports.deserializePattern=Cm;exports.detectChord=Zg;exports.downsampleAndQuantizePitchPoints=Do;exports.drawGlossyBarOnCanvas=Tn;exports.drawTimeline=ma;exports.estimateLatencyMs=_o;exports.estimateLatencyMsFromRecording=ll;exports.evaluateLFO=Ea;exports.evaluateLFOAsCC=Ia;exports.exportCCLane=Zi;exports.extractBpmFromNotes=po;exports.findTextureByUrl=ih;exports.formatShortcut=cg;exports.generateArpEvents=au;exports.generatePlaceholderWaveform=Km;exports.generateSeed=Gl;exports.generateUltrastarText=Um;exports.getActiveGradient=pl;exports.getActiveLyrics=ju;exports.getActiveWords=Mu;exports.getAlgorithmColor=Rh;exports.getAlgorithmCssVar=Nh;exports.getAlgorithmLabel=Mh;exports.getArpModes=so;exports.getArpRates=io;exports.getAudioContext=qn;exports.getAudioInputDevices=Bg;exports.getAudioWorkletProcessorCode=oc;exports.getBackgroundUrl=jh;exports.getCachedImage=rh;exports.getCapStyleByName=Rn;exports.getComboMultiplier=Qo;exports.getCoverUrl=Ch;exports.getGrooveTemplate=Xm;exports.getGrooveTemplateNames=Qm;exports.getLaneForPitch=qo;exports.getNextPlayerColor=rd;exports.getNextPlayerColorCss=ad;exports.getOverlayCanvasPattern=En;exports.getPatternByName=Nn;exports.getSACNMulticastAddress=$g;exports.getScoringPreset=Dr;exports.getTexturePattern=Pn;exports.getVerseRatingLabel=Xo;exports.handleAddCCEvent=_m;exports.handleRedo=vu;exports.handleRemoveCCEvent=Om;exports.handleSelectCCLane=Dm;exports.handleUndo=yu;exports.handleUpdateCCEvent=Fm;exports.hexToHsl=Pr;exports.humanizeMidiNotes=tg;exports.hydrateKaraokeDisplayFromBackend=ap;exports.hydratePlayerKaraokeSettingsFromBackend=Du;exports.hzToUltrastarPitch=fo;exports.importCCLane=Xi;exports.initKaraokeDisplaySettings=ip;exports.instrumentPresets=nm;exports.isAudioContextRunning=Pi;exports.isInLoopRegion=sg;exports.isWebRTCSupported=Og;exports.loadAllKaraokeSettings=_u;exports.loadAudioWorkletModule=lc;exports.loadKaraokeDisplaySettings=hl;exports.loadKaraokeSettings=Va;exports.loadRemoteScoringPresets=Iu;exports.makeClickReference=ol;exports.makeClipSelectionId=Vm;exports.mergeWaveforms=Hm;exports.midiSeedGenerator=gm;exports.midiToHz=ga;exports.normalizeHex=Ar;exports.openAudioFilePicker=yg;exports.ornate_L=Ga;exports.ornate_R=Tr;exports.parseLyrics=ku;exports.parseNotes=Hn;exports.parseUltraStarText=Bo;exports.parseVersesWithSyllables=uo;exports.parseVersesWithWords=Cu;exports.parseVideoMetadata=Io;exports.pasteCCEvents=Vi;exports.pill_L=Ht;exports.pill_R=Ft;exports.preloadTexture=qa;exports.preloadTextures=ah;exports.probeAudioFile=vc;exports.pushCCState=Oi;exports.pushOperation=qg;exports.quantizeMidiNotes=Jm;exports.quantizeNotes=Yg;exports.quantizeStepInBeats=gc;exports.quantizeStepInSeconds=cs;exports.randomizeVelocity=rc;exports.recordCCEvent=Ki;exports.redoCC=Gi;exports.redoOperation=Kg;exports.removeEffectFromLayer=Pm;exports.removeMidiNote=Lm;exports.renderGlossyBarSvg=Co;exports.resumeAudioContext=Zt;exports.reversePattern=tc;exports.sampleLFOForDisplay=no;exports.sampleLFOToCCEvents=to;exports.saveKaraokeDisplaySettings=sp;exports.saveKaraokeSettings=zu;exports.scaleResult=nl;exports.scaleTo10k=tl;exports.scoreNotesWithPitchPoints=Jo;exports.selectCCEventsInRange=Bd;exports.serializeLFO=Xd;exports.serializePattern=km;exports.setLoopFromSelection=rg;exports.setProjectWithUndo=lo;exports.setStepGate=Xl;exports.setStepNote=Yl;exports.setStepProbability=Ql;exports.setStepVelocity=Zl;exports.sharp_L=hn;exports.sharp_R=pn;exports.shield_L=Rr;exports.shield_R=yo;exports.shiftPattern=nc;exports.shouldTrigger=ic;exports.skewTL_L=hr;exports.skewTL_R=fa;exports.skewTR_L=pa;exports.skewTR_R=pr;exports.snapLoopToGrid=ag;exports.snapTimeToQuantize=Na;exports.snapToGrid=qm;exports.snapToScale=Xg;exports.soft_L=Fa;exports.soft_R=go;exports.stepDuration=is;exports.stepTimeOffset=sc;exports.syncDivisionToHz=Ji;exports.tab_L=Ba;exports.tab_R=bo;exports.thinCCEvents=Yi;exports.toTrack=Oo;exports.toggleEffectBypass=Am;exports.toggleStep=Kl;exports.toggleStepSlide=Jl;exports.transposePattern=ec;exports.undoCC=Bi;exports.undoOperation=Hg;exports.updateEffectParams=Em;exports.useAudioWorklet=Tm;exports.useAutoSave=pu;exports.useCCAutomation=Qi;exports.useCanPickSong=ep;exports.useDMXAudioSync=Ig;exports.useDMXEngine=Eg;exports.useEditorTrack=wu;exports.useKaraokePitch=Zo;exports.useKaraokeScoring=rl;exports.useLocalPlaylists=es;exports.useMPE=im;exports.useMidiLearn=am;exports.useNiceTranslation=Te;exports.useOxygen25=lm;exports.usePitchWorker=Mm;exports.usePlaybackEngine=fu;exports.useProjectCRUD=Su;exports.useRadioStream=jc;exports.useRecording=mu;exports.useScoringWorker=Rm;exports.useStepSequencer=jm;exports.useWebMidi=Ur;exports.useWorker=os;exports.validateAudioFiles=ds;exports.wave_L=Nr;exports.wave_R=Wa;exports.waveformValue=eo;exports.wrapTimeInLoop=ig;
|
|
430
|
+
E`}}function ng(e,t){return`${e}:${t}`}function rg(e,t,n,a=1){if(t==="off")return e;const s=60/n;if(t==="beat")return Math.round(e/(s/a))*(s/a);if(t==="bar"){const i=s*4;return Math.round(e/i)*i}return e}function ag(e){return e.length===0?[]:e.flat()}function sg(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const ls=[{id:"mpc-60-tight",name:"MPC 60 Tight",stepsPerBar:16,timingOffsets:[0,.02,0,.01,0,.03,0,.01,0,.02,0,.01,0,.03,0,.01],velocityScales:[1.1,.85,.95,.8,1.05,.85,.9,.8,1.1,.85,.95,.8,1.05,.85,.9,.8],durationScales:[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]},{id:"mpc-60-swing",name:"MPC 60 Swing",stepsPerBar:16,timingOffsets:[0,.06,0,.04,0,.07,0,.04,0,.06,0,.04,0,.07,0,.04],velocityScales:[1.15,.7,.9,.75,1.1,.7,.85,.75,1.15,.7,.9,.75,1.1,.7,.85,.75],durationScales:[1.05,.9,1,.95,1.05,.9,1,.95,1.05,.9,1,.95,1.05,.9,1,.95]},{id:"hip-hop-lazy",name:"Hip-Hop Lazy",stepsPerBar:16,timingOffsets:[0,.04,.01,.05,0,.04,.02,.06,0,.04,.01,.05,0,.04,.02,.06],velocityScales:[1.2,.65,.85,.6,1.1,.65,.8,.6,1.2,.65,.85,.6,1.1,.65,.8,.6],durationScales:[1.1,1,1,.9,1.1,1,1,.9,1.1,1,1,.9,1.1,1,1,.9]},{id:"funk-pocket",name:"Funk Pocket",stepsPerBar:16,timingOffsets:[0,-.01,.03,0,0,-.01,.04,0,0,-.01,.03,0,0,-.01,.04,0],velocityScales:[1.2,.9,.7,1.05,.85,.9,.7,1,1.15,.9,.7,1.05,.85,.9,.7,1],durationScales:[1,.95,1.1,1,1,.95,1.1,1,1,.95,1.1,1,1,.95,1.1,1]},{id:"shuffle-blues",name:"Shuffle / Blues",stepsPerBar:8,timingOffsets:[0,.11,0,.11,0,.11,0,.11],velocityScales:[1.2,.8,1.1,.8,1.2,.8,1.1,.8],durationScales:[1.1,.8,1.1,.8,1.1,.8,1.1,.8]},{id:"reggaeton",name:"Reggaeton",stepsPerBar:16,timingOffsets:[0,0,0,.03,0,0,0,.03,0,0,0,.03,0,0,0,.03],velocityScales:[1.3,.6,.9,1.1,.7,.6,.9,1.1,1.3,.6,.9,1.1,.7,.6,.9,1.1],durationScales:[1,1,1,.9,1,1,1,.9,1,1,1,.9,1,1,1,.9]}];function ig(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function fc(e,t){return t.amount===0?e:e.map(n=>{const a=n.time/t.grid;if(Math.round(a)%2===1){const o=t.grid*t.amount*.5;return{...n,time:n.time+o}}return{...n}})}function mc(e,t){const n=t.seed!=null?ig(t.seed):Math.random;return e.map(a=>{const s=(n()-.5)*2*t.timingAmount,i=Math.round((n()-.5)*2*t.velocityAmount),o=(n()-.5)*2*t.durationAmount;return{...a,time:Math.max(0,a.time+s),velocity:Math.max(1,Math.min(127,a.velocity+i)),duration:Math.max(.01,a.duration+o)}})}function gc(e,t,n=1){const a=4/t.stepsPerBar;return e.map(s=>{const i=s.time/a,o=Math.round(i)%t.stepsPerBar,l=t.timingOffsets[o]*a*n,c=1+(t.velocityScales[o]-1)*n,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 og(e,t){let n=[...e.map(a=>({...a}))];return t.template&&t.grooveStrength>0&&(n=gc(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=fc(n,t.swing)),t.humanize&&(n=mc(n,t.humanize)),n}function lg(e){return ls.find(t=>t.id===e)}function cg(){return ls.map(({id:e,name:t})=>({id:e,name:t}))}function yc(e){switch(e){case"1/4":return 1;case"1/8":return .5;case"1/16":return .25;case"1/32":return .125;case"1/4T":return 2/3;case"1/8T":return 1/3;case"1/16T":return 1/6}}function cs(e,t){return yc(e)*60/t}function Na(e,t,n){const a=cs(t,n);return Math.round(e/a)*a}function dg(e,t){const{value:n,bpm:a,strength:s=1,quantizeStarts:i=!0,quantizeDurations:o=!1}=t,l=cs(n,a);return e.map(c=>{let{start: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 ug(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function hg(e,t={}){const{timingRange:n=.02,velocityRange:a=10,seed:s}=t,i=s!=null?ug(s):Math.random;return e.map(o=>{const l=(i()*2-1)*n,c=Math.round((i()*2-1)*a);return{...o,start:Math.max(0,o.start+l),velocity:o.velocity!=null?Math.max(1,Math.min(127,(o.velocity??100)+c)):void 0}})}function pg(){return{start:0,end:0,enabled:!1}}function fg(e,t){return{...e<t?{start:e,end:t}:{start:t,end:e},enabled:!0}}function mg(e,t,n){return{start:Na(e.start,t,n),end:Na(e.end,t,n),enabled:e.enabled}}function gg(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function yg(e,t){if(!t.enabled||t.end<=t.start||e<t.start)return e;if(e>=t.end){const n=t.end-t.start;return t.start+(e-t.start)%n}return e}function Ta(e){return e.length===1?e.toLowerCase():e}function Cr(e){var n,a,s,i;const t=[];return(n=e.modifiers)!=null&&n.ctrl&&t.push("Ctrl"),(a=e.modifiers)!=null&&a.shift&&t.push("Shift"),(s=e.modifiers)!=null&&s.alt&&t.push("Alt"),(i=e.modifiers)!=null&&i.meta&&t.push("Meta"),t.push(Ta(e.key)),t.join("+")}function vg(e,t){var l,c,u,h;const n=Ta(e.key)===Ta(t.key),a=!!e.ctrlKey==!!((l=t.modifiers)!=null&&l.ctrl),s=!!e.shiftKey==!!((c=t.modifiers)!=null&&c.shift),i=!!e.altKey==!!((u=t.modifiers)!=null&&u.alt),o=!!e.metaKey==!!((h=t.modifiers)!=null&&h.meta);return n&&a&&s&&i&&o}class vc{constructor(){this.actions=new Map,this.activeScopes=new Set(["global"]),this.enabled=!0,this.listener=null}register(t){this.actions.set(t.id,{...t,enabled:t.enabled??!0})}unregister(t){this.actions.delete(t)}rebind(t,n){const a=this.actions.get(t);a&&(a.binding=n)}setActiveScopes(t){this.activeScopes.clear(),this.activeScopes.add("global");for(const n of t)this.activeScopes.add(n)}setEnabled(t){this.enabled=t}setActionEnabled(t,n){const a=this.actions.get(t);a&&(a.enabled=n)}findConflicts(){const t=[],n=[...this.actions.values()];for(let a=0;a<n.length;a++)for(let s=a+1;s<n.length;s++){const i=n[a],o=n[s];Cr(i.binding)===Cr(o.binding)&&(i.scope===o.scope||i.scope==="global"||o.scope==="global")&&t.push([i,o])}return t}getGrouped(){const t={};for(const n of this.actions.values())t[n.group]||(t[n.group]=[]),t[n.group].push(n);return t}getAll(){return[...this.actions.values()]}exportConfig(){return[...this.actions.values()].map(t=>({id:t.id,binding:t.binding}))}importConfig(t){for(const n of t)this.rebind(n.id,n.binding)}formatBinding(t){const n=this.actions.get(t);return n?Cr(n.binding):""}handleKeyDown(t){if(!this.enabled)return!1;for(const n of this.actions.values())if(n.enabled&&this.activeScopes.has(n.scope)&&vg(t,n.binding))return t.preventDefault(),t.stopPropagation(),n.callback(),!0;return!1}attach(){this.listener||(this.listener=t=>{const n=t.target;n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable||this.handleKeyDown(t)},window.addEventListener("keydown",this.listener,!0))}detach(){this.listener&&(window.removeEventListener("keydown",this.listener,!0),this.listener=null)}destroy(){this.detach(),this.actions.clear()}}function bg(e={}){const t=new vc,n=()=>{},a=[{id:"transport.play",label:"Play / Pause",group:"Transport",scope:"global",binding:{key:" "}},{id:"transport.stop",label:"Stop",group:"Transport",scope:"global",binding:{key:"Escape"}},{id:"transport.record",label:"Record",group:"Transport",scope:"global",binding:{key:"r",modifiers:{ctrl:!0}}},{id:"transport.rewind",label:"Rewind",group:"Transport",scope:"global",binding:{key:"Home"}},{id:"transport.forward",label:"Forward",group:"Transport",scope:"global",binding:{key:"End"}},{id:"transport.loopToggle",label:"Toggle Loop",group:"Transport",scope:"global",binding:{key:"l"}},{id:"edit.undo",label:"Undo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0}}},{id:"edit.redo",label:"Redo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0,shift:!0}}},{id:"edit.cut",label:"Cut",group:"Edit",scope:"editor",binding:{key:"x",modifiers:{ctrl:!0}}},{id:"edit.copy",label:"Copy",group:"Edit",scope:"editor",binding:{key:"c",modifiers:{ctrl:!0}}},{id:"edit.paste",label:"Paste",group:"Edit",scope:"editor",binding:{key:"v",modifiers:{ctrl:!0}}},{id:"edit.delete",label:"Delete",group:"Edit",scope:"editor",binding:{key:"Delete"}},{id:"edit.selectAll",label:"Select All",group:"Edit",scope:"editor",binding:{key:"a",modifiers:{ctrl:!0}}},{id:"edit.duplicate",label:"Duplicate",group:"Edit",scope:"editor",binding:{key:"d",modifiers:{ctrl:!0}}},{id:"view.zoomIn",label:"Zoom In",group:"View",scope:"global",binding:{key:"=",modifiers:{ctrl:!0}}},{id:"view.zoomOut",label:"Zoom Out",group:"View",scope:"global",binding:{key:"-",modifiers:{ctrl:!0}}},{id:"view.zoomFit",label:"Zoom to Fit",group:"View",scope:"global",binding:{key:"0",modifiers:{ctrl:!0}}},{id:"view.toggleMixer",label:"Toggle Mixer",group:"View",scope:"global",binding:{key:"m"}},{id:"view.togglePianoRoll",label:"Toggle Piano Roll",group:"View",scope:"global",binding:{key:"p"}},{id:"pianoRoll.quantize",label:"Quantize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"q"}},{id:"pianoRoll.humanize",label:"Humanize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"h"}},{id:"pianoRoll.velocityUp",label:"Velocity +10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{shift:!0}}},{id:"pianoRoll.velocityDown",label:"Velocity -10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{shift:!0}}},{id:"pianoRoll.octaveUp",label:"Octave Up",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{ctrl:!0,shift:!0}}},{id:"pianoRoll.octaveDown",label:"Octave Down",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{ctrl:!0,shift:!0}}},{id:"timeline.split",label:"Split at Cursor",group:"Timeline",scope:"timeline",binding:{key:"s"}},{id:"timeline.mute",label:"Mute Track",group:"Timeline",scope:"timeline",binding:{key:"m",modifiers:{ctrl:!0}}},{id:"timeline.solo",label:"Solo Track",group:"Timeline",scope:"timeline",binding:{key:"s",modifiers:{ctrl:!0}}},{id:"timeline.addTrack",label:"Add Track",group:"Timeline",scope:"timeline",binding:{key:"t",modifiers:{ctrl:!0}}},{id:"mixer.resetFader",label:"Reset Fader",group:"Mixer",scope:"mixer",binding:{key:"0"}},{id:"mixer.bypassFx",label:"Bypass All FX",group:"Mixer",scope:"mixer",binding:{key:"b"}}];for(const s of a)t.register({...s,callback:e[s.id]??n});return t}function xg(e){return Cr(e)}const Sg=["audio/mpeg","audio/wav","audio/ogg","audio/flac","audio/aac","audio/webm","audio/mp4","audio/x-m4a","audio/x-wav","audio/x-aiff","audio/aiff","audio/midi","audio/x-midi"],kg=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],wg=500*1024*1024,Cg=20;function Bt(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function jg(e,t){return!!(e.type&&t.some(n=>e.type.startsWith(n.replace("*","")))||e.type.startsWith("audio/"))}function Mg(e,t){const n=Bt(e.name);return n!==""&&t.includes(n)}function ds(e,t={}){const n=t.maxSize??wg,a=t.allowedTypes??Sg,s=t.allowedExtensions??kg,i=t.maxFiles??Cg,o=[],l=[];for(let c=0;c<e.length;c++){const 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(!jg(u,a)&&!Mg(u,s)){l.push({file:u,reason:"type",message:`Unsupported file type: ${u.type||Bt(u.name)}`});continue}o.push(u)}return{valid:o,errors:l}}async function bc(e){const t={file:e,name:e.name.replace(/\.[^.]+$/,""),extension:Bt(e.name),sizeBytes:e.size,mimeType:e.type||`audio/${Bt(e.name)}`};try{const n=await e.arrayBuffer(),s=await new OfflineAudioContext(1,1,44100).decodeAudioData(n);t.duration=s.duration,t.sampleRate=s.sampleRate,t.channels=s.numberOfChannels}catch{}return t}function Rg(e){let t=0;return{onDragEnter:n=>{var a;n.preventDefault(),n.stopPropagation(),t++,t===1&&((a=e.onDragEnter)==null||a.call(e))},onDragOver:n=>{n.preventDefault(),n.stopPropagation(),(n instanceof DragEvent&&n.dataTransfer||"dataTransfer"in n&&n.dataTransfer)&&(n.dataTransfer.dropEffect="copy")},onDragLeave:n=>{var a;n.preventDefault(),n.stopPropagation(),t--,t===0&&((a=e.onDragLeave)==null||a.call(e))},onDrop:async n=>{var 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}=ds(s,e.validation),l=[],c=[...o];for(const p of i)if(e.probe)try{l.push(await bc(p))}catch{c.push({file:p,reason:"decode",message:"Failed to decode audio"})}else l.push({file:p,name:p.name.replace(/\.[^.]+$/,""),extension:Bt(p.name),sizeBytes:p.size,mimeType:p.type||`audio/${Bt(p.name)}`});e.onDrop({accepted:l,rejected:c})}}}function Ng(e={}){return new Promise(t=>{const n=document.createElement("input");n.type="file",n.accept="audio/*,.mid,.midi",n.multiple=e.multiple??!0,n.onchange=async()=>{var l;if(!((l=n.files)!=null&&l.length)){t({accepted:[],rejected:[]});return}const a=Array.from(n.files),{valid:s,errors:i}=ds(a,e.validation),o=s.map(c=>({file:c,name:c.name.replace(/\.[^.]+$/,""),extension:Bt(c.name),sizeBytes:c.size,mimeType:c.type||`audio/${Bt(c.name)}`}));t({accepted:o,rejected:i})},n.click()})}var Ft=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(Ft||{}),xc=(e=>(e[e.Equalizer=0]="Equalizer",e[e.Compressor=1]="Compressor",e[e.Reverb=2]="Reverb",e[e.Delay=3]="Delay",e[e.Distortion=4]="Distortion",e[e.Chorus=5]="Chorus",e[e.Flanger=6]="Flanger",e[e.Phaser=7]="Phaser",e))(xc||{}),Sc=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(Sc||{});const Tg=["var(--nice-success, #4caf50)","var(--nice-primary, #2196f3)","var(--nice-warning, #ff9800)","var(--nice-color-accent-pink, #e91e63)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-success, #8bc34a)","var(--nice-warning, #ffc107)"],Lr=["off","no function","brak"],Pg=e=>e.segments.some(t=>t.isOff||Lr.some(n=>t.name.toLowerCase().includes(n))),Eg=e=>e.segments.find(t=>t.isOff||Lr.some(n=>t.name.toLowerCase().includes(n))),kc=e=>Math.floor((e.valueFrom+e.valueTo)/2),$g=e=>{const t=Eg(e);return t?kc(t):0},Ag=(e,t)=>e.segments.find(n=>t>=n.valueFrom&&t<=n.valueTo),Mn=(e,t=0,n=255)=>Math.max(t,Math.min(n,Math.round(e))),Vn=({channel:e,value:t,onChange:n,onCommit:a,showDirectionHint:s})=>{const{t:i}=xe(),[o,l]=d.useState(Mn(t)),c=d.useMemo(()=>Ag(e,o),[e,o]);d.useEffect(()=>l(Mn(t)),[t]);const u=h=>{const p=Mn(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=Mn(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=Mn(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}})}),Pg(e)&&r.jsx("button",{type:"button",onClick:()=>u($g(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")})]})},us=({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)+(Lr.some(p=>l.name.toLowerCase().includes(p))?-1:0),h=(c.isOff?-1:0)+(Lr.some(p=>c.name.toLowerCase().includes(p))?-1:0);return u!==h?u-h:l.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),o},[e]),i=o=>{const l=kc(o);n(l),a==null||a(l)};return r.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[r.jsxs("strong",{children:[e.channel,". ",e.name]}),r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(120px, 1fr))",gap:8,marginTop:8,maxHeight:220,overflowY:"auto"},children:s.map((o,l)=>{const c=t>=o.valueFrom&&t<=o.valueTo;return r.jsx("button",{type:"button",onClick:()=>i(o),style:{padding:"8px 10px",borderRadius:8,border:c?"2px solid var(--nice-primary-hover, #2563eb)":"1px solid var(--nice-border, #d1d5db)",background:c?"var(--nice-primary-bg, #eff6ff)":"var(--nice-bg, #fff)",textAlign:"left",cursor:"pointer",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:`${o.name} [${o.valueFrom}..${o.valueTo}]`,children:o.name},`${o.name}-${l}`)})})]})},hs=e=>{switch(e.channel.type){case Ft.Dimmer:case Ft.DimmerWithOff:return r.jsx(Vn,{...e});case Ft.RotationWithOff:case Ft.RotationWithOffAndCcw:return r.jsx(Vn,{...e,showDirectionHint:!0});case Ft.Options:return r.jsx(us,{...e});default:return r.jsx(Vn,{...e})}},oa=e=>Math.max(0,Math.min(255,Math.round(e))),Ig=[{target:".ntd-dmx-editor",titleKey:"tutorial.dmxEditor.intro.title",title:"DMX editor",contentKey:"tutorial.dmxEditor.intro.content",content:"Pick the FTDI device and port, then set each DMX channel’s value with the sliders to control your lighting fixtures live.",placement:"auto"}];function wc({service:e,...t}){const{t:n}=xe();return e?r.jsx(Lg,{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 Lg({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),k=d.useRef(null);d.useEffect(()=>{let I=!1;return e.getDevices().then(L=>{I||(l(L),L.length>0&&u(L[0]))}).catch(()=>{}),()=>{I=!0}},[e]),d.useEffect(()=>{if(k.current&&window.clearInterval(k.current),!(t<=0))return k.current=window.setInterval(async()=>{try{const I=await e.getState();Array.isArray(I.frontSnapshot)&&I.frontSnapshot.length>=513&&p(I.frontSnapshot.slice(0,513)),typeof I.fps=="number"&&y(I.fps),typeof I.startCode=="number"&&x(I.startCode)}catch{}},t),()=>{k.current&&window.clearInterval(k.current)}},[e,t]);const v=async()=>{c&&(await e.openPort(c.serialNumber||c.description),f(!0))},w=async()=>{await e.closePort(),f(!1)},R=async()=>{await e.blackout(),p(I=>{const L=[...I];for(let N=1;N<L.length;N++)L[N]=0;return L})},M=()=>e.configure(g,m),j=(I,L)=>{const N=oa(L);p(_=>{const ee=[..._];return ee[I]=N,ee})},T=(I,L)=>e.setChannel(I,oa(L)),P=(c==null?void 0:c.deviceInfo)??null,A=d.useMemo(()=>{var I;return(I=P==null?void 0:P.channels)!=null&&I.length?P.channels:Array.from({length:16},(L,N)=>({channel:N+1,name:`Channel ${N+1}`,type:Ft.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(ke.NiceTutorialButton,{steps:ke.resolveTutorial(s,Ig)})}),r.jsxs("section",{style:{display:"grid",gap:12,gridTemplateColumns:"1fr auto auto auto",alignItems:"end"},children:[r.jsxs("div",{children:[r.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:i("dmxEditor.ftdiDevice","FTDI Device")}),r.jsx("select",{value:(c==null?void 0:c.serialNumber)||"",onChange:I=>u(o.find(L=>L.serialNumber===I.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"},children:o.map(I=>{var L,N;return r.jsxs("option",{value:I.serialNumber,children:[((L=I.deviceInfo)==null?void 0:L.manufacturer)??""," ",((N=I.deviceInfo)==null?void 0:N.model)??I.description," (",I.serialNumber||I.description,")"]},I.serialNumber||I.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:w,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:R,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:I=>y(Number(I.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:I=>x(oa(Number(I.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:A.map(I=>r.jsx(hs,{channel:I,value:h[I.channel]??0,onChange:L=>j(I.channel,L),onCommit:L=>T(I.channel,L)},I.channel))})]})]})}const Cc=[{id:"generic-dimmer-1ch",name:"Generic Dimmer",manufacturer:"Generic",type:"dimmer",channelCount:1,channels:[{name:"Dimmer",type:"dimmer",defaultValue:0}]},{id:"generic-rgb-3ch",name:"Generic RGB",manufacturer:"Generic",type:"rgb",channelCount:3,channels:[{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0}]},{id:"generic-rgbw-4ch",name:"Generic RGBW",manufacturer:"Generic",type:"rgbw",channelCount:4,channels:[{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0}]},{id:"generic-rgbw-dimmer-5ch",name:"Generic RGBW+D",manufacturer:"Generic",type:"rgbw",channelCount:5,channels:[{name:"Dimmer",type:"dimmer",defaultValue:255},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0}]},{id:"generic-par-7ch",name:"Generic PAR 7ch",manufacturer:"Generic",type:"par",channelCount:7,channels:[{name:"Dimmer",type:"dimmer",defaultValue:255},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0},{name:"Strobe",type:"strobe",defaultValue:0},{name:"Function",type:"function",defaultValue:0}]},{id:"generic-moving-head-16ch",name:"Generic Moving Head 16ch",manufacturer:"Generic",type:"moving_head",channelCount:16,channels:[{name:"Pan",type:"pan",defaultValue:128,min:0,max:255},{name:"Pan Fine",type:"pan",defaultValue:0},{name:"Tilt",type:"tilt",defaultValue:128,min:0,max:255},{name:"Tilt Fine",type:"tilt",defaultValue:0},{name:"Pan/Tilt Speed",type:"speed",defaultValue:0},{name:"Dimmer",type:"dimmer",defaultValue:0},{name:"Strobe",type:"strobe",defaultValue:0},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0},{name:"Color Wheel",type:"function",defaultValue:0},{name:"Gobo",type:"gobo",defaultValue:0},{name:"Gobo Rotation",type:"speed",defaultValue:128},{name:"Prism",type:"function",defaultValue:0},{name:"Function",type:"function",defaultValue:0}]},{id:"generic-strobe-2ch",name:"Generic Strobe",manufacturer:"Generic",type:"strobe",channelCount:2,channels:[{name:"Dimmer",type:"dimmer",defaultValue:0},{name:"Strobe Speed",type:"strobe",defaultValue:0}]},{id:"generic-fog-2ch",name:"Generic Fog Machine",manufacturer:"Generic",type:"fog",channelCount:2,channels:[{name:"Output",type:"dimmer",defaultValue:0},{name:"Fan",type:"speed",defaultValue:128}]}];class jc{constructor(){this.universes=new Map,this.fixtures=new Map,this.profiles=new Map,this.outputCallback=null,this.running=!1,this.frameRate=44,this.intervalId=null,Cc.forEach(t=>this.profiles.set(t.id,t)),this.createUniverse(1,"Universe 1")}createUniverse(t,n){const a={id:String(t),name:n,channels:new Uint8Array(512)};return this.universes.set(t,a),a}getUniverse(t){return this.universes.get(t)}addFixture(t){this.fixtures.set(t.id,t)}removeFixture(t){this.fixtures.delete(t)}getFixture(t){return this.fixtures.get(t)}getAllFixtures(){return Array.from(this.fixtures.values())}getProfile(t){return this.profiles.get(t)}registerProfile(t){this.profiles.set(t.id,t)}setChannel(t,n,a){const s=this.universes.get(t);s&&n>=1&&n<=512&&(s.channels[n-1]=Math.max(0,Math.min(255,a)))}getChannel(t,n){const a=this.universes.get(t);return a&&n>=1&&n<=512?a.channels[n-1]:0}setFixtureValues(t,n){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);if(s)for(let i=0;i<Math.min(n.length,s.channelCount);i++)a.values[i]=n[i],this.setChannel(a.universe,a.startChannel+i,n[i])}setFixtureColor(t,n,a,s,i=0){const o=this.fixtures.get(t);if(!o)return;const l=this.profiles.get(o.profileId);if(!l)return;const c=[...o.values];l.channels.forEach((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 _g=6454,zg=new Uint8Array([65,114,116,45,78,101,116,0]);function Dg(e,t){const n=new Uint8Array(18+t.length);return n.set(zg,0),n[8]=0,n[9]=80,n[10]=0,n[11]=14,n[12]=0,n[13]=0,n[14]=e&255,n[15]=e>>8&255,n[16]=t.length>>8&255,n[17]=t.length&255,n.set(t.slice(0,512),18),n}const Fg=5568;function Og(e,t,n,a=100,s="Nice2Dev DMX"){const i=Math.min(t.length,512),o=126+i,l=new Uint8Array(o),c=new DataView(l.buffer);c.setUint16(0,16,!1),c.setUint16(2,0,!1);const 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 Bg(e){const t=e>>8&255,n=e&255;return`239.255.${t}.${n}`}class Gg{constructor(t,n){this.config=t,this.scenes=n,this.currentStep=0,this.direction=1,this.isRunning=!1,this.timer=null,this.fadeStartTime=0,this.fadeFromValues=new Uint8Array(512),this.fadeToValues=new Uint8Array(512),this.onOutput=null}setOutputCallback(t){this.onOutput=t}start(){this.isRunning||(this.isRunning=!0,this.currentStep=this.config.direction==="backward"?this.config.steps.length-1:0,this.direction=this.config.direction==="backward"?-1:1,this.executeStep())}stop(){this.isRunning=!1,this.timer&&(clearTimeout(this.timer),this.timer=null)}executeStep(){var o;if(!this.isRunning)return;const t=this.config.steps[this.currentStep];if(!t)return;const n=this.scenes.get(t.sceneId);if(!n){this.advanceStep();return}const a=new Uint8Array(512);if(n.channels)for(const l of n.channels)l.channel>=1&&l.channel<=512&&(a[l.channel-1]=l.value);this.fadeFromValues.set(this.fadeToValues),this.fadeToValues.set(a),this.fadeStartTime=performance.now();const s=t.fadeTime/this.config.speed,i=t.holdTime/this.config.speed;s>0?this.runFade(s,()=>{var l;(l=this.onOutput)==null||l.call(this,this.fadeToValues),this.timer=setTimeout(()=>this.advanceStep(),i)}):((o=this.onOutput)==null||o.call(this,a),this.timer=setTimeout(()=>this.advanceStep(),i))}runFade(t,n){const a=performance.now(),s=new Uint8Array(512),i=()=>{var c;if(!this.isRunning)return;const o=performance.now()-a,l=Math.min(o/t,1);for(let 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 Wg=({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,k]=d.useState(1),[v,w]=d.useState(0),[R,M]=d.useState(!1),[j,T]=d.useState(null),[P,A]=d.useState(null),[I,L]=d.useState(!0),[N,_]=d.useState(1e3),ee=d.useRef(null),Y=d.useRef(null),O=d.useRef(0),U=d.useMemo(()=>.1*f,[f]),V=d.useCallback(E=>E*U,[U]),K=d.useCallback(E=>E/U,[U]),G=d.useCallback(E=>{if(!I)return E;const q=6e4/i;return Math.round(E/q)*q},[I,i]),W=d.useRef(()=>{});d.useEffect(()=>{if(!R)return;const E=performance.now(),q=s,X=()=>{const re=performance.now()-E,oe=q+re;if(oe>=a){M(!1),o==null||o(0),m==null||m();return}W.current(oe),o==null||o(oe),Y.current=requestAnimationFrame(X)};return Y.current=requestAnimationFrame(X),()=>{Y.current!==null&&(cancelAnimationFrame(Y.current),Y.current=null)}},[R,s,a,o,m]);const C=d.useRef(!1);d.useEffect(()=>{R!==C.current&&(C.current=R,R?g==null||g():y==null||y())},[R,g,y]);const $=d.useCallback(E=>{t.forEach(q=>{q.muted||q.cues.forEach(X=>{const re=X.startTime,oe=re+X.duration;if(E>=re&&E<oe&&O.current<re){const se=n.find(D=>D.id===X.sceneId);se&&se.fixtures.forEach(D=>{X.fadeIn&&X.fadeIn>0?e.fadeFixture(D.fixtureId,D.values,X.fadeIn):e.setFixtureValues(D.fixtureId,D.values)})}if(O.current<oe&&E>=oe){const se=n.find(D=>D.id===X.sceneId);se&&se.fixtures.forEach(D=>{if(e.getFixture(D.fixtureId)&&X.fadeOut&&X.fadeOut>0){const ae=new Array(D.values.length).fill(0);e.fadeFixture(D.fixtureId,ae,X.fadeOut)}})}})}),O.current=E},[t,n,e]);W.current=$;const S=E=>{const q=Math.floor(E/1e3),X=Math.floor(q/60),re=q%60,oe=Math.floor(E%1e3/(1e3/30));return`${X}:${re.toString().padStart(2,"0")}:${oe.toString().padStart(2,"0")}`},B=d.useCallback(E=>{if(!ee.current)return;const q=ee.current.getBoundingClientRect(),X=E.clientX-q.left+v,re=G(K(X));o==null||o(Math.max(0,Math.min(a,re)))},[v,K,G,a,o]),H=d.useCallback((E,q,X)=>{const re=t.find(D=>D.id===q),oe=re==null?void 0:re.cues.find(D=>D.id===E);if(!oe)return;const se=G(Math.max(0,oe.startTime+K(X)));c==null||c({...oe,startTime:se})},[t,K,G,c]),z=()=>{const E=6e4/i,q=Math.ceil(a/E),X=[];for(let re=0;re<=q;re++){const oe=re*E,se=V(oe),D=re%4===0;X.push(r.jsx("div",{className:`nice-dmx-timeline__beat ${D?"nice-dmx-timeline__beat--measure":""}`,style:{left:se},children:D&&r.jsx("span",{className:"nice-dmx-timeline__beat-label",children:re/4+1})},re))}return X},Z=(E,q)=>{const X=V(E.startTime),re=V(E.duration),oe=n.find(se=>se.id===E.sceneId);return r.jsxs("div",{className:`nice-dmx-timeline__cue ${j===E.id?"nice-dmx-timeline__cue--selected":""}`,style:{left:X,width:re,backgroundColor:(oe==null?void 0:oe.color)||q.color||"var(--nice-accent, #8b5cf6)"},onClick:se=>{se.stopPropagation(),T(E.id)},draggable:!q.locked,onDragEnd:se=>{var J;const D=(J=se.target.parentElement)==null?void 0:J.getBoundingClientRect();D&&H(E.id,q.id,se.clientX-D.left-X)},children:[r.jsx("span",{className:"nice-dmx-timeline__cue-name",children:E.name||(oe==null?void 0:oe.name)}),E.fadeIn&&E.fadeIn>0&&r.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--in",style:{width:V(E.fadeIn)}}),E.fadeOut&&E.fadeOut>0&&r.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--out",style:{width:V(E.fadeOut)}})]},E.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(F.NtdSkipBack,{size:14})}),r.jsx("button",{type:"button",onClick:()=>M(!R),title:R?b("dmxTimeline.pause","Pause"):b("dmxTimeline.play","Play"),"aria-label":R?b("dmxTimeline.pause","Pause"):b("dmxTimeline.play","Play"),children:R?r.jsx(F.NtdPause,{size:14}):r.jsx(F.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(F.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 ${I?"nice-dmx-timeline__tool--active":""}`,onClick:()=>L(!I),title:b("dmxTimeline.snapToGrid","Snap to grid"),"aria-label":b("dmxTimeline.snapToGrid","Snap to grid"),children:r.jsx(F.NtdGrid,{size:14})}),r.jsx("button",{type:"button",onClick:()=>k(Math.max(.25,f-.25)),title:b("dmxTimeline.zoomOut","Zoom out"),"aria-label":b("dmxTimeline.zoomOut","Zoom out"),children:r.jsx(F.NtdZoomOut,{size:14})}),r.jsxs("span",{className:"nice-dmx-timeline__zoom",children:[Math.round(f*100),"%"]}),r.jsx("button",{type:"button",onClick:()=>k(Math.min(4,f+.25)),title:b("dmxTimeline.zoomIn","Zoom in"),"aria-label":b("dmxTimeline.zoomIn","Zoom in"),children:r.jsx(F.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(F.NtdMoon,{size:14})})]}),r.jsxs("div",{className:"nice-dmx-timeline__content",children:[r.jsxs("div",{className:"nice-dmx-timeline__headers",children:[t.map(E=>r.jsxs("div",{className:`nice-dmx-timeline__header ${P===E.id?"nice-dmx-timeline__header--selected":""}`,onClick:()=>A(E.id),children:[r.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:E.color||"var(--nice-accent, #8b5cf6)"}}),r.jsx("span",{className:"nice-dmx-timeline__track-name",children:E.name}),r.jsxs("div",{className:"nice-dmx-timeline__track-controls",children:[r.jsx("button",{type:"button",className:`nice-dmx-timeline__track-toggle ${E.muted?"nice-dmx-timeline__track-toggle--active":""}`,onClick:q=>{q.stopPropagation(),p==null||p({...E,muted:!E.muted})},title:b("dmxTimeline.mute","Mute"),children:"M"}),r.jsx("button",{type:"button",className:`nice-dmx-timeline__track-toggle ${E.locked?"nice-dmx-timeline__track-toggle--active":""}`,onClick:q=>{q.stopPropagation(),p==null||p({...E,locked:!E.locked})},title:b("dmxTimeline.lock","Lock"),"aria-label":b("dmxTimeline.lock","Lock"),children:r.jsx(F.NtdLock,{size:14})})]})]},E.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(F.NtdPlus,{size:14})," ",b("dmxTimeline.addTrack","Add Track")]})]}),r.jsxs("div",{className:"nice-dmx-timeline__tracks",ref:ee,onClick:B,onScroll:E=>w(E.currentTarget.scrollLeft),children:[r.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:V(a)},children:z()}),t.map(E=>r.jsx("div",{className:`nice-dmx-timeline__track ${E.muted?"nice-dmx-timeline__track--muted":""}`,style:{width:V(a)},children:E.cues.map(q=>Z(q,E))},E.id)),r.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:V(s)}})]})]})]})};function Vg(){const[e]=d.useState(()=>new jc);return d.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function Ug(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 qg=[],Hg=[],Kg=[{name:"Flat",bands:[{frequency:60,gain:0},{frequency:250,gain:0},{frequency:1e3,gain:0},{frequency:4e3,gain:0},{frequency:16e3,gain:0}]},{name:"Bass Boost",bands:[{frequency:60,gain:8},{frequency:250,gain:4},{frequency:1e3,gain:0},{frequency:4e3,gain:-2},{frequency:16e3,gain:-4}]},{name:"Treble Boost",bands:[{frequency:60,gain:-4},{frequency:250,gain:-2},{frequency:1e3,gain:0},{frequency:4e3,gain:4},{frequency:16e3,gain:8}]},{name:"Voice",bands:[{frequency:60,gain:-6},{frequency:250,gain:2},{frequency:1e3,gain:6},{frequency:4e3,gain:4},{frequency:16e3,gain:-2}]},{name:"Rock",bands:[{frequency:60,gain:4},{frequency:250,gain:2},{frequency:1e3,gain:-2},{frequency:4e3,gain:4},{frequency:16e3,gain:6}]}];function Mc(){const{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([]),k=d.useRef(null),v=d.useRef(null),w=d.useRef(a),R=d.useCallback(()=>{if(m.current)return;const Y=new AudioContext;m.current=Y;const O=Y.createGain();O.gain.value=w.current,b.current=O;const U=Y.createAnalyser();U.fftSize=256,k.current=U,O.connect(U).connect(Y.destination)},[]),M=d.useCallback(()=>{const Y=y.current,O=m.current,U=b.current;if(!Y||!O||!U||x.current)return;const V=O.createMediaElementSource(Y);x.current=V,f.current.length>0?(V.connect(f.current[0]),f.current[f.current.length-1].connect(U)):V.connect(U)},[]),j=d.useCallback(()=>{var O;const Y=y.current;!Y||!v.current||(Yt(),R(),M(),((O=m.current)==null?void 0:O.state)==="suspended"&&m.current.resume(),Y.play().catch(U=>h(String(U))))},[R,M]),T=d.useCallback(()=>{var Y;(Y=y.current)==null||Y.pause()},[]),P=d.useCallback(()=>{t?T():j()},[t,j,T]),A=d.useCallback(Y=>{const O=Math.max(0,Math.min(1,Y));s(O),w.current=O,b.current&&(b.current.gain.value=O),y.current&&(y.current.volume=O)},[]),I=d.useCallback(Y=>{v.current=Y,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=Y.streamUrl,y.current.load(),c({genre:Y.genre,bitrate:Y.bitrate})},[e]),L=d.useCallback(Y=>{m.current||R();const U=m.current;f.current.forEach(K=>K.disconnect());const V=Y.bands.map(K=>{const G=U.createBiquadFilter();return G.type="peaking",G.frequency.value=K.frequency,G.gain.value=K.gain,G.Q.value=K.Q??1.4,G});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(Y.name)},[R]),N=d.useCallback(()=>{f.current.forEach(Y=>Y.disconnect()),f.current=[],x.current&&b.current&&(x.current.disconnect(),x.current.connect(b.current)),g(null)},[]);return d.useEffect(()=>()=>{var Y,O,U;(Y=y.current)==null||Y.pause(),y.current=null,f.current.forEach(V=>V.disconnect()),(O=x.current)==null||O.disconnect(),(U=m.current)==null||U.close()},[]),[{isPlaying:t,volume:a,isBuffering:i,metadata:l,error:u,activePreset:p},{play:j,pause:T,toggle:P,setVolume:A,setStation:I,applyEQPreset:L,clearEQ:N}]}function Rc({stations:e=qg,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(F.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(F.NtdStar,{size:14,style:{color:m.isFavorite?"var(--nice-warning, #facc15)":"var(--nice-text-muted)"}})})]},m.id)),y.length===0&&r.jsx("div",{className:"nice-station-browser__empty",children:i("radioPlayer.noStationsFound","No stations found")})]})]})}function Yg({stations:e=Hg,initialStationId:t,autoPlay:n=!1,eqPresets:a=Kg,onStationChange:s,onPlayingChange:i,onMetadata:o,onToggleFavorite:l,onRecordingStart:c,onRecordingStop:u,showBrowser:h=!0,showEqualizer:p=!1,showVisualizer:g=!1,showMetadataHistory:y=!1,showRecording:m=!1,showSleepTimer:x=!1,className:b,style:f}){var B,H;const{t:k}=xe(),[v,w]=Mc(),[R,M]=d.useState(()=>t?e.find(z=>z.id===t)??null:null),[j,T]=d.useState(p),P=d.useRef(null),A=d.useRef(0),[I,L]=d.useState([]),[N,_]=d.useState(!1),ee=d.useRef(null),Y=d.useRef([]),[O,U]=d.useState(0),V=d.useRef(null),[K,G]=d.useState(0),[W,C]=d.useState(null),$=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(z=>[{time:new Date,meta:v.metadata},...z.slice(0,49)]))},[v.metadata,o]);const S=d.useCallback(z=>{M(z),w.setStation(z),s==null||s(z),n&&setTimeout(()=>w.play(),100)},[w,s,n]);return d.useEffect(()=>{if(t&&!R){const z=e.find(Z=>Z.id===t);z&&S(z)}},[t,e,R,S]),d.useEffect(()=>{if(!g||!P.current)return;const z=P.current,Z=z.getContext("2d");if(!Z)return;const E=()=>{A.current=requestAnimationFrame(E),Z.clearRect(0,0,z.width,z.height);const q=Z.createLinearGradient(0,z.height,0,0);if(q.addColorStop(0,ke.resolveCssColor("var(--nice-accent-tint-80, rgba(99, 102, 241, 0.8))",Z.canvas)),q.addColorStop(.5,ke.resolveCssColor("var(--nice-accent-tint-50, rgba(168,85,247,0.6))",Z.canvas)),q.addColorStop(1,"rgba(236,72,153,0.4)"),!v.isPlaying){const se=z.width/32;for(let D=0;D<32;D++){const J=4+Math.sin(Date.now()/1e3+D*.3)*3;Z.fillStyle=q,Z.fillRect(D*se+1,z.height-J,se-2,J)}return}const X=32,re=z.width/X;for(let oe=0;oe<X;oe++){const se=oe/X,J=(Math.sin(Date.now()/200+oe*.5)*.3+.5)*z.height*(1-se*.5)*(.5+Math.random()*.5);Z.fillStyle=q,Z.fillRect(oe*re+1,z.height-J,re-2,J)}};return E(),()=>cancelAnimationFrame(A.current)},[g,v.isPlaying]),d.useCallback(()=>{if(v.isPlaying)try{const Z=new AudioContext().createMediaStreamDestination();Y.current=[];const E=new MediaRecorder(Z.stream,{mimeType:"audio/webm"});E.ondataavailable=q=>{q.data.size>0&&Y.current.push(q.data)},E.onstop=()=>{const q=new Blob(Y.current,{type:"audio/webm"});u==null||u(q),U(0),V.current&&window.clearInterval(V.current)},E.start(1e3),ee.current=E,_(!0),U(0),V.current=window.setInterval(()=>{U(q=>q+1)},1e3),c==null||c()}catch{}},[v.isPlaying,c,u]),d.useCallback(()=>{ee.current&&N&&(ee.current.stop(),_(!1),V.current&&window.clearInterval(V.current))},[N]),d.useCallback(z=>{$.current&&window.clearInterval($.current),G(z),C(z*60),$.current=window.setInterval(()=>{C(Z=>!Z||Z<=1?($.current&&window.clearInterval($.current),$.current=null,w.pause(),null):Z-1)},1e3)},[w]),d.useCallback(()=>{$.current&&window.clearInterval($.current),$.current=null,C(null),G(0)},[]),d.useEffect(()=>()=>{V.current&&window.clearInterval(V.current),$.current&&window.clearInterval($.current),cancelAnimationFrame(A.current)},[]),r.jsxs("div",{className:`nice-radio-player${b?` ${b}`:""}`,style:f,children:[r.jsx("div",{className:"nice-radio-player__now-playing",children:R?r.jsxs(r.Fragment,{children:[R.logoUrl&&r.jsx("img",{className:"nice-radio-player__cover",src:R.logoUrl,alt:R.name}),r.jsxs("div",{className:"nice-radio-player__info",children:[r.jsx("span",{className:"nice-radio-player__station-name",children:R.name}),((B=v.metadata)==null?void 0:B.title)&&r.jsx("span",{className:"nice-radio-player__track",children:v.metadata.artist?`${v.metadata.artist} — ${v.metadata.title}`:v.metadata.title}),((H=v.metadata)==null?void 0:H.genre)&&r.jsx("span",{className:"nice-radio-player__genre",children:v.metadata.genre}),v.isBuffering&&r.jsx("span",{className:"nice-radio-player__buffering",children:k("radioPlayer.buffering","Buffering…")})]})]}):r.jsx("div",{className:"nice-radio-player__placeholder",children:k("radioPlayer.selectStation","Select a station")})}),r.jsxs("div",{className:"nice-radio-player__controls",children:[r.jsx("button",{className:"nice-radio-player__play-btn",onClick:w.toggle,disabled:!R,"aria-label":v.isPlaying?k("radioPlayer.pause","Pause"):k("radioPlayer.play","Play"),children:v.isPlaying?r.jsx(F.NtdPause,{size:16}):r.jsx(F.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(F.NtdVolume,{size:16})}),r.jsx("input",{type:"range",min:0,max:1,step:.01,value:v.volume,onChange:z=>w.setVolume(parseFloat(z.target.value)),className:"nice-radio-player__volume-slider","aria-label":k("radioPlayer.volume","Volume")})]}),r.jsx("button",{className:`nice-radio-player__eq-btn${j?" nice-radio-player__eq-btn--active":""}`,onClick:()=>T(!j),title:k("radioPlayer.equalizer","Equalizer"),children:"EQ"})]}),v.error&&r.jsx("div",{className:"nice-radio-player__error",children:v.error}),j&&r.jsx("div",{className:"nice-radio-player__equalizer",children:r.jsxs("div",{className:"nice-radio-player__eq-presets",children:[a.map(z=>r.jsx("button",{className:`nice-radio-player__eq-preset${v.activePreset===z.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>w.applyEQPreset(z),children:z.name},z.name)),v.activePreset&&r.jsx("button",{className:"nice-radio-player__eq-preset",onClick:w.clearEQ,children:k("clear","Clear")})]})}),h&&r.jsx(Rc,{stations:e,activeStationId:R==null?void 0:R.id,onSelect:S})]})}const Zg=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],Xg={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class Nc{constructor(t,n={}){this.localStream=null,this.peers=new Map,this.onRemoteStream=null,this.onPeerStateChange=null,this.onSignalingMessage=null,this.localUserId=t,this.config={iceServers:n.iceServers??Zg,audioConstraints:{...Xg,echoCancellation:n.echoCancellation??!0,noiseSuppression:n.noiseSuppression??!0,autoGainControl:n.autoGainControl??!0}}}async initialize(){return this.localStream?this.localStream:(this.localStream=await navigator.mediaDevices.getUserMedia({audio:this.config.audioConstraints,video:!1}),this.localStream)}getLocalStream(){return this.localStream}getPeerIds(){return Array.from(this.peers.keys())}getPeerState(t){var n;return((n=this.peers.get(t))==null?void 0:n.state)??null}async createOffer(t){if(!this.localStream)throw new Error("WebRTCAudioManager not initialized. Call initialize() first.");const n=this.createPeerConnection(t),a=await n.createOffer();await n.setLocalDescription(a),this.sendSignalingMessage({type:"offer",from:this.localUserId,to:t,payload:a})}async handleSignalingMessage(t){if(t.to===this.localUserId)switch(t.type){case"offer":await this.handleOffer(t.from,t.payload);break;case"answer":await this.handleAnswer(t.from,t.payload);break;case"ice-candidate":await this.handleIceCandidate(t.from,t.payload);break;case"leave":this.removePeer(t.from);break}}removePeer(t){const n=this.peers.get(t);n&&(n.pc.close(),this.peers.delete(t))}disconnect(){for(const t of this.peers.keys())this.sendSignalingMessage({type:"leave",from:this.localUserId,to:t,payload:null});for(const t of this.peers.values())t.pc.close();this.peers.clear(),this.localStream&&(this.localStream.getTracks().forEach(t=>t.stop()),this.localStream=null)}setMuted(t){this.localStream&&this.localStream.getAudioTracks().forEach(n=>{n.enabled=!t})}isMuted(){if(!this.localStream)return!0;const t=this.localStream.getAudioTracks()[0];return t?!t.enabled:!0}createPeerConnection(t){const n=new RTCPeerConnection({iceServers:this.config.iceServers}),a={id:t,pc:n,remoteStream:null,state:n.connectionState};return this.peers.set(t,a),this.localStream&&this.localStream.getTracks().forEach(s=>{n.addTrack(s,this.localStream)}),n.onicecandidate=s=>{s.candidate&&this.sendSignalingMessage({type:"ice-candidate",from:this.localUserId,to:t,payload:s.candidate.toJSON()})},n.ontrack=s=>{var o;const[i]=s.streams;i&&(a.remoteStream=i,(o=this.onRemoteStream)==null||o.call(this,t,i))},n.onconnectionstatechange=()=>{var s;a.state=n.connectionState,(s=this.onPeerStateChange)==null||s.call(this,t,n.connectionState),(n.connectionState==="failed"||n.connectionState==="disconnected")&&this.removePeer(t)},n}async handleOffer(t,n){this.localStream||await this.initialize();const a=this.createPeerConnection(t);await a.setRemoteDescription(new RTCSessionDescription(n));const s=await a.createAnswer();await a.setLocalDescription(s),this.sendSignalingMessage({type:"answer",from:this.localUserId,to:t,payload:s})}async handleAnswer(t,n){const a=this.peers.get(t);a&&await a.pc.setRemoteDescription(new RTCSessionDescription(n))}async handleIceCandidate(t,n){const a=this.peers.get(t);a&&n&&await a.pc.addIceCandidate(new RTCIceCandidate(n))}sendSignalingMessage(t){var n;(n=this.onSignalingMessage)==null||n.call(this,t)}}function Qg(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function Jg(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function ey(){return new AudioContext({sampleRate:48e3,latencyHint:"interactive"})}const ps=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:k,onError:v,className:w,style:R,barBorderRadius:M=2,barGap:j=2,lineWidth:T=2}=t,P=d.useRef(null),A=d.useRef(null),I=d.useRef(null),L=d.useRef(null),N=d.useRef(0),_=d.useRef(null),ee=d.useRef(0),[Y,O]=d.useState(!1),U=Array.isArray(c)?c.join("|"):c,V=d.useMemo(()=>U.split("|").map(z=>ke.resolveCssColor(z,P.current)),[U]),K=d.useCallback((z,Z,E=!0)=>{const q=E?z.createLinearGradient(0,o,0,0):z.createLinearGradient(0,0,i,0);return Z.forEach((X,re)=>{q.addColorStop(re/(Z.length-1),X)}),q},[i,o]),G=d.useCallback((z,Z)=>{const q=(i-(l-1)*j)/l,X=Math.floor(Z.length/l),re=V,oe=re.length>1?K(z,re):re[0];z.fillStyle=oe;for(let se=0;se<l;se++){const J=Z[se*X]/255*o,ae=se*(q+j),ce=o-J;M>0?(z.beginPath(),z.roundRect(ae,ce,q,J,M),z.fill()):z.fillRect(ae,ce,q,J)}},[l,V,j,M,i,o,K]),W=d.useCallback((z,Z)=>{const E=o/2,X=(i-(l-1)*j)/l,re=Math.floor(Z.length/l),oe=V,se=oe.length>1?K(z,oe):oe[0];z.fillStyle=se;for(let D=0;D<l;D++){const ae=Z[D*re]/255*E,ce=D*(X+j);M>0?(z.beginPath(),z.roundRect(ce,E-ae,X,ae,M),z.fill(),z.beginPath(),z.roundRect(ce,E,X,ae,M),z.fill()):(z.fillRect(ce,E-ae,X,ae),z.fillRect(ce,E,X,ae))}},[l,V,j,M,i,o,K]),C=d.useCallback((z,Z)=>{const E=V;z.strokeStyle=E.length>1?K(z,E,!1):E[0],z.lineWidth=T,z.lineCap="round",z.lineJoin="round",z.beginPath();const q=i/Z.length;let X=0;for(let re=0;re<Z.length;re++){const se=Z[re]/128*o/2;re===0?z.moveTo(X,se):z.lineTo(X,se),X+=q}z.stroke()},[V,T,i,o,K]),$=d.useCallback((z,Z)=>{const E=i/2,q=o/2,X=Math.min(i,o)/3,re=V;z.strokeStyle=re.length>1?K(z,re):re[0],z.lineWidth=T;const oe=Math.floor(Z.length/64),se=Math.PI*2/64;z.beginPath();for(let D=0;D<64;D++){const J=Z[D*oe]/255,ae=X+J*X*.5,ce=D*se-Math.PI/2,le=E+Math.cos(ce)*ae,ne=q+Math.sin(ce)*ae;D===0?z.moveTo(le,ne):z.lineTo(le,ne)}z.closePath(),z.stroke()},[V,T,i,o,K]),S=d.useCallback(()=>{const z=P.current,Z=I.current,E=_.current;if(!z||!Z||!E)return;const q=z.getContext("2d");if(!q)return;s==="waveform"?Z.getByteTimeDomainData(E):Z.getByteFrequencyData(E);let X=0;for(let re=0;re<E.length;re++)X+=E[re];switch(ee.current=X/(E.length*255),k==null||k(ee.current),q.clearRect(0,0,i,o),u!=="transparent"&&(q.fillStyle=ke.resolveCssColor(u,q.canvas),q.fillRect(0,0,i,o)),s){case"bars":G(q,E);break;case"mirror-bars":W(q,E);break;case"waveform":C(q,E);break;case"circle":$(q,E);break}N.current=requestAnimationFrame(S)},[s,i,o,u,G,W,C,$,k]),B=d.useCallback(async()=>{try{if(Y)return;const z=await navigator.mediaDevices.getUserMedia({audio:m?{deviceId:{exact:m}}:!0,video:!1});L.current=z;const Z=new AudioContext;A.current=Z;const E=Z.createMediaStreamSource(z),q=Z.createAnalyser();q.fftSize=h,q.smoothingTimeConstant=p,q.minDecibels=g,q.maxDecibels=y,E.connect(q),I.current=q,_.current=new Uint8Array(q.frequencyBinCount),O(!0),b==null||b(),S()}catch(z){v==null||v(z instanceof Error?z:new Error(String(z)))}},[Y,m,h,p,g,y,b,v,S]),H=d.useCallback(()=>{cancelAnimationFrame(N.current),L.current&&(L.current.getTracks().forEach(Z=>Z.stop()),L.current=null),A.current&&(A.current.close(),A.current=null),I.current=null,_.current=null,ee.current=0,O(!1),f==null||f();const z=P.current;if(z){const Z=z.getContext("2d");Z&&(Z.clearRect(0,0,i,o),u!=="transparent"&&(Z.fillStyle=ke.resolveCssColor(u,Z.canvas),Z.fillRect(0,0,i,o)))}},[i,o,u,f]);return d.useImperativeHandle(n,()=>({start:B,stop:H,isCapturing:()=>Y,getAudioLevel:()=>ee.current}),[B,H,Y]),d.useEffect(()=>(x&&B(),()=>{H()}),[x]),r.jsx("canvas",{ref:P,width:i,height:o,className:w,style:{display:"block",...R},"aria-label":a("streamingVisualizer.audioVisualizer","Audio visualizer")})}),Ni=e=>{switch(e){case"top-left":return{top:16,left:16};case"top-right":return{top:16,right:16};case"bottom-left":return{bottom:16,left:16};case"bottom-right":default:return{bottom:16,right:16}}},ty={position:"fixed",display:"flex",flexDirection:"column",gap:8,padding:12,borderRadius:12,boxShadow:"0 4px 20px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:14,minWidth:200,maxWidth:280,transition:"all 0.2s ease"},ny={background:"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",text:"var(--nice-overlay-85, rgba(0, 0, 0, 0.85))",textSecondary:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",border:"var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-bg, #fee2e2)",mutedIcon:"var(--nice-danger, #ef4444)",activeBg:"var(--nice-success-bg, #dcfce7)",activeIcon:"var(--nice-success, #22c55e)",hoverBg:"var(--nice-overlay-5, rgba(0, 0, 0, 0.05))"},ry={background:"var(--nice-overlay-90, rgba(30, 30, 30, 0.95))",text:"var(--nice-color-white, #fff)",textSecondary:"var(--nice-text-muted, #a0a0a0)",border:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-dark, #7f1d1d)",mutedIcon:"var(--nice-danger-light, #fca5a5)",activeBg:"var(--nice-success, #14532d)",activeIcon:"var(--nice-success-light, #86efac)",hoverBg:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))"},Tc=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:k,zIndex:v=1e3}=t,w=d.useRef(null),R=d.useRef(null),M=d.useRef(new Map);d.useRef(new Map);const[j,T]=d.useState(!1),[P,A]=d.useState(!1),[I,L]=d.useState(!1),[N,_]=d.useState(h),Y=d.useMemo(()=>b==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":b,[b])==="dark"?ry:ny;d.useEffect(()=>{const C=new Nc(s,c);C.onRemoteStream=(S,B)=>{let H=M.current.get(S);H||(H=new Audio,H.autoplay=!0,M.current.set(S,H)),H.srcObject=B},C.onSignalingMessage=S=>{p==null||p(S)},C.onPeerStateChange=(S,B)=>{B==="connected"&&A(!0)},w.current=C,C.initialize().then(()=>{var S;(S=R.current)==null||S.start()});const $=M.current;return()=>{C.disconnect(),$.forEach(S=>{S.srcObject=null}),$.clear()}},[s,c,p]);const O=d.useCallback(()=>{var $;const C=!j;T(C),($=w.current)==null||$.setMuted(C),g==null||g(C)},[j,g]),U=d.useCallback(()=>{var C,$;(C=w.current)==null||C.disconnect(),($=R.current)==null||$.stop(),A(!1),y==null||y()},[y]),V=d.useCallback(C=>{const $=C>x;$!==I&&(L($),m==null||m(s,$))},[x,I,s,m]),K=d.useCallback(async C=>{var $;await(($=w.current)==null?void 0:$.createOffer(C))},[]),G=d.useCallback(async C=>{var $;await(($=w.current)==null?void 0:$.handleSignalingMessage(C))},[]);d.useImperativeHandle(n,()=>({connectToPeer:K,handleSignalingMessage:G,toggleMute:O,isMuted:()=>j,leave:U,getManager:()=>w.current}),[K,G,O,j,U]);const W=({participant:C,isLocal:$,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:Y.hoverBg,border:`2px solid ${S?Y.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:Y.text,transition:"border-color 0.15s ease"},children:C.avatarUrl?r.jsx("img",{src:C.avatarUrl,alt:C.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):C.name.charAt(0).toUpperCase()}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsxs("div",{style:{color:Y.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[C.name,$&&r.jsxs("span",{style:{color:Y.textSecondary,fontWeight:400},children:[" ",a("voiceChatOverlay.you","(You)")]})]})}),C.isMuted&&r.jsx(F.NtdMicrophoneOff,{size:16,variant:"outline",primaryColor:Y.mutedIcon})]});return N?r.jsxs("div",{className:f,style:{...ty,...Ni(u),backgroundColor:Y.background,border:`1px solid ${Y.border}`,zIndex:v,...k},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${Y.border}`},children:[r.jsx("span",{style:{color:Y.text,fontWeight:600},children:a("voiceChatOverlay.voiceChat","Voice Chat")}),r.jsx("button",{onClick:()=>_(!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(F.NtdMinimize,{size:16,variant:"outline",primaryColor:Y.textSecondary})})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[r.jsx(W,{participant:{id:s,name:i,avatarUrl:o,isMuted:j},isLocal:!0,isSpeaking:I&&!j}),l.map(C=>r.jsx(W,{participant:C,isSpeaking:C.isSpeaking},C.id))]}),r.jsx(ps,{ref:R,mode:"bars",width:256,height:32,barCount:24,barColor:j?"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:j?.5:1}}),r.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[r.jsx("button",{onClick:O,style:{flex:1,padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:j?Y.mutedBg:Y.activeBg,color:j?Y.mutedIcon:Y.activeIcon,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":j?a("voiceChatOverlay.unmute","Unmute"):a("voiceChatOverlay.mute","Mute"),children:j?r.jsxs(r.Fragment,{children:[r.jsx(F.NtdMicrophoneOff,{size:16,variant:"outline"}),a("voiceChatOverlay.muted","Muted")]}):r.jsxs(r.Fragment,{children:[r.jsx(F.NtdMicrophone,{size:16,variant:"outline"}),a("voiceChatOverlay.micOn","Mic On")]})}),r.jsx("button",{onClick:U,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(F.NtdLogOut,{size:16,variant:"outline"})})]})]}):r.jsx("div",{className:f,style:{position:"fixed",...Ni(u),zIndex:v,...k},children:r.jsxs("button",{onClick:()=>_(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:Y.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(F.NtdMicrophone,{size:24,variant:"outline",primaryColor:Y.text}),l.length>0&&r.jsx("span",{style:{position:"absolute",top:-4,right:-4,width:20,height:20,borderRadius:"50%",backgroundColor:Y.speakingRing,color:"var(--nice-color-white, #fff)",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:l.length+1})]})})});function ay(e,t){const n={...t,id:`op_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now()},a=e.operations.slice(0,e.undoIndex+1);return a.push(n),{...e,operations:a,undoIndex:a.length-1}}function sy(e){return e.undoIndex<0?e:{...e,undoIndex:e.undoIndex-1}}function iy(e){return e.undoIndex>=e.operations.length-1?e:{...e,undoIndex:e.undoIndex+1}}function oy(e,t,n){const s=({"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":.6666666666666666,"1/8T":.3333333333333333,"1/16T":.16666666666666666,"1/4D":1.5,"1/8D":.75}[t.grid]??1)*n,i=t.strength/100;return e.map(o=>{const l=Math.round(o.startTick/s)*s,c=o.startTick+(l-o.startTick)*i,u=(Math.random()-.5)*2*t.humanize;return{...o,startTick:Math.max(0,Math.round(c+u))}})}function ly(e){if(e.length<2)return null;const t=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],n=[...new Set(e.map(s=>s%12))].sort((s,i)=>s-i),a=[{intervals:[0,4,7],quality:"maj"},{intervals:[0,3,7],quality:"min"},{intervals:[0,4,7,11],quality:"maj7"},{intervals:[0,3,7,10],quality:"min7"},{intervals:[0,4,7,10],quality:"7"},{intervals:[0,3,6],quality:"dim"},{intervals:[0,4,8],quality:"aug"},{intervals:[0,3,6,9],quality:"dim7"},{intervals:[0,2,7],quality:"sus2"},{intervals:[0,5,7],quality:"sus4"},{intervals:[0,4,7,9],quality:"6"},{intervals:[0,3,7,9],quality:"min6"}];for(const s of n){const i=n.map(o=>(o-s+12)%12).sort((o,l)=>o-l);for(const o of a)if(o.intervals.length===i.length&&o.intervals.every((l,c)=>l===i[c])){const l=t[s],c=t[e[0]%12];return{root:l,quality:o.quality,bass:c!==l?c:void 0,symbol:`${l}${o.quality==="maj"?"":o.quality}${c!==l?`/${c}`:""}`,intervals:o.intervals}}}return null}const Pc={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],aeolian:[0,2,3,5,7,8,10],locrian:[0,1,3,5,6,8,10],"harmonic-minor":[0,2,3,5,7,8,11],"melodic-minor":[0,2,3,5,7,9,11],"pentatonic-major":[0,2,4,7,9],"pentatonic-minor":[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11],"whole-tone":[0,2,4,6,8,10]};function cy(e,t,n){const a=Pc[n],s=(e-t+120)%12;let i=a[0],o=999;for(const c of a){const 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 dy(e,t){switch(t.type){case"transpose":return e.map(n=>({...n,pitch:Math.max(0,Math.min(127,n.pitch+(t.params.semitones??0)))}));case"invert":{const n=t.params.axis??60;return e.map(a=>({...a,pitch:Math.max(0,Math.min(127,Math.round(2*n-a.pitch)))}))}case"retrograde":{if(e.length===0)return e;const n=Math.max(...e.map(a=>a.startTick+a.durationTicks));return e.map(a=>({...a,startTick:n-a.startTick-a.durationTicks}))}case"randomize-velocity":return e.map(n=>({...n,velocity:Math.max(1,Math.min(127,n.velocity+Math.round((Math.random()-.5)*2*(t.params.range??20))))}));default:return e}}function uy(e){return e>=95?"S":e>=85?"A":e>=70?"B":e>=55?"C":e>=40?"D":"F"}const hy={"guitar-standard":{instrument:"guitar-6",stringPitches:[40,45,50,55,59,64]},"guitar-drop-d":{instrument:"guitar-6",stringPitches:[38,45,50,55,59,64]},"bass-standard":{instrument:"bass-4",stringPitches:[28,33,38,43]},"ukulele-standard":{instrument:"ukulele",stringPitches:[67,60,64,69]}},py={"Bass Drum":{staffLine:4,noteHead:"normal",stem:"down"},Snare:{staffLine:2,noteHead:"normal",stem:"up"},"Hi-Hat Closed":{staffLine:0,noteHead:"x",stem:"up"},"Hi-Hat Open":{staffLine:0,noteHead:"diamond",stem:"up"},Ride:{staffLine:-1,noteHead:"x",stem:"up"},Crash:{staffLine:-2,noteHead:"x",stem:"up"},"High Tom":{staffLine:1,noteHead:"normal",stem:"up"},"Mid Tom":{staffLine:2,noteHead:"normal",stem:"down"},"Low Tom":{staffLine:3,noteHead:"normal",stem:"down"}};exports.ALL_CAP_STYLES=Wn;exports.ALL_EFFECTS=_l;exports.ALL_TEXTURES=Eo;exports.ARTNET_PORT=_g;exports.ASYMMETRIC_CAPS=ko;exports.AudioEffectType=xc;exports.AudioPlaybackEngine=h0;exports.AudioRecorder=La;exports.AutoSavePanel=Li;exports.CONTROLLER_PROFILES=Kl;exports.ChaseRunner=Gg;exports.CollaboratorPermission=Sc;exports.DEFAULT_ARP_CONFIG=ua;exports.DEFAULT_AUDIO_INPUT_SETTINGS=Dl;exports.DEFAULT_BAR_FILL=Gt;exports.DEFAULT_CAP_STYLE=Co;exports.DEFAULT_EMPTY_BAR_FILL=Dr;exports.DEFAULT_FONT_SETTINGS=Br;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=Fr;exports.DEFAULT_GOLD_FILLED_BAR_FILL=Or;exports.DEFAULT_KARAOKE_SETTINGS=jo;exports.DEFAULT_SEED_CONFIG=Ol;exports.DMXEngine=jc;exports.DRUM_PATTERN_NAMES=M0;exports.DefaultScoringPresets=Da;exports.DmxChannelControl=hs;exports.DmxChannelType=Ft;exports.DmxEditor=wc;exports.DmxOptionsControl=us;exports.DmxSliderControl=Vn;exports.DynamicRuleField=ot;exports.DynamicRuleOperator=lt;exports.EditorTrackProvider=_a;exports.EditorUndoManager=wu;exports.FIXTURE_PROFILES=Cc;exports.GENERIC_PROFILE=as;exports.GM_DRUM_MAP=py;exports.GRADIENT_PRESETS=hl;exports.GROOVE_TEMPLATES=ls;exports.GenericPlaylistItem=Qa;exports.KARAOKE_FONT_OPTIONS=fp;exports.KEY_MAPS=qo;exports.KaraokeFormat=Ya;exports.LANE_COLORS=In;exports.LAUNCH_CONTROL_PROFILE=Hl;exports.LAYER_COLORS=Tg;exports.MINILAB_PROFILE=ql;exports.MPK_MINI_PROFILE=Ul;exports.MasterFXPanel=zi;exports.MidiCCMapper=N0;exports.NOTE_NAMES=x0;exports.NiceArpeggiatorPanel=cu;exports.NiceAudioEffectsRack=o0;exports.NiceAudioErrorBoundary=Oc;exports.NiceAudioInputPicker=u0;exports.NiceAudioPitchAnalyzer=ph;exports.NiceAudioStudio=Gd;exports.NiceAudioTimeline=Ii;exports.NiceAutoSavePanel=Li;exports.NiceBarFillEditor=hh;exports.NiceCCAutomationLaneEditor=iu;exports.NiceCCLane=Qc;exports.NiceDMXTimeline=Wg;exports.NiceDmxChannelControl=hs;exports.NiceDmxEditor=wc;exports.NiceDmxOptionsControl=us;exports.NiceDmxSliderControl=Vn;exports.NiceDynamicRuleEditor=Of;exports.NiceEditorTrackProvider=_a;exports.NiceGenericPlayer=Io;exports.NiceGenericPlayerControls=Mp;exports.NiceGenericPlayerStage=af;exports.NiceGenericPlaylist=vf;exports.NiceGenericPlaylistItem=Qa;exports.NiceI18nProvider=Dc;exports.NiceKaraokeEditorManager=xp;exports.NiceKaraokeLyrics=po;exports.NiceKaraokeManager=Kh;exports.NiceKaraokePhaserRenderer=wp;exports.NiceKaraokeSelectionMode=ul;exports.NiceKaraokeSessionJoin=hp;exports.NiceKaraokeSetupPanel=dl;exports.NiceKaraokeSongBrowser=rp;exports.NiceKaraokeSummaryOverlay=$o;exports.NiceKaraokeTimeline=To;exports.NiceKaraokeUploader=Vo;exports.NiceLFOPanel=hu;exports.NiceLatencyCalibrator=sp;exports.NiceMasterFXPanel=zi;exports.NiceModeSwitcher=ml;exports.NiceMusicLibraryExplorer=uf;exports.NiceNoteParticles=Wm;exports.NiceNoteRiver=_m;exports.NicePadKaraokeOverlay=Uo;exports.NicePianoRoll=Ea;exports.NicePlaylistBrowser=Xf;exports.NicePlaylistDualPane=Wf;exports.NicePlaylistGridView=tm;exports.NicePlaylistImportWizard=um;exports.NicePlaylistList=ts;exports.NicePlaylistOverview=rm;exports.NicePlaylistSearchBar=am;exports.NicePlaylistSidebar=Jf;exports.NicePlaylistTagEditor=xf;exports.NicePlaylistTrackList=Cl;exports.NiceRadioPlayer=Yg;exports.NiceRecordingOptionsPanel=Di;exports.NiceSampleBrowser=Vd;exports.NiceStageVisualizer=gl;exports.NiceStationBrowser=Rc;exports.NiceStepSequencerPanel=gu;exports.NiceStreamingVisualizer=ps;exports.NiceUndoRedoPanel=_i;exports.NiceVocalEffectsRack=c0;exports.NiceVocalPerformanceReport=Qh;exports.NiceVoiceChatOverlay=Tc;exports.NiceWaveform=Pi;exports.NiceYouTubePlayer=sf;exports.NiceZoomSnapControls=$a;exports.OVERLAY_PATTERNS=Pr;exports.OXYGEN25_PROFILE=Vl;exports.PLAYER_COLORS=Xe;exports.PLAYER_COLOR_VARS=ur;exports.PROGRESSION_NAMES=j0;exports.PadNotePlayer=Zo;exports.PaneSide=xl;exports.PianoRoll=Ea;exports.PlaylistList=ts;exports.PlaylistType=Ja;exports.RecordingOptionsPanel=Di;exports.SACN_PORT=Fg;exports.SCALE_INTERVALS=Pc;exports.SCALE_NAMES=C0;exports.SKEW_CAPS=wo;exports.STANDARD_TUNINGS=hy;exports.SYMMETRIC_CAPS=Va;exports.ShortcutManager=vc;exports.SimpleSynth=Fl;exports.SortDirection=dn;exports.SortField=Sl;exports.StreamingVisualizer=ps;exports.TEXTURE_CATEGORIES=Ha;exports.TrackSource=xt;exports.UndoRedoPanel=_i;exports.ViewMode=bl;exports.VocalEffectsEngine=zl;exports.VoiceChatOverlay=Tc;exports.WebRTCAudioManager=Nc;exports.ZoomSnapControls=$a;exports.addEffectToLayer=B0;exports.addMidiNote=U0;exports.analyzeAudioFileWithAlgorithm=eg;exports.applyGroove=og;exports.applyGrooveTemplate=gc;exports.applyHumanize=mc;exports.applyKaraokeDisplayVars=Xa;exports.applyMidiTransform=dy;exports.applySwing=fc;exports.arrow_L=Ot;exports.arrow_R=Nt;exports.autoCorrelate=zo;exports.bracket_L=Oa;exports.bracket_R=xo;exports.buildArpSequence=so;exports.buildLanes=Ho;exports.buildNoteDescriptors=Ka;exports.buildPadNoteEvents=Yo;exports.buildSegmentScores=Do;exports.canRedo=Ui;exports.canUndo=Vi;exports.chamfer_L=Mr;exports.chamfer_R=fn;exports.clearMidiNotes=H0;exports.clearPattern=sc;exports.computeGrade=uy;exports.computeTheoreticalMax=nl;exports.computeVocalPerformanceReport=ol;exports.convertBrowserSongToKaraokeSongFile=$h;exports.copyCCEvents=da;exports.createAnalyserNode=dc;exports.createArpPattern=$0;exports.createArtNetPacket=Dg;exports.createBasslinePattern=A0;exports.createCCHistory=Oi;exports.createCompressorNode=hc;exports.createDefaultLFO=_r;exports.createDefaultShortcuts=bg;exports.createDropZoneHandlers=Rg;exports.createEmptyPattern=Zt;exports.createEmptyStep=ss;exports.createGainNode=uc;exports.createHiHatPattern=E0;exports.createKickPattern=T0;exports.createLoopRegion=pg;exports.createSACNPacket=Og;exports.createSnarePattern=P0;exports.createVocoderNode=pc;exports.createVoiceChatAudioContext=ey;exports.cutCCEvents=Hi;exports.deleteCCEventsInRange=Ki;exports.deserializeLFO=nu;exports.deserializePattern=L0;exports.detectChord=ly;exports.downsampleAndQuantizePitchPoints=Fo;exports.drawGlossyBarOnCanvas=Tn;exports.drawTimeline=ma;exports.estimateLatencyMs=Oo;exports.estimateLatencyMsFromRecording=cl;exports.evaluateLFO=Aa;exports.evaluateLFOAsCC=Ia;exports.exportCCLane=Xi;exports.extractBpmFromNotes=fo;exports.findTextureByUrl=ch;exports.formatShortcut=xg;exports.generateArpEvents=lu;exports.generatePlaceholderWaveform=sg;exports.generateSeed=Wl;exports.generateUltrastarText=tg;exports.getActiveGradient=fl;exports.getActiveLyrics=Tu;exports.getActiveWords=Pu;exports.getAlgorithmColor=Ph;exports.getAlgorithmCssVar=Eh;exports.getAlgorithmLabel=Th;exports.getArpModes=io;exports.getArpRates=oo;exports.getAudioContext=qn;exports.getAudioInputDevices=Jg;exports.getAudioWorkletProcessorCode=lc;exports.getBackgroundUrl=Nh;exports.getCachedImage=ih;exports.getCapStyleByName=Rn;exports.getComboMultiplier=el;exports.getCoverUrl=Rh;exports.getGrooveTemplate=lg;exports.getGrooveTemplateNames=cg;exports.getLaneForPitch=Ko;exports.getNextPlayerColor=sd;exports.getNextPlayerColorCss=id;exports.getOverlayCanvasPattern=An;exports.getPatternByName=Nn;exports.getSACNMulticastAddress=Bg;exports.getScoringPreset=zr;exports.getTexturePattern=En;exports.getVerseRatingLabel=Jo;exports.handleAddCCEvent=Y0;exports.handleRedo=ku;exports.handleRemoveCCEvent=X0;exports.handleSelectCCLane=K0;exports.handleUndo=Su;exports.handleUpdateCCEvent=Z0;exports.hexToHsl=Er;exports.humanizeMidiNotes=hg;exports.hydrateKaraokeDisplayFromBackend=mp;exports.hydratePlayerKaraokeSettingsFromBackend=Ou;exports.hzToUltrastarPitch=mo;exports.importCCLane=Qi;exports.initKaraokeDisplaySettings=yp;exports.instrumentPresets=p0;exports.isAudioContextRunning=Ei;exports.isInLoopRegion=gg;exports.isWebRTCSupported=Qg;exports.loadAllKaraokeSettings=Bu;exports.loadAudioWorkletModule=cc;exports.loadKaraokeDisplaySettings=pl;exports.loadKaraokeSettings=Ua;exports.loadRemoteScoringPresets=zu;exports.makeClickReference=ll;exports.makeClipSelectionId=ng;exports.mergeWaveforms=ag;exports.midiSeedGenerator=R0;exports.midiToHz=ga;exports.normalizeHex=$r;exports.openAudioFilePicker=Ng;exports.ornate_L=Ga;exports.ornate_R=Tr;exports.parseLyrics=Ru;exports.parseNotes=Hn;exports.parseUltraStarText=Wo;exports.parseVersesWithSyllables=ho;exports.parseVersesWithWords=Nu;exports.parseVideoMetadata=_o;exports.pasteCCEvents=qi;exports.pill_L=qt;exports.pill_R=Dt;exports.preloadTexture=qa;exports.preloadTextures=oh;exports.probeAudioFile=bc;exports.pushCCState=Bi;exports.pushOperation=ay;exports.quantizeMidiNotes=dg;exports.quantizeNotes=oy;exports.quantizeStepInBeats=yc;exports.quantizeStepInSeconds=cs;exports.randomizeVelocity=ac;exports.recordCCEvent=Yi;exports.redoCC=Wi;exports.redoOperation=iy;exports.removeEffectFromLayer=G0;exports.removeMidiNote=q0;exports.renderGlossyBarSvg=Mo;exports.resumeAudioContext=Yt;exports.reversePattern=nc;exports.sampleLFOForDisplay=ro;exports.sampleLFOToCCEvents=no;exports.saveKaraokeDisplaySettings=gp;exports.saveKaraokeSettings=Fu;exports.scaleResult=al;exports.scaleTo10k=rl;exports.scoreNotesWithPitchPoints=tl;exports.selectCCEventsInRange=Ud;exports.serializeLFO=tu;exports.serializePattern=I0;exports.setLoopFromSelection=fg;exports.setProjectWithUndo=co;exports.setStepGate=Ql;exports.setStepNote=Zl;exports.setStepProbability=Jl;exports.setStepVelocity=Xl;exports.sharp_L=hn;exports.sharp_R=pn;exports.shield_L=Rr;exports.shield_R=bo;exports.shiftPattern=rc;exports.shouldTrigger=oc;exports.skewTL_L=hr;exports.skewTL_R=fa;exports.skewTR_L=pa;exports.skewTR_R=pr;exports.snapLoopToGrid=mg;exports.snapTimeToQuantize=Na;exports.snapToGrid=rg;exports.snapToScale=cy;exports.soft_L=Fa;exports.soft_R=vo;exports.stepDuration=is;exports.stepTimeOffset=ic;exports.syncDivisionToHz=eo;exports.tab_L=Ba;exports.tab_R=So;exports.thinCCEvents=Zi;exports.toTrack=Go;exports.toggleEffectBypass=W0;exports.toggleStep=Yl;exports.toggleStepSlide=ec;exports.transposePattern=tc;exports.undoCC=Gi;exports.undoOperation=sy;exports.updateEffectParams=V0;exports.useAudioWorklet=O0;exports.useAutoSave=yu;exports.useCCAutomation=Ji;exports.useCanPickSong=up;exports.useDMXAudioSync=Ug;exports.useDMXEngine=Vg;exports.useEditorTrack=Mu;exports.useKaraokePitch=Qo;exports.useKaraokeScoring=sl;exports.useLocalPlaylists=es;exports.useMPE=y0;exports.useMidiLearn=m0;exports.useNiceTranslation=xe;exports.useOxygen25=b0;exports.usePitchWorker=z0;exports.usePlaybackEngine=vu;exports.useProjectCRUD=ju;exports.useRadioStream=Mc;exports.useRecording=bu;exports.useScoringWorker=D0;exports.useStepSequencer=_0;exports.useWebMidi=Vr;exports.useWorker=os;exports.validateAudioFiles=ds;exports.wave_L=Nr;exports.wave_R=Wa;exports.waveformValue=to;exports.wrapTimeInLoop=yg;
|