@nice2dev/ui-audio 1.0.12 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -50,7 +50,7 @@ Artist � Title [Remastered 2011]
50
50
  OR: Artist;Title;Version`),rows:3,style:{width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:8,fontFamily:"inherit"}}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:6},children:[s.jsx("div",{style:{color:"var(--nice-text-secondary, #6b7280)",fontSize:12},children:h("genericPlaylist.bulkPasteHint","Each line will be added as a separate song.")}),s.jsx("button",{type:"button",onClick:Y,disabled:!p.trim(),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},children:h("genericPlaylist.addFromList","Add from list")})]})]})]})})]})},ts=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #f59e0b)","var(--nice-warning, #eab308)","var(--nice-success, #84cc16)","var(--nice-success, #22c55e)","var(--nice-info, #14b8a6)","var(--nice-info, #06b6d4)","var(--nice-primary, #3b82f6)","var(--nice-info, #6366f1)","var(--nice-accent, #8b5cf6)","var(--nice-accent, #a855f7)","var(--nice-accent-pink, #d946ef)","var(--nice-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)","#78716c","var(--nice-text-secondary, #64748b)","var(--nice-text, #000000)"],Ln=["??","??","??","??","??","??","??","??","??","?","??","??","??","??","??","??"],Uo=({tags:e,onCreateTag:t,onUpdateTag:n,onDeleteTag:r,selectedTracks:a,onAssignTag:o,onUnassignTag:i})=>{const{t:l}=xe(),[c,d]=u.useState(null),[h,f]=u.useState(""),[m,g]=u.useState(ts[8]),[p,v]=u.useState(Ln[0]),[x,b]=u.useState(!1),[w,y]=u.useState(null),[k,M]=u.useState(""),[N,R]=u.useState(""),[_,E]=u.useState(""),U=u.useCallback(O=>{d(O.id),M(O.name),R(O.color),E(O.icon||Ln[0])},[]),W=u.useCallback(()=>{c&&k.trim()&&(n(c,k.trim(),N,_),d(null))},[c,k,N,_,n]),j=u.useCallback(()=>{h.trim()&&(t(h.trim(),m,p),f(""),b(!1))},[h,m,p,t]),L=u.useCallback(O=>{w===O?(r(O),y(null)):(y(O),setTimeout(()=>y(null),3e3))},[w,r]),I=a&&a.length>0,q=O=>!a||a.length===0?!1:a.every(Z=>Z.tags.includes(O)),Y=O=>!a||a.length===0?!1:a.some(Z=>Z.tags.includes(O))&&!q(O);return s.jsxs("div",{style:{border:"1px solid var(--border-color, #e5e7eb)",borderRadius:10,background:"var(--card-bg, #fff)",overflow:"hidden"},children:[s.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border-color, #e5e7eb)",display:"flex",alignItems:"center",gap:8,background:"var(--surface-bg, #f9fafb)"},children:[s.jsx("span",{style:{fontSize:"1rem"},children:"???"}),s.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:l("playlistManager.tagManager")}),s.jsx("div",{style:{flex:1}}),s.jsxs("button",{onClick:()=>b(!x),style:{background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"4px 10px",fontSize:"0.72rem",cursor:"pointer"},children:["+ ",l("playlistManager.newTag")]})]}),s.jsxs("div",{style:{padding:12},children:[x&&s.jsxs("div",{style:{border:"1px solid var(--border-color, #d1d5db)",borderRadius:8,padding:10,marginBottom:12,background:"var(--surface-bg, #f9fafb)"},children:[s.jsxs("div",{style:{display:"flex",gap:6,marginBottom:8},children:[s.jsx("input",{type:"text",value:h,onChange:O=>f(O.target.value),placeholder:l("playlistManager.tagName"),style:{flex:1,padding:"5px 10px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",fontSize:"0.8rem",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)"},onKeyDown:O=>O.key==="Enter"&&j()}),s.jsx("button",{onClick:j,disabled:!h.trim(),style:{background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"5px 12px",fontSize:"0.78rem",cursor:"pointer",opacity:h.trim()?1:.5},children:"?"})]}),s.jsxs("div",{style:{marginBottom:6},children:[s.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.color")}),s.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:ts.map(O=>s.jsx("div",{onClick:()=>g(O),style:{width:20,height:20,borderRadius:"50%",background:O,cursor:"pointer",border:m===O?"3px solid var(--accent, #3b82f6)":"2px solid transparent",boxSizing:"border-box"}},O))})]}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.icon")}),s.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:Ln.map(O=>s.jsx("div",{onClick:()=>v(O),style:{width:26,height:26,borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"0.85rem",background:p===O?"var(--accent-bg, #eff6ff)":"transparent",border:p===O?"1px solid var(--accent, #3b82f6)":"1px solid transparent"},children:O},O))})]})]}),I&&s.jsx("div",{style:{padding:"6px 10px",background:"var(--accent-bg, #eff6ff)",borderRadius:6,marginBottom:8,fontSize:"0.72rem",color:"var(--accent, #3b82f6)"},children:l("playlistManager.bulkTagHint")+": "+a.length}),e.length===0?s.jsx("div",{style:{textAlign:"center",padding:20,opacity:.3,fontSize:"0.82rem"},children:l("playlistManager.noTags")}):s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.map(O=>s.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderRadius:8,border:"1px solid var(--border-color, #e5e7eb)",background:c===O.id?"var(--surface-bg, #f9fafb)":"transparent"},children:c===O.id?s.jsxs(s.Fragment,{children:[s.jsx("select",{value:_,onChange:Z=>E(Z.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:Ln.map(Z=>s.jsx("option",{value:Z,children:Z},Z))}),s.jsx("input",{type:"color",value:N,onChange:Z=>R(Z.target.value),style:{width:24,height:24,border:"none",cursor:"pointer",padding:0}}),s.jsx("input",{type:"text",value:k,onChange:Z=>M(Z.target.value),style:{flex:1,padding:"3px 8px",borderRadius:4,border:"1px solid var(--border-color, #d1d5db)",fontSize:"0.78rem",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)"},onKeyDown:Z=>Z.key==="Enter"&&W()}),s.jsx("button",{onClick:W,style:Fn("var(--accent, #3b82f6)"),children:"?"}),s.jsx("button",{onClick:()=>d(null),style:Fn("var(--text-secondary, #9ca3af)"),children:"?"})]}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 10px",borderRadius:20,background:`${O.color}18`,color:O.color,fontWeight:600,fontSize:"0.78rem"},children:[O.icon&&s.jsx("span",{children:O.icon}),O.name]}),I&&o&&i&&s.jsx("input",{type:"checkbox",checked:q(O.id),ref:Z=>{Z&&(Z.indeterminate=Y(O.id))},onChange:()=>{const Z=a.map(H=>H.id);q(O.id)?i(Z,O.id):o(Z,O.id)},style:{cursor:"pointer"}}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:()=>U(O),style:Fn("var(--text-secondary, #9ca3af)"),title:l("playlistManager.editTag"),children:"?"}),s.jsx("button",{onClick:()=>L(O.id),style:Fn(w===O.id?"var(--error, #ef4444)":"var(--text-secondary, #9ca3af)"),title:w===O.id?l("playlistManager.confirmDelete"):l("playlistManager.deleteTag"),children:w===O.id?"?":"??"})]})},O.id))})]})]})},Fn=e=>({background:"none",border:"none",cursor:"pointer",fontSize:"0.82rem",color:e,padding:"2px 4px"});var ma=(e=>(e.Static="static",e.Dynamic="dynamic",e))(ma||{}),Vo=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(Vo||{}),qo=(e=>(e.Left="left",e.Right="right",e))(qo||{}),Ye=(e=>(e.Artist="artist",e.Title="title",e.Album="album",e.Genre="genre",e.Year="year",e.Duration="duration",e.Rating="rating",e.PlayCount="playCount",e.Tag="tag",e.Source="source",e.AddedDate="addedDate",e))(Ye||{}),Ze=(e=>(e.Equals="eq",e.NotEquals="neq",e.Contains="contains",e.NotContains="notContains",e.StartsWith="startsWith",e.GreaterThan="gt",e.LessThan="lt",e.Between="between",e.In="in",e.NotIn="notIn",e))(Ze||{}),Ho=(e=>(e.Title="title",e.Artist="artist",e.Album="album",e.Duration="duration",e.AddedDate="addedDate",e.Year="year",e.Rating="rating",e.Custom="custom",e))(Ho||{}),qt=(e=>(e.Asc="asc",e.Desc="desc",e))(qt||{}),lt=(e=>(e.Library="library",e.Spotify="spotify",e.Tidal="tidal",e.YouTube="youtube",e.MusicBrainz="musicbrainz",e.Import="import",e.Manual="manual",e))(lt||{});const Xu=[{value:Ye.Artist,label:"Artist"},{value:Ye.Title,label:"Title"},{value:Ye.Album,label:"Album"},{value:Ye.Genre,label:"Genre"},{value:Ye.Year,label:"Year"},{value:Ye.Duration,label:"Duration (s)"},{value:Ye.Rating,label:"Rating"},{value:Ye.PlayCount,label:"Play Count"},{value:Ye.Tag,label:"Tag"},{value:Ye.Source,label:"Source"},{value:Ye.AddedDate,label:"Added Date"}],Qu=[{value:Ze.Equals,label:"="},{value:Ze.NotEquals,label:"≠"},{value:Ze.Contains,label:"contains"},{value:Ze.NotContains,label:"not contains"},{value:Ze.StartsWith,label:"starts with"},{value:Ze.GreaterThan,label:">"},{value:Ze.LessThan,label:"<"},{value:Ze.Between,label:"between"},{value:Ze.In,label:"in"},{value:Ze.NotIn,label:"not in"}];function Ju(e){return"logic"in e&&"rules"in e}function zr(){return{id:crypto.randomUUID(),field:Ye.Artist,operator:Ze.Contains,value:""}}function Ko(){return{id:crypto.randomUUID(),logic:"and",rules:[zr()]}}const eh=({rule:e,onChange:t,onRemove:n})=>s.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[s.jsx("select",{className:"form-select form-select-sm",style:{width:130},value:e.field,onChange:r=>t({...e,field:r.target.value}),children:Xu.map(r=>s.jsx("option",{value:r.value,children:r.label},r.value))}),s.jsx("select",{className:"form-select form-select-sm",style:{width:130},value:e.operator,onChange:r=>t({...e,operator:r.target.value}),children:Qu.map(r=>s.jsx("option",{value:r.value,children:r.label},r.value))}),s.jsx("input",{type:"text",className:"form-control form-control-sm",style:{width:160},value:e.value,placeholder:"Value",onChange:r=>t({...e,value:r.target.value})}),e.operator===Ze.Between&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-muted",children:"–"}),s.jsx("input",{type:"text",className:"form-control form-control-sm",style:{width:120},value:e.value2??"",placeholder:"Value 2",onChange:r=>t({...e,value2:r.target.value})})]}),s.jsx("button",{className:"btn btn-outline-danger btn-sm",onClick:n,title:"Remove rule",children:"✕"})]}),Yo=({group:e,onChange:t,onRemove:n,depth:r=0})=>{const{t:a}=xe(),o=u.useCallback((f,m)=>{const g=[...e.rules];g[f]=m,t({...e,rules:g})},[e,t]),i=u.useCallback(f=>{const m=e.rules.filter((g,p)=>p!==f);t({...e,rules:m.length>0?m:[zr()]})},[e,t]),l=u.useCallback(()=>{t({...e,rules:[...e.rules,zr()]})},[e,t]),c=u.useCallback(()=>{t({...e,rules:[...e.rules,Ko()]})},[e,t]),d=u.useCallback(()=>{t({...e,logic:e.logic==="and"?"or":"and"})},[e,t]),h=e.logic==="and"?"var(--bs-primary)":"var(--bs-warning)";return s.jsxs("div",{className:"p-2 mb-2 rounded",style:{borderLeft:`3px solid ${h}`,backgroundColor:r%2===0?"rgba(var(--bs-body-color-rgb), 0.03)":"transparent"},children:[s.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[s.jsx("button",{className:`btn btn-sm ${e.logic==="and"?"btn-primary":"btn-warning"}`,onClick:d,title:a("playlistManager.toggleLogic","Toggle AND/OR"),children:e.logic.toUpperCase()}),s.jsx("span",{className:"text-muted small",children:a("playlistManager.matchAll","Match all / any of these rules")}),s.jsxs("div",{className:"ms-auto d-flex gap-1",children:[s.jsx("button",{className:"btn btn-outline-secondary btn-sm",onClick:l,title:"Add rule",children:"+ Rule"}),r<3&&s.jsx("button",{className:"btn btn-outline-secondary btn-sm",onClick:c,title:"Add nested group",children:"+ Group"}),n&&s.jsx("button",{className:"btn btn-outline-danger btn-sm",onClick:n,title:"Remove group",children:"✕"})]})]}),e.rules.map((f,m)=>Ju(f)?s.jsx(Yo,{group:f,onChange:g=>o(m,g),onRemove:()=>i(m),depth:r+1},f.id):s.jsx(eh,{rule:f,onChange:g=>o(m,g),onRemove:()=>i(m)},f.id))]})},Zo=({rules:e,onChange:t,limit:n,onLimitChange:r})=>{const{t:a}=xe(),o=e??Ko();return s.jsxs("div",{className:"border rounded p-3",children:[s.jsxs("h6",{className:"mb-3",children:["🔄 ",a("playlistManager.dynamicRules","Dynamic Playlist Rules")]}),s.jsx("p",{className:"text-muted small mb-3",children:a("playlistManager.dynamicRulesHint","Tracks matching these rules will automatically be included in the playlist.")}),s.jsx(Yo,{group:o,onChange:t}),r&&s.jsxs("div",{className:"d-flex align-items-center gap-2 mt-3 pt-2 border-top",children:[s.jsx("label",{className:"form-label mb-0 small",children:a("playlistManager.maxTracks","Max tracks:")}),s.jsx("input",{type:"number",className:"form-control form-control-sm",style:{width:100},min:0,value:n??"",placeholder:"∞",onChange:i=>{const l=parseInt(i.target.value,10);r(isNaN(l)||l<=0?void 0:l)}}),s.jsx("span",{className:"text-muted small",children:a("playlistManager.leaveEmptyForAll","(leave empty for unlimited)")})]})]})},ns=e=>{if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`},th={library:"??",spotify:"??",tidal:"?",youtube:"??",musicbrainz:"??",import:"??",manual:"?"},ga=({tracks:e,tags:t,selectedTrackIds:n,onSelectionChange:r,onPlay:a,onRemove:o,onReorder:i,onTagTracks:l,onRateTracks:c,sortField:d,sortDir:h,onSortChange:f,filterText:m,onFilterChange:g,compact:p=!1,draggable:v=!1,onDragStart:x,dropTarget:b=!1,onDrop:w})=>{const{t:y}=xe(),[k,M]=u.useState(null),[N,R]=u.useState(null),_=u.useRef(null),E=u.useMemo(()=>{let S=e??[];if(m.trim()){const P=m.toLowerCase();S=S.filter($=>{var T,C;return $.title.toLowerCase().includes(P)||$.artist.toLowerCase().includes(P)||((T=$.album)==null?void 0:T.toLowerCase().includes(P))||((C=$.genre)==null?void 0:C.toLowerCase().includes(P))})}return[...S].sort((P,$)=>{const T=h==="asc"?1:-1;switch(d){case"title":return T*P.title.localeCompare($.title);case"artist":return T*P.artist.localeCompare($.artist);case"album":return T*(P.album??"").localeCompare($.album??"");case"duration":return T*((P.duration??0)-($.duration??0));case"year":return T*((P.year??0)-($.year??0));case"rating":return T*((P.rating??0)-($.rating??0));case"addedDate":return T*(P.addedAt??"").localeCompare($.addedAt??"");case"custom":return T*((P.customOrder??0)-($.customOrder??0));default:return 0}})},[e,m,d,h]),U=u.useCallback((S,P)=>{const $=E[S];if($){if(P.ctrlKey||P.metaKey){const T=new Set(n);T.has($.id)?T.delete($.id):T.add($.id),r(T)}else if(P.shiftKey&&_.current!==null){const T=Math.min(_.current,S),C=Math.max(_.current,S),A=new Set(n);for(let D=T;D<=C;D++)A.add(E[D].id);r(A)}else r(new Set([$.id]));_.current=S}},[E,n,r]),W=u.useCallback(()=>{n.size===E.length?r(new Set):r(new Set(E.map(S=>S.id)))},[E,n,r]),j=({field:S,label:P,width:$})=>{const T=d===S;return s.jsxs("div",{style:{width:$,flex:$?void 0:1,cursor:"pointer",userSelect:"none",fontWeight:T?700:500,fontSize:"0.72rem",textTransform:"uppercase",letterSpacing:"0.04em",opacity:T?1:.6,display:"flex",alignItems:"center",gap:4},onClick:()=>{T?f(S,h===qt.Asc?qt.Desc:qt.Asc):f(S,qt.Asc)},children:[P,T&&s.jsx("span",{children:"?"})]})},L=u.useCallback((S,P)=>{const $=n.has(S.id)?Array.from(n):[S.id];P.dataTransfer.setData("trackIds",JSON.stringify($)),P.dataTransfer.effectAllowed="move",x==null||x($,P)},[n,x]),I=u.useCallback((S,P)=>{P.preventDefault(),P.dataTransfer.dropEffect="move",M(S)},[]),q=u.useCallback((S,P)=>{P.preventDefault(),M(null);try{const $=P.dataTransfer.getData("trackIds");if($&&i){const T=JSON.parse($),C=E.filter(V=>!T.includes(V.id)),A=E.filter(V=>T.includes(V.id)),D=Math.min(S,C.length);C.splice(D,0,...A),i(C.map(V=>V.id))}}catch{}},[E,i]),Y=u.useCallback(S=>{S.preventDefault(),M(null),w==null||w(S)},[w]),O=u.useMemo(()=>new Map(t.map(S=>[S.id,S])),[t]),Z=S=>S.replace(/[^a-z0-9_-]/gi,"-"),H=p?36:48,te={display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)",color:"var(--text-secondary, #6b7280)"},G=(S,P)=>({display:"flex",alignItems:"center",gap:8,padding:p?"4px 12px":"6px 12px",height:H,cursor:"pointer",background:P?"var(--accent-light, #dbeafe)":S?"var(--selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--border-subtle, #f3f4f6)",transition:"background 0.1s"}),z=E.length>0&&n.size===E.length;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:b?S=>{S.preventDefault(),S.dataTransfer.dropEffect="copy"}:void 0,onDrop:b?Y:void 0,children:[s.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)",display:"flex",gap:8,alignItems:"center"},children:[s.jsx("input",{type:"text",value:m,onChange:S=>g(S.target.value),placeholder:"?? "+y("playlistManager.filterTracks"),style:{flex:1,fontSize:"0.82rem",padding:"6px 10px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #f9fafb)",color:"var(--text-primary, #1f2937)"}}),s.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[E.length,"/",(e??[]).length]}),n.size>0&&o&&s.jsxs("button",{style:{fontSize:"0.72rem",padding:"4px 8px",borderRadius:4,border:"1px solid var(--error, #ef4444)",background:"transparent",color:"var(--error, #ef4444)",cursor:"pointer"},onClick:()=>o(Array.from(n)),children:["?? ",n.size]})]}),s.jsxs("div",{style:te,children:[s.jsx("div",{style:{width:28},children:s.jsx("input",{type:"checkbox",checked:z,onChange:W,style:{cursor:"pointer"}})}),s.jsx("div",{style:{width:20},children:"#"}),!p&&s.jsx("div",{style:{width:44}}),s.jsx(j,{field:"title",label:y("playlistManager.colTitle")}),s.jsx(j,{field:"artist",label:y("playlistManager.colArtist")}),!p&&s.jsx(j,{field:"album",label:y("playlistManager.colAlbum")}),s.jsx(j,{field:"duration",label:y("playlistManager.colDuration"),width:60}),!p&&s.jsx(j,{field:"year",label:y("playlistManager.colYear"),width:50}),s.jsx("div",{style:{width:30}})," ",!p&&s.jsx("div",{style:{width:60}})," ",s.jsx("div",{style:{width:24}})," "]}),s.jsxs("div",{style:{flex:1,overflow:"auto"},children:[E.length===0&&s.jsx("div",{style:{padding:24,textAlign:"center",opacity:.4,fontSize:"0.85rem"},children:e.length===0?y("playlistManager.emptyPlaylist"):y("playlistManager.noMatchingTracks")}),E.map((S,P)=>{const $=n.has(S.id),T=k===P;return s.jsxs("div",{style:G($,T),onClick:C=>U(P,C),onDoubleClick:()=>a==null?void 0:a(S),draggable:v,onDragStart:C=>L(S,C),onDragOver:C=>I(P,C),onDrop:C=>q(P,C),onDragLeave:()=>M(null),children:[s.jsx("div",{style:{width:28},children:s.jsx("input",{type:"checkbox",checked:$,onChange:()=>{const C=new Set(n);$?C.delete(S.id):C.add(S.id),r(C)},onClick:C=>C.stopPropagation(),style:{cursor:"pointer"}})}),s.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:P+1}),!p&&s.jsx("div",{style:{width:44,height:36,flexShrink:0},children:S.coverUrl?s.jsx("img",{src:S.coverUrl,alt:S.title||y("common.coverArt","Cover art"),style:{width:36,height:36,borderRadius:4,objectFit:"cover"},loading:"lazy"}):s.jsx("div",{style:{width:36,height:36,borderRadius:4,background:"var(--surface-bg, #f3f4f6)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.9rem"},children:"??"})}),s.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",fontWeight:500},children:S.title}),s.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",opacity:.7},children:S.artist}),!p&&s.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",opacity:.5},children:S.album}),s.jsx("div",{style:{width:60,fontSize:"0.78rem",opacity:.5,textAlign:"right"},children:ns(S.duration)}),!p&&s.jsx("div",{style:{width:50,fontSize:"0.72rem",opacity:.4,textAlign:"center"},children:S.year||""}),s.jsx("div",{style:{width:30,textAlign:"center",fontSize:"0.75rem"},title:S.source,children:th[S.source]??"?"}),!p&&s.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[S.tags.slice(0,2).map(C=>{const A=O.get(C);if(!A)return null;const D=`--tag-${Z(C)}`;return s.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${D}-bg, ${A.color}22)`,color:`var(${D}, ${A.color})`,whiteSpace:"nowrap"},children:A.name},C)}),S.tags.length>2&&s.jsxs("span",{style:{fontSize:"0.6rem",opacity:.4},children:["+",S.tags.length-2]})]}),s.jsxs("div",{style:{width:24,display:"flex",alignItems:"center"},children:[s.jsx("button",{style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:2,opacity:.5,position:"relative"},onClick:C=>{C.stopPropagation(),R(N===S.id?null:S.id)},title:y("playlistManager.morActions"),children:"?"}),N===S.id&&t.length>0&&s.jsxs("div",{style:{position:"absolute",right:12,marginTop:4,background:"var(--card-bg, #fff)",border:"1px solid var(--border-color, #e5e7eb)",borderRadius:8,padding:8,zIndex:100,boxShadow:"0 4px 12px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",minWidth:140},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:y("playlistManager.assignTag")}),t.map(C=>{const A=S.tags.includes(C.id);return s.jsxs("div",{style:{padding:"4px 8px",borderRadius:4,cursor:"pointer",fontSize:"0.78rem",display:"flex",alignItems:"center",gap:6,background:A?`var(--tag-${Z(C.id)}-bg, ${C.color}22)`:"transparent"},onClick:D=>{D.stopPropagation();const V=n.size>0?Array.from(n):[S.id];A||l==null||l(V,[C.id]),R(null)},children:[s.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:`var(--tag-${Z(C.id)}, ${C.color})`,flexShrink:0}}),s.jsx("span",{children:C.name}),A&&s.jsx("span",{style:{marginLeft:"auto"},children:"?"})]},C.id)})]})]})]},S.id)})]}),s.jsxs("div",{style:{padding:"6px 12px",borderTop:"1px solid var(--border-color, #e5e7eb)",fontSize:"0.72rem",opacity:.5,display:"flex",gap:16},children:[s.jsxs("span",{children:[E.length," ",y("playlistManager.tracks")]}),s.jsx("span",{children:ns(E.reduce((S,P)=>S+(P.duration??0),0))}),n.size>0&&s.jsxs("span",{children:[n.size," ",y("playlistManager.selected")]})]})]})},rs=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),Xo=({playlists:e=[],tags:t=[],onCopyTracks:n=()=>{},onMoveTracks:r=()=>{},onRemoveTracks:a=()=>{},onReorderTracks:o=()=>{},onPlay:i=()=>{},onTagTracks:l=()=>{},initialLeftId:c,initialRightId:d,library:h,queue:f,onAddToQueue:m,onRemoveFromQueue:g})=>{const{t:p}=xe(),[v,x]=u.useState(()=>rs(c??null)),[b,w]=u.useState(()=>rs(d??null)),[y,k]=u.useState("left"),[M,N]=u.useState(null),[R,_]=u.useState(50),[E,U]=u.useState(!1),W=u.useMemo(()=>e.find(T=>T.id===v.playlistId),[e,v.playlistId]),j=u.useMemo(()=>e.find(T=>T.id===b.playlistId),[e,b.playlistId]),L=u.useCallback((T,C)=>{T==="left"?x(A=>({...A,...C})):w(A=>({...A,...C}))},[]),I=u.useCallback(T=>T==="left"?v:b,[v,b]),q=T=>T==="left"?"right":"left",Y=u.useCallback(T=>{const C=I(T),A=I(q(T));!C.playlistId||!A.playlistId||C.selectedTrackIds.size===0||(n(C.playlistId,A.playlistId,Array.from(C.selectedTrackIds)),L(T,{selectedTrackIds:new Set}))},[I,n,L]),O=u.useCallback(T=>{const C=I(T),A=I(q(T));!C.playlistId||!A.playlistId||C.selectedTrackIds.size===0||(r(C.playlistId,A.playlistId,Array.from(C.selectedTrackIds)),L(T,{selectedTrackIds:new Set}))},[I,r,L]),Z=u.useCallback(T=>{const C=I(T);!C.playlistId||C.selectedTrackIds.size===0||N({operation:"copy",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[I]),H=u.useCallback(T=>{const C=I(T);!C.playlistId||C.selectedTrackIds.size===0||N({operation:"cut",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[I]),te=u.useCallback(T=>{const C=I(T);!M||!C.playlistId||(M.operation==="copy"?n(M.sourcePlaylistId,C.playlistId,M.trackIds):r(M.sourcePlaylistId,C.playlistId,M.trackIds),N(null))},[M,I,n,r]),G=u.useCallback(T=>{T.key==="Tab"&&!T.shiftKey&&(T.preventDefault(),k(C=>q(C))),(T.ctrlKey||T.metaKey)&&T.key==="c"&&Z(y),(T.ctrlKey||T.metaKey)&&T.key==="x"&&H(y),(T.ctrlKey||T.metaKey)&&T.key==="v"&&te(y)},[y,Z,H,te]),z=u.useCallback(()=>U(!0),[]),S=u.useCallback(T=>{if(!E)return;const C=T.currentTarget.getBoundingClientRect(),A=(T.clientX-C.left)/C.width*100;_(Math.max(20,Math.min(80,A)))},[E]),P=u.useCallback(()=>U(!1),[]),$=T=>{const C=I(T),A=T==="left"?W:j,D=y===T,Q=!!I(q(T)).playlistId;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",border:D?"2px solid var(--accent, #3b82f6)":"2px solid transparent",borderRadius:8,overflow:"hidden",background:"var(--card-bg, #fff)"},onClick:()=>k(T),children:[s.jsx("div",{style:{padding:"8px 12px",background:D?"var(--accent, #3b82f6)":"var(--surface-bg, #f3f4f6)",color:D?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:s.jsxs("select",{value:C.playlistId??"",onChange:J=>L(T,{playlistId:J.target.value||null,selectedTrackIds:new Set}),style:{flex:1,fontSize:"0.82rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",background:D?"var(--accent-overlay, #ffffff30)":"var(--input-bg, #fff)",color:D?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)"},children:[s.jsx("option",{value:"",children:p("playlistManager.selectPlaylist")}),e.map(J=>s.jsxs("option",{value:J.id,children:[J.name," (",J.trackCount,")"]},J.id))]})}),s.jsxs("div",{style:{display:"flex",gap:4,padding:"4px 8px",borderBottom:"1px solid var(--border-color, #e5e7eb)",flexWrap:"wrap"},children:[s.jsxs("button",{style:kr(!1),onClick:()=>Y(T),disabled:!C.playlistId||!Q||C.selectedTrackIds.size===0,title:p("playlistManager.copyToOther"),children:["???"," ",p("playlistManager.copy")]}),s.jsxs("button",{style:kr(!1),onClick:()=>O(T),disabled:!C.playlistId||!Q||C.selectedTrackIds.size===0,title:p("playlistManager.moveToOther"),children:["??"," ",p("playlistManager.move")]}),s.jsx("div",{style:{flex:1}}),M&&s.jsxs("button",{style:kr(!0),onClick:()=>te(T),disabled:!C.playlistId,children:["?? ",p("playlistManager.paste")," (",M.trackIds.length,")"]})]}),A?s.jsx(ga,{tracks:A.tracks,tags:t,selectedTrackIds:C.selectedTrackIds,onSelectionChange:J=>L(T,{selectedTrackIds:J}),onPlay:i,onRemove:J=>a(A.id,J),onReorder:J=>o(A.id,J),onTagTracks:l,sortField:C.sortField,sortDir:C.sortDir,onSortChange:(J,ae)=>L(T,{sortField:J,sortDir:ae}),filterText:C.filterText,onFilterChange:J=>L(T,{filterText:J}),compact:!0,draggable:!0}):s.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",opacity:.3,fontSize:"0.85rem"},children:p("playlistManager.selectPlaylistPrompt")})]})};return s.jsxs("div",{style:{display:"flex",height:"100%",userSelect:E?"none":"auto"},onKeyDown:G,onMouseMove:S,onMouseUp:P,tabIndex:0,children:[s.jsx("div",{style:{width:`${R}%`,minWidth:200},children:$("left")}),s.jsx("div",{style:{width:6,cursor:"col-resize",background:E?"var(--accent, #3b82f6)":"var(--border-color, #e5e7eb)",transition:E?"none":"background 0.15s",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseDown:z,children:s.jsx("div",{style:{width:2,height:40,borderRadius:1,background:E?"var(--btn-text, #fff)":"var(--text-secondary, #9ca3af)"}})}),s.jsx("div",{style:{flex:1,minWidth:200},children:$("right")})]})},kr=e=>({background:e?"var(--accent, #3b82f6)":"transparent",color:e?"var(--btn-text, #fff)":"var(--text-secondary, #6b7280)",border:e?"none":"1px solid var(--border-color, #d1d5db)",borderRadius:6,padding:"3px 8px",fontSize:"0.72rem",cursor:"pointer",whiteSpace:"nowrap"}),Qo="av:local-playlists";function nh(){try{const e=localStorage.getItem(Qo);return e?JSON.parse(e):[]}catch{return[]}}function rh(e){const t=JSON.stringify(e);try{localStorage.setItem(Qo,t)}catch{}}function ya(){const[e,t]=u.useState(()=>nh()),n=u.useRef(!1);return u.useEffect(()=>{n.current=!0},[]),u.useEffect(()=>{rh(e)},[e]),u.useMemo(()=>({list:()=>e,get:a=>e.find(o=>o.id===a),create:a=>{const o=new Date().toISOString(),i={id:crypto.randomUUID(),name:a,items:[],updatedAt:o};return t(l=>[i,...l]),i},rename:(a,o)=>t(i=>i.map(l=>l.id===a?{...l,name:o,updatedAt:new Date().toISOString()}:l)),remove:a=>t(o=>o.filter(i=>i.id!==a)),replaceItems:(a,o)=>t(i=>i.map(l=>l.id===a?{...l,items:o,updatedAt:new Date().toISOString()}:l)),addItems:(a,o)=>t(i=>i.map(l=>l.id===a?{...l,items:[...l.items,...o],updatedAt:new Date().toISOString()}:l))}),[e])}const ah=et.scoped("PlaylistList"),sh={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,background:"var(--nice-bg, #fff)"},oh={...sh,padding:"8px 10px",cursor:"pointer"},Jo={border:"1px solid var(--border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--bg, #fff)",cursor:"pointer"},ih={...Jo,background:"var(--primary, #4f46e5)",borderColor:"var(--primary, #4f46e5)",color:"var(--bg, #fff)"},ba=({selectedId:e,onSelect:t,onCreateRemote:n})=>{const{t:r}=xe(),a=ya(),[o,i]=u.useState(""),l=u.useMemo(()=>a.list(),[a]);return s.jsxs("div",{style:{display:"grid",gap:10},children:[s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("input",{placeholder:r("playlistList.playlistName","Playlist name..."),value:o,onChange:c=>i(c.target.value),style:{flex:1,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px"},"aria-label":"Playlist name"}),s.jsxs("button",{type:"button",disabled:!o.trim(),style:o.trim()?ih:{...Jo,cursor:"not-allowed",color:"var(--muted, #9ca3af)",background:"var(--bg-muted, #f3f4f6)"},onClick:async()=>{const c=a.create(o.trim());if(i(""),n)try{await n({platform:"tidal",name:c.name,songs:c.items})}catch(d){ah.error("Remote playlist create failed:",d)}t==null||t(c)},children:["+ ",r("common.add","Add")]})]}),s.jsxs("div",{style:{display:"grid",gap:6},children:[l.map(c=>{const d=c.id===e;return s.jsxs("button",{onClick:()=>t==null?void 0:t(c),style:{...oh,background:d?"var(--active-bg, #eef2ff)":"var(--bg, #fff)"},children:[s.jsx("div",{style:{fontWeight:600},children:c.name}),s.jsxs("div",{style:{color:"var(--text-dim, #64748b)",fontSize:12},children:[c.items.length+" "+r("playlistList.songs","songs")," \\u2022"," ",new Date(c.updatedAt).toLocaleString()]})]},c.id)}),!l.length&&s.jsx("div",{style:{color:"var(--muted, #6b7280)"},children:r("playlistList.emptyState","No playlists. Add the first one ↑")})]})]})},lh=et.scoped("PlaylistBrowser"),as={display:"grid",gap:12},ss=e=>({artist:(e.artists??[]).join(", "),title:e.title}),ei=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:n,tracks:r,view:a,onSelect:o,onPlay:i})=>{var x;const{t:l}=xe(),c=ya(),[d,h]=u.useState(null),[f,m]=u.useState(""),[,g]=u.useState([]),p=d==null?void 0:d.id,v=(b,w)=>{if("addItems"in c){c.addItems(b.id,w);const k=c.list().find(M=>M.id===b.id)||b;h(k);return}const y=c;if("update"in c&&typeof y.update=="function"){const k=Array.from([...b.items||[],...w]);y.update({...b,items:k});const M=c.list().find(N=>N.id===b.id)||{...b,items:k};h(M);return}lh.warn("useLocalPlaylists: missing addItems/update method — update hook implementation.")};return s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(min(200px, 100%), 320px) 1fr",gap:16},children:[s.jsxs("div",{style:as,children:[s.jsx("h3",{style:{margin:0},children:l("playlistBrowser.playlists")}),s.jsx(ba,{selectedId:p,onSelect:h}),d&&s.jsxs("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:[l("playlistBrowser.selected","Selected"),": ",s.jsx("strong",{children:d.name})," �"," ",((x=d.items)==null?void 0:x.length)??0," ",l("playlistBrowser.tracks","tracks")]})]}),s.jsxs("div",{style:as,children:[s.jsx("h3",{style:{margin:0},children:l("playlistBrowser.library")}),s.jsxs("div",{children:[e==null?void 0:e({placeholder:l("playlistBrowser.searchAndAdd","Search and add to playlist..."),onSelect:b=>{d&&v(d,[ss(b)])}}),s.jsx("input",{placeholder:l("playlistBrowser.fullSearch","Full search (Enter does not add, full list below)"),value:f,onChange:b=>m(b.target.value),style:{width:"100%",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px",marginTop:10}})]}),t==null?void 0:t({query:f,onSelect:b=>{d&&v(d,[ss(b)])}}),n==null?void 0:n({onPlayNow:b=>g(b),onAddToQueue:b=>g(w=>[...w,...b]),onAddDescriptors:b=>d&&v(d,b)})]})]})};var Tt=(e=>(e[e.None=0]="None",e[e.Spotify=1]="Spotify",e[e.Tidal=2]="Tidal",e[e.YouTube=4]="YouTube",e[e.All=7]="All",e))(Tt||{});const ti=(e,t=null)=>e.filter(n=>n.parentId===t).sort((n,r)=>n.sortOrder-r.sortOrder).map(n=>({...n,children:ti(e,n.id)})),ch={[Tt.Spotify]:{icon:"??",label:"Spotify",color:"var(--source-spotify, #1DB954)",bg:"var(--source-spotify-bg, #1DB95418)"},[Tt.Tidal]:{icon:"?",label:"Tidal",color:"var(--source-tidal, #000000)",bg:"var(--source-tidal-bg, #00000010)"},[Tt.YouTube]:{icon:"??",label:"YouTube",color:"var(--source-youtube, #FF0000)",bg:"var(--source-youtube-bg, #FF000010)"}},ni=({folders:e,playlists:t,tags:n,services:r,activeFolderId:a,activePlaylistId:o,onSelectFolder:i,onSelectPlaylist:l,onCreateFolder:c,onRenameFolder:d,onDeleteFolder:h,onCreatePlaylist:f,onConnectService:m,onDisconnectService:g,onDragPlaylistToFolder:p,collapsed:v=!1,onToggleCollapse:x})=>{const{t:b}=xe(),[w,y]=u.useState(new Set),[k,M]=u.useState(!1),[N,R]=u.useState(""),[_,E]=u.useState(null),[U,W]=u.useState(!1),[j,L]=u.useState(""),[I,q]=u.useState("static"),[Y,O]=u.useState(null),[Z,H]=u.useState(""),[te,G]=u.useState(null),[z,S]=u.useState(!1),P=u.useMemo(()=>ti(e),[e]),$=u.useCallback(X=>{y(ue=>{const ye=new Set(ue);return ye.has(X)?ye.delete(X):ye.add(X),ye})},[]),T=u.useCallback(()=>{N.trim()&&(c(N.trim(),_),R(""),M(!1))},[N,_,c]),C=u.useCallback(()=>{j.trim()&&(f(j.trim(),I,a),L(""),W(!1))},[j,I,a,f]),A=u.useCallback(X=>{Z.trim()&&(d(X,Z.trim()),O(null),H(""))},[Z,d]),D=u.useCallback((X,ue)=>{X.preventDefault(),X.dataTransfer.dropEffect="move",G(ue)},[]),V=u.useCallback((X,ue)=>{X.preventDefault();const ye=X.dataTransfer.getData("playlistId");ye&&p&&p(ye,ue),G(null)},[p]),Q=u.useCallback(()=>G(null),[]),J=u.useCallback(X=>t.filter(ue=>(ue.folderId??null)===X),[t]),ae={width:v?48:280,minWidth:v?48:280,background:"var(--sidebar-bg, #f8f9fa)",borderRight:"1px solid var(--border-color, #e5e7eb)",display:"flex",flexDirection:"column",transition:"width 0.2s, min-width 0.2s",overflow:"hidden",height:"100%"},re={padding:"8px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)"},ee=(X,ue=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:ue?"var(--accent-light, #dbeafe)":X?"var(--accent, #3b82f6)":"transparent",color:X?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",transition:"background 0.15s",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),F={background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:"2px 6px",borderRadius:4,color:"var(--text-secondary, #6b7280)"},K={fontSize:"0.8rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)",width:"100%"},se=(X,ue)=>{var Se,ne;const ye=w.has(X.id),je=a===X.id,Fe=te===X.id,Re=J(X.id);return s.jsxs("div",{children:[s.jsxs("div",{style:{...ee(je,Fe),paddingLeft:12+ue*16},onClick:()=>{i(X.id),X.children&&X.children.length>0&&$(X.id)},onDragOver:oe=>D(oe,X.id),onDrop:oe=>V(oe,X.id),onDragLeave:Q,children:[s.jsx("span",{style:{width:14,textAlign:"center",flexShrink:0,fontSize:"0.7rem"},children:(((Se=X.children)==null?void 0:Se.length)||0)>0||Re.length>0?"?":"�"}),Y===X.id?s.jsx("input",{value:Z,onChange:oe=>H(oe.target.value),onKeyDown:oe=>{oe.key==="Enter"&&A(X.id),oe.key==="Escape"&&O(null)},onBlur:()=>A(X.id),autoFocus:!0,style:{...K,flex:1},onClick:oe=>oe.stopPropagation()}):s.jsxs(s.Fragment,{children:[s.jsx("span",{children:X.icon??"??"}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:X.name}),s.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:Re.length}),s.jsx("button",{style:F,onClick:oe=>{oe.stopPropagation(),O(X.id),H(X.name)},title:b("common.rename"),children:"?"}),s.jsx("button",{style:{...F,color:"var(--error, #ef4444)"},onClick:oe=>{oe.stopPropagation(),h(X.id)},title:b("common.delete"),children:"?"})]})]}),ye&&s.jsxs(s.Fragment,{children:[Re.map(oe=>ce(oe,ue+1)),(ne=X.children)==null?void 0:ne.map(oe=>se(oe,ue+1))]})]},X.id)},ce=(X,ue)=>{const ye=o===X.id;return s.jsxs("div",{style:{...ee(ye),paddingLeft:12+ue*16+22},onClick:()=>l(X.id),draggable:!0,onDragStart:je=>{je.dataTransfer.setData("playlistId",X.id),je.dataTransfer.effectAllowed="move"},children:[s.jsx("span",{style:{fontSize:"0.7rem"},children:X.type==="dynamic"?"?":"??"}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:X.name}),s.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:X.trackCount})]},X.id)};if(v)return s.jsx("div",{style:ae,children:s.jsx("button",{style:{...F,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:x,title:b("playlistManager.expandSidebar"),children:"?"})});const fe=J(null);return s.jsxs("div",{style:ae,children:[s.jsxs("div",{style:{...re,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s.jsxs("span",{style:{fontWeight:700,fontSize:"0.85rem"},children:["?? ",b("playlistManager.title")]}),s.jsx("button",{style:F,onClick:x,title:b("playlistManager.collapseSidebar"),children:"?"})]}),s.jsxs("div",{style:{...re,display:"flex",gap:4,flexWrap:"wrap"},children:[s.jsxs("button",{style:{...F,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:6,padding:"4px 10px"},onClick:()=>W(!0),children:["+ ",b("playlistManager.newPlaylist")]}),s.jsxs("button",{style:{...F,border:"1px solid var(--border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{M(!0),E(a)},children:["?? ",b("playlistManager.newFolder")]})]}),U&&s.jsxs("div",{style:{...re,display:"flex",flexDirection:"column",gap:6},children:[s.jsx("input",{value:j,onChange:X=>L(X.target.value),placeholder:b("playlistManager.playlistName"),style:K,autoFocus:!0,onKeyDown:X=>{X.key==="Enter"&&C(),X.key==="Escape"&&W(!1)}}),s.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[s.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[s.jsx("input",{type:"radio",checked:I==="static",onChange:()=>q("static")}),b("playlistManager.static")]}),s.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[s.jsx("input",{type:"radio",checked:I==="dynamic",onChange:()=>q("dynamic")}),"? ",b("playlistManager.dynamic")]}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{style:{...F,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:C,"aria-label":"Confirm create playlist",children:"?"}),s.jsx("button",{style:F,onClick:()=>W(!1),"aria-label":"Cancel create playlist",children:"?"})]})]}),k&&s.jsxs("div",{style:{...re,display:"flex",gap:6},children:[s.jsx("input",{value:N,onChange:X=>R(X.target.value),placeholder:b("playlistManager.folderName"),style:{...K,flex:1},autoFocus:!0,onKeyDown:X=>{X.key==="Enter"&&T(),X.key==="Escape"&&M(!1)}}),s.jsx("button",{style:{...F,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:T,"aria-label":"Confirm create folder",children:"?"}),s.jsx("button",{style:F,onClick:()=>M(!1),"aria-label":"Cancel create folder",children:"?"})]}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[s.jsxs("div",{style:ee(a===null&&o===null,te==="__root__"),onClick:()=>i(null),onDragOver:X=>D(X,null),onDrop:X=>V(X,null),onDragLeave:Q,children:[s.jsx("span",{children:"??"}),s.jsx("span",{style:{flex:1},children:b("playlistManager.allPlaylists")}),s.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:t.length})]}),fe.map(X=>ce(X,0)),P.map(X=>se(X,0))]}),n.length>0&&s.jsxs("div",{style:re,children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:b("playlistManager.tags")}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:n.map(X=>s.jsxs("span",{style:{fontSize:"0.7rem",padding:"2px 8px",borderRadius:12,background:X.color+"22",color:X.color,border:`1px solid ${X.color}44`,cursor:"pointer"},children:[X.icon&&`${X.icon} `,X.name]},X.id))})]}),s.jsxs("div",{style:re,children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",cursor:"pointer",fontSize:"0.7rem",fontWeight:600,opacity:.6},onClick:()=>S(!z),children:[s.jsxs("span",{children:["?? ",b("playlistManager.services")]}),s.jsx("span",{children:"?"})]}),z&&s.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[Tt.Spotify,Tt.Tidal,Tt.YouTube].map(X=>{const ue=ch[X],ye=r.find(je=>je.platform===X);return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 8px",borderRadius:6,border:"1px solid var(--border-color, #e5e7eb)",fontSize:"0.78rem"},children:[s.jsx("span",{children:ue.icon}),s.jsx("span",{style:{flex:1},children:ue.label}),ye!=null&&ye.connected?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:"0.65rem",opacity:.6},children:ye.username??b("playlistManager.connected")}),s.jsx("button",{style:{...F,color:"var(--nice-danger, #ef4444)"},onClick:()=>g(X),children:"?"})]}):s.jsx("button",{style:{...F,background:ue.color,color:"var(--nice-bg, #fff)",borderRadius:4,padding:"2px 8px"},onClick:()=>m(X),children:b("playlistManager.connect")})]},X)})})]})]})},dh=({playlist:e,tags:t,onPlay:n,selectedTrackIds:r,onSelectionChange:a})=>{const{t:o}=xe(),i=u.useCallback(l=>{const c=new Set(r);c.has(l)?c.delete(l):c.add(l),a(c)},[r,a]);return e.tracks.length===0?s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:60,opacity:.3},children:[s.jsx("span",{style:{fontSize:"2rem",marginBottom:8},children:"??"}),s.jsx("span",{style:{fontSize:"0.82rem"},children:o("playlistManager.emptyPlaylist")})]}):s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(160px, 1fr))",gap:10},children:e.tracks.map(l=>{const c=r.has(l.id);return s.jsxs("div",{onClick:()=>i(l.id),onDoubleClick:()=>n(l),style:{border:c?"2px solid var(--accent, #3b82f6)":"1px solid var(--border-color, #e5e7eb)",borderRadius:10,padding:10,cursor:"pointer",background:c?"var(--accent-bg, #eff6ff)":"var(--card-bg, #fff)",transition:"all 0.12s"},children:[s.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:6,background:"linear-gradient(135deg, var(--playlist-track-bg1, #6366f140), var(--playlist-track-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"1.5rem",marginBottom:6},children:"?"}),s.jsx("div",{style:{fontWeight:500,fontSize:"0.78rem",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.title}),s.jsx("div",{style:{fontSize:"0.68rem",opacity:.5,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.artist})]},l.id)})})},ri=u.memo(dh),os=e=>e.replace(/[^a-z0-9_-]/gi,"-"),is={background:"none",border:"none",cursor:"pointer",fontSize:"0.78rem",padding:"2px 4px",opacity:.4},uh=({playlists:e,folders:t,tags:n,activeFolderId:r,onSelectPlaylist:a,onDeletePlaylist:o,onDuplicatePlaylist:i})=>{const{t:l}=xe(),c=u.useMemo(()=>r?e.filter(d=>d.folderId===r):e,[e,r]);return c.length===0?s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:60,opacity:.4},children:[s.jsx("span",{style:{fontSize:"2.5rem",marginBottom:12},children:"??"}),s.jsx("span",{style:{fontSize:"0.85rem"},children:l("playlistManager.emptyState")})]}):s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))",gap:12},children:c.map(d=>{var f;const h=t.find(m=>m.id===d.folderId);return s.jsxs("div",{onClick:()=>a(d.id),style:{border:"1px solid var(--border-color, #e5e7eb)",borderRadius:12,padding:16,cursor:"pointer",background:"var(--card-bg, #fff)",transition:"box-shadow 0.15s, transform 0.15s"},onMouseEnter:m=>{m.currentTarget.style.boxShadow="0 4px 12px var(--nice-overlay-8, rgba(0, 0, 0, 0.08))",m.currentTarget.style.transform="translateY(-1px)"},onMouseLeave:m=>{m.currentTarget.style.boxShadow="none",m.currentTarget.style.transform="none"},children:[s.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:8,background:"linear-gradient(135deg, var(--playlist-cover-bg1, #6366f140), var(--playlist-cover-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"2.5rem",marginBottom:10},children:d.type===ma.Dynamic?"?":"??"}),s.jsx("div",{style:{fontWeight:600,fontSize:"0.85rem",marginBottom:2},children:d.name}),s.jsxs("div",{style:{fontSize:"0.72rem",opacity:.5},children:[d.trackCount," ",l("playlistManager.tracks"),h&&` � ?? ${h.name}`]}),((f=d.tags)==null?void 0:f.length)>0&&s.jsx("div",{style:{display:"flex",gap:4,marginTop:6,flexWrap:"wrap"},children:d.tags.slice(0,3).map(m=>{const g=n.find(p=>p.id===m);return g?s.jsx("span",{style:{padding:"1px 8px",borderRadius:12,background:`var(--tag-${os(m)}-bg, ${g.color}18)`,color:`var(--tag-${os(m)}, ${g.color})`,fontSize:"0.65rem",fontWeight:500},children:g.name},m):null})}),s.jsxs("div",{style:{display:"flex",gap:4,marginTop:8},children:[s.jsx("button",{onClick:m=>{m.stopPropagation(),i(d.id)},style:is,title:l("playlistManager.duplicate"),children:"??"}),s.jsx("button",{onClick:m=>{m.stopPropagation(),o(d.id)},style:is,title:l("playlistManager.delete"),children:"??"})]})]},d.id)})})},ai=u.memo(uh),ls=[{value:lt.Library,label:"Library",icon:"??",hex:"var(--nice-info, #6366f1)",css:"var(--source-library, #6366f1)",cssBg:"var(--source-library-bg, #6366f118)"},{value:lt.Spotify,label:"Spotify",icon:"??",hex:"var(--nice-success, #1db954)",css:"var(--source-spotify, #1db954)",cssBg:"var(--source-spotify-bg, #1db95418)"},{value:lt.Tidal,label:"Tidal",icon:"?",hex:"var(--nice-text, #000000)",css:"var(--source-tidal, #000000)",cssBg:"var(--source-tidal-bg, #00000018)"},{value:lt.YouTube,label:"YouTube",icon:"??",hex:"var(--nice-danger, #ff0000)",css:"var(--source-youtube, #ff0000)",cssBg:"var(--source-youtube-bg, #ff000018)"},{value:lt.MusicBrainz,label:"MusicBrainz",icon:"??",hex:"#ba478f",css:"var(--source-musicbrainz, #ba478f)",cssBg:"var(--source-musicbrainz-bg, #ba478f18)"}],si=({onSearch:e,results:t,isSearching:n,onAddToPlaylist:r,onPlayPreview:a})=>{const{t:o}=xe(),[i,l]=u.useState(""),[c,d]=u.useState(new Set([lt.Library,lt.Spotify,lt.Tidal,lt.YouTube])),[h,f]=u.useState(new Set),[m,g]=u.useState(!1),p=u.useRef(null),v=u.useCallback(R=>{d(_=>{const E=new Set(_);return E.has(R)?E.delete(R):E.add(R),E})},[]),x=u.useCallback(R=>{l(R),p.current&&clearTimeout(p.current),R.trim().length>=2&&(p.current=setTimeout(()=>{e(R.trim(),Array.from(c))},350))},[c,e]),b=u.useCallback(R=>{R.preventDefault(),i.trim().length>=2&&e(i.trim(),Array.from(c))},[i,c,e]),w=u.useCallback(R=>{f(_=>{const E=new Set(_);return E.has(R)?E.delete(R):E.add(R),E})},[]),y=u.useCallback(()=>{h.size===t.length?f(new Set):f(new Set(t.map(R=>R.id)))},[h,t]),k=u.useCallback(()=>{const R=t.filter(_=>h.has(_.id));R.length>0&&(r(R),f(new Set))},[t,h,r]),M=R=>{if(!R)return"--:--";const _=Math.floor(R/60),E=R%60;return`${_}:${E.toString().padStart(2,"0")}`},N=R=>{const _=ls.find(E=>E.value===R);return _?_.icon:"?"};return s.jsxs("div",{style:{border:"1px solid var(--border-color, #e5e7eb)",borderRadius:10,background:"var(--card-bg, #fff)",overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 12px",gap:8,cursor:"pointer",background:"var(--surface-bg, #f9fafb)"},onClick:()=>g(!m),children:[s.jsx("span",{style:{fontSize:"1rem"},children:"??"}),s.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:o("playlistManager.search")}),s.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",opacity:.5},children:"?"})]}),m&&s.jsxs("div",{style:{padding:"0 12px 12px"},children:[s.jsx("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap"},children:ls.map(R=>{const _=c.has(R.value);return s.jsxs("button",{onClick:()=>v(R.value),style:{padding:"4px 10px",borderRadius:20,border:_?`2px solid ${R.css}`:"1px solid var(--border-color, #d1d5db)",background:_?R.cssBg:"transparent",color:_?R.css:"var(--text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:_?600:400,transition:"all 0.15s"},children:[R.icon," ",R.label]},R.value)})}),s.jsxs("form",{onSubmit:b,style:{display:"flex",gap:6,marginBottom:8},children:[s.jsx("input",{type:"text",value:i,onChange:R=>x(R.target.value),placeholder:o("playlistManager.searchPlaceholder"),style:{flex:1,padding:"6px 12px",borderRadius:8,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)",fontSize:"0.82rem"}}),s.jsx("button",{type:"submit",disabled:i.trim().length<2||n,style:{padding:"6px 14px",borderRadius:8,border:"none",background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.82rem",cursor:"pointer",opacity:i.trim().length<2?.5:1},children:n?"?":"??"})]}),t.length>0&&s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",gap:6,marginBottom:4,alignItems:"center"},children:[s.jsxs("label",{style:{fontSize:"0.72rem",display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:h.size===t.length&&t.length>0,onChange:y}),o("playlistManager.selectAll")]}),s.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[t.length," ",o("playlistManager.results")]}),s.jsx("div",{style:{flex:1}}),h.size>0&&s.jsxs("button",{onClick:k,style:{padding:"3px 10px",borderRadius:6,border:"none",background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.72rem",cursor:"pointer"},children:["? ",o("playlistManager.addSelected")," (",h.size,")"]})]}),s.jsx("div",{style:{maxHeight:300,overflowY:"auto",borderRadius:6,border:"1px solid var(--border-color, #e5e7eb)"},children:t.map(R=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:"1px solid var(--border-color, #f3f4f6)",background:h.has(R.id)?"var(--accent-bg, #eff6ff)":"transparent",cursor:"pointer",fontSize:"0.78rem"},onClick:()=>w(R.id),children:[s.jsx("input",{type:"checkbox",checked:h.has(R.id),readOnly:!0}),s.jsx("span",{children:N(R.source)}),R.imageUrl&&s.jsx("img",{src:R.imageUrl,alt:R.title||o("common.coverArt","Cover art"),style:{width:28,height:28,borderRadius:4,objectFit:"cover"}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:R.title}),s.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[R.artist,R.album?` � ${R.album}`:""]})]}),s.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:M(R.duration)}),a&&s.jsx("button",{onClick:_=>{_.stopPropagation(),a(R)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem"},title:o("playlistManager.preview"),children:"?"})]},R.id))})]}),n&&s.jsxs("div",{style:{textAlign:"center",padding:20,opacity:.5,fontSize:"0.82rem"},children:["? ",o("playlistManager.searching"),"..."]}),!n&&i.trim().length>=2&&t.length===0&&s.jsx("div",{style:{textAlign:"center",padding:20,opacity:.4,fontSize:"0.82rem"},children:o("playlistManager.noResults")})]})]})},hh=[{value:1,label:"Spotify",icon:"🟢",color:"var(--source-spotify, #1db954)"},{value:2,label:"Tidal",icon:"⬛",color:"var(--source-tidal, #000000)"},{value:3,label:"Apple Music",icon:"🍎",color:"var(--source-apple, #fa243c)"},{value:4,label:"YouTube",icon:"🔴",color:"var(--source-youtube, #ff0000)"},{value:99,label:"Manual Paste",icon:"📋",color:"var(--source-manual, #6366f1)"}],fh={display:"flex",flexDirection:"column",gap:16,padding:24,borderRadius:12,background:"var(--panel-bg, #ffffff)",border:"1px solid var(--border, #e2e8f0)",maxWidth:640,minHeight:400},ph={display:"flex",justifyContent:"space-between",alignItems:"center"},mh={display:"flex",gap:4,marginBottom:8},bn={padding:"8px 20px",borderRadius:6,border:"none",background:"var(--accent, #6366f1)",color:"var(--nice-bg, #fff)",cursor:"pointer",fontWeight:600},Dn={...bn,background:"transparent",color:"var(--text, #334155)",border:"1px solid var(--border, #e2e8f0)"},cs={padding:12,borderRadius:8,border:"1px solid var(--border, #e2e8f0)",cursor:"pointer",transition:"border-color 0.15s"},oi=["connect","browse","tracks","options","importing","done"];function gh(e){return oi.indexOf(e)}function yh(e){if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const ii=({connections:e=[],onConnect:t=()=>{},onDisconnect:n=()=>{},onFetchPlaylists:r=async()=>[],onFetchTracks:a=async()=>[],onImport:o=async()=>({playlistName:"",imported:0,skipped:0,failed:0,failedTracks:[]}),onClose:i=()=>{},targetFolders:l,sources:c})=>{const{t:d}=xe(),[h,f]=u.useState("connect"),[m,g]=u.useState(null),[p,v]=u.useState([]),[x,b]=u.useState(null),[w,y]=u.useState([]),[k,M]=u.useState(new Set),[N,R]=u.useState(!1),[_,E]=u.useState(null),[U,W]=u.useState(null),[j,L]=u.useState(null),[I,q]=u.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[Y,O]=u.useState(""),Z=u.useMemo(()=>new Set(e.filter(F=>F.connected).map(F=>F.platform)),[e]),H=u.useCallback(F=>e.find(K=>K.platform===F),[e]),te=u.useCallback(F=>{if(g(F),F===99){f("tracks"),O(""),y([]),R(!1);return}Z.has(F)?(f("browse"),R(!0),L(null),r(F).then(K=>{v(K),R(!1)}).catch(K=>{L(String(K)),R(!1)})):t(F)},[Z,t,r]),G=u.useCallback(F=>{b(F),f("tracks"),R(!0),L(null),a(F).then(K=>{y(K),M(new Set(K.map(se=>se.externalId))),R(!1)}).catch(K=>{L(String(K)),R(!1)})},[a]),z=u.useCallback(F=>{M(K=>{const se=new Set(K);return se.has(F)?se.delete(F):se.add(F),se})},[]),S=u.useCallback(()=>{M(F=>F.size===w.length?new Set:new Set(w.map(K=>K.externalId)))},[w]),P=u.useCallback(async()=>{if(!x)return;const F=w.filter(K=>k.has(K.externalId));if(F.length!==0){f("importing"),E({total:F.length,imported:0,skipped:0,failed:0}),L(null);try{const K=await o(x,F,I),se=K&&typeof K=="object"&&"imported"in K?K:{playlistName:x.name,imported:F.length,skipped:0,failed:0,failedTracks:[]};W(se),f("done")}catch(K){L(String(K)),f("options")}}},[x,w,k,I,o]),$=h!=="connect"&&h!=="importing"&&h!=="done",T=u.useCallback(()=>{switch(h){case"browse":f("connect");break;case"tracks":f("browse");break;case"options":f("tracks");break}},[h]),C=()=>s.jsx("div",{style:mh,children:oi.map((F,K)=>s.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:K<=gh(h)?"var(--accent, #6366f1)":"var(--border, #e2e8f0)",transition:"background 0.2s"}},F))}),A=()=>s.jsxs("div",{style:{display:"grid",gap:12},children:[s.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:d("importWizard.selectPlatform","Select a music platform to import from")}),hh.map(F=>{const K=H(F.value),se=Z.has(F.value);return s.jsxs("div",{style:{...cs,display:"flex",alignItems:"center",gap:12,borderColor:se?F.color:void 0},onClick:()=>te(F.value),role:"button",tabIndex:0,onKeyDown:ce=>ce.key==="Enter"&&te(F.value),children:[s.jsx("span",{style:{fontSize:24},children:F.icon}),s.jsxs("div",{style:{flex:1},children:[s.jsx("strong",{children:F.label}),(K==null?void 0:K.username)&&s.jsx("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:K.username})]}),se?s.jsxs("span",{style:{color:F.color,fontSize:12,fontWeight:600},children:[d("importWizard.connected","Connected")," ✓"]}):s.jsx("span",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:d("importWizard.clickToConnect","Click to connect")})]},F.value)})]}),D=()=>s.jsxs("div",{style:{display:"grid",gap:12},children:[s.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:d("importWizard.selectPlaylist","Select a playlist to import")}),N?s.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--text-dim, #64748b)"},children:d("importWizard.loading","Loading playlists…")}):s.jsxs("div",{style:{display:"grid",gap:8,maxHeight:320,overflowY:"auto"},children:[p.map(F=>s.jsxs("div",{style:{...cs,display:"flex",alignItems:"center",gap:12},onClick:()=>G(F),role:"button",tabIndex:0,onKeyDown:K=>K.key==="Enter"&&G(F),children:[F.coverUrl&&s.jsx("img",{src:F.coverUrl,alt:"",style:{width:48,height:48,borderRadius:6,objectFit:"cover"}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:F.name}),F.description&&s.jsx("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:F.description})]}),s.jsxs("span",{style:{fontSize:12,color:"var(--text-dim, #64748b)",whiteSpace:"nowrap"},children:[F.trackCount," ",d("importWizard.tracks","tracks")]})]},F.id)),p.length===0&&s.jsx("div",{style:{textAlign:"center",padding:24,color:"var(--text-dim, #64748b)"},children:d("importWizard.noPlaylists","No playlists found")})]})]}),V=u.useCallback(F=>{const se=F.split(`
51
51
  `).map(ce=>ce.trim()).filter(Boolean).map((ce,fe)=>{const X=ce.match(/^(.+?)\s*[-–—]\s*(.+)$/);return X?{externalId:`paste-${fe}`,title:X[2].trim(),artist:X[1].trim(),album:void 0,duration:0}:{externalId:`paste-${fe}`,title:ce,artist:"",album:void 0,duration:0}});y(se),M(new Set(se.map(ce=>ce.externalId)))},[]),Q=()=>s.jsxs("div",{style:{display:"grid",gap:12},children:[m===99&&w.length===0&&s.jsxs("div",{style:{display:"grid",gap:8},children:[s.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:d("importWizard.pasteInstructions",'Paste your track list below (one track per line). Use "Artist - Title" format for best results.')}),s.jsx("textarea",{value:Y,onChange:F=>O(F.target.value),placeholder:`Daft Punk - Get Lucky
52
52
  The Weeknd - Blinding Lights
53
- Tame Impala - Let It Happen`,rows:10,style:{width:"100%",padding:12,borderRadius:6,border:"1px solid var(--border, #e2e8f0)",fontFamily:"monospace",fontSize:13,resize:"vertical"}}),s.jsx("button",{style:{...bn,opacity:Y.trim().length===0?.5:1},disabled:Y.trim().length===0,onClick:()=>V(Y),type:"button",children:d("importWizard.parseTracks","Parse Tracks")})]}),(m!==99||w.length>0)&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("p",{style:{margin:0,fontWeight:600},children:[x==null?void 0:x.name," — ",k.size,"/",w.length," ",d("importWizard.selected","selected")]}),s.jsx("button",{style:Dn,onClick:S,type:"button",children:k.size===w.length?d("importWizard.deselectAll","Deselect All"):d("importWizard.selectAll","Select All")})]}),N?s.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--text-dim, #64748b)"},children:d("importWizard.loadingTracks","Loading tracks…")}):s.jsx("div",{style:{maxHeight:320,overflowY:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid var(--border, #e2e8f0)",textAlign:"left"},children:[s.jsx("th",{style:{padding:"4px 8px",width:32}}),s.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.title","Title")}),s.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.artist","Artist")}),s.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.album","Album")}),s.jsx("th",{style:{padding:"4px 8px",textAlign:"right"},children:d("importWizard.duration","Duration")})]})}),s.jsx("tbody",{children:w.map(F=>{const K=k.has(F.externalId);return s.jsxs("tr",{style:{borderBottom:"1px solid var(--border, #e2e8f0)",opacity:K?1:.5,cursor:"pointer"},onClick:()=>z(F.externalId),children:[s.jsx("td",{style:{padding:"6px 8px"},children:s.jsx("input",{type:"checkbox",checked:K,readOnly:!0})}),s.jsx("td",{style:{padding:"6px 8px",fontWeight:500},children:F.title}),s.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:F.artist}),s.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:F.album??"—"}),s.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--text-dim, #64748b)"},children:yh(F.duration)})]},F.externalId)})})]})}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsxs("button",{style:{...bn,opacity:k.size===0?.5:1},disabled:k.size===0,onClick:()=>f("options"),type:"button",children:[d("importWizard.next","Next")," →"]})})]})]}),J=()=>s.jsxs("div",{style:{display:"grid",gap:16},children:[s.jsx("p",{style:{margin:0,fontWeight:600},children:d("importWizard.importOptions","Import options")}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:I.mergeTags,onChange:F=>q(K=>({...K,mergeTags:F.target.checked}))}),d("importWizard.mergeTags","Merge tags from source playlist")]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:I.mergeFolders,onChange:F=>q(K=>({...K,mergeFolders:F.target.checked}))}),d("importWizard.mergeFolders","Merge into existing folder structure")]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:I.overwriteExisting,onChange:F=>q(K=>({...K,overwriteExisting:F.target.checked}))}),d("importWizard.overwrite","Overwrite existing tracks (match by ISRC)")]}),l&&l.length>0&&s.jsxs("div",{style:{display:"grid",gap:4},children:[s.jsx("label",{style:{fontSize:13,fontWeight:500},children:d("importWizard.targetFolder","Target folder")}),s.jsxs("select",{style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border, #e2e8f0)"},value:I.targetFolderId??"",onChange:F=>q(K=>({...K,targetFolderId:F.target.value||void 0})),children:[s.jsx("option",{value:"",children:d("importWizard.root","— Root —")}),l.map(F=>s.jsx("option",{value:F.id,children:F.name},F.id))]})]}),s.jsx("div",{style:{marginTop:8,padding:12,borderRadius:8,background:"var(--info-bg, #eff6ff)",fontSize:13},children:d("importWizard.summary",`Ready to import ${k.size} tracks from "${(x==null?void 0:x.name)??""}"`)}),s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[s.jsx("button",{style:Dn,onClick:T,type:"button",children:d("importWizard.back","← Back")}),s.jsx("button",{style:bn,onClick:P,type:"button",children:d("importWizard.startImport","Start Import")})]})]}),ae=()=>{const F=_?Math.round(_.imported/_.total*100):0;return s.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[s.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:d("importWizard.importing","Importing…")}),s.jsx("div",{style:{height:8,borderRadius:4,background:"var(--border, #e2e8f0)",overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${F}%`,background:"var(--accent, #6366f1)",borderRadius:4,transition:"width 0.3s"}})}),_&&s.jsxs("div",{style:{fontSize:13,color:"var(--text-dim, #64748b)"},children:[_.imported," / ",_.total," ",d("importWizard.tracks","tracks"),_.currentTrack&&s.jsxs("div",{style:{marginTop:4},children:["🎵 ",_.currentTrack]})]})]})},re=()=>s.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[s.jsx("span",{style:{fontSize:48},children:"✅"}),s.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:d("importWizard.complete","Import Complete")}),U&&s.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[s.jsxs("div",{children:[s.jsx("strong",{children:U.imported})," ",d("importWizard.imported","imported")]}),U.skipped>0&&s.jsxs("div",{style:{color:"var(--warning, #f59e0b)"},children:[U.skipped," ",d("importWizard.skipped","skipped (duplicates)")]}),U.failed>0&&s.jsxs("div",{style:{color:"var(--error, #ef4444)"},children:[U.failed," ",d("importWizard.failed","failed")]}),U.failedTracks.length>0&&s.jsxs("details",{style:{textAlign:"left",marginTop:8,fontSize:12,color:"var(--text-dim, #64748b)"},children:[s.jsx("summary",{style:{cursor:"pointer"},children:d("importWizard.showFailed","Show failed tracks")}),s.jsx("ul",{style:{marginTop:4,paddingLeft:20},children:U.failedTracks.map((F,K)=>s.jsx("li",{children:F},K))})]})]}),s.jsx("button",{style:bn,onClick:i,type:"button",children:d("importWizard.close","Done")})]}),ee={connect:d("importWizard.stepConnect","Connect"),browse:d("importWizard.stepBrowse","Browse"),tracks:d("importWizard.stepTracks","Select Tracks"),options:d("importWizard.stepOptions","Options"),importing:d("importWizard.stepImporting","Importing"),done:d("importWizard.stepDone","Done")};return s.jsxs("div",{style:fh,children:[C(),s.jsxs("div",{style:ph,children:[s.jsxs("h2",{style:{margin:0,fontSize:18},children:[d("importWizard.title","Import Playlist")," — ",ee[h]]}),$&&s.jsxs("button",{style:Dn,onClick:T,type:"button",children:["← ",d("importWizard.back","Back")]}),h==="connect"&&s.jsx("button",{style:Dn,onClick:i,type:"button",children:"✕"})]}),j&&s.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--error-bg, #fef2f2)",color:"var(--error, #ef4444)",fontSize:13},children:j}),h==="connect"&&A(),h==="browse"&&D(),h==="tracks"&&Q(),h==="options"&&J(),h==="importing"&&ae(),h==="done"&&re()]})},bh=[{id:"concert-harp",name:"Concert Harp",description:"Warm concert harp",emoji:"🎵",dir:"concert-harp",attribution:"ConcertHarp SoundFont — source: musical-artifacts.com/artifacts/375"},{id:"celtic-harp",name:"Celtic Harp",description:"Bright celtic harp",emoji:"🍀",dir:"celtic-harp"},{id:"triangle",name:"Triangle",description:"Metallic percussion triangle",emoji:"🔺",dir:"triangle",attribution:"Triangle SoundFont — source: polyphone.io/en/soundfonts/unpitched-percussion/298-triangle"},{id:"synth",name:"Celesta",description:"Synthesized celesta / music-box",emoji:"✨",dir:"synth"},{id:"none",name:"Silent",description:"No sound on click",emoji:"🔇",dir:null}],vh="concert-harp",va=Object.fromEntries(bh.map(e=>[e.id,e])),xh="nice2dev-note-sound-set";function li(){try{const e=localStorage.getItem(xh);if(e&&va[e])return e}catch{}return vh}function ds(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function ci(e){if(!e)return null;const t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle=e;const n=t.fillStyle;if(n.startsWith("#")){const a=parseInt(n.slice(1),16);return{r:a>>16&255,g:a>>8&255,b:a&255}}const r=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return r?{r:+r[1],g:+r[2],b:+r[3]}:null}function Mr(e,t){const n=ci(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function Sh(e){const t=ci(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function di(){const e=ds("--text-primary")||"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",t=ds("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",a=Sh(e)<.45;return{base:Mr(e,.92),staffLine:Mr(e,.22),outline:a?"var(--nice-overlay-light-75, rgba(255, 255, 255, 0.75))":"var(--nice-overlay-55, rgba(0, 0, 0, 0.55))",accents:[Mr(t,.95)],isDark:n,notesDark:a}}const hr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),ui=46,ct=5,Hn=4,wh=(ui-(ct-1)*Hn)/2,Ch=6,kh=18,Mh=110,jh=50,fr=hr?jh:Mh,Rh=hr?4:2,$h=hr?2:4,us=hr?1:0,Th=180,hs=2.8,fs=40,Ph=14,ps=1.2,Eh=16,jr=[64,67,71,74,77],Wt=64,vn=77;function Ah(e){const t=Math.max(0,Math.min(ct-1,e)),n=Math.floor(t),r=Math.min(n+1,ct-1),a=t-n;return Math.round(jr[n]+(jr[r]-jr[n])*a)}function Nh(e){return(Math.max(Wt-1*(vn-Wt)/(ct-1),Math.min(vn+1*(vn-Wt)/(ct-1),e))-Wt)/(vn-Wt)*(ct-1)}const ms=2.5,gs=.72,Ih=.55,xn=new Map;let Kn=null;async function Lh(e){const t=e??li(),n=va[t];if(!n||!n.dir){xn.clear(),Kn=t;return}if(Kn===t&&xn.size>0)return;xn.clear(),Kn=t;const r=tn(),a=[];for(let o=Wt;o<=vn;o++)a.push(fetch(`/assets/soundfonts/notes/${n.dir}/note-${o}.mp3`).then(i=>i.arrayBuffer()).then(i=>r.decodeAudioData(i)).then(i=>{xn.set(o,i)}).catch(()=>{}));await Promise.all(a)}function ys(e){const t=xn.get(e);if(!t)return;const n=tn(),r=n.createBufferSource();r.buffer=t;const a=n.createGain();a.gain.value=.7,r.connect(a).connect(n.destination),r.start()}const bs=["𝅘𝅥","𝅘𝅥𝅮","𝅘𝅥𝅯","𝅘𝅥𝅰","𝅘𝅥𝅱","♪","♫","♬"];function Fh(e){return()=>{e|=0,e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function Dh(e){const t=Fh(42),n=[];for(let r=0;r<e;r++){const o=t()<.15?0:-1;n.push({x:t(),lineIdx:t()*(ct+1)-.5,char:bs[Math.floor(t()*bs.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:o})}return n.sort((r,a)=>r.x-a.x),n}const Je=Dh(fr),on=new Float32Array(fr),On=new Float32Array(fr),Sn=new Float32Array(fr);let Gr=!1;const Oh=(ct-1)/2;function _h(){if(!Gr){Gr=!0;for(let e=0;e<Je.length;e++)Sn[e]=Je[e].lineIdx}}let Br=[],vs="";function zh(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function Gh(e){const t=zh(e);t===vs&&Br.length===Je.length||(vs=t,Br=Je.map(n=>{const r=Math.ceil(n.size*1.6),a=r*2,o=document.createElement("canvas");o.width=a,o.height=a;const i=o.getContext("2d");return i.translate(r,r),i.rotate(n.rot*Math.PI/180),i.font=`${n.size}px serif`,i.textAlign="center",i.textBaseline="middle",i.lineWidth=1.8,i.strokeStyle=e.outline,i.strokeText(n.char,0,0),i.fillStyle=n.colorIdx<0?e.base:e.accents[n.colorIdx%e.accents.length],i.fillText(n.char,0,0),{canvas:o,ox:r,oy:r}}))}function hi({pitchMidiRef:e}={}){const t=u.useRef(null),n=u.useRef(0),r=u.useRef(0),a=u.useRef(0),o=u.useRef(null),i=u.useRef(0),l=u.useRef(0),c=u.useRef(null),d=u.useRef(null),h=u.useRef(!1),f=u.useCallback((v,x,b)=>{const w=wh+v*Hn,y=x/b*Math.PI*2;return w+Math.sin(y)*Ch},[]),m=u.useCallback(v=>{const x=t.current;if(!x)return;if(l.current++,us>0&&l.current%(us+1)!==0){a.current=v,n.current=requestAnimationFrame(m);return}const b=x.getContext("2d");if(!b)return;const w=Math.min(window.devicePixelRatio||1,$h),y=x.getBoundingClientRect(),k=y.width,M=y.height;(x.width!==Math.round(k*w)||x.height!==Math.round(M*w))&&(x.width=Math.round(k*w),x.height=Math.round(M*w),b.setTransform(w,0,0,w,0,0));const N=a.current?(v-a.current)/1e3:0;a.current=v,r.current=(r.current+kh*N)%k,b.clearRect(0,0,k,M),i.current++,(!o.current||i.current%60===0)&&(o.current=di());const R=o.current;Gh(R),b.strokeStyle=R.staffLine,b.lineWidth=.7;for(let W=0;W<ct;W++){b.beginPath();for(let j=0;j<=k;j+=Rh){const L=f(W,j,k);j===0?b.moveTo(j,L):b.lineTo(j,L)}b.stroke()}const _=r.current,E=(e==null?void 0:e.current)??null;if(E!==null){_h();const W=Nh(E),j=ms*N;for(let L=0;L<Je.length;L++){const q=(Je[L].lineIdx-Oh)*Ih,O=W*gs+(W+q)*(1-gs)-Sn[L];Sn[L]+=O>0?Math.min(j,O):Math.max(-j,O)}}else if(Gr){const W=ms*.4*N;for(let j=0;j<Je.length;j++){const I=Je[j].lineIdx-Sn[j];Sn[j]+=I>0?Math.min(W,I):Math.max(-W,I)}}const U=c.current;U&&(U.timer-=N,U.timer<=0&&(c.current=null));for(let W=0;W<Je.length;W++){const j=Je[W];if(On[W]>0){On[W]-=N;const q=Math.max(0,On[W]/hs);on[W]+=Th*q*N,on[W]>k&&(on[W]-=k)}const L=Br[W];if(!L)continue;const I=j.lineIdx;for(let q=0;q<2;q++){let O=((j.x*k-_-on[W]+q*k)%k+k)%k;const Z=f(Math.max(0,Math.min(ct-1,Math.round(I))),O,k),H=(I-Math.round(I))*Hn;let te=Z+H;if(U&&U.timer>0){const G=O-U.x,z=te-U.y,S=Math.sqrt(G*G+z*z);if(S<fs&&S>.1){const P=U.timer/ps,$=Ph*(1-S/fs)*P;O+=G/S*$,te+=z/S*$}}b.drawImage(L.canvas,O-L.ox,te-L.oy)}}n.current=requestAnimationFrame(m)},[f]),g=u.useCallback(v=>{const x=t.current;if(!x)return;const b=x.getBoundingClientRect(),w=v.clientX-b.left,y=v.clientY-b.top,k=b.width,M=r.current;let N=1/0,R=-1;for(let _=0;_<Je.length;_++){const E=Je[_],W=((E.x*k-M-on[_])%k+k)%k,j=f(Math.max(0,Math.min(ct-1,Math.round(E.lineIdx))),W,k),L=(E.lineIdx-Math.round(E.lineIdx))*Hn,I=j+L,q=W-w,Y=I-y,O=q*q+Y*Y;O<N&&(N=O,R=_)}if(R>=0&&Math.sqrt(N)<Eh){On[R]=hs;const _=Je[R],E=Ah(_.lineIdx);try{Et();const U=li(),W=va[U];W!=null&&W.dir&&(Kn!==U||!h.current?(h.current=!0,Lh(U).then(()=>ys(E))):ys(E))}catch{}}c.current={x:w,y,timer:ps}},[f]),p=u.useCallback(v=>{const x=t.current;if(!x)return;const b=x.getBoundingClientRect(),w=v.clientX-b.left,y=v.clientY-b.top;d.current={x:w,y},c.current&&c.current.timer>0&&(c.current.x=w,c.current.y=y)},[]);return u.useEffect(()=>(n.current=requestAnimationFrame(m),()=>cancelAnimationFrame(n.current)),[m]),s.jsx("canvas",{ref:t,"aria-hidden":"true",role:"img","aria-label":"Note river animation canvas",onClick:g,onMouseMove:p,style:{display:"block",width:"100%",height:ui,marginBottom:5,cursor:"pointer",background:"transparent"}})}const Bh=14,Wh=.9,Uh=320,Vh=160,qh=6,xs=8,Hh=14,Ss=["♪","♫","♬","𝅘𝅥𝅮","𝅘𝅥𝅯"];function fi(){const e=u.useRef(null),t=u.useRef([]),n=u.useRef(0),r=u.useRef(0),a=u.useRef([]),o=u.useRef(null),i=u.useRef(0),l=u.useCallback((d,h)=>{for(let f=0;f<Bh;f++){const m=Math.random()*Math.PI*2,g=Vh*(.4+Math.random()*.6),p=Wh*(.6+Math.random()*.4),v=Math.random()<.15?0:-1;t.current.push({x:d,y:h,vx:Math.cos(m)*g,vy:Math.sin(m)*g-60,rot:Math.random()*Math.PI*2,vr:(Math.random()-.5)*qh*2,size:xs+Math.random()*(Hh-xs),char:Ss[Math.floor(Math.random()*Ss.length)],life:p,maxLife:p,colorIdx:v})}},[]),c=u.useCallback(d=>{const h=e.current;if(!h){n.current=requestAnimationFrame(c);return}const f=h.getContext("2d");if(!f){n.current=requestAnimationFrame(c);return}const m=window.devicePixelRatio||1,g=window.innerWidth,p=window.innerHeight;(h.width!==Math.round(g*m)||h.height!==Math.round(p*m))&&(h.width=Math.round(g*m),h.height=Math.round(p*m),h.style.width=`${g}px`,h.style.height=`${p}px`,f.setTransform(m,0,0,m,0,0));const v=r.current?Math.min((d-r.current)/1e3,.05):0;r.current=d,f.clearRect(0,0,g,p),i.current++,(!o.current||i.current%60===0)&&(o.current=di());const x=o.current;if(navigator.getGamepads){const w=navigator.getGamepads();for(let y=0;y<w.length;y++){const k=w[y];if(k)for(let M=0;M<k.buttons.length;M++){const N=y*100+M,R=k.buttons[M].pressed;R&&!a.current[N]&&l(g/2,p/2),a.current[N]=R}}}const b=[];f.textAlign="center",f.textBaseline="middle";for(const w of t.current){if(w.life-=v,w.life<=0)continue;w.vy+=Uh*v,w.x+=w.vx*v,w.y+=w.vy*v,w.rot+=w.vr*v;const y=Math.max(0,w.life/w.maxLife),k=.5+.5*y;f.save(),f.globalAlpha=y,f.translate(w.x,w.y),f.rotate(w.rot),f.font=`${w.size*k}px serif`,f.lineWidth=1.4,f.strokeStyle=x.notesDark?`rgba(255,255,255,${y*.8})`:`rgba(0,0,0,${y*.55})`,f.strokeText(w.char,0,0);const M=w.colorIdx<0?x.base:x.accents[w.colorIdx%x.accents.length];f.fillStyle=M.replace(/[\d.]+\)$/,`${y})`),f.fillText(w.char,0,0),f.restore(),b.push(w)}t.current=b,n.current=requestAnimationFrame(c)},[l]);return u.useEffect(()=>{const d=f=>{l(f.clientX,f.clientY)},h=f=>{if(f.key!=="Enter")return;const m=document.activeElement;if(m){const g=m.getBoundingClientRect();l(g.left+g.width/2,g.top+g.height/2)}else l(window.innerWidth/2,window.innerHeight/2)};return window.addEventListener("click",d,!0),window.addEventListener("keydown",h,!0),n.current=requestAnimationFrame(c),()=>{window.removeEventListener("click",d,!0),window.removeEventListener("keydown",h,!0),cancelAnimationFrame(n.current)}},[c,l]),s.jsx("canvas",{ref:e,"aria-hidden":"true",role:"img","aria-label":"Note particles animation canvas",style:{position:"fixed",inset:0,zIndex:99999,pointerEvents:"none"}})}class pi{constructor(t,n){this.activeNotes=new Map,this.audioContext=t,this.masterGain=t.createGain(),this.masterGain.gain.value=.3,this.masterGain.connect(n)}applyCC(t,n,r){}midiToFreq(t){return 440*Math.pow(2,(t-69)/12)}playNote(t,n=100,r=1,a="sine"){const o=this.midiToFreq(t),i=this.audioContext.createOscillator(),l=this.audioContext.createGain();i.type=a,i.frequency.value=o;const c=n/127*.8;l.gain.value=c,i.connect(l),l.connect(this.masterGain);const d=this.audioContext.currentTime;return l.gain.setValueAtTime(0,d),l.gain.linearRampToValueAtTime(c,d+.01),l.gain.exponentialRampToValueAtTime(c*.7,d+.1),l.gain.setValueAtTime(c*.7,d+r-.05),l.gain.exponentialRampToValueAtTime(.001,d+r),i.start(d),i.stop(d+r),i.onended=()=>{l.disconnect(),i.disconnect()},{osc:i,gain:l}}scheduleNote(t,n,r,a=100,o="sine"){const i=this.midiToFreq(t),l=this.audioContext.createOscillator(),c=this.audioContext.createGain();l.type=o,l.frequency.value=i;const d=a/127*.8;l.connect(c),c.connect(this.masterGain);const h=n;return c.gain.setValueAtTime(0,h),c.gain.linearRampToValueAtTime(d,h+.01),c.gain.exponentialRampToValueAtTime(d*.7,h+.1),c.gain.setValueAtTime(d*.7,h+r-.05),c.gain.exponentialRampToValueAtTime(.001,h+r),l.start(h),l.stop(h+r),l.onended=()=>{c.disconnect(),l.disconnect()},{osc:l,gain:c}}setVolume(t){this.masterGain.gain.value=Math.max(0,Math.min(1,t))}stopAll(){this.activeNotes.forEach(({osc:t,gain:n})=>{try{t.stop(),n.disconnect(),t.disconnect()}catch{}}),this.activeNotes.clear()}dispose(){this.stopAll(),this.masterGain.disconnect()}}const ws=et.scoped("AudioPlaybackEngine");class Kh{constructor(){this.audioContext=null,this.masterGain=null,this.masterFilter=null,this.clips=new Map,this.scheduledSources=new Map,this.midiTracks=new Map,this.synths=new Map,this.isPlaying=!1,this.startTimeOffset=0,this.audioContextStartTime=0,this.currentTime=0,this.loopRegion={start:0,end:0,enabled:!1},this.bpm=120,this.duration=0,this.initAudioContext()}setMidiCCEvents(t,n){const r=this.midiTracks.get(t);r&&(r.ccEvents=n)}getMidiCCEvents(t){const n=this.midiTracks.get(t);return(n==null?void 0:n.ccEvents)||[]}addMidiCCEvent(t,n){const r=this.midiTracks.get(t);r&&(r.ccEvents||(r.ccEvents=[]),r.ccEvents.push(n))}removeMidiCCEvent(t,n){const r=this.midiTracks.get(t);r&&r.ccEvents&&(r.ccEvents=r.ccEvents.filter(a=>a.id!==n))}initAudioContext(){try{this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.masterGain=this.audioContext.createGain(),this.masterFilter=this.audioContext.createBiquadFilter(),this.masterFilter.type="peaking",this.masterFilter.frequency.value=1200,this.masterFilter.Q.value=.7,this.masterFilter.gain.value=0,this.masterGain.connect(this.masterFilter),this.masterFilter.connect(this.audioContext.destination),this.masterGain.gain.value=.8,this.audioContext.state==="suspended"&&this.audioContext.resume()}catch(t){ws.error("Failed to initialize AudioContext:",t)}}createEffectNode(t){if(!this.audioContext||t.bypass)return null;try{switch(t.type){case"eq3":{const n=this.audioContext.createBiquadFilter(),r=this.audioContext.createBiquadFilter(),a=this.audioContext.createBiquadFilter();return n.type="lowshelf",n.frequency.value=t.params.lowFreq||250,n.gain.value=t.params.lowGain||0,r.type="peaking",r.frequency.value=1e3,r.Q.value=1,r.gain.value=t.params.midGain||0,a.type="highshelf",a.frequency.value=t.params.highFreq||4e3,a.gain.value=t.params.highGain||0,n.connect(r),r.connect(a),{input:n,output:a}}case"compressor":{const n=this.audioContext.createDynamicsCompressor();return n.threshold.value=t.params.threshold||-24,n.ratio.value=t.params.ratio||4,n.attack.value=t.params.attack||.003,n.release.value=t.params.release||.25,n.knee.value=t.params.knee||30,n}case"delay":{const n=this.audioContext.createDelay(5);n.delayTime.value=t.params.time||.25;const r=this.audioContext.createGain();r.gain.value=t.params.feedback||.3;const a=this.audioContext.createGain();a.gain.value=t.params.mix||.3;const o=this.audioContext.createGain();return o.gain.value=1-(t.params.mix||.3),n.connect(r),r.connect(n),n.connect(a),{input:n,output:a,dry:o,connect:function(i){a.connect(i),o.connect(i)}}}case"reverb":{const n=this.audioContext.createConvolver(),r=this.audioContext.sampleRate*(t.params.decay||2),a=this.audioContext.createBuffer(2,r,this.audioContext.sampleRate);for(let l=0;l<2;l++){const c=a.getChannelData(l);for(let d=0;d<r;d++)c[d]=(Math.random()*2-1)*Math.pow(1-d/r,2)}n.buffer=a;const o=this.audioContext.createGain();o.gain.value=t.params.mix||.3;const i=this.audioContext.createGain();return i.gain.value=1-(t.params.mix||.3),n.connect(o),{input:n,output:o,dry:i,connect:function(l){o.connect(l),i.connect(l)}}}case"distortion":{const n=this.audioContext.createWaveShaper(),r=t.params.amount||20,a=44100,o=new Float32Array(a),i=Math.PI/180;for(let d=0;d<a;d++){const h=d*2/a-1;o[d]=(3+r)*h*20*i/(Math.PI+r*Math.abs(h))}n.curve=o,n.oversample="4x";const l=this.audioContext.createGain();l.gain.value=t.params.mix||.5;const c=this.audioContext.createGain();return c.gain.value=1-(t.params.mix||.5),n.connect(l),{input:n,output:l,dry:c,connect:function(d){l.connect(d),c.connect(d)}}}default:return null}}catch(n){return ws.error("Failed to create effect node:",t.type,n),null}}addClip(t){this.clips.set(t.id,t),this.updateDuration()}removeClip(t){this.clips.delete(t),this.stopClip(t),this.updateDuration()}updateClip(t,n){const r=this.clips.get(t);r&&(Object.assign(r,n),this.updateDuration())}getClipsByLayer(t){return Array.from(this.clips.values()).filter(n=>n.layerId===t)}setMidiTrack(t,n,r="sine",a=.5){if(this.midiTracks.set(t,{layerId:t,notes:n,instrument:r,volume:a}),!this.synths.has(t)&&this.audioContext&&this.masterGain){const o=new pi(this.audioContext,this.masterGain);o.setVolume(a),this.synths.set(t,o)}}removeMidiTrack(t){this.midiTracks.delete(t);const n=this.synths.get(t);n&&(n.dispose(),this.synths.delete(t))}updateMidiTrackVolume(t,n){const r=this.midiTracks.get(t);r&&(r.volume=n);const a=this.synths.get(t);a&&a.setVolume(n)}updateDuration(){let t=0;this.clips.forEach(n=>{const r=n.startTime+n.duration;r>t&&(t=r)}),this.duration=t}play(){!this.audioContext||this.isPlaying||(this.audioContext.state==="suspended"&&this.audioContext.resume(),this.isPlaying=!0,this.audioContextStartTime=this.audioContext.currentTime,this.startTimeOffset=this.currentTime,this.scheduleClips(),this.scheduleMidiNotes(),this.startTimeTracking(),this.onPlayStateChange&&this.onPlayStateChange(!0))}pause(){this.isPlaying&&(this.isPlaying=!1,this.stopAllSources(),this.onPlayStateChange&&this.onPlayStateChange(!1))}stop(){this.pause(),this.seek(0)}seek(t){const n=this.isPlaying;n&&this.pause(),this.currentTime=Math.max(0,Math.min(t,this.duration)),this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),n&&this.play()}scheduleClips(){!this.audioContext||!this.masterGain||this.clips.forEach(t=>{if(t.startTime+t.duration<=this.currentTime)return;const r=this.audioContext.createBufferSource();r.buffer=t.buffer,t.stretchFactor&&t.stretchFactor!==1&&(r.playbackRate.value=1/t.stretchFactor);const a=this.audioContext.createGain();a.gain.value=t.volume;const o=this.audioContext.createStereoPanner();o.pan.value=t.pan,r.connect(a);let i=a;if(t.effectChain&&t.effectChain.length>0)for(const h of t.effectChain){const f=this.createEffectNode(h);if(f)if("input"in f&&"output"in f){const m=f;i.connect(m.input),i=m.output,"dry"in f&&a.connect(m.dry)}else i.connect(f),i=f}i.connect(o),o.connect(this.masterGain);const l=t.startTime,c=Math.max(0,this.currentTime-l),d=this.audioContext.currentTime+(l-this.currentTime);d>=this.audioContext.currentTime&&(r.start(d,t.offset+c,t.duration-c),this.scheduledSources.set(t.id,r),r.onended=()=>{this.scheduledSources.delete(t.id)})})}stopClip(t){const n=this.scheduledSources.get(t);if(n){try{n.stop()}catch{}this.scheduledSources.delete(t)}}stopAllSources(){this.scheduledSources.forEach(t=>{try{t.stop()}catch{}}),this.scheduledSources.clear(),this.synths.forEach(t=>t.stopAll())}scheduleMidiNotes(){this.audioContext&&this.midiTracks.forEach(t=>{const n=this.synths.get(t.layerId);if(n&&(t.notes.forEach(r=>{if(r.start+r.duration<=this.currentTime)return;const o=Math.max(0,this.currentTime-r.start),i=this.audioContext.currentTime+(r.start-this.currentTime);i>=this.audioContext.currentTime&&n.scheduleNote(r.pitch,i,r.duration-o,r.velocity,t.instrument)}),t.ccEvents&&Array.isArray(t.ccEvents)&&t.ccEvents.length>0)){const r=[...t.ccEvents].sort((i,l)=>i.time-l.time);let o=r[0];for(let i=1;i<r.length;++i){const l=r[i],c=o.time,d=l.time,h=o.value,f=l.value,m=o.handleType||"linear",g=Math.max(2,Math.ceil((d-c)*20));for(let p=0;p<=g;++p){const v=p/g;let x=h;if(m==="linear")x=h+(f-h)*v;else if(m==="step")x=v<1?h:f;else if(m==="exp"){const k=Math.max(h/127,.001),M=Math.max(f/127,.001);x=k*Math.pow(M/k,v)*127}const b=c+(d-c)*v,w=this.audioContext.currentTime+(b-this.currentTime);w>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(l.cc,x,w)}o=l}}})}startTimeTracking(){if(!this.audioContext)return;const t=()=>{if(!this.isPlaying||!this.audioContext)return;const n=this.audioContext.currentTime-this.audioContextStartTime;if(this.currentTime=this.startTimeOffset+n,this.loopRegion.enabled&&this.currentTime>=this.loopRegion.end){this.seek(this.loopRegion.start);return}if(this.currentTime>=this.duration){this.stop();return}this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),requestAnimationFrame(t)};requestAnimationFrame(t)}setLoopRegion(t,n,r){this.loopRegion={start:t,end:n,enabled:r}}setBPM(t){this.bpm=Math.max(20,Math.min(300,t))}getBPM(){return this.bpm}setMasterVolume(t){this.masterGain&&(this.masterGain.gain.value=Math.max(0,Math.min(1,t)))}setMasterFilter(t){this.masterFilter&&(t.type&&(this.masterFilter.type=t.type),t.frequency!=null&&(this.masterFilter.frequency.value=Math.max(20,Math.min(2e4,t.frequency))),t.q!=null&&(this.masterFilter.Q.value=Math.max(.1,Math.min(18,t.q))),t.gain!=null&&"gain"in this.masterFilter&&(this.masterFilter.gain.value=Math.max(-40,Math.min(40,t.gain))))}getCurrentTime(){return this.currentTime}getDuration(){return this.duration}getIsPlaying(){return this.isPlaying}setOnTimeUpdate(t){this.onTimeUpdate=t}setOnPlayStateChange(t){this.onPlayStateChange=t}dispose(){this.stop(),this.audioContext&&this.audioContext.close(),this.clips.clear()}}const Yh=[{name:"Grand Piano",waveform:"sawtooth",attack:.02,sustain:.7,release:1.2,eq:{C:2,D:1,E:1,F:0,G:0,A:-1,B:-2,C2:-3},category:"Keyboard"},{name:"Electric Piano",waveform:"triangle",attack:.03,sustain:.8,release:1,eq:{C:0,D:1,E:2,F:3,G:1,A:-1,B:-2,C2:-2},category:"Keyboard"},{name:"Harpsichord",waveform:"square",attack:.01,sustain:.5,release:.6,eq:{C:-1,D:-1,E:0,F:2,G:3,A:1,B:0,C2:-1},category:"Keyboard"},{name:"Violin",waveform:"triangle",attack:.3,sustain:1,release:1.5,eq:{C:3,D:2,E:2,F:1,G:-1,A:-2,B:-3,C2:-3},category:"String"},{name:"Acoustic Guitar",waveform:"sawtooth",attack:.2,sustain:.6,release:.9,eq:{C:-1,D:-2,E:0,F:1,G:3,A:2,B:0,C2:-2},category:"String"},{name:"Electric Guitar",waveform:"square",attack:.05,sustain:.7,release:1.2,eq:{C:-2,D:1,E:2,F:2,G:1,A:0,B:-1,C2:-3},category:"String"},{name:"Kick Drum",waveform:"sine",attack:.005,sustain:.1,release:.2,eq:{C:5,D:3,E:0,F:-3,G:-5,A:-7,B:-9,C2:-10},category:"Percussion"},{name:"Snare Drum",waveform:"triangle",attack:.01,sustain:.2,release:.3,eq:{C:-2,D:-1,E:1,F:2,G:3,A:2,B:0,C2:-2},category:"Percussion"},{name:"Hi-Hat",waveform:"square",attack:.002,sustain:.05,release:.1,eq:{C:-5,D:-3,E:0,F:2,G:5,A:7,B:9,C2:10},category:"Percussion"},{name:"Acoustic Bass",waveform:"sine",attack:.08,sustain:.8,release:1.2,eq:{C:4,D:3,E:2,F:1,G:0,A:-1,B:-2,C2:-3},category:"Bass"},{name:"Electric Bass",waveform:"square",attack:.05,sustain:.9,release:1.3,eq:{C:3,D:2,E:1,F:0,G:-1,A:-2,B:-3,C2:-4},category:"Bass"},{name:"Trumpet",waveform:"sawtooth",attack:.1,sustain:.9,release:1.5,eq:{C:2,D:3,E:4,F:5,G:3,A:1,B:-1,C2:-3},category:"Brass"},{name:"Trombone",waveform:"triangle",attack:.2,sustain:1,release:1.7,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-2,C2:-4},category:"Brass"},{name:"Saxophone",waveform:"sawtooth",attack:.15,sustain:.8,release:1.3,eq:{C:2,D:3,E:4,F:3,G:1,A:-1,B:-2,C2:-3},category:"Woodwind"},{name:"Clarinet",waveform:"triangle",attack:.18,sustain:.9,release:1.6,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-1,C2:-2},category:"Woodwind"},{name:"Saw Synth",waveform:"sawtooth",attack:.05,sustain:.9,release:1.2,eq:{C:2,D:3,E:4,F:3,G:2,A:0,B:-1,C2:-2},category:"Synth"},{name:"Square Lead",waveform:"square",attack:.04,sustain:.85,release:1.1,eq:{C:2,D:3,E:4,F:3,G:1,A:0,B:-1,C2:-3},category:"Synth"}];function pr(e={}){const{channelFilter:t,sysex:n=!1,onEvent:r,inputNameIncludes:a,onInputsChanged:o}=e,[i,l]=u.useState(null),[c,d]=u.useState(!1),[h,f]=u.useState([]),m=u.useRef(null),g=u.useCallback((p,v)=>{const x=p.data??new Uint8Array(0),b=x[0]??0,w=x[1]??0,y=x[2]??0,k=p.timeStamp,M=b&240,N=b&15,R=v.id,_=v.name??"MIDI Input",E=t===void 0||t===N;if((M===144||M===128)&&E){const U=M===144&&y>0;return{type:U?"noteon":"noteoff",note:w,velocity:U?y:0,channel:N,ts:k,deviceId:R,deviceName:_}}return M===176&&E?{type:"cc",controller:w,value:y,channel:N,ts:k,deviceId:R,deviceName:_}:M===208&&E?{type:"aftertouch",pressure:w,channel:N,ts:k,deviceId:R,deviceName:_}:M===224&&E?{type:"pitchbend",value:(w|y<<7)-8192,channel:N,ts:k,deviceId:R,deviceName:_}:M===192&&E?{type:"program",program:w,channel:N,ts:k,deviceId:R,deviceName:_}:{type:"unknown",status:b,data1:w,data2:y,channel:N,ts:k,deviceId:R,deviceName:_}},[t]);return u.useEffect(()=>{if(!("requestMIDIAccess"in navigator)){l(!1);return}l(!0);let p=!1;return navigator.requestMIDIAccess({sysex:n}).then(v=>{if(p)return;m.current=v,d(!0);const x=()=>{const b=Array.from(v.inputs.values()),w=a?b.filter(y=>(y.name||"").toUpperCase().includes(a.toUpperCase())):b;f(w),o==null||o(w),b.forEach(y=>y.onmidimessage=null),w.forEach(y=>{y.onmidimessage=k=>r==null?void 0:r(g(k,y))})};x(),v.onstatechange=()=>x()}),()=>{p=!0;const v=m.current;v&&(v.inputs.forEach(x=>x.onmidimessage=null),v.onstatechange=null)}},[a,r,o,g,n]),{supported:i,granted:c,inputs:h}}const xa="nice2dev.midiLearn";function Zh(){try{const e=localStorage.getItem(xa);return e?JSON.parse(e):{}}catch{return{}}}function Cs(e){const t={};for(const n of e)t[n.id]={id:n.id,type:n.type,number:n.number,channel:n.channel,min:n.min,max:n.max};localStorage.setItem(xa,JSON.stringify(t))}function Xh(e){const{parameters:t,onParameterChange:n}=e,[r,a]=u.useState(()=>{const y=Zh();return t.map(k=>{const M=y[k.id];return{id:k.id,paramName:k.name,type:(M==null?void 0:M.type)??"cc",number:M==null?void 0:M.number,channel:M==null?void 0:M.channel,min:(M==null?void 0:M.min)??k.min??0,max:(M==null?void 0:M.max)??k.max??127,value:0}})}),[o,i]=u.useState({learning:!1,targetId:null}),[l,c]=u.useState(null),d=u.useRef(r);d.current=r;const h=u.useRef(n);h.current=n;const f=u.useRef(o);f.current=o;const m=u.useCallback(y=>{var M;c(y);const k=f.current;if(k.learning&&k.targetId){if(!d.current.find(_=>_.id===k.targetId))return;let R={};switch(y.type){case"cc":R={type:"cc",number:y.controller,channel:y.channel};break;case"noteon":R={type:"note",number:y.note,channel:y.channel};break;case"pitchbend":R={type:"pitchbend",channel:y.channel};break;case"aftertouch":R={type:"aftertouch",channel:y.channel};break;default:return}a(_=>{const E=_.map(U=>U.id===k.targetId?{...U,...R}:U);return Cs(E),E}),i({learning:!1,targetId:null});return}for(const N of d.current){if(N.number===void 0&&N.type!=="pitchbend"&&N.type!=="aftertouch"||N.channel!==void 0&&y.channel!==N.channel)continue;let R=null,_=127;if(N.type==="cc"&&y.type==="cc"&&y.controller===N.number?R=y.value:N.type==="note"&&y.type==="noteon"&&y.note===N.number?R=y.velocity:N.type==="pitchbend"&&y.type==="pitchbend"?(R=y.value+8192,_=16383):N.type==="aftertouch"&&y.type==="aftertouch"&&(R=y.pressure),R!==null){const E=R/_,U=N.min+E*(N.max-N.min);a(W=>W.map(j=>j.id===N.id?{...j,value:E}:j)),(M=h.current)==null||M.call(h,N.id,U,E)}}},[]),{supported:g,granted:p}=pr({onEvent:m}),v=u.useCallback(y=>{i({learning:!0,targetId:y})},[]),x=u.useCallback(()=>{i({learning:!1,targetId:null})},[]),b=u.useCallback(y=>{a(k=>{const M=k.map(N=>N.id===y?{...N,type:"cc",number:void 0,channel:void 0}:N);return Cs(M),M})},[]),w=u.useCallback(()=>{a(y=>{const k=y.map(M=>({...M,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(xa),k})},[]);return{bindings:r,startLearn:v,cancelLearn:x,removeBinding:b,clearAll:w,learnState:o,midiSupported:g,midiGranted:p,lastEvent:l}}const Qh={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function Jh(e={}){const{lowerZone:t=Qh,onNoteExpression:n,onNoteOn:r,onNoteOff:a}=e,[o,i]=u.useState([]),l=u.useRef(new Map),c=u.useRef(n);c.current=n;const d=u.useRef(r);d.current=r;const h=u.useRef(a);h.current=a;const f=u.useRef(new Set(t.memberChannels));u.useEffect(()=>{f.current=new Set(t.memberChannels)},[t.memberChannels]);const m=u.useCallback(v=>{var b,w,y,k,M;if(!f.current.has(v.channel??-1))return;const x=`${v.channel}`;switch(v.type){case"noteon":{const N={note:v.note,channel:v.channel,velocity:v.velocity,pitchBend:0,pressure:0,slide:0,lastUpdate:v.ts};l.current.set(x,N),i(Array.from(l.current.values())),(b=d.current)==null||b.call(d,N);break}case"noteoff":{l.current.delete(x),i(Array.from(l.current.values())),(w=h.current)==null||w.call(h,v.channel,v.note);break}case"pitchbend":{const N=l.current.get(x);N&&(N.pitchBend=v.value,N.lastUpdate=v.ts,(y=c.current)==null||y.call(c,N),i(Array.from(l.current.values())));break}case"aftertouch":{const N=l.current.get(x);N&&(N.pressure=v.pressure,N.lastUpdate=v.ts,(k=c.current)==null||k.call(c,N),i(Array.from(l.current.values())));break}case"cc":{if(v.controller===74){const N=l.current.get(x);N&&(N.slide=v.value,N.lastUpdate=v.ts,(M=c.current)==null||M.call(c,N),i(Array.from(l.current.values())))}break}}},[]),{supported:g,granted:p}=pr({onEvent:m,sysex:!1});return{activeNotes:o,midiSupported:g,midiGranted:p}}const ef={name:"M-Audio Oxygen 25 (MKIV)",deviceMatch:"OXYGEN",knobs:[{index:1,cc:21,label:"Knob 1"},{index:2,cc:22,label:"Knob 2"},{index:3,cc:23,label:"Knob 3"},{index:4,cc:24,label:"Knob 4"},{index:5,cc:25,label:"Knob 5"},{index:6,cc:26,label:"Knob 6"},{index:7,cc:27,label:"Knob 7"},{index:8,cc:28,label:"Knob 8"}],fader:{cc:7,label:"Fader (Channel Volume)"},pads:[{note:36,label:"Kick C1"},{note:38,label:"Snare D1"},{note:42,label:"HH Closed F#1"},{note:46,label:"HH Open A#1"},{note:48,label:"Tom1 C2"},{note:45,label:"Tom2 A1"},{note:43,label:"Floor G1"},{note:49,label:"Crash C#2"}],transport:{play:115,stop:114,record:117,rew:112,ff:113,loop:116}};function tf(e={},t=ef){const[n,r]=u.useState(()=>{const g=localStorage.getItem("oxygen25.layout");return g?JSON.parse(g):t}),[a,o]=u.useState([]),i=u.useRef({mode:"idle"}),l=u.useCallback(g=>{r(p=>{const v={...p,...g};return localStorage.setItem("oxygen25.layout",JSON.stringify(v)),v})},[]),c=u.useCallback(g=>{var x,b,w,y,k,M,N,R,_;const p=g.deviceName||"MIDI";o(E=>E.includes(p)?E:[...E,p]);const v=i.current;if(v.mode!=="idle"){if(v.mode==="knob"&&g.type==="cc"){const E=v.index;l({knobs:n.knobs.map(U=>U.index===E?{...U,cc:g.controller}:U)}),i.current={mode:"idle"};return}if(v.mode==="fader"&&g.type==="cc"){l({fader:{cc:g.controller,label:"Fader"}}),i.current={mode:"idle"};return}if(v.mode==="pad"&&g.type==="noteon"){const E=n.pads.slice();E[v.padIdx]={...E[v.padIdx],note:g.note},l({pads:E}),i.current={mode:"idle"};return}if(v.mode==="transport"&&g.type==="cc"){const E={...n.transport};E[v.action]=g.controller,l({transport:E}),i.current={mode:"idle"};return}}switch(g.type){case"noteon":{n.pads.findIndex(U=>U.note===g.note)>=0?(x=e.onPad)==null||x.call(e,{note:g.note,velocity:g.velocity,ts:g.ts,device:p}):(b=e.onKey)==null||b.call(e,{note:g.note,velocity:g.velocity,ts:g.ts,device:p});break}case"cc":{if(n.fader&&g.controller===n.fader.cc){(w=e.onFader)==null||w.call(e,{cc:g.controller,value:g.value,ts:g.ts,device:p});break}const E=n.knobs.find(W=>W.cc===g.controller);if(E){(y=e.onKnob)==null||y.call(e,{index:E.index,cc:g.controller,value:g.value,ts:g.ts,device:p});break}const U=Object.keys(n.transport).find(W=>n.transport[W]===g.controller);if(U){(k=e.onTransport)==null||k.call(e,{action:U,value:g.value,ts:g.ts,device:p});break}(M=e.onUnknown)==null||M.call(e,g);break}case"pitchbend":(N=e.onPitchBend)==null||N.call(e,{value:g.value,ts:g.ts,device:p});break;case"aftertouch":(R=e.onAftertouch)==null||R.call(e,{pressure:g.pressure,ts:g.ts,device:p});break;default:(_=e.onUnknown)==null||_.call(e,g)}},[l,e,n]),{supported:d,granted:h,inputs:f}=pr({inputNameIncludes:void 0,onEvent:c,sysex:!1,channelFilter:void 0,onInputsChanged:g=>o(g.map(p=>p.name||"MIDI"))}),m=u.useMemo(()=>({knob:g=>i.current={mode:"knob",index:g},fader:()=>i.current={mode:"fader"},pad:g=>i.current={mode:"pad",padIdx:g},transport:g=>i.current={mode:"transport",action:g},cancel:()=>i.current={mode:"idle"},state:()=>i.current}),[]);return{supported:d,granted:h,inputs:f,layout:n,setLayout:l,learn:m,inputsInfo:a}}const Wr={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],mixolydian:[0,2,4,5,7,9,10],pentatonic:[0,2,4,7,9],minorPenta:[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11]},nf=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Ur={pop:[[0,4,7],[5,9,0],[7,11,2],[5,9,0]],rock:[[0,4,7],[5,9,0],[3,7,10],[5,9,0]],jazz:[[0,4,7,11],[2,5,9,0],[5,9,0,4],[0,4,7,11]],blues12:[[0,4,7],[0,4,7],[0,4,7],[0,4,7],[5,9,0],[5,9,0],[0,4,7],[0,4,7],[7,11,2],[5,9,0],[0,4,7],[7,11,2]]},_t=36,ln=38,pt=42,zt=51,rf=49,Vr={basic:[{step:0,pitch:_t,vel:110},{step:0,pitch:pt,vel:80},{step:2,pitch:pt,vel:70},{step:4,pitch:ln,vel:100},{step:4,pitch:pt,vel:80},{step:6,pitch:pt,vel:70},{step:8,pitch:_t,vel:100},{step:10,pitch:pt,vel:70},{step:12,pitch:ln,vel:100},{step:12,pitch:pt,vel:80},{step:14,pitch:pt,vel:70}],rock:[{step:0,pitch:_t,vel:120},{step:0,pitch:rf,vel:90},{step:4,pitch:ln,vel:110},{step:4,pitch:pt,vel:80},{step:8,pitch:_t,vel:110},{step:8,pitch:pt,vel:80},{step:10,pitch:_t,vel:90},{step:12,pitch:ln,vel:110},{step:12,pitch:pt,vel:80}],swing:[{step:0,pitch:zt,vel:90},{step:3,pitch:zt,vel:70},{step:4,pitch:zt,vel:80},{step:8,pitch:zt,vel:90},{step:11,pitch:zt,vel:70},{step:12,pitch:zt,vel:80},{step:4,pitch:_t,vel:80},{step:12,pitch:ln,vel:70}]},mi={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function af(e){let t=e|0;return()=>{t=t+1831565813|0;let n=Math.imul(t^t>>>15,1|t);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}let gi=1;const _n=()=>gi++,yi=e=>60/e,sf=e=>yi(e)/4;function Rr(e,t,n,r){const a=t.length,o=Math.floor(n/a),i=(n%a+a)%a;return e+t[i]+(r+o)*12}function bi(e=mi){gi=1;const t=e.seed>0?af(e.seed):Math.random,n=Wr[e.scale]??Wr.pentatonic,r=Ur[e.progression]??Ur.pop,a=Vr[e.drumPattern]??Vr.basic,o=yi(e.tempo),i=sf(e.tempo),l=Math.max(1,e.bars),c=16,d=[],h=[],f=[],m=[];let g=0;for(let p=0;p<l;p++){const v=p*4*o,x=p%r.length,b=r[x];for(const y of b)f.push({id:_n(),pitch:Rr(e.root,n,y,e.octave-1),start:v,duration:4*o-.01,velocity:70+Math.floor(t()*20)});const w=b[0];for(let y=0;y<4;y++){const k=y===2?w+(t()>.5?2:0):w;h.push({id:_n(),pitch:Rr(e.root,n,k,e.octave-2),start:v+y*o,duration:o*.9,velocity:80+Math.floor(t()*30)})}for(let y=0;y<c;y++){if(t()>e.density)continue;const k=v+y*i,M=t()>.8?t()>.5?2:-2:t()>.5?1:-1;g=Math.max(-3,Math.min(n.length+3,g+M));const N=1+Math.floor(t()*3);d.push({id:_n(),pitch:Rr(e.root,n,g,e.octave),start:k,duration:N*i*.95,velocity:85+Math.floor(t()*30)})}for(const y of a)m.push({id:_n(),pitch:y.pitch,start:v+y.step*i,duration:i*.8,velocity:y.vel+Math.floor(t()*10-5)})}return{melody:d,bass:h,chords:f,drums:m,config:e}}const of=Object.keys(Wr),lf=Object.keys(Ur),cf=Object.keys(Vr),df=bi;function Le(e,t,n){return{cc:e,paramId:n,label:`Knob ${t}`,controlType:"knob",min:0,max:127,inverted:!1}}function jn(e,t,n){return{cc:e,paramId:n,label:t,controlType:"fader",min:0,max:127,inverted:!1}}function Gt(e,t,n){return{cc:e,paramId:n,label:t,controlType:"button",min:0,max:127,inverted:!1}}const vi={id:"oxygen25",name:"M-Audio Oxygen 25 (MkIV)",deviceMatch:"OXYGEN",mappings:[Le(21,1,"mixer.volume"),Le(22,2,"mixer.pan"),Le(23,3,"fx.reverb"),Le(24,4,"fx.delay"),Le(25,5,"fx.chorus"),Le(26,6,"fx.filter"),Le(27,7,"fx.drive"),Le(28,8,"fx.eq"),jn(7,"Master Fader","mixer.master"),Gt(115,"Play","transport.play"),Gt(114,"Stop","transport.stop"),Gt(117,"Record","transport.record"),Gt(112,"Rewind","transport.rewind"),Gt(113,"Forward","transport.forward"),Gt(116,"Loop","transport.loop")]},xi={id:"mpk-mini",name:"Akai MPK Mini",deviceMatch:"MPK",mappings:[Le(1,1,"mixer.volume"),Le(2,2,"mixer.pan"),Le(3,3,"fx.reverb"),Le(4,4,"fx.delay"),Le(5,5,"fx.chorus"),Le(6,6,"fx.filter"),Le(7,7,"fx.drive"),Le(8,8,"fx.eq")]},Si={id:"minilab",name:"Arturia MiniLab",deviceMatch:"Arturia MiniLab",mappings:[Le(7,1,"mixer.volume"),Le(74,2,"mixer.pan"),Le(71,3,"fx.reverb"),Le(76,4,"fx.delay"),Le(77,5,"fx.chorus"),Le(93,6,"fx.filter"),Le(73,7,"fx.drive"),Le(75,8,"fx.eq"),jn(1,"Mod Wheel","mixer.master")]},wi={id:"launch-control-xl",name:"Novation Launch Control XL",deviceMatch:"Launch Control",mappings:[...Array.from({length:8},(e,t)=>Le(13+t,t+1,`mixer.send${t+1}`)),...Array.from({length:8},(e,t)=>jn(77+t,`Fader ${t+1}`,`mixer.track${t+1}`))]},Sa={id:"generic",name:"Generic MIDI Controller",deviceMatch:"",mappings:[Le(1,1,"mixer.modWheel"),jn(7,"Volume","mixer.volume"),Le(10,2,"mixer.pan"),jn(11,"Expression","mixer.expression")]},Ci=[vi,xi,Si,wi,Sa];class uf{constructor(t){this.ccMap=new Map,this.onChange=null,this.profile=t??Sa,this.rebuildMap()}setProfile(t){this.profile=t,this.rebuildMap()}getProfile(){return this.profile}autoDetect(t){const n=t.toUpperCase(),r=Ci.find(a=>a.deviceMatch&&n.includes(a.deviceMatch.toUpperCase()));return r?(this.setProfile(r),r):null}onMappedChange(t){this.onChange=t}handleCC(t,n){var c;const r=this.ccMap.get(t);if(!r)return null;const o=(r.inverted?127-n:n)/127,i=r.min+o*(r.max-r.min),l={paramId:r.paramId,label:r.label,rawValue:n,scaledValue:i,normalizedValue:o};return(c=this.onChange)==null||c.call(this,l),l}setMapping(t,n,r,a="knob"){const o={cc:t,paramId:n,label:r,controlType:a,min:0,max:127,inverted:!1},i=this.profile.mappings.findIndex(l=>l.cc===t);i>=0?this.profile.mappings[i]=o:this.profile.mappings.push(o),this.ccMap.set(t,o)}removeMapping(t){this.profile.mappings=this.profile.mappings.filter(n=>n.cc!==t),this.ccMap.delete(t)}getMappings(){return[...this.profile.mappings]}getMapping(t){return this.ccMap.get(t)}exportConfig(){return{...this.profile,mappings:this.profile.mappings.map(t=>({...t}))}}importConfig(t){this.profile={...t,mappings:t.mappings.map(n=>({...n}))},this.rebuildMap()}static createCustomProfile(t,n){return{id:`custom-${t.toLowerCase().replace(/\s+/g,"-")}`,name:t,deviceMatch:"",mappings:n.map(r=>({...r,min:0,max:127,inverted:!1}))}}rebuildMap(){this.ccMap.clear();for(const t of this.profile.mappings)this.ccMap.set(t.cc,t)}}function ki(e){return{past:[],present:e,future:[]}}function Mi(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function ji(e){if(e.past.length===0)return e;const t=e.past[e.past.length-1];return{past:e.past.slice(0,-1),present:t,future:[e.present,...e.future]}}function Ri(e){if(e.future.length===0)return e;const t=e.future[0];return{past:[...e.past,e.present],present:t,future:e.future.slice(1)}}function $i(e){return e.past.length>0}function Ti(e){return e.future.length>0}function qr(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>({...n}))}function Pi(e,t,n){if(t.length===0)return e;const r=Math.min(...t.map(i=>i.time)),a=n-r,o=t.map(i=>({...i,id:Date.now()+Math.floor(Math.random()*1e4)+i.id,time:i.time+a}));return[...e,...o]}function Ei(e,t){const n=[],r=[];for(const a of e)a.time>=t.start&&a.time<=t.end?n.push({...a}):r.push(a);return{remaining:r,cut:n}}function Ai(e,t){return e.filter(n=>n.time<t.start||n.time>t.end)}function hf(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>n.id)}function Ni(e,t,n,r){const a={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:r};return[...e,a]}function Ii(e,t=3){if(e.length<=2)return e;const n=[...e].sort((a,o)=>a.time-o.time),r=[n[0]];for(let a=1;a<n.length-1;a++)a%t===0&&r.push(n[a]);return r.push(n[n.length-1]),r}function Li(e){return JSON.stringify(e,null,2)}function Fi(e){try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&"id"in n&&"cc"in n&&"value"in n&&"time"in n):[]}catch{return[]}}function rt(e,t){var n;return((n=e.find(r=>r.layerId===t))==null?void 0:n.events)??[]}function mt(e,t,n){return e.find(a=>a.layerId===t)?e.map(a=>a.layerId===t?{...a,events:n}:a):[...e,{layerId:t,events:n}]}function ff(e,t){switch(t.type){case"UNDO":return ji(e);case"REDO":return Ri(e);default:{let n=e.present;switch(t.type){case"ADD_EVENT":{const r=[...rt(n,t.layerId),t.event];n=mt(n,t.layerId,r);break}case"UPDATE_EVENT":{const r=rt(n,t.layerId).map(a=>a.id===t.id?{...a,value:t.value,time:t.time,handleType:t.handleType??a.handleType}:a);n=mt(n,t.layerId,r);break}case"REMOVE_EVENT":{const r=rt(n,t.layerId).filter(a=>a.id!==t.id);n=mt(n,t.layerId,r);break}case"SET_EVENTS":n=mt(n,t.layerId,t.events);break;case"PASTE":{const r=rt(n,t.layerId),a=Pi(r,t.clipboard,t.targetTime);n=mt(n,t.layerId,a);break}case"CUT":{const r=rt(n,t.layerId),{remaining:a}=Ei(r,t.range);n=mt(n,t.layerId,a);break}case"DELETE_RANGE":{const r=rt(n,t.layerId),a=Ai(r,t.range);n=mt(n,t.layerId,a);break}case"RECORD":{const r=rt(n,t.layerId),a=Ni(r,t.cc,t.value,t.time);n=mt(n,t.layerId,a);break}case"THIN":{const r=rt(n,t.layerId),a=Ii(r,t.keepEveryN);n=mt(n,t.layerId,a);break}case"IMPORT":{const r=Fi(t.json);r.length>0&&(n=mt(n,t.layerId,r));break}}return Mi(e,n)}}}function pf(e=[]){const[t,n]=u.useReducer(ff,ki(e)),r=u.useRef([]),a=u.useCallback(y=>rt(t.present,y),[t.present]),o=u.useCallback((y,k)=>n({type:"ADD_EVENT",layerId:y,event:k}),[]),i=u.useCallback((y,k,M,N,R)=>n({type:"UPDATE_EVENT",layerId:y,id:k,value:M,time:N,handleType:R}),[]),l=u.useCallback((y,k)=>n({type:"REMOVE_EVENT",layerId:y,id:k}),[]),c=u.useCallback((y,k)=>n({type:"SET_EVENTS",layerId:y,events:k}),[]),d=u.useCallback(()=>n({type:"UNDO"}),[]),h=u.useCallback(()=>n({type:"REDO"}),[]),f=u.useCallback((y,k)=>{r.current=qr(rt(t.present,y),k)},[t.present]),m=u.useCallback((y,k)=>{r.current=qr(rt(t.present,y),k),n({type:"CUT",layerId:y,range:k})},[t.present]),g=u.useCallback((y,k)=>{r.current.length>0&&n({type:"PASTE",layerId:y,clipboard:r.current,targetTime:k})},[]),p=u.useCallback((y,k)=>n({type:"DELETE_RANGE",layerId:y,range:k}),[]),v=u.useCallback((y,k,M,N)=>n({type:"RECORD",layerId:y,cc:k,value:M,time:N}),[]),x=u.useCallback((y,k)=>n({type:"THIN",layerId:y,keepEveryN:k}),[]),b=u.useCallback(y=>Li(rt(t.present,y)),[t.present]),w=u.useCallback((y,k)=>n({type:"IMPORT",layerId:y,json:k}),[]);return{snapshots:t.present,getEvents:a,addEvent:o,updateEvent:i,removeEvent:l,setEvents:c,undo:d,redo:h,canUndo:$i(t),canRedo:Ti(t),copy:f,cut:m,paste:g,clipboard:r.current,deleteRange:p,record:v,thin:x,exportLane:b,importLane:w}}function wa(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function Nt(e="New Pattern",t=16,n=120){return{name:e,length:t,steps:Array.from({length:t},()=>wa()),bpm:n,swing:0,rootNote:60}}function Di(e,t){const n=e.steps.map((r,a)=>a===t?{...r,active:!r.active}:r);return{...e,steps:n}}function Oi(e,t,n){const r=e.steps.map((a,o)=>o===t?{...a,note:Math.max(0,Math.min(127,n))}:a);return{...e,steps:r}}function _i(e,t,n){const r=e.steps.map((a,o)=>o===t?{...a,velocity:Math.max(0,Math.min(127,n))}:a);return{...e,steps:r}}function zi(e,t,n){const r=e.steps.map((a,o)=>o===t?{...a,gate:Math.max(0,Math.min(1,n))}:a);return{...e,steps:r}}function Gi(e,t,n){const r=e.steps.map((a,o)=>o===t?{...a,probability:Math.max(0,Math.min(1,n))}:a);return{...e,steps:r}}function Bi(e,t){const n=e.steps.map((r,a)=>a===t?{...r,slide:!r.slide}:r);return{...e,steps:n}}function Wi(e,t){const n=e.steps.map(r=>r.active?{...r,note:Math.max(0,Math.min(127,r.note+t))}:r);return{...e,steps:n,rootNote:Math.max(0,Math.min(127,e.rootNote+t))}}function Ui(e){return{...e,steps:[...e.steps].reverse()}}function Vi(e,t){const n=e.steps.length,r=(t%n+n)%n,a=[...e.steps.slice(r),...e.steps.slice(0,r)];return{...e,steps:a}}function qi(e,t=60,n=127){const r=e.steps.map(a=>a.active?{...a,velocity:Math.floor(t+Math.random()*(n-t+1))}:a);return{...e,steps:r}}function Hi(e){return{...e,steps:e.steps.map(()=>wa(e.rootNote))}}function Ca(e,t=4){return 60/e/t}function Ki(e,t,n=0,r=4){const a=Ca(t,r),o=e*a;return e%2===1&&n>0?o+a*n*.5:o}function Yi(e){return e.active&&Math.random()<e.probability}function mf(){const e=Nt("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function gf(){const e=Nt("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function yf(){const e=Nt("Hi-Hat",16);for(let t=0;t<16;t+=2)e.steps[t]={...e.steps[t],active:!0,note:42,velocity:80};return e}function bf(e=60){const t=Nt("Arp",16,120);return[0,4,7,12,7,4,0,-5,0,3,7,12,7,3,0,-5].forEach((r,a)=>{t.steps[a]={...t.steps[a],active:!0,note:e+r,velocity:90,gate:.5}}),{...t,rootNote:e}}function vf(e=36){const t=Nt("Bassline",16,120),n=[0,0,7,0,5,5,3,0,0,0,7,12,5,5,3,0],r=[1,0,1,0,1,0,1,1,1,0,1,1,1,0,1,0];return n.forEach((a,o)=>{t.steps[o]={...t.steps[o],active:!!r[o],note:e+a,velocity:100,gate:.7}}),{...t,rootNote:e}}function xf(e){return JSON.stringify(e,null,2)}function Sf(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function wf(e={}){const{onTrigger:t,onLFOOutput:n,initialPattern:r}=e,[a,o]=u.useState(()=>r??Nt()),[i,l]=u.useState(-1),[c,d]=u.useState(!1),[h,f]=u.useState([]),m=u.useRef(a);m.current=a;const g=u.useRef(h);g.current=h;const p=u.useRef(c);p.current=c;const v=u.useRef(t);v.current=t;const x=u.useRef(n);x.current=n;const b=u.useRef(null),w=u.useRef(0),y=u.useRef(0),k=u.useCallback(()=>{var Q,J;if(!p.current)return;const $=m.current,T=w.current%$.length,C=$.steps[T];if(Yi(C)){const ae=Ki(w.current,$.bpm,$.swing);(Q=v.current)==null||Q.call(v,C,T,ae)}const A=(Date.now()-y.current)/1e3;for(let ae=0;ae<g.current.length;ae++){const re=g.current[ae];if(re.enabled&&re.targetCC!==void 0){const ee=Xr(re,A,$.bpm);(J=x.current)==null||J.call(x,ae,re.targetCC,ee)}}l(T),w.current++;const D=Ca($.bpm)*1e3,V=T%2===0?0:D*$.swing*.5;b.current=setTimeout(k,D+V)},[]),M=u.useCallback(()=>{p.current||(w.current=0,y.current=Date.now(),d(!0),p.current=!0,k())},[k]),N=u.useCallback(()=>{d(!1),p.current=!1,l(-1),b.current&&(clearTimeout(b.current),b.current=null)},[]),R=u.useCallback(()=>{p.current?N():M()},[M,N]);u.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const _=u.useCallback($=>o(T=>Di(T,$)),[]),E=u.useCallback(($,T)=>o(C=>Oi(C,$,T)),[]),U=u.useCallback(($,T)=>o(C=>_i(C,$,T)),[]),W=u.useCallback(($,T)=>o(C=>zi(C,$,T)),[]),j=u.useCallback(($,T)=>o(C=>Gi(C,$,T)),[]),L=u.useCallback($=>o(T=>Bi(T,$)),[]),I=u.useCallback($=>o(T=>Wi(T,$)),[]),q=u.useCallback(()=>o($=>Ui($)),[]),Y=u.useCallback($=>o(T=>Vi(T,$)),[]),O=u.useCallback(($,T)=>o(C=>qi(C,$,T)),[]),Z=u.useCallback(()=>o($=>Hi($)),[]),H=u.useCallback($=>o(T=>({...T,bpm:Math.max(20,Math.min(300,$))})),[]),te=u.useCallback($=>o(T=>({...T,swing:Math.max(0,Math.min(1,$))})),[]),G=u.useCallback($=>{o(T=>{if(T.length===$)return T;const C=Array.from({length:$},(A,D)=>D<T.steps.length?T.steps[D]:{active:!1,note:T.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...T,length:$,steps:C}})},[]),z=u.useCallback($=>{f(T=>[...T,$??ir()])},[]),S=u.useCallback($=>{f(T=>T.filter((C,A)=>A!==$))},[]),P=u.useCallback(($,T)=>{f(C=>C.map((A,D)=>D===$?{...A,...T}:A))},[]);return{pattern:a,currentStep:i,playing:c,lfos:h,play:M,stop:N,togglePlayback:R,toggle:_,setNote:E,setVelocity:U,setGate:W,setProbability:j,toggleSlide:L,transpose:I,reverse:q,shift:Y,randomizeVel:O,clear:Z,setPattern:o,setBpm:H,setSwing:te,setLength:G,addLFO:z,removeLFO:S,updateLFO:P}}function ka(e){const t=u.useRef(null),n=u.useRef(new Map),r=u.useRef(1),a=u.useCallback(()=>{if(!t.current){const i=e();i.onmessage=l=>{const{id:c}=l.data,d=n.current.get(c);d&&(n.current.delete(c),d.resolve(l.data))},i.onerror=l=>{console.error("[useWorker] Worker error:",l.message);for(const[c,d]of n.current)d.reject(new Error(`Worker error: ${l.message}`));n.current.clear(),i.terminate(),t.current=null},t.current=i}return t.current},[e]);return u.useEffect(()=>()=>{var i;(i=t.current)==null||i.terminate(),t.current=null;for(const[,l]of n.current)l.reject(new Error("Worker terminated on unmount"));n.current.clear()},[]),u.useCallback((i,l)=>{const c=r.current++,d=a();return new Promise((h,f)=>{n.current.set(c,{resolve:h,reject:f}),d.postMessage({...i,id:c},l??[])})},[a])}function Cf(){const e=ka(u.useCallback(()=>new Worker(new URL("/assets/pitchWorker-BgAp5Z97.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:st&&st.tagName.toUpperCase()==="SCRIPT"&&st.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return u.useCallback(async(n,r,a=.01)=>(await e({buffer:n,sampleRate:r,rmsThreshold:a})).hz,[e])}function kf(){const e=ka(u.useCallback(()=>new Worker(new URL("/assets/scoringWorker-B1PkYu_m.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:st&&st.tagName.toUpperCase()==="SCRIPT"&&st.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return u.useCallback(async(n,r,a)=>(await e({notes:n,points:r,params:a})).result,[e])}const Mf={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function Zi(){return`
53
+ Tame Impala - Let It Happen`,rows:10,style:{width:"100%",padding:12,borderRadius:6,border:"1px solid var(--border, #e2e8f0)",fontFamily:"monospace",fontSize:13,resize:"vertical"}}),s.jsx("button",{style:{...bn,opacity:Y.trim().length===0?.5:1},disabled:Y.trim().length===0,onClick:()=>V(Y),type:"button",children:d("importWizard.parseTracks","Parse Tracks")})]}),(m!==99||w.length>0)&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("p",{style:{margin:0,fontWeight:600},children:[x==null?void 0:x.name," — ",k.size,"/",w.length," ",d("importWizard.selected","selected")]}),s.jsx("button",{style:Dn,onClick:S,type:"button",children:k.size===w.length?d("importWizard.deselectAll","Deselect All"):d("importWizard.selectAll","Select All")})]}),N?s.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--text-dim, #64748b)"},children:d("importWizard.loadingTracks","Loading tracks…")}):s.jsx("div",{style:{maxHeight:320,overflowY:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid var(--border, #e2e8f0)",textAlign:"left"},children:[s.jsx("th",{style:{padding:"4px 8px",width:32}}),s.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.title","Title")}),s.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.artist","Artist")}),s.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.album","Album")}),s.jsx("th",{style:{padding:"4px 8px",textAlign:"right"},children:d("importWizard.duration","Duration")})]})}),s.jsx("tbody",{children:w.map(F=>{const K=k.has(F.externalId);return s.jsxs("tr",{style:{borderBottom:"1px solid var(--border, #e2e8f0)",opacity:K?1:.5,cursor:"pointer"},onClick:()=>z(F.externalId),children:[s.jsx("td",{style:{padding:"6px 8px"},children:s.jsx("input",{type:"checkbox",checked:K,readOnly:!0})}),s.jsx("td",{style:{padding:"6px 8px",fontWeight:500},children:F.title}),s.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:F.artist}),s.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:F.album??"—"}),s.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--text-dim, #64748b)"},children:yh(F.duration)})]},F.externalId)})})]})}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:s.jsxs("button",{style:{...bn,opacity:k.size===0?.5:1},disabled:k.size===0,onClick:()=>f("options"),type:"button",children:[d("importWizard.next","Next")," →"]})})]})]}),J=()=>s.jsxs("div",{style:{display:"grid",gap:16},children:[s.jsx("p",{style:{margin:0,fontWeight:600},children:d("importWizard.importOptions","Import options")}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:I.mergeTags,onChange:F=>q(K=>({...K,mergeTags:F.target.checked}))}),d("importWizard.mergeTags","Merge tags from source playlist")]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:I.mergeFolders,onChange:F=>q(K=>({...K,mergeFolders:F.target.checked}))}),d("importWizard.mergeFolders","Merge into existing folder structure")]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:I.overwriteExisting,onChange:F=>q(K=>({...K,overwriteExisting:F.target.checked}))}),d("importWizard.overwrite","Overwrite existing tracks (match by ISRC)")]}),l&&l.length>0&&s.jsxs("div",{style:{display:"grid",gap:4},children:[s.jsx("label",{style:{fontSize:13,fontWeight:500},children:d("importWizard.targetFolder","Target folder")}),s.jsxs("select",{style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border, #e2e8f0)"},value:I.targetFolderId??"",onChange:F=>q(K=>({...K,targetFolderId:F.target.value||void 0})),children:[s.jsx("option",{value:"",children:d("importWizard.root","— Root —")}),l.map(F=>s.jsx("option",{value:F.id,children:F.name},F.id))]})]}),s.jsx("div",{style:{marginTop:8,padding:12,borderRadius:8,background:"var(--info-bg, #eff6ff)",fontSize:13},children:d("importWizard.summary",`Ready to import ${k.size} tracks from "${(x==null?void 0:x.name)??""}"`)}),s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[s.jsx("button",{style:Dn,onClick:T,type:"button",children:d("importWizard.back","← Back")}),s.jsx("button",{style:bn,onClick:P,type:"button",children:d("importWizard.startImport","Start Import")})]})]}),ae=()=>{const F=_?Math.round(_.imported/_.total*100):0;return s.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[s.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:d("importWizard.importing","Importing…")}),s.jsx("div",{style:{height:8,borderRadius:4,background:"var(--border, #e2e8f0)",overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${F}%`,background:"var(--accent, #6366f1)",borderRadius:4,transition:"width 0.3s"}})}),_&&s.jsxs("div",{style:{fontSize:13,color:"var(--text-dim, #64748b)"},children:[_.imported," / ",_.total," ",d("importWizard.tracks","tracks"),_.currentTrack&&s.jsxs("div",{style:{marginTop:4},children:["🎵 ",_.currentTrack]})]})]})},re=()=>s.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[s.jsx("span",{style:{fontSize:48},children:"✅"}),s.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:d("importWizard.complete","Import Complete")}),U&&s.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[s.jsxs("div",{children:[s.jsx("strong",{children:U.imported})," ",d("importWizard.imported","imported")]}),U.skipped>0&&s.jsxs("div",{style:{color:"var(--warning, #f59e0b)"},children:[U.skipped," ",d("importWizard.skipped","skipped (duplicates)")]}),U.failed>0&&s.jsxs("div",{style:{color:"var(--error, #ef4444)"},children:[U.failed," ",d("importWizard.failed","failed")]}),U.failedTracks.length>0&&s.jsxs("details",{style:{textAlign:"left",marginTop:8,fontSize:12,color:"var(--text-dim, #64748b)"},children:[s.jsx("summary",{style:{cursor:"pointer"},children:d("importWizard.showFailed","Show failed tracks")}),s.jsx("ul",{style:{marginTop:4,paddingLeft:20},children:U.failedTracks.map((F,K)=>s.jsx("li",{children:F},K))})]})]}),s.jsx("button",{style:bn,onClick:i,type:"button",children:d("importWizard.close","Done")})]}),ee={connect:d("importWizard.stepConnect","Connect"),browse:d("importWizard.stepBrowse","Browse"),tracks:d("importWizard.stepTracks","Select Tracks"),options:d("importWizard.stepOptions","Options"),importing:d("importWizard.stepImporting","Importing"),done:d("importWizard.stepDone","Done")};return s.jsxs("div",{style:fh,children:[C(),s.jsxs("div",{style:ph,children:[s.jsxs("h2",{style:{margin:0,fontSize:18},children:[d("importWizard.title","Import Playlist")," — ",ee[h]]}),$&&s.jsxs("button",{style:Dn,onClick:T,type:"button",children:["← ",d("importWizard.back","Back")]}),h==="connect"&&s.jsx("button",{style:Dn,onClick:i,type:"button",children:"✕"})]}),j&&s.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--error-bg, #fef2f2)",color:"var(--error, #ef4444)",fontSize:13},children:j}),h==="connect"&&A(),h==="browse"&&D(),h==="tracks"&&Q(),h==="options"&&J(),h==="importing"&&ae(),h==="done"&&re()]})},bh=[{id:"concert-harp",name:"Concert Harp",description:"Warm concert harp",emoji:"🎵",dir:"concert-harp",attribution:"ConcertHarp SoundFont — source: musical-artifacts.com/artifacts/375"},{id:"celtic-harp",name:"Celtic Harp",description:"Bright celtic harp",emoji:"🍀",dir:"celtic-harp"},{id:"triangle",name:"Triangle",description:"Metallic percussion triangle",emoji:"🔺",dir:"triangle",attribution:"Triangle SoundFont — source: polyphone.io/en/soundfonts/unpitched-percussion/298-triangle"},{id:"synth",name:"Celesta",description:"Synthesized celesta / music-box",emoji:"✨",dir:"synth"},{id:"none",name:"Silent",description:"No sound on click",emoji:"🔇",dir:null}],vh="concert-harp",va=Object.fromEntries(bh.map(e=>[e.id,e])),xh="nice2dev-note-sound-set";function li(){try{const e=localStorage.getItem(xh);if(e&&va[e])return e}catch{}return vh}function ds(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function ci(e){if(!e)return null;const t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle=e;const n=t.fillStyle;if(n.startsWith("#")){const a=parseInt(n.slice(1),16);return{r:a>>16&255,g:a>>8&255,b:a&255}}const r=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return r?{r:+r[1],g:+r[2],b:+r[3]}:null}function Mr(e,t){const n=ci(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function Sh(e){const t=ci(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function di(){const e=ds("--text-primary")||"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",t=ds("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",a=Sh(e)<.45;return{base:Mr(e,.92),staffLine:Mr(e,.22),outline:a?"var(--nice-overlay-light-75, rgba(255, 255, 255, 0.75))":"var(--nice-overlay-55, rgba(0, 0, 0, 0.55))",accents:[Mr(t,.95)],isDark:n,notesDark:a}}const hr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),ui=46,ct=5,Hn=4,wh=(ui-(ct-1)*Hn)/2,Ch=6,kh=18,Mh=110,jh=50,fr=hr?jh:Mh,Rh=hr?4:2,$h=hr?2:4,us=hr?1:0,Th=180,hs=2.8,fs=40,Ph=14,ps=1.2,Eh=16,jr=[64,67,71,74,77],Wt=64,vn=77;function Ah(e){const t=Math.max(0,Math.min(ct-1,e)),n=Math.floor(t),r=Math.min(n+1,ct-1),a=t-n;return Math.round(jr[n]+(jr[r]-jr[n])*a)}function Nh(e){return(Math.max(Wt-1*(vn-Wt)/(ct-1),Math.min(vn+1*(vn-Wt)/(ct-1),e))-Wt)/(vn-Wt)*(ct-1)}const ms=2.5,gs=.72,Ih=.55,xn=new Map;let Kn=null;async function Lh(e){const t=e??li(),n=va[t];if(!n||!n.dir){xn.clear(),Kn=t;return}if(Kn===t&&xn.size>0)return;xn.clear(),Kn=t;const r=tn(),a=[];for(let o=Wt;o<=vn;o++)a.push(fetch(`/assets/soundfonts/notes/${n.dir}/note-${o}.mp3`).then(i=>i.arrayBuffer()).then(i=>r.decodeAudioData(i)).then(i=>{xn.set(o,i)}).catch(()=>{}));await Promise.all(a)}function ys(e){const t=xn.get(e);if(!t)return;const n=tn(),r=n.createBufferSource();r.buffer=t;const a=n.createGain();a.gain.value=.7,r.connect(a).connect(n.destination),r.start()}const bs=["𝅘𝅥","𝅘𝅥𝅮","𝅘𝅥𝅯","𝅘𝅥𝅰","𝅘𝅥𝅱","♪","♫","♬"];function Fh(e){return()=>{e|=0,e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function Dh(e){const t=Fh(42),n=[];for(let r=0;r<e;r++){const o=t()<.15?0:-1;n.push({x:t(),lineIdx:t()*(ct+1)-.5,char:bs[Math.floor(t()*bs.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:o})}return n.sort((r,a)=>r.x-a.x),n}const Je=Dh(fr),on=new Float32Array(fr),On=new Float32Array(fr),Sn=new Float32Array(fr);let Gr=!1;const Oh=(ct-1)/2;function _h(){if(!Gr){Gr=!0;for(let e=0;e<Je.length;e++)Sn[e]=Je[e].lineIdx}}let Br=[],vs="";function zh(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function Gh(e){const t=zh(e);t===vs&&Br.length===Je.length||(vs=t,Br=Je.map(n=>{const r=Math.ceil(n.size*1.6),a=r*2,o=document.createElement("canvas");o.width=a,o.height=a;const i=o.getContext("2d");return i.translate(r,r),i.rotate(n.rot*Math.PI/180),i.font=`${n.size}px serif`,i.textAlign="center",i.textBaseline="middle",i.lineWidth=1.8,i.strokeStyle=e.outline,i.strokeText(n.char,0,0),i.fillStyle=n.colorIdx<0?e.base:e.accents[n.colorIdx%e.accents.length],i.fillText(n.char,0,0),{canvas:o,ox:r,oy:r}}))}function hi({pitchMidiRef:e}={}){const t=u.useRef(null),n=u.useRef(0),r=u.useRef(0),a=u.useRef(0),o=u.useRef(null),i=u.useRef(0),l=u.useRef(0),c=u.useRef(null),d=u.useRef(null),h=u.useRef(!1),f=u.useCallback((v,x,b)=>{const w=wh+v*Hn,y=x/b*Math.PI*2;return w+Math.sin(y)*Ch},[]),m=u.useCallback(v=>{const x=t.current;if(!x)return;if(l.current++,us>0&&l.current%(us+1)!==0){a.current=v,n.current=requestAnimationFrame(m);return}const b=x.getContext("2d");if(!b)return;const w=Math.min(window.devicePixelRatio||1,$h),y=x.getBoundingClientRect(),k=y.width,M=y.height;(x.width!==Math.round(k*w)||x.height!==Math.round(M*w))&&(x.width=Math.round(k*w),x.height=Math.round(M*w),b.setTransform(w,0,0,w,0,0));const N=a.current?(v-a.current)/1e3:0;a.current=v,r.current=(r.current+kh*N)%k,b.clearRect(0,0,k,M),i.current++,(!o.current||i.current%60===0)&&(o.current=di());const R=o.current;Gh(R),b.strokeStyle=R.staffLine,b.lineWidth=.7;for(let W=0;W<ct;W++){b.beginPath();for(let j=0;j<=k;j+=Rh){const L=f(W,j,k);j===0?b.moveTo(j,L):b.lineTo(j,L)}b.stroke()}const _=r.current,E=(e==null?void 0:e.current)??null;if(E!==null){_h();const W=Nh(E),j=ms*N;for(let L=0;L<Je.length;L++){const q=(Je[L].lineIdx-Oh)*Ih,O=W*gs+(W+q)*(1-gs)-Sn[L];Sn[L]+=O>0?Math.min(j,O):Math.max(-j,O)}}else if(Gr){const W=ms*.4*N;for(let j=0;j<Je.length;j++){const I=Je[j].lineIdx-Sn[j];Sn[j]+=I>0?Math.min(W,I):Math.max(-W,I)}}const U=c.current;U&&(U.timer-=N,U.timer<=0&&(c.current=null));for(let W=0;W<Je.length;W++){const j=Je[W];if(On[W]>0){On[W]-=N;const q=Math.max(0,On[W]/hs);on[W]+=Th*q*N,on[W]>k&&(on[W]-=k)}const L=Br[W];if(!L)continue;const I=j.lineIdx;for(let q=0;q<2;q++){let O=((j.x*k-_-on[W]+q*k)%k+k)%k;const Z=f(Math.max(0,Math.min(ct-1,Math.round(I))),O,k),H=(I-Math.round(I))*Hn;let te=Z+H;if(U&&U.timer>0){const G=O-U.x,z=te-U.y,S=Math.sqrt(G*G+z*z);if(S<fs&&S>.1){const P=U.timer/ps,$=Ph*(1-S/fs)*P;O+=G/S*$,te+=z/S*$}}b.drawImage(L.canvas,O-L.ox,te-L.oy)}}n.current=requestAnimationFrame(m)},[f]),g=u.useCallback(v=>{const x=t.current;if(!x)return;const b=x.getBoundingClientRect(),w=v.clientX-b.left,y=v.clientY-b.top,k=b.width,M=r.current;let N=1/0,R=-1;for(let _=0;_<Je.length;_++){const E=Je[_],W=((E.x*k-M-on[_])%k+k)%k,j=f(Math.max(0,Math.min(ct-1,Math.round(E.lineIdx))),W,k),L=(E.lineIdx-Math.round(E.lineIdx))*Hn,I=j+L,q=W-w,Y=I-y,O=q*q+Y*Y;O<N&&(N=O,R=_)}if(R>=0&&Math.sqrt(N)<Eh){On[R]=hs;const _=Je[R],E=Ah(_.lineIdx);try{Et();const U=li(),W=va[U];W!=null&&W.dir&&(Kn!==U||!h.current?(h.current=!0,Lh(U).then(()=>ys(E))):ys(E))}catch{}}c.current={x:w,y,timer:ps}},[f]),p=u.useCallback(v=>{const x=t.current;if(!x)return;const b=x.getBoundingClientRect(),w=v.clientX-b.left,y=v.clientY-b.top;d.current={x:w,y},c.current&&c.current.timer>0&&(c.current.x=w,c.current.y=y)},[]);return u.useEffect(()=>(n.current=requestAnimationFrame(m),()=>cancelAnimationFrame(n.current)),[m]),s.jsx("canvas",{ref:t,"aria-hidden":"true",role:"img","aria-label":"Note river animation canvas",onClick:g,onMouseMove:p,style:{display:"block",width:"100%",height:ui,marginBottom:5,cursor:"pointer",background:"transparent"}})}const Bh=14,Wh=.9,Uh=320,Vh=160,qh=6,xs=8,Hh=14,Ss=["♪","♫","♬","𝅘𝅥𝅮","𝅘𝅥𝅯"];function fi(){const e=u.useRef(null),t=u.useRef([]),n=u.useRef(0),r=u.useRef(0),a=u.useRef([]),o=u.useRef(null),i=u.useRef(0),l=u.useCallback((d,h)=>{for(let f=0;f<Bh;f++){const m=Math.random()*Math.PI*2,g=Vh*(.4+Math.random()*.6),p=Wh*(.6+Math.random()*.4),v=Math.random()<.15?0:-1;t.current.push({x:d,y:h,vx:Math.cos(m)*g,vy:Math.sin(m)*g-60,rot:Math.random()*Math.PI*2,vr:(Math.random()-.5)*qh*2,size:xs+Math.random()*(Hh-xs),char:Ss[Math.floor(Math.random()*Ss.length)],life:p,maxLife:p,colorIdx:v})}},[]),c=u.useCallback(d=>{const h=e.current;if(!h){n.current=requestAnimationFrame(c);return}const f=h.getContext("2d");if(!f){n.current=requestAnimationFrame(c);return}const m=window.devicePixelRatio||1,g=window.innerWidth,p=window.innerHeight;(h.width!==Math.round(g*m)||h.height!==Math.round(p*m))&&(h.width=Math.round(g*m),h.height=Math.round(p*m),h.style.width=`${g}px`,h.style.height=`${p}px`,f.setTransform(m,0,0,m,0,0));const v=r.current?Math.min((d-r.current)/1e3,.05):0;r.current=d,f.clearRect(0,0,g,p),i.current++,(!o.current||i.current%60===0)&&(o.current=di());const x=o.current;if(navigator.getGamepads){const w=navigator.getGamepads();for(let y=0;y<w.length;y++){const k=w[y];if(k)for(let M=0;M<k.buttons.length;M++){const N=y*100+M,R=k.buttons[M].pressed;R&&!a.current[N]&&l(g/2,p/2),a.current[N]=R}}}const b=[];f.textAlign="center",f.textBaseline="middle";for(const w of t.current){if(w.life-=v,w.life<=0)continue;w.vy+=Uh*v,w.x+=w.vx*v,w.y+=w.vy*v,w.rot+=w.vr*v;const y=Math.max(0,w.life/w.maxLife),k=.5+.5*y;f.save(),f.globalAlpha=y,f.translate(w.x,w.y),f.rotate(w.rot),f.font=`${w.size*k}px serif`,f.lineWidth=1.4,f.strokeStyle=x.notesDark?`rgba(255,255,255,${y*.8})`:`rgba(0,0,0,${y*.55})`,f.strokeText(w.char,0,0);const M=w.colorIdx<0?x.base:x.accents[w.colorIdx%x.accents.length];f.fillStyle=M.replace(/[\d.]+\)$/,`${y})`),f.fillText(w.char,0,0),f.restore(),b.push(w)}t.current=b,n.current=requestAnimationFrame(c)},[l]);return u.useEffect(()=>{const d=f=>{l(f.clientX,f.clientY)},h=f=>{if(f.key!=="Enter")return;const m=document.activeElement;if(m){const g=m.getBoundingClientRect();l(g.left+g.width/2,g.top+g.height/2)}else l(window.innerWidth/2,window.innerHeight/2)};return window.addEventListener("click",d,!0),window.addEventListener("keydown",h,!0),n.current=requestAnimationFrame(c),()=>{window.removeEventListener("click",d,!0),window.removeEventListener("keydown",h,!0),cancelAnimationFrame(n.current)}},[c,l]),s.jsx("canvas",{ref:e,"aria-hidden":"true",role:"img","aria-label":"Note particles animation canvas",style:{position:"fixed",inset:0,zIndex:99999,pointerEvents:"none"}})}class pi{constructor(t,n){this.activeNotes=new Map,this.audioContext=t,this.masterGain=t.createGain(),this.masterGain.gain.value=.3,this.masterGain.connect(n)}applyCC(t,n,r){}midiToFreq(t){return 440*Math.pow(2,(t-69)/12)}playNote(t,n=100,r=1,a="sine"){const o=this.midiToFreq(t),i=this.audioContext.createOscillator(),l=this.audioContext.createGain();i.type=a,i.frequency.value=o;const c=n/127*.8;l.gain.value=c,i.connect(l),l.connect(this.masterGain);const d=this.audioContext.currentTime;return l.gain.setValueAtTime(0,d),l.gain.linearRampToValueAtTime(c,d+.01),l.gain.exponentialRampToValueAtTime(c*.7,d+.1),l.gain.setValueAtTime(c*.7,d+r-.05),l.gain.exponentialRampToValueAtTime(.001,d+r),i.start(d),i.stop(d+r),i.onended=()=>{l.disconnect(),i.disconnect()},{osc:i,gain:l}}scheduleNote(t,n,r,a=100,o="sine"){const i=this.midiToFreq(t),l=this.audioContext.createOscillator(),c=this.audioContext.createGain();l.type=o,l.frequency.value=i;const d=a/127*.8;l.connect(c),c.connect(this.masterGain);const h=n;return c.gain.setValueAtTime(0,h),c.gain.linearRampToValueAtTime(d,h+.01),c.gain.exponentialRampToValueAtTime(d*.7,h+.1),c.gain.setValueAtTime(d*.7,h+r-.05),c.gain.exponentialRampToValueAtTime(.001,h+r),l.start(h),l.stop(h+r),l.onended=()=>{c.disconnect(),l.disconnect()},{osc:l,gain:c}}setVolume(t){this.masterGain.gain.value=Math.max(0,Math.min(1,t))}stopAll(){this.activeNotes.forEach(({osc:t,gain:n})=>{try{t.stop(),n.disconnect(),t.disconnect()}catch{}}),this.activeNotes.clear()}dispose(){this.stopAll(),this.masterGain.disconnect()}}const ws=et.scoped("AudioPlaybackEngine");class Kh{constructor(){this.audioContext=null,this.masterGain=null,this.masterFilter=null,this.clips=new Map,this.scheduledSources=new Map,this.midiTracks=new Map,this.synths=new Map,this.isPlaying=!1,this.startTimeOffset=0,this.audioContextStartTime=0,this.currentTime=0,this.loopRegion={start:0,end:0,enabled:!1},this.bpm=120,this.duration=0,this.initAudioContext()}setMidiCCEvents(t,n){const r=this.midiTracks.get(t);r&&(r.ccEvents=n)}getMidiCCEvents(t){const n=this.midiTracks.get(t);return(n==null?void 0:n.ccEvents)||[]}addMidiCCEvent(t,n){const r=this.midiTracks.get(t);r&&(r.ccEvents||(r.ccEvents=[]),r.ccEvents.push(n))}removeMidiCCEvent(t,n){const r=this.midiTracks.get(t);r&&r.ccEvents&&(r.ccEvents=r.ccEvents.filter(a=>a.id!==n))}initAudioContext(){try{this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.masterGain=this.audioContext.createGain(),this.masterFilter=this.audioContext.createBiquadFilter(),this.masterFilter.type="peaking",this.masterFilter.frequency.value=1200,this.masterFilter.Q.value=.7,this.masterFilter.gain.value=0,this.masterGain.connect(this.masterFilter),this.masterFilter.connect(this.audioContext.destination),this.masterGain.gain.value=.8,this.audioContext.state==="suspended"&&this.audioContext.resume()}catch(t){ws.error("Failed to initialize AudioContext:",t)}}createEffectNode(t){if(!this.audioContext||t.bypass)return null;try{switch(t.type){case"eq3":{const n=this.audioContext.createBiquadFilter(),r=this.audioContext.createBiquadFilter(),a=this.audioContext.createBiquadFilter();return n.type="lowshelf",n.frequency.value=t.params.lowFreq||250,n.gain.value=t.params.lowGain||0,r.type="peaking",r.frequency.value=1e3,r.Q.value=1,r.gain.value=t.params.midGain||0,a.type="highshelf",a.frequency.value=t.params.highFreq||4e3,a.gain.value=t.params.highGain||0,n.connect(r),r.connect(a),{input:n,output:a}}case"compressor":{const n=this.audioContext.createDynamicsCompressor();return n.threshold.value=t.params.threshold||-24,n.ratio.value=t.params.ratio||4,n.attack.value=t.params.attack||.003,n.release.value=t.params.release||.25,n.knee.value=t.params.knee||30,n}case"delay":{const n=this.audioContext.createDelay(5);n.delayTime.value=t.params.time||.25;const r=this.audioContext.createGain();r.gain.value=t.params.feedback||.3;const a=this.audioContext.createGain();a.gain.value=t.params.mix||.3;const o=this.audioContext.createGain();return o.gain.value=1-(t.params.mix||.3),n.connect(r),r.connect(n),n.connect(a),{input:n,output:a,dry:o,connect:function(i){a.connect(i),o.connect(i)}}}case"reverb":{const n=this.audioContext.createConvolver(),r=this.audioContext.sampleRate*(t.params.decay||2),a=this.audioContext.createBuffer(2,r,this.audioContext.sampleRate);for(let l=0;l<2;l++){const c=a.getChannelData(l);for(let d=0;d<r;d++)c[d]=(Math.random()*2-1)*Math.pow(1-d/r,2)}n.buffer=a;const o=this.audioContext.createGain();o.gain.value=t.params.mix||.3;const i=this.audioContext.createGain();return i.gain.value=1-(t.params.mix||.3),n.connect(o),{input:n,output:o,dry:i,connect:function(l){o.connect(l),i.connect(l)}}}case"distortion":{const n=this.audioContext.createWaveShaper(),r=t.params.amount||20,a=44100,o=new Float32Array(a),i=Math.PI/180;for(let d=0;d<a;d++){const h=d*2/a-1;o[d]=(3+r)*h*20*i/(Math.PI+r*Math.abs(h))}n.curve=o,n.oversample="4x";const l=this.audioContext.createGain();l.gain.value=t.params.mix||.5;const c=this.audioContext.createGain();return c.gain.value=1-(t.params.mix||.5),n.connect(l),{input:n,output:l,dry:c,connect:function(d){l.connect(d),c.connect(d)}}}default:return null}}catch(n){return ws.error("Failed to create effect node:",t.type,n),null}}addClip(t){this.clips.set(t.id,t),this.updateDuration()}removeClip(t){this.clips.delete(t),this.stopClip(t),this.updateDuration()}updateClip(t,n){const r=this.clips.get(t);r&&(Object.assign(r,n),this.updateDuration())}getClipsByLayer(t){return Array.from(this.clips.values()).filter(n=>n.layerId===t)}setMidiTrack(t,n,r="sine",a=.5){if(this.midiTracks.set(t,{layerId:t,notes:n,instrument:r,volume:a}),!this.synths.has(t)&&this.audioContext&&this.masterGain){const o=new pi(this.audioContext,this.masterGain);o.setVolume(a),this.synths.set(t,o)}}removeMidiTrack(t){this.midiTracks.delete(t);const n=this.synths.get(t);n&&(n.dispose(),this.synths.delete(t))}updateMidiTrackVolume(t,n){const r=this.midiTracks.get(t);r&&(r.volume=n);const a=this.synths.get(t);a&&a.setVolume(n)}updateDuration(){let t=0;this.clips.forEach(n=>{const r=n.startTime+n.duration;r>t&&(t=r)}),this.duration=t}play(){!this.audioContext||this.isPlaying||(this.audioContext.state==="suspended"&&this.audioContext.resume(),this.isPlaying=!0,this.audioContextStartTime=this.audioContext.currentTime,this.startTimeOffset=this.currentTime,this.scheduleClips(),this.scheduleMidiNotes(),this.startTimeTracking(),this.onPlayStateChange&&this.onPlayStateChange(!0))}pause(){this.isPlaying&&(this.isPlaying=!1,this.stopAllSources(),this.onPlayStateChange&&this.onPlayStateChange(!1))}stop(){this.pause(),this.seek(0)}seek(t){const n=this.isPlaying;n&&this.pause(),this.currentTime=Math.max(0,Math.min(t,this.duration)),this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),n&&this.play()}scheduleClips(){!this.audioContext||!this.masterGain||this.clips.forEach(t=>{if(t.startTime+t.duration<=this.currentTime)return;const r=this.audioContext.createBufferSource();r.buffer=t.buffer,t.stretchFactor&&t.stretchFactor!==1&&(r.playbackRate.value=1/t.stretchFactor);const a=this.audioContext.createGain();a.gain.value=t.volume;const o=this.audioContext.createStereoPanner();o.pan.value=t.pan,r.connect(a);let i=a;if(t.effectChain&&t.effectChain.length>0)for(const h of t.effectChain){const f=this.createEffectNode(h);if(f)if("input"in f&&"output"in f){const m=f;i.connect(m.input),i=m.output,"dry"in f&&a.connect(m.dry)}else i.connect(f),i=f}i.connect(o),o.connect(this.masterGain);const l=t.startTime,c=Math.max(0,this.currentTime-l),d=this.audioContext.currentTime+(l-this.currentTime);d>=this.audioContext.currentTime&&(r.start(d,t.offset+c,t.duration-c),this.scheduledSources.set(t.id,r),r.onended=()=>{this.scheduledSources.delete(t.id)})})}stopClip(t){const n=this.scheduledSources.get(t);if(n){try{n.stop()}catch{}this.scheduledSources.delete(t)}}stopAllSources(){this.scheduledSources.forEach(t=>{try{t.stop()}catch{}}),this.scheduledSources.clear(),this.synths.forEach(t=>t.stopAll())}scheduleMidiNotes(){this.audioContext&&this.midiTracks.forEach(t=>{const n=this.synths.get(t.layerId);if(n&&(t.notes.forEach(r=>{if(r.start+r.duration<=this.currentTime)return;const o=Math.max(0,this.currentTime-r.start),i=this.audioContext.currentTime+(r.start-this.currentTime);i>=this.audioContext.currentTime&&n.scheduleNote(r.pitch,i,r.duration-o,r.velocity,t.instrument)}),t.ccEvents&&Array.isArray(t.ccEvents)&&t.ccEvents.length>0)){const r=[...t.ccEvents].sort((i,l)=>i.time-l.time);let o=r[0];for(let i=1;i<r.length;++i){const l=r[i],c=o.time,d=l.time,h=o.value,f=l.value,m=o.handleType||"linear",g=Math.max(2,Math.ceil((d-c)*20));for(let p=0;p<=g;++p){const v=p/g;let x=h;if(m==="linear")x=h+(f-h)*v;else if(m==="step")x=v<1?h:f;else if(m==="exp"){const k=Math.max(h/127,.001),M=Math.max(f/127,.001);x=k*Math.pow(M/k,v)*127}const b=c+(d-c)*v,w=this.audioContext.currentTime+(b-this.currentTime);w>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(l.cc,x,w)}o=l}}})}startTimeTracking(){if(!this.audioContext)return;const t=()=>{if(!this.isPlaying||!this.audioContext)return;const n=this.audioContext.currentTime-this.audioContextStartTime;if(this.currentTime=this.startTimeOffset+n,this.loopRegion.enabled&&this.currentTime>=this.loopRegion.end){this.seek(this.loopRegion.start);return}if(this.currentTime>=this.duration){this.stop();return}this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),requestAnimationFrame(t)};requestAnimationFrame(t)}setLoopRegion(t,n,r){this.loopRegion={start:t,end:n,enabled:r}}setBPM(t){this.bpm=Math.max(20,Math.min(300,t))}getBPM(){return this.bpm}setMasterVolume(t){this.masterGain&&(this.masterGain.gain.value=Math.max(0,Math.min(1,t)))}setMasterFilter(t){this.masterFilter&&(t.type&&(this.masterFilter.type=t.type),t.frequency!=null&&(this.masterFilter.frequency.value=Math.max(20,Math.min(2e4,t.frequency))),t.q!=null&&(this.masterFilter.Q.value=Math.max(.1,Math.min(18,t.q))),t.gain!=null&&"gain"in this.masterFilter&&(this.masterFilter.gain.value=Math.max(-40,Math.min(40,t.gain))))}getCurrentTime(){return this.currentTime}getDuration(){return this.duration}getIsPlaying(){return this.isPlaying}setOnTimeUpdate(t){this.onTimeUpdate=t}setOnPlayStateChange(t){this.onPlayStateChange=t}dispose(){this.stop(),this.audioContext&&this.audioContext.close(),this.clips.clear()}}const Yh=[{name:"Grand Piano",waveform:"sawtooth",attack:.02,sustain:.7,release:1.2,eq:{C:2,D:1,E:1,F:0,G:0,A:-1,B:-2,C2:-3},category:"Keyboard"},{name:"Electric Piano",waveform:"triangle",attack:.03,sustain:.8,release:1,eq:{C:0,D:1,E:2,F:3,G:1,A:-1,B:-2,C2:-2},category:"Keyboard"},{name:"Harpsichord",waveform:"square",attack:.01,sustain:.5,release:.6,eq:{C:-1,D:-1,E:0,F:2,G:3,A:1,B:0,C2:-1},category:"Keyboard"},{name:"Violin",waveform:"triangle",attack:.3,sustain:1,release:1.5,eq:{C:3,D:2,E:2,F:1,G:-1,A:-2,B:-3,C2:-3},category:"String"},{name:"Acoustic Guitar",waveform:"sawtooth",attack:.2,sustain:.6,release:.9,eq:{C:-1,D:-2,E:0,F:1,G:3,A:2,B:0,C2:-2},category:"String"},{name:"Electric Guitar",waveform:"square",attack:.05,sustain:.7,release:1.2,eq:{C:-2,D:1,E:2,F:2,G:1,A:0,B:-1,C2:-3},category:"String"},{name:"Kick Drum",waveform:"sine",attack:.005,sustain:.1,release:.2,eq:{C:5,D:3,E:0,F:-3,G:-5,A:-7,B:-9,C2:-10},category:"Percussion"},{name:"Snare Drum",waveform:"triangle",attack:.01,sustain:.2,release:.3,eq:{C:-2,D:-1,E:1,F:2,G:3,A:2,B:0,C2:-2},category:"Percussion"},{name:"Hi-Hat",waveform:"square",attack:.002,sustain:.05,release:.1,eq:{C:-5,D:-3,E:0,F:2,G:5,A:7,B:9,C2:10},category:"Percussion"},{name:"Acoustic Bass",waveform:"sine",attack:.08,sustain:.8,release:1.2,eq:{C:4,D:3,E:2,F:1,G:0,A:-1,B:-2,C2:-3},category:"Bass"},{name:"Electric Bass",waveform:"square",attack:.05,sustain:.9,release:1.3,eq:{C:3,D:2,E:1,F:0,G:-1,A:-2,B:-3,C2:-4},category:"Bass"},{name:"Trumpet",waveform:"sawtooth",attack:.1,sustain:.9,release:1.5,eq:{C:2,D:3,E:4,F:5,G:3,A:1,B:-1,C2:-3},category:"Brass"},{name:"Trombone",waveform:"triangle",attack:.2,sustain:1,release:1.7,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-2,C2:-4},category:"Brass"},{name:"Saxophone",waveform:"sawtooth",attack:.15,sustain:.8,release:1.3,eq:{C:2,D:3,E:4,F:3,G:1,A:-1,B:-2,C2:-3},category:"Woodwind"},{name:"Clarinet",waveform:"triangle",attack:.18,sustain:.9,release:1.6,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-1,C2:-2},category:"Woodwind"},{name:"Saw Synth",waveform:"sawtooth",attack:.05,sustain:.9,release:1.2,eq:{C:2,D:3,E:4,F:3,G:2,A:0,B:-1,C2:-2},category:"Synth"},{name:"Square Lead",waveform:"square",attack:.04,sustain:.85,release:1.1,eq:{C:2,D:3,E:4,F:3,G:1,A:0,B:-1,C2:-3},category:"Synth"}];function pr(e={}){const{channelFilter:t,sysex:n=!1,onEvent:r,inputNameIncludes:a,onInputsChanged:o}=e,[i,l]=u.useState(null),[c,d]=u.useState(!1),[h,f]=u.useState([]),m=u.useRef(null),g=u.useCallback((p,v)=>{const x=p.data??new Uint8Array(0),b=x[0]??0,w=x[1]??0,y=x[2]??0,k=p.timeStamp,M=b&240,N=b&15,R=v.id,_=v.name??"MIDI Input",E=t===void 0||t===N;if((M===144||M===128)&&E){const U=M===144&&y>0;return{type:U?"noteon":"noteoff",note:w,velocity:U?y:0,channel:N,ts:k,deviceId:R,deviceName:_}}return M===176&&E?{type:"cc",controller:w,value:y,channel:N,ts:k,deviceId:R,deviceName:_}:M===208&&E?{type:"aftertouch",pressure:w,channel:N,ts:k,deviceId:R,deviceName:_}:M===224&&E?{type:"pitchbend",value:(w|y<<7)-8192,channel:N,ts:k,deviceId:R,deviceName:_}:M===192&&E?{type:"program",program:w,channel:N,ts:k,deviceId:R,deviceName:_}:{type:"unknown",status:b,data1:w,data2:y,channel:N,ts:k,deviceId:R,deviceName:_}},[t]);return u.useEffect(()=>{if(!("requestMIDIAccess"in navigator)){l(!1);return}l(!0);let p=!1;return navigator.requestMIDIAccess({sysex:n}).then(v=>{if(p)return;m.current=v,d(!0);const x=()=>{const b=Array.from(v.inputs.values()),w=a?b.filter(y=>(y.name||"").toUpperCase().includes(a.toUpperCase())):b;f(w),o==null||o(w),b.forEach(y=>y.onmidimessage=null),w.forEach(y=>{y.onmidimessage=k=>r==null?void 0:r(g(k,y))})};x(),v.onstatechange=()=>x()}),()=>{p=!0;const v=m.current;v&&(v.inputs.forEach(x=>x.onmidimessage=null),v.onstatechange=null)}},[a,r,o,g,n]),{supported:i,granted:c,inputs:h}}const xa="nice2dev.midiLearn";function Zh(){try{const e=localStorage.getItem(xa);return e?JSON.parse(e):{}}catch{return{}}}function Cs(e){const t={};for(const n of e)t[n.id]={id:n.id,type:n.type,number:n.number,channel:n.channel,min:n.min,max:n.max};localStorage.setItem(xa,JSON.stringify(t))}function Xh(e){const{parameters:t,onParameterChange:n}=e,[r,a]=u.useState(()=>{const y=Zh();return t.map(k=>{const M=y[k.id];return{id:k.id,paramName:k.name,type:(M==null?void 0:M.type)??"cc",number:M==null?void 0:M.number,channel:M==null?void 0:M.channel,min:(M==null?void 0:M.min)??k.min??0,max:(M==null?void 0:M.max)??k.max??127,value:0}})}),[o,i]=u.useState({learning:!1,targetId:null}),[l,c]=u.useState(null),d=u.useRef(r);d.current=r;const h=u.useRef(n);h.current=n;const f=u.useRef(o);f.current=o;const m=u.useCallback(y=>{var M;c(y);const k=f.current;if(k.learning&&k.targetId){if(!d.current.find(_=>_.id===k.targetId))return;let R={};switch(y.type){case"cc":R={type:"cc",number:y.controller,channel:y.channel};break;case"noteon":R={type:"note",number:y.note,channel:y.channel};break;case"pitchbend":R={type:"pitchbend",channel:y.channel};break;case"aftertouch":R={type:"aftertouch",channel:y.channel};break;default:return}a(_=>{const E=_.map(U=>U.id===k.targetId?{...U,...R}:U);return Cs(E),E}),i({learning:!1,targetId:null});return}for(const N of d.current){if(N.number===void 0&&N.type!=="pitchbend"&&N.type!=="aftertouch"||N.channel!==void 0&&y.channel!==N.channel)continue;let R=null,_=127;if(N.type==="cc"&&y.type==="cc"&&y.controller===N.number?R=y.value:N.type==="note"&&y.type==="noteon"&&y.note===N.number?R=y.velocity:N.type==="pitchbend"&&y.type==="pitchbend"?(R=y.value+8192,_=16383):N.type==="aftertouch"&&y.type==="aftertouch"&&(R=y.pressure),R!==null){const E=R/_,U=N.min+E*(N.max-N.min);a(W=>W.map(j=>j.id===N.id?{...j,value:E}:j)),(M=h.current)==null||M.call(h,N.id,U,E)}}},[]),{supported:g,granted:p}=pr({onEvent:m}),v=u.useCallback(y=>{i({learning:!0,targetId:y})},[]),x=u.useCallback(()=>{i({learning:!1,targetId:null})},[]),b=u.useCallback(y=>{a(k=>{const M=k.map(N=>N.id===y?{...N,type:"cc",number:void 0,channel:void 0}:N);return Cs(M),M})},[]),w=u.useCallback(()=>{a(y=>{const k=y.map(M=>({...M,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(xa),k})},[]);return{bindings:r,startLearn:v,cancelLearn:x,removeBinding:b,clearAll:w,learnState:o,midiSupported:g,midiGranted:p,lastEvent:l}}const Qh={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function Jh(e={}){const{lowerZone:t=Qh,onNoteExpression:n,onNoteOn:r,onNoteOff:a}=e,[o,i]=u.useState([]),l=u.useRef(new Map),c=u.useRef(n);c.current=n;const d=u.useRef(r);d.current=r;const h=u.useRef(a);h.current=a;const f=u.useRef(new Set(t.memberChannels));u.useEffect(()=>{f.current=new Set(t.memberChannels)},[t.memberChannels]);const m=u.useCallback(v=>{var b,w,y,k,M;if(!f.current.has(v.channel??-1))return;const x=`${v.channel}`;switch(v.type){case"noteon":{const N={note:v.note,channel:v.channel,velocity:v.velocity,pitchBend:0,pressure:0,slide:0,lastUpdate:v.ts};l.current.set(x,N),i(Array.from(l.current.values())),(b=d.current)==null||b.call(d,N);break}case"noteoff":{l.current.delete(x),i(Array.from(l.current.values())),(w=h.current)==null||w.call(h,v.channel,v.note);break}case"pitchbend":{const N=l.current.get(x);N&&(N.pitchBend=v.value,N.lastUpdate=v.ts,(y=c.current)==null||y.call(c,N),i(Array.from(l.current.values())));break}case"aftertouch":{const N=l.current.get(x);N&&(N.pressure=v.pressure,N.lastUpdate=v.ts,(k=c.current)==null||k.call(c,N),i(Array.from(l.current.values())));break}case"cc":{if(v.controller===74){const N=l.current.get(x);N&&(N.slide=v.value,N.lastUpdate=v.ts,(M=c.current)==null||M.call(c,N),i(Array.from(l.current.values())))}break}}},[]),{supported:g,granted:p}=pr({onEvent:m,sysex:!1});return{activeNotes:o,midiSupported:g,midiGranted:p}}const ef={name:"M-Audio Oxygen 25 (MKIV)",deviceMatch:"OXYGEN",knobs:[{index:1,cc:21,label:"Knob 1"},{index:2,cc:22,label:"Knob 2"},{index:3,cc:23,label:"Knob 3"},{index:4,cc:24,label:"Knob 4"},{index:5,cc:25,label:"Knob 5"},{index:6,cc:26,label:"Knob 6"},{index:7,cc:27,label:"Knob 7"},{index:8,cc:28,label:"Knob 8"}],fader:{cc:7,label:"Fader (Channel Volume)"},pads:[{note:36,label:"Kick C1"},{note:38,label:"Snare D1"},{note:42,label:"HH Closed F#1"},{note:46,label:"HH Open A#1"},{note:48,label:"Tom1 C2"},{note:45,label:"Tom2 A1"},{note:43,label:"Floor G1"},{note:49,label:"Crash C#2"}],transport:{play:115,stop:114,record:117,rew:112,ff:113,loop:116}};function tf(e={},t=ef){const[n,r]=u.useState(()=>{const g=localStorage.getItem("oxygen25.layout");return g?JSON.parse(g):t}),[a,o]=u.useState([]),i=u.useRef({mode:"idle"}),l=u.useCallback(g=>{r(p=>{const v={...p,...g};return localStorage.setItem("oxygen25.layout",JSON.stringify(v)),v})},[]),c=u.useCallback(g=>{var x,b,w,y,k,M,N,R,_;const p=g.deviceName||"MIDI";o(E=>E.includes(p)?E:[...E,p]);const v=i.current;if(v.mode!=="idle"){if(v.mode==="knob"&&g.type==="cc"){const E=v.index;l({knobs:n.knobs.map(U=>U.index===E?{...U,cc:g.controller}:U)}),i.current={mode:"idle"};return}if(v.mode==="fader"&&g.type==="cc"){l({fader:{cc:g.controller,label:"Fader"}}),i.current={mode:"idle"};return}if(v.mode==="pad"&&g.type==="noteon"){const E=n.pads.slice();E[v.padIdx]={...E[v.padIdx],note:g.note},l({pads:E}),i.current={mode:"idle"};return}if(v.mode==="transport"&&g.type==="cc"){const E={...n.transport};E[v.action]=g.controller,l({transport:E}),i.current={mode:"idle"};return}}switch(g.type){case"noteon":{n.pads.findIndex(U=>U.note===g.note)>=0?(x=e.onPad)==null||x.call(e,{note:g.note,velocity:g.velocity,ts:g.ts,device:p}):(b=e.onKey)==null||b.call(e,{note:g.note,velocity:g.velocity,ts:g.ts,device:p});break}case"cc":{if(n.fader&&g.controller===n.fader.cc){(w=e.onFader)==null||w.call(e,{cc:g.controller,value:g.value,ts:g.ts,device:p});break}const E=n.knobs.find(W=>W.cc===g.controller);if(E){(y=e.onKnob)==null||y.call(e,{index:E.index,cc:g.controller,value:g.value,ts:g.ts,device:p});break}const U=Object.keys(n.transport).find(W=>n.transport[W]===g.controller);if(U){(k=e.onTransport)==null||k.call(e,{action:U,value:g.value,ts:g.ts,device:p});break}(M=e.onUnknown)==null||M.call(e,g);break}case"pitchbend":(N=e.onPitchBend)==null||N.call(e,{value:g.value,ts:g.ts,device:p});break;case"aftertouch":(R=e.onAftertouch)==null||R.call(e,{pressure:g.pressure,ts:g.ts,device:p});break;default:(_=e.onUnknown)==null||_.call(e,g)}},[l,e,n]),{supported:d,granted:h,inputs:f}=pr({inputNameIncludes:void 0,onEvent:c,sysex:!1,channelFilter:void 0,onInputsChanged:g=>o(g.map(p=>p.name||"MIDI"))}),m=u.useMemo(()=>({knob:g=>i.current={mode:"knob",index:g},fader:()=>i.current={mode:"fader"},pad:g=>i.current={mode:"pad",padIdx:g},transport:g=>i.current={mode:"transport",action:g},cancel:()=>i.current={mode:"idle"},state:()=>i.current}),[]);return{supported:d,granted:h,inputs:f,layout:n,setLayout:l,learn:m,inputsInfo:a}}const Wr={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],mixolydian:[0,2,4,5,7,9,10],pentatonic:[0,2,4,7,9],minorPenta:[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11]},nf=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Ur={pop:[[0,4,7],[5,9,0],[7,11,2],[5,9,0]],rock:[[0,4,7],[5,9,0],[3,7,10],[5,9,0]],jazz:[[0,4,7,11],[2,5,9,0],[5,9,0,4],[0,4,7,11]],blues12:[[0,4,7],[0,4,7],[0,4,7],[0,4,7],[5,9,0],[5,9,0],[0,4,7],[0,4,7],[7,11,2],[5,9,0],[0,4,7],[7,11,2]]},_t=36,ln=38,pt=42,zt=51,rf=49,Vr={basic:[{step:0,pitch:_t,vel:110},{step:0,pitch:pt,vel:80},{step:2,pitch:pt,vel:70},{step:4,pitch:ln,vel:100},{step:4,pitch:pt,vel:80},{step:6,pitch:pt,vel:70},{step:8,pitch:_t,vel:100},{step:10,pitch:pt,vel:70},{step:12,pitch:ln,vel:100},{step:12,pitch:pt,vel:80},{step:14,pitch:pt,vel:70}],rock:[{step:0,pitch:_t,vel:120},{step:0,pitch:rf,vel:90},{step:4,pitch:ln,vel:110},{step:4,pitch:pt,vel:80},{step:8,pitch:_t,vel:110},{step:8,pitch:pt,vel:80},{step:10,pitch:_t,vel:90},{step:12,pitch:ln,vel:110},{step:12,pitch:pt,vel:80}],swing:[{step:0,pitch:zt,vel:90},{step:3,pitch:zt,vel:70},{step:4,pitch:zt,vel:80},{step:8,pitch:zt,vel:90},{step:11,pitch:zt,vel:70},{step:12,pitch:zt,vel:80},{step:4,pitch:_t,vel:80},{step:12,pitch:ln,vel:70}]},mi={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function af(e){let t=e|0;return()=>{t=t+1831565813|0;let n=Math.imul(t^t>>>15,1|t);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}let gi=1;const _n=()=>gi++,yi=e=>60/e,sf=e=>yi(e)/4;function Rr(e,t,n,r){const a=t.length,o=Math.floor(n/a),i=(n%a+a)%a;return e+t[i]+(r+o)*12}function bi(e=mi){gi=1;const t=e.seed>0?af(e.seed):Math.random,n=Wr[e.scale]??Wr.pentatonic,r=Ur[e.progression]??Ur.pop,a=Vr[e.drumPattern]??Vr.basic,o=yi(e.tempo),i=sf(e.tempo),l=Math.max(1,e.bars),c=16,d=[],h=[],f=[],m=[];let g=0;for(let p=0;p<l;p++){const v=p*4*o,x=p%r.length,b=r[x];for(const y of b)f.push({id:_n(),pitch:Rr(e.root,n,y,e.octave-1),start:v,duration:4*o-.01,velocity:70+Math.floor(t()*20)});const w=b[0];for(let y=0;y<4;y++){const k=y===2?w+(t()>.5?2:0):w;h.push({id:_n(),pitch:Rr(e.root,n,k,e.octave-2),start:v+y*o,duration:o*.9,velocity:80+Math.floor(t()*30)})}for(let y=0;y<c;y++){if(t()>e.density)continue;const k=v+y*i,M=t()>.8?t()>.5?2:-2:t()>.5?1:-1;g=Math.max(-3,Math.min(n.length+3,g+M));const N=1+Math.floor(t()*3);d.push({id:_n(),pitch:Rr(e.root,n,g,e.octave),start:k,duration:N*i*.95,velocity:85+Math.floor(t()*30)})}for(const y of a)m.push({id:_n(),pitch:y.pitch,start:v+y.step*i,duration:i*.8,velocity:y.vel+Math.floor(t()*10-5)})}return{melody:d,bass:h,chords:f,drums:m,config:e}}const of=Object.keys(Wr),lf=Object.keys(Ur),cf=Object.keys(Vr),df=bi;function Le(e,t,n){return{cc:e,paramId:n,label:`Knob ${t}`,controlType:"knob",min:0,max:127,inverted:!1}}function jn(e,t,n){return{cc:e,paramId:n,label:t,controlType:"fader",min:0,max:127,inverted:!1}}function Gt(e,t,n){return{cc:e,paramId:n,label:t,controlType:"button",min:0,max:127,inverted:!1}}const vi={id:"oxygen25",name:"M-Audio Oxygen 25 (MkIV)",deviceMatch:"OXYGEN",mappings:[Le(21,1,"mixer.volume"),Le(22,2,"mixer.pan"),Le(23,3,"fx.reverb"),Le(24,4,"fx.delay"),Le(25,5,"fx.chorus"),Le(26,6,"fx.filter"),Le(27,7,"fx.drive"),Le(28,8,"fx.eq"),jn(7,"Master Fader","mixer.master"),Gt(115,"Play","transport.play"),Gt(114,"Stop","transport.stop"),Gt(117,"Record","transport.record"),Gt(112,"Rewind","transport.rewind"),Gt(113,"Forward","transport.forward"),Gt(116,"Loop","transport.loop")]},xi={id:"mpk-mini",name:"Akai MPK Mini",deviceMatch:"MPK",mappings:[Le(1,1,"mixer.volume"),Le(2,2,"mixer.pan"),Le(3,3,"fx.reverb"),Le(4,4,"fx.delay"),Le(5,5,"fx.chorus"),Le(6,6,"fx.filter"),Le(7,7,"fx.drive"),Le(8,8,"fx.eq")]},Si={id:"minilab",name:"Arturia MiniLab",deviceMatch:"Arturia MiniLab",mappings:[Le(7,1,"mixer.volume"),Le(74,2,"mixer.pan"),Le(71,3,"fx.reverb"),Le(76,4,"fx.delay"),Le(77,5,"fx.chorus"),Le(93,6,"fx.filter"),Le(73,7,"fx.drive"),Le(75,8,"fx.eq"),jn(1,"Mod Wheel","mixer.master")]},wi={id:"launch-control-xl",name:"Novation Launch Control XL",deviceMatch:"Launch Control",mappings:[...Array.from({length:8},(e,t)=>Le(13+t,t+1,`mixer.send${t+1}`)),...Array.from({length:8},(e,t)=>jn(77+t,`Fader ${t+1}`,`mixer.track${t+1}`))]},Sa={id:"generic",name:"Generic MIDI Controller",deviceMatch:"",mappings:[Le(1,1,"mixer.modWheel"),jn(7,"Volume","mixer.volume"),Le(10,2,"mixer.pan"),jn(11,"Expression","mixer.expression")]},Ci=[vi,xi,Si,wi,Sa];class uf{constructor(t){this.ccMap=new Map,this.onChange=null,this.profile=t??Sa,this.rebuildMap()}setProfile(t){this.profile=t,this.rebuildMap()}getProfile(){return this.profile}autoDetect(t){const n=t.toUpperCase(),r=Ci.find(a=>a.deviceMatch&&n.includes(a.deviceMatch.toUpperCase()));return r?(this.setProfile(r),r):null}onMappedChange(t){this.onChange=t}handleCC(t,n){var c;const r=this.ccMap.get(t);if(!r)return null;const o=(r.inverted?127-n:n)/127,i=r.min+o*(r.max-r.min),l={paramId:r.paramId,label:r.label,rawValue:n,scaledValue:i,normalizedValue:o};return(c=this.onChange)==null||c.call(this,l),l}setMapping(t,n,r,a="knob"){const o={cc:t,paramId:n,label:r,controlType:a,min:0,max:127,inverted:!1},i=this.profile.mappings.findIndex(l=>l.cc===t);i>=0?this.profile.mappings[i]=o:this.profile.mappings.push(o),this.ccMap.set(t,o)}removeMapping(t){this.profile.mappings=this.profile.mappings.filter(n=>n.cc!==t),this.ccMap.delete(t)}getMappings(){return[...this.profile.mappings]}getMapping(t){return this.ccMap.get(t)}exportConfig(){return{...this.profile,mappings:this.profile.mappings.map(t=>({...t}))}}importConfig(t){this.profile={...t,mappings:t.mappings.map(n=>({...n}))},this.rebuildMap()}static createCustomProfile(t,n){return{id:`custom-${t.toLowerCase().replace(/\s+/g,"-")}`,name:t,deviceMatch:"",mappings:n.map(r=>({...r,min:0,max:127,inverted:!1}))}}rebuildMap(){this.ccMap.clear();for(const t of this.profile.mappings)this.ccMap.set(t.cc,t)}}function ki(e){return{past:[],present:e,future:[]}}function Mi(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function ji(e){if(e.past.length===0)return e;const t=e.past[e.past.length-1];return{past:e.past.slice(0,-1),present:t,future:[e.present,...e.future]}}function Ri(e){if(e.future.length===0)return e;const t=e.future[0];return{past:[...e.past,e.present],present:t,future:e.future.slice(1)}}function $i(e){return e.past.length>0}function Ti(e){return e.future.length>0}function qr(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>({...n}))}function Pi(e,t,n){if(t.length===0)return e;const r=Math.min(...t.map(i=>i.time)),a=n-r,o=t.map(i=>({...i,id:Date.now()+Math.floor(Math.random()*1e4)+i.id,time:i.time+a}));return[...e,...o]}function Ei(e,t){const n=[],r=[];for(const a of e)a.time>=t.start&&a.time<=t.end?n.push({...a}):r.push(a);return{remaining:r,cut:n}}function Ai(e,t){return e.filter(n=>n.time<t.start||n.time>t.end)}function hf(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>n.id)}function Ni(e,t,n,r){const a={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:r};return[...e,a]}function Ii(e,t=3){if(e.length<=2)return e;const n=[...e].sort((a,o)=>a.time-o.time),r=[n[0]];for(let a=1;a<n.length-1;a++)a%t===0&&r.push(n[a]);return r.push(n[n.length-1]),r}function Li(e){return JSON.stringify(e,null,2)}function Fi(e){try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&"id"in n&&"cc"in n&&"value"in n&&"time"in n):[]}catch{return[]}}function rt(e,t){var n;return((n=e.find(r=>r.layerId===t))==null?void 0:n.events)??[]}function mt(e,t,n){return e.find(a=>a.layerId===t)?e.map(a=>a.layerId===t?{...a,events:n}:a):[...e,{layerId:t,events:n}]}function ff(e,t){switch(t.type){case"UNDO":return ji(e);case"REDO":return Ri(e);default:{let n=e.present;switch(t.type){case"ADD_EVENT":{const r=[...rt(n,t.layerId),t.event];n=mt(n,t.layerId,r);break}case"UPDATE_EVENT":{const r=rt(n,t.layerId).map(a=>a.id===t.id?{...a,value:t.value,time:t.time,handleType:t.handleType??a.handleType}:a);n=mt(n,t.layerId,r);break}case"REMOVE_EVENT":{const r=rt(n,t.layerId).filter(a=>a.id!==t.id);n=mt(n,t.layerId,r);break}case"SET_EVENTS":n=mt(n,t.layerId,t.events);break;case"PASTE":{const r=rt(n,t.layerId),a=Pi(r,t.clipboard,t.targetTime);n=mt(n,t.layerId,a);break}case"CUT":{const r=rt(n,t.layerId),{remaining:a}=Ei(r,t.range);n=mt(n,t.layerId,a);break}case"DELETE_RANGE":{const r=rt(n,t.layerId),a=Ai(r,t.range);n=mt(n,t.layerId,a);break}case"RECORD":{const r=rt(n,t.layerId),a=Ni(r,t.cc,t.value,t.time);n=mt(n,t.layerId,a);break}case"THIN":{const r=rt(n,t.layerId),a=Ii(r,t.keepEveryN);n=mt(n,t.layerId,a);break}case"IMPORT":{const r=Fi(t.json);r.length>0&&(n=mt(n,t.layerId,r));break}}return Mi(e,n)}}}function pf(e=[]){const[t,n]=u.useReducer(ff,ki(e)),r=u.useRef([]),a=u.useCallback(y=>rt(t.present,y),[t.present]),o=u.useCallback((y,k)=>n({type:"ADD_EVENT",layerId:y,event:k}),[]),i=u.useCallback((y,k,M,N,R)=>n({type:"UPDATE_EVENT",layerId:y,id:k,value:M,time:N,handleType:R}),[]),l=u.useCallback((y,k)=>n({type:"REMOVE_EVENT",layerId:y,id:k}),[]),c=u.useCallback((y,k)=>n({type:"SET_EVENTS",layerId:y,events:k}),[]),d=u.useCallback(()=>n({type:"UNDO"}),[]),h=u.useCallback(()=>n({type:"REDO"}),[]),f=u.useCallback((y,k)=>{r.current=qr(rt(t.present,y),k)},[t.present]),m=u.useCallback((y,k)=>{r.current=qr(rt(t.present,y),k),n({type:"CUT",layerId:y,range:k})},[t.present]),g=u.useCallback((y,k)=>{r.current.length>0&&n({type:"PASTE",layerId:y,clipboard:r.current,targetTime:k})},[]),p=u.useCallback((y,k)=>n({type:"DELETE_RANGE",layerId:y,range:k}),[]),v=u.useCallback((y,k,M,N)=>n({type:"RECORD",layerId:y,cc:k,value:M,time:N}),[]),x=u.useCallback((y,k)=>n({type:"THIN",layerId:y,keepEveryN:k}),[]),b=u.useCallback(y=>Li(rt(t.present,y)),[t.present]),w=u.useCallback((y,k)=>n({type:"IMPORT",layerId:y,json:k}),[]);return{snapshots:t.present,getEvents:a,addEvent:o,updateEvent:i,removeEvent:l,setEvents:c,undo:d,redo:h,canUndo:$i(t),canRedo:Ti(t),copy:f,cut:m,paste:g,clipboard:r.current,deleteRange:p,record:v,thin:x,exportLane:b,importLane:w}}function wa(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function Nt(e="New Pattern",t=16,n=120){return{name:e,length:t,steps:Array.from({length:t},()=>wa()),bpm:n,swing:0,rootNote:60}}function Di(e,t){const n=e.steps.map((r,a)=>a===t?{...r,active:!r.active}:r);return{...e,steps:n}}function Oi(e,t,n){const r=e.steps.map((a,o)=>o===t?{...a,note:Math.max(0,Math.min(127,n))}:a);return{...e,steps:r}}function _i(e,t,n){const r=e.steps.map((a,o)=>o===t?{...a,velocity:Math.max(0,Math.min(127,n))}:a);return{...e,steps:r}}function zi(e,t,n){const r=e.steps.map((a,o)=>o===t?{...a,gate:Math.max(0,Math.min(1,n))}:a);return{...e,steps:r}}function Gi(e,t,n){const r=e.steps.map((a,o)=>o===t?{...a,probability:Math.max(0,Math.min(1,n))}:a);return{...e,steps:r}}function Bi(e,t){const n=e.steps.map((r,a)=>a===t?{...r,slide:!r.slide}:r);return{...e,steps:n}}function Wi(e,t){const n=e.steps.map(r=>r.active?{...r,note:Math.max(0,Math.min(127,r.note+t))}:r);return{...e,steps:n,rootNote:Math.max(0,Math.min(127,e.rootNote+t))}}function Ui(e){return{...e,steps:[...e.steps].reverse()}}function Vi(e,t){const n=e.steps.length,r=(t%n+n)%n,a=[...e.steps.slice(r),...e.steps.slice(0,r)];return{...e,steps:a}}function qi(e,t=60,n=127){const r=e.steps.map(a=>a.active?{...a,velocity:Math.floor(t+Math.random()*(n-t+1))}:a);return{...e,steps:r}}function Hi(e){return{...e,steps:e.steps.map(()=>wa(e.rootNote))}}function Ca(e,t=4){return 60/e/t}function Ki(e,t,n=0,r=4){const a=Ca(t,r),o=e*a;return e%2===1&&n>0?o+a*n*.5:o}function Yi(e){return e.active&&Math.random()<e.probability}function mf(){const e=Nt("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function gf(){const e=Nt("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function yf(){const e=Nt("Hi-Hat",16);for(let t=0;t<16;t+=2)e.steps[t]={...e.steps[t],active:!0,note:42,velocity:80};return e}function bf(e=60){const t=Nt("Arp",16,120);return[0,4,7,12,7,4,0,-5,0,3,7,12,7,3,0,-5].forEach((r,a)=>{t.steps[a]={...t.steps[a],active:!0,note:e+r,velocity:90,gate:.5}}),{...t,rootNote:e}}function vf(e=36){const t=Nt("Bassline",16,120),n=[0,0,7,0,5,5,3,0,0,0,7,12,5,5,3,0],r=[1,0,1,0,1,0,1,1,1,0,1,1,1,0,1,0];return n.forEach((a,o)=>{t.steps[o]={...t.steps[o],active:!!r[o],note:e+a,velocity:100,gate:.7}}),{...t,rootNote:e}}function xf(e){return JSON.stringify(e,null,2)}function Sf(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function wf(e={}){const{onTrigger:t,onLFOOutput:n,initialPattern:r}=e,[a,o]=u.useState(()=>r??Nt()),[i,l]=u.useState(-1),[c,d]=u.useState(!1),[h,f]=u.useState([]),m=u.useRef(a);m.current=a;const g=u.useRef(h);g.current=h;const p=u.useRef(c);p.current=c;const v=u.useRef(t);v.current=t;const x=u.useRef(n);x.current=n;const b=u.useRef(null),w=u.useRef(0),y=u.useRef(0),k=u.useCallback(()=>{var Q,J;if(!p.current)return;const $=m.current,T=w.current%$.length,C=$.steps[T];if(Yi(C)){const ae=Ki(w.current,$.bpm,$.swing);(Q=v.current)==null||Q.call(v,C,T,ae)}const A=(Date.now()-y.current)/1e3;for(let ae=0;ae<g.current.length;ae++){const re=g.current[ae];if(re.enabled&&re.targetCC!==void 0){const ee=Xr(re,A,$.bpm);(J=x.current)==null||J.call(x,ae,re.targetCC,ee)}}l(T),w.current++;const D=Ca($.bpm)*1e3,V=T%2===0?0:D*$.swing*.5;b.current=setTimeout(k,D+V)},[]),M=u.useCallback(()=>{p.current||(w.current=0,y.current=Date.now(),d(!0),p.current=!0,k())},[k]),N=u.useCallback(()=>{d(!1),p.current=!1,l(-1),b.current&&(clearTimeout(b.current),b.current=null)},[]),R=u.useCallback(()=>{p.current?N():M()},[M,N]);u.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const _=u.useCallback($=>o(T=>Di(T,$)),[]),E=u.useCallback(($,T)=>o(C=>Oi(C,$,T)),[]),U=u.useCallback(($,T)=>o(C=>_i(C,$,T)),[]),W=u.useCallback(($,T)=>o(C=>zi(C,$,T)),[]),j=u.useCallback(($,T)=>o(C=>Gi(C,$,T)),[]),L=u.useCallback($=>o(T=>Bi(T,$)),[]),I=u.useCallback($=>o(T=>Wi(T,$)),[]),q=u.useCallback(()=>o($=>Ui($)),[]),Y=u.useCallback($=>o(T=>Vi(T,$)),[]),O=u.useCallback(($,T)=>o(C=>qi(C,$,T)),[]),Z=u.useCallback(()=>o($=>Hi($)),[]),H=u.useCallback($=>o(T=>({...T,bpm:Math.max(20,Math.min(300,$))})),[]),te=u.useCallback($=>o(T=>({...T,swing:Math.max(0,Math.min(1,$))})),[]),G=u.useCallback($=>{o(T=>{if(T.length===$)return T;const C=Array.from({length:$},(A,D)=>D<T.steps.length?T.steps[D]:{active:!1,note:T.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...T,length:$,steps:C}})},[]),z=u.useCallback($=>{f(T=>[...T,$??ir()])},[]),S=u.useCallback($=>{f(T=>T.filter((C,A)=>A!==$))},[]),P=u.useCallback(($,T)=>{f(C=>C.map((A,D)=>D===$?{...A,...T}:A))},[]);return{pattern:a,currentStep:i,playing:c,lfos:h,play:M,stop:N,togglePlayback:R,toggle:_,setNote:E,setVelocity:U,setGate:W,setProbability:j,toggleSlide:L,transpose:I,reverse:q,shift:Y,randomizeVel:O,clear:Z,setPattern:o,setBpm:H,setSwing:te,setLength:G,addLFO:z,removeLFO:S,updateLFO:P}}function ka(e){const t=u.useRef(null),n=u.useRef(new Map),r=u.useRef(1),a=u.useCallback(()=>{if(!t.current){const i=e();i.onmessage=l=>{const{id:c}=l.data,d=n.current.get(c);d&&(n.current.delete(c),d.resolve(l.data))},i.onerror=l=>{console.error("[useWorker] Worker error:",l.message);for(const[c,d]of n.current)d.reject(new Error(`Worker error: ${l.message}`));n.current.clear(),i.terminate(),t.current=null},t.current=i}return t.current},[e]);return u.useEffect(()=>{const i=n.current;return()=>{var l;(l=t.current)==null||l.terminate(),t.current=null;for(const[,c]of i)c.reject(new Error("Worker terminated on unmount"));i.clear()}},[]),u.useCallback((i,l)=>{const c=r.current++,d=a();return new Promise((h,f)=>{n.current.set(c,{resolve:h,reject:f}),d.postMessage({...i,id:c},l??[])})},[a])}function Cf(){const e=ka(u.useCallback(()=>new Worker(new URL("/assets/pitchWorker-BgAp5Z97.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:st&&st.tagName.toUpperCase()==="SCRIPT"&&st.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return u.useCallback(async(n,r,a=.01)=>(await e({buffer:n,sampleRate:r,rmsThreshold:a})).hz,[e])}function kf(){const e=ka(u.useCallback(()=>new Worker(new URL("/assets/scoringWorker-B1PkYu_m.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:st&&st.tagName.toUpperCase()==="SCRIPT"&&st.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return u.useCallback(async(n,r,a)=>(await e({notes:n,points:r,params:a})).result,[e])}const Mf={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function Zi(){return`
54
54
  /**
55
55
  * NiceAudioProcessor — Main audio analysis processor.
56
56
  */
@@ -409,4 +409,4 @@ E`;case"ultrastarws":return`#TITLE:Analyzed Song
409
409
  E`;default:return`#TITLE:Analyzed Song
410
410
  #ARTIST:AI
411
411
  : 0 2 40 Test
412
- E`}}function np(e,t){return`${e}:${t}`}function rp(e,t,n,r=1){if(t==="off")return e;const a=60/n;if(t==="beat")return Math.round(e/(a/r))*(a/r);if(t==="bar"){const o=a*4;return Math.round(e/o)*o}return e}function ap(e){return e.length===0?[]:e.flat()}function sp(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const Ma=[{id:"mpc-60-tight",name:"MPC 60 Tight",stepsPerBar:16,timingOffsets:[0,.02,0,.01,0,.03,0,.01,0,.02,0,.01,0,.03,0,.01],velocityScales:[1.1,.85,.95,.8,1.05,.85,.9,.8,1.1,.85,.95,.8,1.05,.85,.9,.8],durationScales:[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]},{id:"mpc-60-swing",name:"MPC 60 Swing",stepsPerBar:16,timingOffsets:[0,.06,0,.04,0,.07,0,.04,0,.06,0,.04,0,.07,0,.04],velocityScales:[1.15,.7,.9,.75,1.1,.7,.85,.75,1.15,.7,.9,.75,1.1,.7,.85,.75],durationScales:[1.05,.9,1,.95,1.05,.9,1,.95,1.05,.9,1,.95,1.05,.9,1,.95]},{id:"hip-hop-lazy",name:"Hip-Hop Lazy",stepsPerBar:16,timingOffsets:[0,.04,.01,.05,0,.04,.02,.06,0,.04,.01,.05,0,.04,.02,.06],velocityScales:[1.2,.65,.85,.6,1.1,.65,.8,.6,1.2,.65,.85,.6,1.1,.65,.8,.6],durationScales:[1.1,1,1,.9,1.1,1,1,.9,1.1,1,1,.9,1.1,1,1,.9]},{id:"funk-pocket",name:"Funk Pocket",stepsPerBar:16,timingOffsets:[0,-.01,.03,0,0,-.01,.04,0,0,-.01,.03,0,0,-.01,.04,0],velocityScales:[1.2,.9,.7,1.05,.85,.9,.7,1,1.15,.9,.7,1.05,.85,.9,.7,1],durationScales:[1,.95,1.1,1,1,.95,1.1,1,1,.95,1.1,1,1,.95,1.1,1]},{id:"shuffle-blues",name:"Shuffle / Blues",stepsPerBar:8,timingOffsets:[0,.11,0,.11,0,.11,0,.11],velocityScales:[1.2,.8,1.1,.8,1.2,.8,1.1,.8],durationScales:[1.1,.8,1.1,.8,1.1,.8,1.1,.8]},{id:"reggaeton",name:"Reggaeton",stepsPerBar:16,timingOffsets:[0,0,0,.03,0,0,0,.03,0,0,0,.03,0,0,0,.03],velocityScales:[1.3,.6,.9,1.1,.7,.6,.9,1.1,1.3,.6,.9,1.1,.7,.6,.9,1.1],durationScales:[1,1,1,.9,1,1,1,.9,1,1,1,.9,1,1,1,.9]}];function op(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function ll(e,t){return t.amount===0?e:e.map(n=>{const r=n.time/t.grid;if(Math.round(r)%2===1){const i=t.grid*t.amount*.5;return{...n,time:n.time+i}}return{...n}})}function cl(e,t){const n=t.seed!=null?op(t.seed):Math.random;return e.map(r=>{const a=(n()-.5)*2*t.timingAmount,o=Math.round((n()-.5)*2*t.velocityAmount),i=(n()-.5)*2*t.durationAmount;return{...r,time:Math.max(0,r.time+a),velocity:Math.max(1,Math.min(127,r.velocity+o)),duration:Math.max(.01,r.duration+i)}})}function dl(e,t,n=1){const r=4/t.stepsPerBar;return e.map(a=>{const o=a.time/r,i=Math.round(o)%t.stepsPerBar,l=t.timingOffsets[i]*r*n,c=1+(t.velocityScales[i]-1)*n,d=1+(t.durationScales[i]-1)*n;return{...a,time:Math.max(0,a.time+l),velocity:Math.max(1,Math.min(127,Math.round(a.velocity*c))),duration:Math.max(.01,a.duration*d)}})}function ip(e,t){let n=[...e.map(r=>({...r}))];return t.template&&t.grooveStrength>0&&(n=dl(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=ll(n,t.swing)),t.humanize&&(n=cl(n,t.humanize)),n}function lp(e){return Ma.find(t=>t.id===e)}function cp(){return Ma.map(({id:e,name:t})=>({id:e,name:t}))}const dp=[{type:"chipmunk",enabled:!1,intensity:60,label:"Chipmunk",icon:"🐿️"},{type:"helium",enabled:!1,intensity:80,label:"Helium",icon:"🎈"},{type:"deep",enabled:!1,intensity:50,label:"Deep Voice",icon:"🎸"},{type:"demon",enabled:!1,intensity:70,label:"Demon",icon:"😈"},{type:"robot",enabled:!1,intensity:50,label:"Robot",icon:"🤖"},{type:"alien",enabled:!1,intensity:60,label:"Alien",icon:"👽"},{type:"echo",enabled:!1,intensity:50,label:"Echo",icon:"🏔️"},{type:"cave",enabled:!1,intensity:60,label:"Cave",icon:"🕳️"},{type:"reverb",enabled:!1,intensity:50,label:"Reverb",icon:"⛪"},{type:"chorus",enabled:!1,intensity:50,label:"Chorus",icon:"🎵"},{type:"flanger",enabled:!1,intensity:50,label:"Flanger",icon:"🌊"},{type:"distortion",enabled:!1,intensity:40,label:"Distortion",icon:"🔥"},{type:"telephone",enabled:!1,intensity:80,label:"Telephone",icon:"📞"},{type:"megaphone",enabled:!1,intensity:60,label:"Megaphone",icon:"📢"},{type:"radio",enabled:!1,intensity:70,label:"AM Radio",icon:"📻"},{type:"underwater",enabled:!1,intensity:50,label:"Underwater",icon:"🌊"},{type:"whisper",enabled:!1,intensity:60,label:"Whisper",icon:"🤫"},{type:"tremolo",enabled:!1,intensity:50,label:"Tremolo",icon:"〰️"},{type:"autotune",enabled:!1,intensity:60,label:"Auto-Tune",icon:"🎤"},{type:"vocoder",enabled:!1,intensity:50,label:"Vocoder",icon:"🔊"}];function Ms(e,t,n){const r=e.sampleRate,a=Math.round(r*t),o=e.createBuffer(2,a,r);for(let i=0;i<2;i++){const l=o.getChannelData(i);for(let c=0;c<a;c++)l[c]=(Math.random()*2-1)*Math.pow(1-c/a,n)}return o}function Bn(e){const t=Math.max(1,e),n=44100,r=new Float32Array(n),a=Math.PI/180;for(let o=0;o<n;o++){const i=o*2/n-1;r[o]=(3+t)*i*20*a/(Math.PI+t*Math.abs(i))}return r}class up{constructor(){this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.activeEffects=new Map,this.effectOrder=[],this.monitoring=!0,this._volume=1,this._inputVolume=1,this.started=!1,this.externalStream=!1,this.analyser=null}get isStarted(){return this.started}get context(){return this.audioCtx}get activeEffectTypes(){return[...this.effectOrder]}async start(t){this.started||(this.audioCtx=new AudioContext,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),this.sourceNode=this.audioCtx.createMediaStreamSource(this.mediaStream),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}async startWithStream(t){this.started||(this.externalStream=!0,this.audioCtx=new AudioContext,this.mediaStream=t,this.sourceNode=this.audioCtx.createMediaStreamSource(t),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}stop(){var t,n,r,a,o,i;this.clearAllEffects();try{(t=this.analyser)==null||t.disconnect()}catch{}try{(n=this.outputGain)==null||n.disconnect()}catch{}try{(r=this.inputGain)==null||r.disconnect()}catch{}try{(a=this.sourceNode)==null||a.disconnect()}catch{}try{(o=this.audioCtx)==null||o.close()}catch{}if(!this.externalStream)try{(i=this.mediaStream)==null||i.getTracks().forEach(l=>l.stop())}catch{}this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.analyser=null,this.started=!1}setMonitoring(t){this.monitoring=t,this.outputGain&&(this.outputGain.gain.value=t?this._volume:0)}setVolume(t){this._volume=Math.max(0,Math.min(2,t)),this.outputGain&&this.monitoring&&(this.outputGain.gain.value=this._volume)}setInputGain(t){this._inputVolume=Math.max(0,Math.min(3,t)),this.inputGain&&(this.inputGain.gain.value=this._inputVolume)}getLevel(){if(!this.analyser)return 0;const t=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(t);let n=0;for(let r=0;r<t.length;r++){const a=(t[r]-128)/128;n+=a*a}return Math.sqrt(n/t.length)}addEffect(t,n=50){if(!this.audioCtx||!this.inputGain||!this.outputGain||this.activeEffects.has(t))return;const r=this.buildEffectChain(t,n);r&&(this.activeEffects.set(t,r),this.effectOrder.push(t),this.reconnectChain())}removeEffect(t){const n=this.activeEffects.get(t);if(n){for(const r of n.nodes)try{r.disconnect()}catch{}this.activeEffects.delete(t),this.effectOrder=this.effectOrder.filter(r=>r!==t),this.reconnectChain()}}toggleEffect(t,n=50){return this.activeEffects.has(t)?(this.removeEffect(t),!1):(this.addEffect(t,n),!0)}updateIntensity(t,n){this.activeEffects.has(t)&&(this.removeEffect(t),this.addEffect(t,n))}clearAllEffects(){for(const[t]of this.activeEffects){const n=this.activeEffects.get(t);if(n)for(const r of n.nodes)try{r.disconnect()}catch{}}this.activeEffects.clear(),this.effectOrder=[],this.reconnectChain()}reconnectChain(){if(!this.inputGain||!this.outputGain)return;try{this.inputGain.disconnect()}catch{}for(const[,n]of this.activeEffects)try{n.output.disconnect()}catch{}if(this.effectOrder.length===0){this.inputGain.connect(this.outputGain);return}let t=this.inputGain;for(const n of this.effectOrder){const r=this.activeEffects.get(n);r&&(t.connect(r.input),t=r.output)}t.connect(this.outputGain)}buildEffectChain(t,n){const r=this.audioCtx,a=n/100;switch(t){case"chipmunk":return this.buildPitchShift(r,1+a*.8,a);case"helium":return this.buildPitchShift(r,1.5+a*1,a);case"deep":return this.buildPitchShift(r,1/(1+a*.5),a);case"demon":return this.buildDemon(r,a);case"robot":return this.buildRobot(r,a);case"alien":return this.buildAlien(r,a);case"echo":return this.buildDelay(r,.15+a*.35,.3+a*.4,a);case"cave":return this.buildCave(r,a);case"reverb":return this.buildReverb(r,1.5+a*3,2+a*4,a);case"chorus":return this.buildChorus(r,a);case"flanger":return this.buildFlanger(r,a);case"distortion":return this.buildDistortion(r,20+a*100,a);case"telephone":return this.buildBandpass(r,400,3500,a);case"megaphone":return this.buildMegaphone(r,a);case"radio":return this.buildRadio(r,a);case"underwater":return this.buildUnderwater(r,a);case"whisper":return this.buildWhisper(r,a);case"tremolo":return this.buildTremolo(r,a);case"autotune":return this.buildAutotune(r,a);case"vocoder":return this.buildVocoder(r,a);default:return null}}buildPitchShift(t,n,r){const a=t.createGain();a.gain.value=1;const o=t.createGain();o.gain.value=1;const i=t.createGain();i.gain.value=.7+r*.3;const l=t.createGain();l.gain.value=1-r*.5;const c=t.createDelay(1),d=t.createDelay(1),h=t.createOscillator(),f=t.createOscillator(),m=t.createGain(),g=t.createGain(),p=n-1,v=Math.abs(p)*5+2,x=Math.abs(p)*.015;h.type="sawtooth",h.frequency.value=v,m.gain.value=x,h.connect(m),m.connect(c.delayTime),c.delayTime.value=.02,f.type="sawtooth",f.frequency.value=v,g.gain.value=x,f.connect(g),g.connect(d.delayTime),d.delayTime.value=.02+x;const b=t.createGain();b.gain.value=.5;const w=t.createGain();return w.gain.value=.5,a.connect(c),a.connect(d),c.connect(b),d.connect(w),b.connect(i),w.connect(i),a.connect(l),i.connect(o),l.connect(o),h.start(),f.start(),{type:"chipmunk",nodes:[a,c,d,h,f,m,g,b,w,i,l,o],input:a,output:o}}buildRobot(t,n){const r=t.createGain(),a=t.createGain(),o=t.createGain();o.gain.value=.6+n*.4;const i=t.createGain();i.gain.value=1-n*.6;const l=t.createOscillator();l.type="square",l.frequency.value=50+n*200;const c=t.createGain();return c.gain.value=0,l.connect(c.gain),r.connect(c),c.connect(o),r.connect(i),o.connect(a),i.connect(a),l.start(),{type:"robot",nodes:[r,l,c,o,i,a],input:r,output:a}}buildAlien(t,n){const r=t.createGain(),a=t.createGain(),o=t.createOscillator();o.type="sine",o.frequency.value=300+n*700;const i=t.createGain();i.gain.value=0,o.connect(i.gain),r.connect(i);const l=t.createDelay(.1);l.delayTime.value=.005;const c=t.createOscillator();c.type="sine",c.frequency.value=3+n*10;const d=t.createGain();d.gain.value=.004,c.connect(d),d.connect(l.delayTime),i.connect(l),l.connect(a);const h=t.createGain();return h.gain.value=.3,r.connect(h),h.connect(a),o.start(),c.start(),{type:"alien",nodes:[r,o,i,l,c,d,h,a],input:r,output:a}}buildDelay(t,n,r,a){const o=t.createGain(),i=t.createGain(),l=t.createDelay(2);l.delayTime.value=n;const c=t.createGain();c.gain.value=Math.min(.85,r);const d=t.createGain();d.gain.value=.5+a*.5;const h=t.createGain();return h.gain.value=1,o.connect(l),l.connect(c),c.connect(l),l.connect(d),o.connect(h),d.connect(i),h.connect(i),{type:"echo",nodes:[o,l,c,d,h,i],input:o,output:i}}buildCave(t,n){const r=t.createGain(),a=t.createGain(),o=t.createDelay(2);o.delayTime.value=.2+n*.3;const i=t.createDelay(2);i.delayTime.value=.35+n*.25;const l=t.createDelay(2);l.delayTime.value=.55+n*.3;const c=t.createGain();c.gain.value=.5;const d=t.createGain();d.gain.value=.35;const h=t.createGain();h.gain.value=.25;const f=t.createConvolver();f.buffer=Ms(t,2+n*3,3);const m=t.createGain();m.gain.value=.3+n*.3,r.connect(o),o.connect(c),c.connect(o),r.connect(i),i.connect(d),d.connect(i),r.connect(l),l.connect(h),h.connect(l),o.connect(m),i.connect(m),l.connect(m),r.connect(f),f.connect(m);const g=t.createGain();return g.gain.value=.7,r.connect(g),g.connect(a),m.connect(a),{type:"cave",nodes:[r,o,i,l,c,d,h,f,m,g,a],input:r,output:a}}buildReverb(t,n,r,a){const o=t.createGain(),i=t.createGain(),l=t.createConvolver();l.buffer=Ms(t,n,r);const c=t.createGain();c.gain.value=.4+a*.5;const d=t.createGain();return d.gain.value=1,o.connect(l),l.connect(c),o.connect(d),c.connect(i),d.connect(i),{type:"reverb",nodes:[o,l,c,d,i],input:o,output:i}}buildChorus(t,n){const r=t.createGain(),a=t.createGain(),o=[{delayMs:20,lfoFreq:.5,depth:.003},{delayMs:25,lfoFreq:.7,depth:.004},{delayMs:30,lfoFreq:1.1,depth:.005}],i=[r,a],l=t.createGain();l.gain.value=.7,r.connect(l),l.connect(a),i.push(l);for(const c of o){const d=t.createDelay(.1);d.delayTime.value=c.delayMs/1e3;const h=t.createOscillator();h.type="sine",h.frequency.value=c.lfoFreq;const f=t.createGain();f.gain.value=c.depth*(.5+n),h.connect(f),f.connect(d.delayTime);const m=t.createGain();m.gain.value=.3+n*.2,r.connect(d),d.connect(m),m.connect(a),h.start(),i.push(d,h,f,m)}return{type:"chorus",nodes:i,input:r,output:a}}buildFlanger(t,n){const r=t.createGain(),a=t.createGain(),o=t.createDelay(.02);o.delayTime.value=.005;const i=t.createOscillator();i.type="sine",i.frequency.value=.2+n*2;const l=t.createGain();l.gain.value=.003+n*.002,i.connect(l),l.connect(o.delayTime);const c=t.createGain();c.gain.value=.5+n*.35;const d=t.createGain();d.gain.value=.5+n*.3;const h=t.createGain();return h.gain.value=1,r.connect(o),o.connect(c),c.connect(o),o.connect(d),r.connect(h),d.connect(a),h.connect(a),i.start(),{type:"flanger",nodes:[r,o,i,l,c,d,h,a],input:r,output:a}}buildDistortion(t,n,r){const a=t.createGain(),o=t.createGain(),i=t.createWaveShaper();i.curve=Bn(n),i.oversample="4x";const l=t.createGain();l.gain.value=.6+r*.4;const c=t.createGain();return c.gain.value=1-r*.4,a.connect(i),i.connect(l),a.connect(c),l.connect(o),c.connect(o),{type:"distortion",nodes:[a,i,l,c,o],input:a,output:o}}buildBandpass(t,n,r,a){const o=t.createGain(),i=t.createGain(),l=t.createBiquadFilter();l.type="highpass",l.frequency.value=n,l.Q.value=.7;const c=t.createBiquadFilter();return c.type="lowpass",c.frequency.value=r,c.Q.value=.7,o.connect(l),l.connect(c),c.connect(i),{type:"telephone",nodes:[o,l,c,i],input:o,output:i}}buildMegaphone(t,n){const r=t.createGain(),a=t.createGain(),o=t.createBiquadFilter();o.type="highpass",o.frequency.value=500;const i=t.createBiquadFilter();i.type="lowpass",i.frequency.value=4e3;const l=t.createWaveShaper();l.curve=Bn(15+n*30),l.oversample="2x";const c=t.createBiquadFilter();return c.type="peaking",c.frequency.value=2e3,c.gain.value=6+n*6,c.Q.value=1,r.connect(o),o.connect(i),i.connect(l),l.connect(c),c.connect(a),{type:"megaphone",nodes:[r,o,i,l,c,a],input:r,output:a}}buildRadio(t,n){const r=t.createGain(),a=t.createGain(),o=t.createBiquadFilter();o.type="highpass",o.frequency.value=300+n*200;const i=t.createBiquadFilter();i.type="lowpass",i.frequency.value=3e3-n*500;const l=t.createBiquadFilter();l.type="peaking",l.frequency.value=1500,l.gain.value=8,l.Q.value=2;const c=t.createWaveShaper();return c.curve=Bn(10),r.connect(o),o.connect(i),i.connect(l),l.connect(c),c.connect(a),{type:"radio",nodes:[r,o,i,l,c,a],input:r,output:a}}buildUnderwater(t,n){const r=t.createGain(),a=t.createGain(),o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=300+(1-n)*400,o.Q.value=5+n*10;const i=t.createOscillator();i.type="sine",i.frequency.value=.5+n*2;const l=t.createGain();l.gain.value=100+n*200,i.connect(l),l.connect(o.frequency);const c=t.createGain();c.gain.value=.7+n*.3;const d=t.createGain();return d.gain.value=.3-n*.2,r.connect(o),o.connect(c),r.connect(d),c.connect(a),d.connect(a),i.start(),{type:"underwater",nodes:[r,o,i,l,c,d,a],input:r,output:a}}buildWhisper(t,n){const r=t.createGain(),a=t.createGain(),o=t.createBiquadFilter();o.type="highpass",o.frequency.value=500+n*500,o.Q.value=.5;const i=t.createWaveShaper(),l=new Float32Array(256);for(let d=0;d<256;d++){const h=d/255*2-1;l[d]=Math.sign(h)*Math.pow(Math.abs(h),.3+n*.5)}i.curve=l;const c=t.createBiquadFilter();return c.type="highshelf",c.frequency.value=3e3,c.gain.value=6+n*6,r.connect(o),o.connect(i),i.connect(c),c.connect(a),{type:"whisper",nodes:[r,o,i,c,a],input:r,output:a}}buildDemon(t,n){const r=t.createGain(),a=t.createGain(),o=t.createDelay(.1);o.delayTime.value=.03;const i=t.createOscillator();i.type="sawtooth",i.frequency.value=2+n*3;const l=t.createGain();l.gain.value=.02+n*.015,i.connect(l),l.connect(o.delayTime);const c=t.createWaveShaper();c.curve=Bn(20+n*50),c.oversample="2x";const d=t.createBiquadFilter();d.type="lowshelf",d.frequency.value=200,d.gain.value=8+n*8;const h=t.createGain();h.gain.value=.7+n*.3;const f=t.createGain();return f.gain.value=.3,r.connect(o),o.connect(c),c.connect(d),d.connect(h),r.connect(f),h.connect(a),f.connect(a),i.start(),{type:"demon",nodes:[r,o,i,l,c,d,h,f,a],input:r,output:a}}buildTremolo(t,n){const r=t.createGain(),a=t.createGain(),o=t.createGain();o.gain.value=1;const i=t.createOscillator();i.type="sine",i.frequency.value=3+n*12;const l=t.createGain();return l.gain.value=.3+n*.5,i.connect(l),l.connect(o.gain),r.connect(o),o.connect(a),i.start(),{type:"tremolo",nodes:[r,o,i,l,a],input:r,output:a}}buildAutotune(t,n){const r=t.createGain(),a=t.createGain(),o=t.createDelay(.05);o.delayTime.value=.005;const i=t.createOscillator();i.type="sine",i.frequency.value=6+n*8;const l=t.createGain();l.gain.value=.002+n*.002,i.connect(l),l.connect(o.delayTime);const c=[],d=[261.6,293.7,329.6,349.2,392,440,493.9,523.3],h=t.createGain();h.gain.value=.15;for(const g of d){const p=t.createBiquadFilter();p.type="peaking",p.frequency.value=g,p.Q.value=8+n*15,p.gain.value=4+n*8,r.connect(p),p.connect(h),c.push(p)}const f=t.createGain();f.gain.value=.7;const m=t.createGain();return m.gain.value=.5+n*.3,r.connect(o),o.connect(m),h.connect(m),r.connect(f),m.connect(a),f.connect(a),i.start(),{type:"autotune",nodes:[r,o,i,l,...c,h,m,f,a],input:r,output:a}}buildVocoder(t,n){const r=t.createGain(),a=t.createGain(),o=t.createOscillator();o.type="sawtooth",o.frequency.value=110+n*110;const i=t.createGain();i.gain.value=0;const l=8,c=[r,a,o,i],d=t.createGain();d.gain.value=.5+n*.5,c.push(d);for(let f=0;f<l;f++){const m=200*Math.pow(2,f*.5),g=t.createBiquadFilter();g.type="bandpass",g.frequency.value=m,g.Q.value=4;const p=t.createBiquadFilter();p.type="bandpass",p.frequency.value=m,p.Q.value=4;const v=t.createGain();v.gain.value=0,r.connect(g),g.connect(v.gain),o.connect(p),p.connect(v),v.connect(d),c.push(g,p,v)}d.connect(a);const h=t.createGain();return h.gain.value=.3-n*.2,r.connect(h),h.connect(a),c.push(h),o.start(),{type:"vocoder",nodes:c,input:r,output:a}}}const ul=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Ut(e){return 12*Math.log2(e/440)+69}function Wn(e){const t=ul[Math.round(e)%12],n=Math.floor(Math.round(e)/12)-1;return`${t}${n}`}function $r(e,t){if(e.length===0)return 0;const n=t/100*(e.length-1),r=Math.floor(n),a=Math.ceil(n);return r===a?e[r]:e[r]+(e[a]-e[r])*(n-r)}function hp(e){const{playerName:t,playerColor:n,songTitle:r,songArtist:a,songBpm:o,difficulty:i,pitchPoints:l,notes:c,verseRatings:d,combo:h,classicScore:f,bonusScore:m,totalScore:g,micSettings:p}=e,v=l.filter(ne=>ne.hz>0),x=v.map(ne=>Ut(ne.hz)),b=[],w=[],y=[],k=[...c].sort((ne,oe)=>ne.startTime-oe.startTime);function M(ne){let oe=0,Ne=k.length-1;for(;oe<=Ne;){const De=oe+Ne>>>1,Pe=k[De];if(ne<Pe.startTime)Ne=De-1;else if(ne>Pe.startTime+Pe.duration)oe=De+1;else return Pe.pitch}return 0}for(const ne of l){const oe=ne.hz>0?Ut(ne.hz):0,Ne=M(ne.t);if(w.push({t:ne.t,sung:oe,expected:Ne}),oe>0&&Ne>0){const De=(oe-Ne)*100;b.push(De)}}let N=0;for(const ne of k){const oe=ne.startTime-.3,Ne=ne.startTime+ne.duration;for(;N<v.length&&v[N].t<oe;)N++;N<v.length&&v[N].t<=Ne&&y.push((v[N].t-ne.startTime)*1e3)}const R=b.map(Math.abs),_=[...R].sort((ne,oe)=>ne-oe),E=R.length>0?R.reduce((ne,oe)=>ne+oe,0)/R.length:0,U=$r(_,50),W=R.length>1?Math.sqrt(R.reduce((ne,oe)=>ne+(oe-E)**2,0)/(R.length-1)):0,j=R.filter(ne=>ne<=50).length,L=R.filter(ne=>ne<=15).length,I=R.length>0?j/R.length*100:0,q=R.length>0?L/R.length*100:0,Y=["< −100","−100 to −50","−50 to −25","−25 to −15","−15 to 0","0 to +15","+15 to +25","+25 to +50","+50 to +100","> +100"],O=new Array(10).fill(0);for(const ne of b){const oe=ne<-100?0:ne<-50?1:ne<-25?2:ne<-15?3:ne<0?4:ne<15?5:ne<25?6:ne<50?7:ne<100?8:9;O[oe]++}const Z=Y.map((ne,oe)=>({centRange:ne,count:O[oe],pct:b.length>0?O[oe]/b.length*100:0})),H=v.map(ne=>ne.hz).sort((ne,oe)=>ne-oe),te=H.length>0?H[0]:0,G=H.length>0?H[H.length-1]:0,z=te>0?Ut(te):0,S=G>0?Ut(G):0,P=S-z,$=[...x].sort((ne,oe)=>ne-oe),T=$r($,10),C=$r($,90),A=new Array(12).fill(0);for(const ne of x){const oe=Math.round(ne)%12;oe>=0&&oe<12&&A[oe]++}const D=A.reduce((ne,oe)=>ne+oe,0),V=ul.map((ne,oe)=>({note:ne,count:A[oe],pct:D>0?A[oe]/D*100:0})),Q=fp(v),J=y.length>0?y.reduce((ne,oe)=>ne+oe,0)/y.length:0,ae=y.length>1?Math.sqrt(y.reduce((ne,oe)=>ne+(oe-J)**2,0)/(y.length-1)):0,re=ae>0?Math.max(0,Math.min(100,100-ae/2)):100;let ee=0,F=0;for(let ne=1;ne<x.length;ne++){const oe=Math.abs(x[ne]-x[ne-1]);ee+=oe,F++}const K=F>0?ee/F*100/12:0,se=l.filter(ne=>ne.hz<=0).length,ce=l.length>0?(1-se/l.length)*100:0,fe=new Map;for(const ne of c){const oe=ne.line??0;fe.has(oe)||fe.set(oe,[]),fe.get(oe).push(ne)}const X=new Map;for(const ne of v){const oe=M(ne.t);if(oe<=0)continue;let Ne=0,De=k.length-1,Pe=-1;for(;Ne<=De;){const we=Ne+De>>>1,dt=k[we];if(ne.t<dt.startTime)De=we-1;else if(ne.t>dt.startTime+dt.duration)Ne=we+1;else{Pe=dt.line??0;break}}if(Pe<0)continue;const tt=Math.abs((Ut(ne.hz)-oe)*100);X.has(Pe)||X.set(Pe,[]),X.get(Pe).push(tt)}const ue=d.map(ne=>{const oe=fe.get(ne.verseIndex)??[],Ne=X.get(ne.verseIndex)??[],De=Ne.length>0?Ne.reduce((Pe,tt)=>Pe+tt,0)/Ne.length:0;return{verseIndex:ne.verseIndex,label:ne.label,hitFraction:ne.hitFraction,avgCentDeviation:Math.round(De*10)/10,noteCount:oe.length,notesHit:Math.round(ne.hitFraction*oe.length),comboBonus:ne.comboBonus}}),ye=2,je=.5,Fe=l.length>0?l[l.length-1].t:0,Re=[],Se=w.filter(ne=>ne.sung>0&&ne.expected>0);if(Se.length>0){let ne=0,oe=0,Ne=0;for(let De=0;De<=Fe;De+=je){const Pe=De-ye/2,tt=De+ye/2;for(;oe<Se.length&&Se[oe].t<tt;)Math.abs(Se[oe].sung-Se[oe].expected)<=.5&&Ne++,oe++;for(;ne<oe&&Se[ne].t<Pe;)Math.abs(Se[ne].sung-Se[ne].expected)<=.5&&Ne--,ne++;const we=oe-ne;Re.push({t:De,accuracy:we>0?Ne/we*100:0})}}else for(let ne=0;ne<=Fe;ne+=je)Re.push({t:ne,accuracy:0});return{playerName:t,playerColor:n,songTitle:r,songArtist:a,songBpm:o,difficulty:i,timestamp:new Date().toISOString(),classicScore:f,bonusScore:m,totalScore:g,maxCombo:(h==null?void 0:h.maxCombo)??0,totalComboBonus:(h==null?void 0:h.totalComboBonus)??0,totalPitchPoints:l.length,avgCentDeviation:Math.round(E*10)/10,medianCentDeviation:Math.round(U*10)/10,stdDevCents:Math.round(W*10)/10,intonationAccuracyPct:Math.round(I*10)/10,perfectHitPct:Math.round(q*10)/10,pitchDeviationHistogram:Z,lowestHz:Math.round(te*10)/10,highestHz:Math.round(G*10)/10,lowestNote:z>0?Wn(z):"—",highestNote:S>0?Wn(S):"—",rangeInSemitones:Math.round(P*10)/10,tessituraLow:T>0?Wn(T):"—",tessituraHigh:C>0?Wn(C):"—",pitchClassDistribution:V,vibrato:Q,avgOnsetDeviationMs:Math.round(J*10)/10,rhythmStabilityPct:Math.round(re*10)/10,jitterPct:Math.round(K*100)/100,shimmerProxy:Math.round(ce*10)/10,verseMetrics:ue,micSettings:p,pitchOverTime:w,accuracyOverTime:Re}}function fp(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(g=>Ut(g.hz)),n=e.map(g=>g.t),r=.5,a=[],o=[];let i=0,l=0,c=0;for(let g=0;g<e.length;g++){for(l+=t[g],c++;i<g&&n[g]-n[i]>=r;)l-=t[i],c--,i++;if(c<6||(g-i)%10!==0)continue;const p=l/c;let v=0,x=t[i]-p,b=Math.abs(x);for(let k=i+1;k<=g;k++){const M=t[k]-p;M*x<0&&v++,x=M;const N=Math.abs(M);N>b&&(b=N)}const w=n[g]-n[i];if(w<=0)continue;const y=v/2/w;y>=3&&y<=12&&(a.push(y),o.push(b*100))}if(a.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const d=a.reduce((g,p)=>g+p,0)/a.length,h=o.reduce((g,p)=>g+p,0)/o.length,f=Math.sqrt(a.reduce((g,p)=>g+(p-d)**2,0)/a.length),m=Math.max(0,Math.min(100,100-f*20));return{detected:!0,avgRateHz:Math.round(d*10)/10,avgExtentCents:Math.round(h*10)/10,regularityPct:Math.round(m)}}function hl(e,t,n=50,r=30){const a=Math.round(e/1e3*t),o=Math.round(n/1e3*t),i=Math.max(1,Math.round(r/1e3*t)),l=new Float32Array(a);for(let c=0;c<i;c++){const d=.5*(1-Math.cos(2*Math.PI*c/(i-1))),h=o+c-Math.floor(i/2);h>=0&&h<a&&(l[h]=d)}return l}function js(e,t,n=1e3){const r=Math.max(1,Math.round(t/n)),a=Math.ceil(e.length/r),o=new Float32Array(a);for(let l=0;l<a;l++){const c=l*r,d=Math.min(e.length,c+r);let h=0;for(let f=c;f<d;f++)h+=Math.abs(e[f]);o[l]=h/(d-c||1)}let i=0;for(let l=0;l<o.length;l++)o[l]>i&&(i=o[l]);if(i>0)for(let l=0;l<o.length;l++)o[l]=o[l]/i;return{env:o,factor:r}}function pp(e,t){const n=e.length,r=t.length;if(n===0||r===0)return 0;let a={lag:0,score:-1/0};const o=Math.min(2e3,r);for(let i=-o;i<=o;i++){let l=0,c=0,d=0;for(let m=0;m<n;m++){const g=m+i+Math.floor((r-n)/2);if(g<0||g>=r)continue;const p=e[m],v=t[g];l+=p*v,c+=p*p,d+=v*v}const h=Math.sqrt(Math.max(1e-9,c*d)),f=l/h;f>a.score&&(a={lag:i,score:f})}return a.lag}function mp(e,t,n=50,r=30){try{const a=Math.max(300,Math.round(e.length/t*1e3)),o=hl(a,t,n,r),i=js(e,t,1e3),l=js(o,t,1e3),d=pp(l.env,i.env)*1e3/1e3;return Math.round(d)}catch{return null}}function fl(e){switch(e){case"1/4":return 1;case"1/8":return .5;case"1/16":return .25;case"1/32":return .125;case"1/4T":return 2/3;case"1/8T":return 1/3;case"1/16T":return 1/6}}function ja(e,t){return fl(e)*60/t}function Hr(e,t,n){const r=ja(t,n);return Math.round(e/r)*r}function gp(e,t){const{value:n,bpm:r,strength:a=1,quantizeStarts:o=!0,quantizeDurations:i=!1}=t,l=ja(n,r);return e.map(c=>{let{start:d,duration:h}=c;if(o){const f=Math.round(d/l)*l;d=d+(f-d)*a}if(i){const f=Math.max(l,Math.round(h/l)*l);h=h+(f-h)*a}return d===c.start&&h===c.duration?c:{...c,start:d,duration:h}})}function yp(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function bp(e,t={}){const{timingRange:n=.02,velocityRange:r=10,seed:a}=t,o=a!=null?yp(a):Math.random;return e.map(i=>{const l=(o()*2-1)*n,c=Math.round((o()*2-1)*r);return{...i,start:Math.max(0,i.start+l),velocity:i.velocity!=null?Math.max(1,Math.min(127,(i.velocity??100)+c)):void 0}})}function vp(){return{start:0,end:0,enabled:!1}}function xp(e,t){return{...e<t?{start:e,end:t}:{start:t,end:e},enabled:!0}}function Sp(e,t,n){return{start:Hr(e.start,t,n),end:Hr(e.end,t,n),enabled:e.enabled}}function wp(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function Cp(e,t){if(!t.enabled||t.end<=t.start||e<t.start)return e;if(e>=t.end){const n=t.end-t.start;return t.start+(e-t.start)%n}return e}function Kr(e){return e.length===1?e.toLowerCase():e}function Yn(e){var n,r,a,o;const t=[];return(n=e.modifiers)!=null&&n.ctrl&&t.push("Ctrl"),(r=e.modifiers)!=null&&r.shift&&t.push("Shift"),(a=e.modifiers)!=null&&a.alt&&t.push("Alt"),(o=e.modifiers)!=null&&o.meta&&t.push("Meta"),t.push(Kr(e.key)),t.join("+")}function kp(e,t){var l,c,d,h;const n=Kr(e.key)===Kr(t.key),r=!!e.ctrlKey==!!((l=t.modifiers)!=null&&l.ctrl),a=!!e.shiftKey==!!((c=t.modifiers)!=null&&c.shift),o=!!e.altKey==!!((d=t.modifiers)!=null&&d.alt),i=!!e.metaKey==!!((h=t.modifiers)!=null&&h.meta);return n&&r&&a&&o&&i}class pl{constructor(){this.actions=new Map,this.activeScopes=new Set(["global"]),this.enabled=!0,this.listener=null}register(t){this.actions.set(t.id,{...t,enabled:t.enabled??!0})}unregister(t){this.actions.delete(t)}rebind(t,n){const r=this.actions.get(t);r&&(r.binding=n)}setActiveScopes(t){this.activeScopes.clear(),this.activeScopes.add("global");for(const n of t)this.activeScopes.add(n)}setEnabled(t){this.enabled=t}setActionEnabled(t,n){const r=this.actions.get(t);r&&(r.enabled=n)}findConflicts(){const t=[],n=[...this.actions.values()];for(let r=0;r<n.length;r++)for(let a=r+1;a<n.length;a++){const o=n[r],i=n[a];Yn(o.binding)===Yn(i.binding)&&(o.scope===i.scope||o.scope==="global"||i.scope==="global")&&t.push([o,i])}return t}getGrouped(){const t={};for(const n of this.actions.values())t[n.group]||(t[n.group]=[]),t[n.group].push(n);return t}getAll(){return[...this.actions.values()]}exportConfig(){return[...this.actions.values()].map(t=>({id:t.id,binding:t.binding}))}importConfig(t){for(const n of t)this.rebind(n.id,n.binding)}formatBinding(t){const n=this.actions.get(t);return n?Yn(n.binding):""}handleKeyDown(t){if(!this.enabled)return!1;for(const n of this.actions.values())if(n.enabled&&this.activeScopes.has(n.scope)&&kp(t,n.binding))return t.preventDefault(),t.stopPropagation(),n.callback(),!0;return!1}attach(){this.listener||(this.listener=t=>{const n=t.target;n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable||this.handleKeyDown(t)},window.addEventListener("keydown",this.listener,!0))}detach(){this.listener&&(window.removeEventListener("keydown",this.listener,!0),this.listener=null)}destroy(){this.detach(),this.actions.clear()}}function Mp(e={}){const t=new pl,n=()=>{},r=[{id:"transport.play",label:"Play / Pause",group:"Transport",scope:"global",binding:{key:" "}},{id:"transport.stop",label:"Stop",group:"Transport",scope:"global",binding:{key:"Escape"}},{id:"transport.record",label:"Record",group:"Transport",scope:"global",binding:{key:"r",modifiers:{ctrl:!0}}},{id:"transport.rewind",label:"Rewind",group:"Transport",scope:"global",binding:{key:"Home"}},{id:"transport.forward",label:"Forward",group:"Transport",scope:"global",binding:{key:"End"}},{id:"transport.loopToggle",label:"Toggle Loop",group:"Transport",scope:"global",binding:{key:"l"}},{id:"edit.undo",label:"Undo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0}}},{id:"edit.redo",label:"Redo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0,shift:!0}}},{id:"edit.cut",label:"Cut",group:"Edit",scope:"editor",binding:{key:"x",modifiers:{ctrl:!0}}},{id:"edit.copy",label:"Copy",group:"Edit",scope:"editor",binding:{key:"c",modifiers:{ctrl:!0}}},{id:"edit.paste",label:"Paste",group:"Edit",scope:"editor",binding:{key:"v",modifiers:{ctrl:!0}}},{id:"edit.delete",label:"Delete",group:"Edit",scope:"editor",binding:{key:"Delete"}},{id:"edit.selectAll",label:"Select All",group:"Edit",scope:"editor",binding:{key:"a",modifiers:{ctrl:!0}}},{id:"edit.duplicate",label:"Duplicate",group:"Edit",scope:"editor",binding:{key:"d",modifiers:{ctrl:!0}}},{id:"view.zoomIn",label:"Zoom In",group:"View",scope:"global",binding:{key:"=",modifiers:{ctrl:!0}}},{id:"view.zoomOut",label:"Zoom Out",group:"View",scope:"global",binding:{key:"-",modifiers:{ctrl:!0}}},{id:"view.zoomFit",label:"Zoom to Fit",group:"View",scope:"global",binding:{key:"0",modifiers:{ctrl:!0}}},{id:"view.toggleMixer",label:"Toggle Mixer",group:"View",scope:"global",binding:{key:"m"}},{id:"view.togglePianoRoll",label:"Toggle Piano Roll",group:"View",scope:"global",binding:{key:"p"}},{id:"pianoRoll.quantize",label:"Quantize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"q"}},{id:"pianoRoll.humanize",label:"Humanize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"h"}},{id:"pianoRoll.velocityUp",label:"Velocity +10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{shift:!0}}},{id:"pianoRoll.velocityDown",label:"Velocity -10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{shift:!0}}},{id:"pianoRoll.octaveUp",label:"Octave Up",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{ctrl:!0,shift:!0}}},{id:"pianoRoll.octaveDown",label:"Octave Down",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{ctrl:!0,shift:!0}}},{id:"timeline.split",label:"Split at Cursor",group:"Timeline",scope:"timeline",binding:{key:"s"}},{id:"timeline.mute",label:"Mute Track",group:"Timeline",scope:"timeline",binding:{key:"m",modifiers:{ctrl:!0}}},{id:"timeline.solo",label:"Solo Track",group:"Timeline",scope:"timeline",binding:{key:"s",modifiers:{ctrl:!0}}},{id:"timeline.addTrack",label:"Add Track",group:"Timeline",scope:"timeline",binding:{key:"t",modifiers:{ctrl:!0}}},{id:"mixer.resetFader",label:"Reset Fader",group:"Mixer",scope:"mixer",binding:{key:"0"}},{id:"mixer.bypassFx",label:"Bypass All FX",group:"Mixer",scope:"mixer",binding:{key:"b"}}];for(const a of r)t.register({...a,callback:e[a.id]??n});return t}function jp(e){return Yn(e)}const Rp=["audio/mpeg","audio/wav","audio/ogg","audio/flac","audio/aac","audio/webm","audio/mp4","audio/x-m4a","audio/x-wav","audio/x-aiff","audio/aiff","audio/midi","audio/x-midi"],$p=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],Tp=500*1024*1024,Pp=20;function jt(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function Ep(e,t){return!!(e.type&&t.some(n=>e.type.startsWith(n.replace("*","")))||e.type.startsWith("audio/"))}function Ap(e,t){const n=jt(e.name);return n!==""&&t.includes(n)}function Ra(e,t={}){const n=t.maxSize??Tp,r=t.allowedTypes??Rp,a=t.allowedExtensions??$p,o=t.maxFiles??Pp,i=[],l=[];for(let c=0;c<e.length;c++){const d=e[c];if(c>=o){l.push({file:d,reason:"limit",message:`Exceeded maximum of ${o} files`});continue}if(d.size>n){l.push({file:d,reason:"size",message:`File exceeds ${Math.round(n/1024/1024)}MB limit`});continue}if(!Ep(d,r)&&!Ap(d,a)){l.push({file:d,reason:"type",message:`Unsupported file type: ${d.type||jt(d.name)}`});continue}i.push(d)}return{valid:i,errors:l}}async function ml(e){const t={file:e,name:e.name.replace(/\.[^.]+$/,""),extension:jt(e.name),sizeBytes:e.size,mimeType:e.type||`audio/${jt(e.name)}`};try{const n=await e.arrayBuffer(),a=await new OfflineAudioContext(1,1,44100).decodeAudioData(n);t.duration=a.duration,t.sampleRate=a.sampleRate,t.channels=a.numberOfChannels}catch{}return t}function Np(e){let t=0;return{onDragEnter:n=>{var r;n.preventDefault(),n.stopPropagation(),t++,t===1&&((r=e.onDragEnter)==null||r.call(e))},onDragOver:n=>{n.preventDefault(),n.stopPropagation(),(n instanceof DragEvent&&n.dataTransfer||"dataTransfer"in n&&n.dataTransfer)&&(n.dataTransfer.dropEffect="copy")},onDragLeave:n=>{var r;n.preventDefault(),n.stopPropagation(),t--,t===0&&((r=e.onDragLeave)==null||r.call(e))},onDrop:async n=>{var d,h;n.preventDefault(),n.stopPropagation(),t=0,(d=e.onDragLeave)==null||d.call(e);const r="dataTransfer"in n?n.dataTransfer:null;if(!((h=r==null?void 0:r.files)!=null&&h.length))return;const a=Array.from(r.files),{valid:o,errors:i}=Ra(a,e.validation),l=[],c=[...i];for(const f of o)if(e.probe)try{l.push(await ml(f))}catch{c.push({file:f,reason:"decode",message:"Failed to decode audio"})}else l.push({file:f,name:f.name.replace(/\.[^.]+$/,""),extension:jt(f.name),sizeBytes:f.size,mimeType:f.type||`audio/${jt(f.name)}`});e.onDrop({accepted:l,rejected:c})}}}function Ip(e={}){return new Promise(t=>{const n=document.createElement("input");n.type="file",n.accept="audio/*,.mid,.midi",n.multiple=e.multiple??!0,n.onchange=async()=>{var l;if(!((l=n.files)!=null&&l.length)){t({accepted:[],rejected:[]});return}const r=Array.from(n.files),{valid:a,errors:o}=Ra(r,e.validation),i=a.map(c=>({file:c,name:c.name.replace(/\.[^.]+$/,""),extension:jt(c.name),sizeBytes:c.size,mimeType:c.type||`audio/${jt(c.name)}`}));t({accepted:i,rejected:o})},n.click()})}var gl=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(gl||{}),kt=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(kt||{}),yl=(e=>(e[e.Equalizer=0]="Equalizer",e[e.Compressor=1]="Compressor",e[e.Reverb=2]="Reverb",e[e.Delay=3]="Delay",e[e.Distortion=4]="Distortion",e[e.Chorus=5]="Chorus",e[e.Flanger=6]="Flanger",e[e.Phaser=7]="Phaser",e))(yl||{}),bl=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(bl||{});const Lp=["var(--nice-success, #4caf50)","var(--nice-primary, #2196f3)","var(--nice-warning, #ff9800)","var(--nice-accent-pink, #e91e63)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-success, #8bc34a)","var(--nice-warning, #ffc107)"],Pt=["var(--nice-primary, #2196f3)","var(--nice-danger, #e53935)","var(--nice-warning, #ffeb3b)","var(--nice-success, #43a047)","var(--nice-warning, #ff9800)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-warning, #ffc107)","var(--nice-success, #8bc34a)","var(--nice-danger, #f44336)","var(--nice-accent, #3f51b5)","var(--nice-text-secondary, #607d8b)","var(--nice-warning-dark, #795548)","var(--nice-warning, #cddc39)","var(--nice-accent, #673ab7)","#009688"];function Fp(e){for(const t of Pt)if(!e.includes(t))return t;return Pt[Math.floor(Math.random()*Pt.length)]}const Zn=Pt.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function Dp(e){for(let t=0;t<Pt.length;t++){const n=Pt[t],r=Zn[t];if(!e.includes(n)&&!e.includes(r))return r}return Zn[Math.floor(Math.random()*Zn.length)]}const or=["off","no function","brak"],Op=e=>e.segments.some(t=>t.isOff||or.some(n=>t.name.toLowerCase().includes(n))),_p=e=>e.segments.find(t=>t.isOff||or.some(n=>t.name.toLowerCase().includes(n))),vl=e=>Math.floor((e.valueFrom+e.valueTo)/2),zp=e=>{const t=_p(e);return t?vl(t):0},Gp=(e,t)=>e.segments.find(n=>t>=n.valueFrom&&t<=n.valueTo),cn=(e,t=0,n=255)=>Math.max(t,Math.min(n,Math.round(e))),kn=({channel:e,value:t,onChange:n,onCommit:r,showDirectionHint:a})=>{const[o,i]=u.useState(cn(t)),l=u.useMemo(()=>Gp(e,o),[e,o]);u.useEffect(()=>i(cn(t)),[t]);const c=d=>{const h=cn(d);i(h),n(h),r==null||r(h)};return s.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:6},children:[s.jsxs("strong",{children:[e.channel,". ",e.name]}),a&&l&&s.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:l.name})]}),s.jsx("input",{type:"range",min:0,max:255,value:o,onChange:d=>{const h=cn(Number(d.target.value));i(h),n(h)},onMouseUp:()=>r==null?void 0:r(o),onTouchEnd:()=>r==null?void 0:r(o),style:{width:"100%"}}),s.jsx("div",{style:{marginTop:6},children:s.jsx("input",{type:"number",min:0,max:255,value:o,onChange:d=>{const h=cn(Number(d.target.value));i(h),n(h)},onBlur:()=>r==null?void 0:r(o),style:{width:80,padding:6,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:6}})}),Op(e)&&s.jsx("button",{type:"button",onClick:()=>c(zp(e)),style:{width:"100%",marginTop:8,padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)",cursor:"pointer"},children:"OFF"})]})},$a=({channel:e,value:t,onChange:n,onCommit:r})=>{const a=u.useMemo(()=>{const i=[...e.segments];return i.sort((l,c)=>{const d=(l.isOff?-1:0)+(or.some(f=>l.name.toLowerCase().includes(f))?-1:0),h=(c.isOff?-1:0)+(or.some(f=>c.name.toLowerCase().includes(f))?-1:0);return d!==h?d-h:l.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),i},[e]),o=i=>{const l=vl(i);n(l),r==null||r(l)};return s.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[s.jsxs("strong",{children:[e.channel,". ",e.name]}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(120px, 1fr))",gap:8,marginTop:8,maxHeight:220,overflowY:"auto"},children:a.map((i,l)=>{const c=t>=i.valueFrom&&t<=i.valueTo;return s.jsx("button",{type:"button",onClick:()=>o(i),style:{padding:"8px 10px",borderRadius:8,border:c?"2px solid var(--nice-primary-hover, #2563eb)":"1px solid var(--nice-border, #d1d5db)",background:c?"var(--nice-primary-bg, #eff6ff)":"var(--nice-bg, #fff)",textAlign:"left",cursor:"pointer",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:`${i.name} [${i.valueFrom}..${i.valueTo}]`,children:i.name},`${i.name}-${l}`)})})]})},Ta=e=>{switch(e.channel.type){case kt.Dimmer:case kt.DimmerWithOff:return s.jsx(kn,{...e});case kt.RotationWithOff:case kt.RotationWithOffAndCcw:return s.jsx(kn,{...e,showDirectionHint:!0});case kt.Options:return s.jsx($a,{...e});default:return s.jsx(kn,{...e})}},Tr=e=>Math.max(0,Math.min(255,Math.round(e)));function xl({service:e,pollInterval:t=500,className:n,style:r,channels:a,onChannelChange:o,fixtures:i}){if(!e)return s.jsx("div",{className:n,style:r,children:s.jsx("small",{children:"Provide a `service` prop (DmxService) to control hardware."})});const[l,c]=u.useState([]),[d,h]=u.useState(null),[f,m]=u.useState(()=>Array(513).fill(0)),[g,p]=u.useState(30),[v,x]=u.useState(0),[b,w]=u.useState(!1),y=u.useRef(null);u.useEffect(()=>{let j=!1;return e.getDevices().then(L=>{j||(c(L),L.length>0&&h(L[0]))}).catch(()=>{}),()=>{j=!0}},[e]),u.useEffect(()=>{if(y.current&&window.clearInterval(y.current),!(t<=0))return y.current=window.setInterval(async()=>{try{const j=await e.getState();Array.isArray(j.frontSnapshot)&&j.frontSnapshot.length>=513&&m(j.frontSnapshot.slice(0,513)),typeof j.fps=="number"&&p(j.fps),typeof j.startCode=="number"&&x(j.startCode)}catch{}},t),()=>{y.current&&window.clearInterval(y.current)}},[e,t]);const k=async()=>{d&&(await e.openPort(d.serialNumber||d.description),w(!0))},M=async()=>{await e.closePort(),w(!1)},N=async()=>{await e.blackout(),m(j=>{const L=[...j];for(let I=1;I<L.length;I++)L[I]=0;return L})},R=()=>e.configure(g,v),_=(j,L)=>{const I=Tr(L);m(q=>{const Y=[...q];return Y[j]=I,Y})},E=(j,L)=>e.setChannel(j,Tr(L)),U=(d==null?void 0:d.deviceInfo)??null,W=u.useMemo(()=>{var j;return(j=U==null?void 0:U.channels)!=null&&j.length?U.channels:Array.from({length:16},(L,I)=>({channel:I+1,name:`Channel ${I+1}`,type:kt.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[U]);return s.jsxs("div",{className:`ntd-dmx-editor ${n??""}`,style:{padding:16,display:"grid",gap:16,...r},children:[s.jsxs("section",{style:{display:"grid",gap:12,gridTemplateColumns:"1fr auto auto auto",alignItems:"end"},children:[s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FTDI Device"}),s.jsx("select",{value:(d==null?void 0:d.serialNumber)||"",onChange:j=>h(l.find(L=>L.serialNumber===j.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"},children:l.map(j=>{var L,I;return s.jsxs("option",{value:j.serialNumber,children:[((L=j.deviceInfo)==null?void 0:L.manufacturer)??""," ",((I=j.deviceInfo)==null?void 0:I.model)??j.description," (",j.serialNumber||j.description,")"]},j.serialNumber||j.description)})}),U&&s.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:["Mode: ",s.jsx("b",{children:U.modeName}),", footprint: ",s.jsx("b",{children:U.footprint})]})]}),s.jsx("button",{onClick:k,disabled:!d||b,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-success, #10b981)",background:"var(--nice-success-bg, #ecfdf5)",cursor:"pointer"},children:"Open port"}),s.jsx("button",{onClick:M,disabled:!b,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-danger, #ef4444)",background:"var(--nice-danger-bg, #fef2f2)",cursor:"pointer"},children:"Close port"}),s.jsx("button",{onClick:N,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-text-secondary, #4b5563)",background:"var(--nice-bg-secondary, #f3f4f6)",cursor:"pointer"},children:"Blackout"})]}),s.jsxs("section",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(160px, 100%), 1fr))",gap:12,alignItems:"end"},children:[s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FPS"}),s.jsx("input",{type:"number",min:10,max:44,value:g,onChange:j=>p(Number(j.target.value)),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"Start Code"}),s.jsx("input",{type:"number",min:0,max:255,value:v,onChange:j=>x(Tr(Number(j.target.value))),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),s.jsx("div",{children:s.jsx("button",{onClick:R,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-primary, #3b82f6)",background:"var(--nice-primary-bg, #eff6ff)",cursor:"pointer"},children:"Apply configuration"})})]}),s.jsxs("section",{children:[s.jsx("h3",{style:{margin:"8px 0 12px",fontSize:16},children:"Channels"}),s.jsx("div",{style:{display:"grid",gap:12,gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))"},children:W.map(j=>s.jsx(Ta,{channel:j,value:f[j.channel]??0,onChange:L=>_(j.channel,L),onCommit:L=>E(j.channel,L)},j.channel))})]})]})}const Sl=[{id:"generic-dimmer-1ch",name:"Generic Dimmer",manufacturer:"Generic",type:"dimmer",channelCount:1,channels:[{name:"Dimmer",type:"dimmer",defaultValue:0}]},{id:"generic-rgb-3ch",name:"Generic RGB",manufacturer:"Generic",type:"rgb",channelCount:3,channels:[{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0}]},{id:"generic-rgbw-4ch",name:"Generic RGBW",manufacturer:"Generic",type:"rgbw",channelCount:4,channels:[{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0}]},{id:"generic-rgbw-dimmer-5ch",name:"Generic RGBW+D",manufacturer:"Generic",type:"rgbw",channelCount:5,channels:[{name:"Dimmer",type:"dimmer",defaultValue:255},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0}]},{id:"generic-par-7ch",name:"Generic PAR 7ch",manufacturer:"Generic",type:"par",channelCount:7,channels:[{name:"Dimmer",type:"dimmer",defaultValue:255},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0},{name:"Strobe",type:"strobe",defaultValue:0},{name:"Function",type:"function",defaultValue:0}]},{id:"generic-moving-head-16ch",name:"Generic Moving Head 16ch",manufacturer:"Generic",type:"moving_head",channelCount:16,channels:[{name:"Pan",type:"pan",defaultValue:128,min:0,max:255},{name:"Pan Fine",type:"pan",defaultValue:0},{name:"Tilt",type:"tilt",defaultValue:128,min:0,max:255},{name:"Tilt Fine",type:"tilt",defaultValue:0},{name:"Pan/Tilt Speed",type:"speed",defaultValue:0},{name:"Dimmer",type:"dimmer",defaultValue:0},{name:"Strobe",type:"strobe",defaultValue:0},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0},{name:"Color Wheel",type:"function",defaultValue:0},{name:"Gobo",type:"gobo",defaultValue:0},{name:"Gobo Rotation",type:"speed",defaultValue:128},{name:"Prism",type:"function",defaultValue:0},{name:"Function",type:"function",defaultValue:0}]},{id:"generic-strobe-2ch",name:"Generic Strobe",manufacturer:"Generic",type:"strobe",channelCount:2,channels:[{name:"Dimmer",type:"dimmer",defaultValue:0},{name:"Strobe Speed",type:"strobe",defaultValue:0}]},{id:"generic-fog-2ch",name:"Generic Fog Machine",manufacturer:"Generic",type:"fog",channelCount:2,channels:[{name:"Output",type:"dimmer",defaultValue:0},{name:"Fan",type:"speed",defaultValue:128}]}];class wl{constructor(){this.universes=new Map,this.fixtures=new Map,this.profiles=new Map,this.outputCallback=null,this.running=!1,this.frameRate=44,this.intervalId=null,Sl.forEach(t=>this.profiles.set(t.id,t)),this.createUniverse(1,"Universe 1")}createUniverse(t,n){const r={id:String(t),name:n,channels:new Uint8Array(512)};return this.universes.set(t,r),r}getUniverse(t){return this.universes.get(t)}addFixture(t){this.fixtures.set(t.id,t)}removeFixture(t){this.fixtures.delete(t)}getFixture(t){return this.fixtures.get(t)}getAllFixtures(){return Array.from(this.fixtures.values())}getProfile(t){return this.profiles.get(t)}registerProfile(t){this.profiles.set(t.id,t)}setChannel(t,n,r){const a=this.universes.get(t);a&&n>=1&&n<=512&&(a.channels[n-1]=Math.max(0,Math.min(255,r)))}getChannel(t,n){const r=this.universes.get(t);return r&&n>=1&&n<=512?r.channels[n-1]:0}setFixtureValues(t,n){const r=this.fixtures.get(t);if(!r)return;const a=this.profiles.get(r.profileId);if(a)for(let o=0;o<Math.min(n.length,a.channelCount);o++)r.values[o]=n[o],this.setChannel(r.universe,r.startChannel+o,n[o])}setFixtureColor(t,n,r,a,o=0){const i=this.fixtures.get(t);if(!i)return;const l=this.profiles.get(i.profileId);if(!l)return;const c=[...i.values];l.channels.forEach((d,h)=>{d.name.toLowerCase().includes("red")?c[h]=n:d.name.toLowerCase().includes("green")?c[h]=r:d.name.toLowerCase().includes("blue")?c[h]=a:d.name.toLowerCase().includes("white")&&(c[h]=o)}),this.setFixtureValues(t,c)}setFixtureDimmer(t,n){const r=this.fixtures.get(t);if(!r)return;const a=this.profiles.get(r.profileId);a&&a.channels.forEach((o,i)=>{o.type==="dimmer"&&(r.values[i]=Math.max(0,Math.min(255,Math.round(n*255))),this.setChannel(r.universe,r.startChannel+i,r.values[i]))})}fadeFixture(t,n,r,a="linear"){return new Promise(o=>{const i=this.fixtures.get(t);if(!i){o();return}const l=[...i.values],c=performance.now(),d=()=>{const h=performance.now()-c,f=Math.min(1,h/r);let m=f;switch(a){case"ease-in":m=f*f;break;case"ease-out":m=1-(1-f)*(1-f);break;case"ease-in-out":m=f<.5?2*f*f:1-Math.pow(-2*f+2,2)/2;break}const g=l.map((p,v)=>{const x=n[v]??p;return Math.round(p+(x-p)*m)});this.setFixtureValues(t,g),f<1?requestAnimationFrame(d):o()};d()})}setOutputCallback(t){this.outputCallback=t}start(){this.running||(this.running=!0,this.intervalId=window.setInterval(()=>{this.sendOutput()},1e3/this.frameRate))}stop(){this.running=!1,this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null)}sendOutput(){this.outputCallback&&this.universes.forEach((t,n)=>{this.outputCallback(n,t.channels)})}blackout(){this.universes.forEach(t=>{t.channels.fill(0)}),this.fixtures.forEach(t=>{t.values.fill(0)})}fullOn(){this.fixtures.forEach(t=>{this.setFixtureDimmer(t.id,1)})}}const Bp=6454,Wp=new Uint8Array([65,114,116,45,78,101,116,0]);function Up(e,t){const n=new Uint8Array(18+t.length);return n.set(Wp,0),n[8]=0,n[9]=80,n[10]=0,n[11]=14,n[12]=0,n[13]=0,n[14]=e&255,n[15]=e>>8&255,n[16]=t.length>>8&255,n[17]=t.length&255,n.set(t.slice(0,512),18),n}const Vp=5568;function qp(e,t,n,r=100,a="Nice2Dev DMX"){const o=Math.min(t.length,512),i=126+o,l=new Uint8Array(i),c=new DataView(l.buffer);c.setUint16(0,16,!1),c.setUint16(2,0,!1);const d=[65,83,67,45,69,49,46,49,55,0,0,0];for(let p=0;p<d.length;p++)l[4+p]=d[p];const h=i-16;c.setUint16(16,28672|h&4095,!1),c.setUint32(18,4,!1);for(let p=0;p<16;p++)l[22+p]=p+1;const f=i-38;c.setUint16(38,28672|f&4095,!1),c.setUint32(40,2,!1);const m=new TextEncoder().encode(a.slice(0,63));l.set(m,44),l[108]=r,c.setUint16(109,0,!1),l[111]=n&255,l[112]=0,c.setUint16(113,e,!1);const g=o+11;return c.setUint16(115,28672|g&4095,!1),l[117]=2,l[118]=161,c.setUint16(119,0,!1),c.setUint16(121,1,!1),c.setUint16(123,o+1,!1),l[125]=0,l.set(t.slice(0,o),126),l}function Hp(e){const t=e>>8&255,n=e&255;return`239.255.${t}.${n}`}class Kp{constructor(t,n){this.config=t,this.scenes=n,this.currentStep=0,this.direction=1,this.isRunning=!1,this.timer=null,this.fadeStartTime=0,this.fadeFromValues=new Uint8Array(512),this.fadeToValues=new Uint8Array(512),this.onOutput=null}setOutputCallback(t){this.onOutput=t}start(){this.isRunning||(this.isRunning=!0,this.currentStep=this.config.direction==="backward"?this.config.steps.length-1:0,this.direction=this.config.direction==="backward"?-1:1,this.executeStep())}stop(){this.isRunning=!1,this.timer&&(clearTimeout(this.timer),this.timer=null)}executeStep(){var i;if(!this.isRunning)return;const t=this.config.steps[this.currentStep];if(!t)return;const n=this.scenes.get(t.sceneId);if(!n){this.advanceStep();return}const r=new Uint8Array(512);if(n.channels)for(const l of n.channels)l.channel>=1&&l.channel<=512&&(r[l.channel-1]=l.value);this.fadeFromValues.set(this.fadeToValues),this.fadeToValues.set(r),this.fadeStartTime=performance.now();const a=t.fadeTime/this.config.speed,o=t.holdTime/this.config.speed;a>0?this.runFade(a,()=>{var l;(l=this.onOutput)==null||l.call(this,this.fadeToValues),this.timer=setTimeout(()=>this.advanceStep(),o)}):((i=this.onOutput)==null||i.call(this,r),this.timer=setTimeout(()=>this.advanceStep(),o))}runFade(t,n){const r=performance.now(),a=new Uint8Array(512),o=()=>{var c;if(!this.isRunning)return;const i=performance.now()-r,l=Math.min(i/t,1);for(let d=0;d<512;d++)a[d]=Math.round(this.fadeFromValues[d]+(this.fadeToValues[d]-this.fadeFromValues[d])*l);(c=this.onOutput)==null||c.call(this,a),l<1?requestAnimationFrame(o):n()};requestAnimationFrame(o)}advanceStep(){if(!this.isRunning)return;const{steps:t,loop:n,direction:r}=this.config;if(this.currentStep+=this.direction,r==="bounce"){if(this.currentStep>=t.length?(this.direction=-1,this.currentStep=t.length-2):this.currentStep<0&&(this.direction=1,this.currentStep=1),this.currentStep<0||this.currentStep>=t.length){if(!n){this.stop();return}this.currentStep=0,this.direction=1}}else if(this.currentStep>=t.length||this.currentStep<0){if(!n){this.stop();return}this.currentStep=r==="backward"?t.length-1:0}this.executeStep()}}const Yp=({engine:e,tracks:t=[],scenes:n=[],duration:r=3e5,currentTime:a=0,bpm:o=120,onTimeChange:i,onCueAdd:l,onCueUpdate:c,onCueDelete:d,onTrackAdd:h,onTrackUpdate:f,onPlay:m,onPause:g,onStop:p,className:v=""})=>{const[x,b]=u.useState(1),[w,y]=u.useState(0),[k,M]=u.useState(!1),[N,R]=u.useState(null),[_,E]=u.useState(null),[U,W]=u.useState(!0),[j,L]=u.useState(1e3),I=u.useRef(null),q=u.useRef(null),Y=u.useRef(0),O=u.useMemo(()=>.1*x,[x]),Z=u.useCallback(C=>C*O,[O]),H=u.useCallback(C=>C/O,[O]),te=u.useCallback(C=>{if(!U)return C;const A=6e4/o;return Math.round(C/A)*A},[U,o]);u.useEffect(()=>{if(k){const C=performance.now(),A=a,D=()=>{const V=performance.now()-C,Q=A+V;if(Q>=r){M(!1),i==null||i(0),p==null||p();return}G(Q),i==null||i(Q),q.current=requestAnimationFrame(D)};q.current=requestAnimationFrame(D),m==null||m()}else q.current!==null&&(cancelAnimationFrame(q.current),q.current=null),g==null||g();return()=>{q.current!==null&&cancelAnimationFrame(q.current)}},[k,a,r,i,m,g,p]);const G=u.useCallback(C=>{t.forEach(A=>{A.muted||A.cues.forEach(D=>{const V=D.startTime,Q=V+D.duration;if(C>=V&&C<Q&&Y.current<V){const J=n.find(ae=>ae.id===D.sceneId);J&&J.fixtures.forEach(ae=>{D.fadeIn&&D.fadeIn>0?e.fadeFixture(ae.fixtureId,ae.values,D.fadeIn):e.setFixtureValues(ae.fixtureId,ae.values)})}if(Y.current<Q&&C>=Q){const J=n.find(ae=>ae.id===D.sceneId);J&&J.fixtures.forEach(ae=>{if(e.getFixture(ae.fixtureId)&&D.fadeOut&&D.fadeOut>0){const ee=new Array(ae.values.length).fill(0);e.fadeFixture(ae.fixtureId,ee,D.fadeOut)}})}})}),Y.current=C},[t,n,e]),z=C=>{const A=Math.floor(C/1e3),D=Math.floor(A/60),V=A%60,Q=Math.floor(C%1e3/(1e3/30));return`${D}:${V.toString().padStart(2,"0")}:${Q.toString().padStart(2,"0")}`},S=u.useCallback(C=>{if(!I.current)return;const A=I.current.getBoundingClientRect(),D=C.clientX-A.left+w,V=te(H(D));i==null||i(Math.max(0,Math.min(r,V)))},[w,H,te,r,i]),P=u.useCallback((C,A,D)=>{const V=t.find(ae=>ae.id===A),Q=V==null?void 0:V.cues.find(ae=>ae.id===C);if(!Q)return;const J=te(Math.max(0,Q.startTime+H(D)));c==null||c({...Q,startTime:J})},[t,H,te,c]),$=()=>{const C=6e4/o,A=Math.ceil(r/C),D=[];for(let V=0;V<=A;V++){const Q=V*C,J=Z(Q),ae=V%4===0;D.push(s.jsx("div",{className:`nice-dmx-timeline__beat ${ae?"nice-dmx-timeline__beat--measure":""}`,style:{left:J},children:ae&&s.jsx("span",{className:"nice-dmx-timeline__beat-label",children:V/4+1})},V))}return D},T=(C,A)=>{const D=Z(C.startTime),V=Z(C.duration),Q=n.find(J=>J.id===C.sceneId);return s.jsxs("div",{className:`nice-dmx-timeline__cue ${N===C.id?"nice-dmx-timeline__cue--selected":""}`,style:{left:D,width:V,backgroundColor:(Q==null?void 0:Q.color)||A.color||"var(--nice-accent, #8b5cf6)"},onClick:J=>{J.stopPropagation(),R(C.id)},draggable:!A.locked,onDragEnd:J=>{var re;const ae=(re=J.target.parentElement)==null?void 0:re.getBoundingClientRect();ae&&P(C.id,A.id,J.clientX-ae.left-D)},children:[s.jsx("span",{className:"nice-dmx-timeline__cue-name",children:C.name||(Q==null?void 0:Q.name)}),C.fadeIn&&C.fadeIn>0&&s.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--in",style:{width:Z(C.fadeIn)}}),C.fadeOut&&C.fadeOut>0&&s.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--out",style:{width:Z(C.fadeOut)}})]},C.id)};return s.jsxs("div",{className:`nice-dmx-timeline ${v}`,children:[s.jsxs("div",{className:"nice-dmx-timeline__toolbar",children:[s.jsxs("div",{className:"nice-dmx-timeline__transport",children:[s.jsx("button",{type:"button",onClick:()=>i==null?void 0:i(0),title:"Go to start",children:"⏮"}),s.jsx("button",{type:"button",onClick:()=>M(!k),title:k?"Pause":"Play",children:k?"⏸":"▶"}),s.jsx("button",{type:"button",onClick:()=>{M(!1),i==null||i(0),e.blackout(),p==null||p()},title:"Stop",children:"⏹"})]}),s.jsx("div",{className:"nice-dmx-timeline__time",children:z(a)}),s.jsxs("div",{className:"nice-dmx-timeline__tools",children:[s.jsx("button",{type:"button",className:U?"active":"",onClick:()=>W(!U),title:"Snap to grid",children:"⊞"}),s.jsx("button",{type:"button",onClick:()=>b(Math.max(.25,x-.25)),title:"Zoom out",children:"−"}),s.jsxs("span",{className:"nice-dmx-timeline__zoom",children:[Math.round(x*100),"%"]}),s.jsx("button",{type:"button",onClick:()=>b(Math.min(4,x+.25)),title:"Zoom in",children:"+"})]}),s.jsxs("div",{className:"nice-dmx-timeline__bpm",children:[s.jsx("label",{children:"BPM:"}),s.jsx("span",{children:o})]}),s.jsx("button",{type:"button",className:"nice-dmx-timeline__blackout",onClick:()=>e.blackout(),title:"Blackout",children:"⬛"})]}),s.jsxs("div",{className:"nice-dmx-timeline__content",children:[s.jsxs("div",{className:"nice-dmx-timeline__headers",children:[t.map(C=>s.jsxs("div",{className:`nice-dmx-timeline__header ${_===C.id?"nice-dmx-timeline__header--selected":""}`,onClick:()=>E(C.id),children:[s.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:C.color||"var(--nice-accent, #8b5cf6)"}}),s.jsx("span",{className:"nice-dmx-timeline__track-name",children:C.name}),s.jsxs("div",{className:"nice-dmx-timeline__track-controls",children:[s.jsx("button",{type:"button",className:C.muted?"active":"",onClick:A=>{A.stopPropagation(),f==null||f({...C,muted:!C.muted})},title:"Mute",children:"M"}),s.jsx("button",{type:"button",className:C.locked?"active":"",onClick:A=>{A.stopPropagation(),f==null||f({...C,locked:!C.locked})},title:"Lock",children:"🔒"})]})]},C.id)),s.jsx("button",{type:"button",className:"nice-dmx-timeline__add-track",onClick:()=>{h==null||h({id:`track-${Date.now()}`,name:`Track ${t.length+1}`,fixtureIds:[],cues:[]})},children:"+ Add Track"})]}),s.jsxs("div",{className:"nice-dmx-timeline__tracks",ref:I,onClick:S,onScroll:C=>y(C.currentTarget.scrollLeft),children:[s.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:Z(r)},children:$()}),t.map(C=>s.jsx("div",{className:`nice-dmx-timeline__track ${C.muted?"nice-dmx-timeline__track--muted":""}`,style:{width:Z(r)},children:C.cues.map(A=>T(A,C))},C.id)),s.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:Z(a)}})]})]})]})};function Zp(){const[e]=u.useState(()=>new wl);return u.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function Xp(e,t,n=120){const[r,a]=u.useState(0),o=u.useRef(0);return u.useEffect(()=>{if(!t)return;const i=60/n,l=()=>{const c=t.currentTime,d=Math.floor(c/i);d!==o.current&&(o.current=d,a(d))};return t.addEventListener("timeupdate",l),()=>t.removeEventListener("timeupdate",l)},[t,n]),{currentBeat:r}}const Qp=[{name:"Flat",bands:[{frequency:60,gain:0},{frequency:250,gain:0},{frequency:1e3,gain:0},{frequency:4e3,gain:0},{frequency:16e3,gain:0}]},{name:"Bass Boost",bands:[{frequency:60,gain:8},{frequency:250,gain:4},{frequency:1e3,gain:0},{frequency:4e3,gain:-2},{frequency:16e3,gain:-4}]},{name:"Treble Boost",bands:[{frequency:60,gain:-4},{frequency:250,gain:-2},{frequency:1e3,gain:0},{frequency:4e3,gain:4},{frequency:16e3,gain:8}]},{name:"Voice",bands:[{frequency:60,gain:-6},{frequency:250,gain:2},{frequency:1e3,gain:6},{frequency:4e3,gain:4},{frequency:16e3,gain:-2}]},{name:"Rock",bands:[{frequency:60,gain:4},{frequency:250,gain:2},{frequency:1e3,gain:-2},{frequency:4e3,gain:4},{frequency:16e3,gain:6}]}];function Cl(){const[e,t]=u.useState(!1),[n,r]=u.useState(.8),[a,o]=u.useState(!1),[i,l]=u.useState(null),[c,d]=u.useState(null),[h,f]=u.useState(null),m=u.useRef(null),g=u.useRef(null),p=u.useRef(null),v=u.useRef(null),x=u.useRef([]),b=u.useRef(null),w=u.useRef(null),y=u.useCallback(()=>{if(g.current)return;const I=new AudioContext;g.current=I;const q=I.createGain();q.gain.value=n,v.current=q;const Y=I.createAnalyser();Y.fftSize=256,b.current=Y,q.connect(Y).connect(I.destination)},[]),k=u.useCallback(()=>{const I=m.current,q=g.current,Y=v.current;if(!I||!q||!Y||p.current)return;const O=q.createMediaElementSource(I);p.current=O,x.current.length>0?(O.connect(x.current[0]),x.current[x.current.length-1].connect(Y)):O.connect(Y)},[]),M=u.useCallback(()=>{var q;const I=m.current;!I||!w.current||(Et(),y(),k(),((q=g.current)==null?void 0:q.state)==="suspended"&&g.current.resume(),I.play().catch(Y=>d(String(Y))))},[y,k]),N=u.useCallback(()=>{var I;(I=m.current)==null||I.pause()},[]),R=u.useCallback(()=>{e?N():M()},[e,M,N]),_=u.useCallback(I=>{const q=Math.max(0,Math.min(1,I));r(q),v.current&&(v.current.gain.value=q),m.current&&(m.current.volume=q)},[]),E=u.useCallback(I=>{w.current=I,d(null),l(null),o(!0),p.current&&(p.current.disconnect(),p.current=null),m.current||(m.current=new Audio,m.current.crossOrigin="anonymous",m.current.addEventListener("playing",()=>{t(!0),o(!1)}),m.current.addEventListener("pause",()=>t(!1)),m.current.addEventListener("waiting",()=>o(!0)),m.current.addEventListener("canplay",()=>o(!1)),m.current.addEventListener("error",()=>d("Failed to load stream"))),m.current.src=I.streamUrl,m.current.load(),l({genre:I.genre,bitrate:I.bitrate})},[]),U=u.useCallback(I=>{g.current||y();const Y=g.current;x.current.forEach(Z=>Z.disconnect());const O=I.bands.map(Z=>{const H=Y.createBiquadFilter();return H.type="peaking",H.frequency.value=Z.frequency,H.gain.value=Z.gain,H.Q.value=Z.Q??1.4,H});for(let Z=0;Z<O.length-1;Z++)O[Z].connect(O[Z+1]);x.current=O,p.current&&v.current&&(p.current.disconnect(),p.current.connect(O[0]),O[O.length-1].connect(v.current)),f(I.name)},[y]),W=u.useCallback(()=>{x.current.forEach(I=>I.disconnect()),x.current=[],p.current&&v.current&&(p.current.disconnect(),p.current.connect(v.current)),f(null)},[]);return u.useEffect(()=>()=>{var I,q,Y;(I=m.current)==null||I.pause(),m.current=null,x.current.forEach(O=>O.disconnect()),(q=p.current)==null||q.disconnect(),(Y=g.current)==null||Y.close()},[]),[{isPlaying:e,volume:n,isBuffering:a,metadata:i,error:c,activePreset:h},{play:M,pause:N,toggle:R,setVolume:_,setStation:E,applyEQPreset:U,clearEQ:W}]}function kl({stations:e,activeStationId:t,onSelect:n,onToggleFavorite:r,className:a}){const{t:o}=xe(),[i,l]=u.useState(""),[c,d]=u.useState(null),[h,f]=u.useState(!1),m=u.useMemo(()=>[...new Set(e.map(p=>p.genre).filter(Boolean))],[e]),g=u.useMemo(()=>e.filter(p=>{var v,x;if(h&&!p.isFavorite||c&&p.genre!==c)return!1;if(i){const b=i.toLowerCase();return p.name.toLowerCase().includes(b)||(((v=p.genre)==null?void 0:v.toLowerCase().includes(b))??!1)||(((x=p.country)==null?void 0:x.toLowerCase().includes(b))??!1)}return!0}),[e,i,c,h]);return s.jsxs("div",{className:`nice-station-browser${a?` ${a}`:""}`,children:[s.jsxs("div",{className:"nice-station-browser__toolbar",children:[s.jsx("input",{type:"text",className:"nice-station-browser__search",placeholder:(o==null?void 0:o("search_stations"))??"Search stations...",value:i,onChange:p=>l(p.target.value)}),s.jsxs("select",{className:"nice-station-browser__genre-filter",value:c??"",onChange:p=>d(p.target.value||null),children:[s.jsx("option",{value:"",children:(o==null?void 0:o("all_genres"))??"All Genres"}),m.map(p=>s.jsx("option",{value:p,children:p},p))]}),s.jsx("button",{className:`nice-station-browser__fav-toggle${h?" nice-station-browser__fav-toggle--active":""}`,onClick:()=>f(!h),title:(o==null?void 0:o("favorites"))??"Favorites",children:"★"})]}),s.jsxs("div",{className:"nice-station-browser__list",children:[g.map(p=>s.jsxs("div",{className:`nice-station-browser__item${p.id===t?" nice-station-browser__item--active":""}`,onClick:()=>n(p),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&n(p)},children:[p.logoUrl&&s.jsx("img",{className:"nice-station-browser__logo",src:p.logoUrl,alt:p.name,loading:"lazy"}),s.jsxs("div",{className:"nice-station-browser__info",children:[s.jsx("span",{className:"nice-station-browser__name",children:p.name}),p.genre&&s.jsx("span",{className:"nice-station-browser__genre",children:p.genre}),p.country&&s.jsx("span",{className:"nice-station-browser__country",children:p.country})]}),p.bitrate&&s.jsxs("span",{className:"nice-station-browser__bitrate",children:[p.bitrate,"kbps"]}),r&&s.jsx("button",{className:`nice-station-browser__fav${p.isFavorite?" nice-station-browser__fav--active":""}`,onClick:v=>{v.stopPropagation(),r(p.id)},children:p.isFavorite?"★":"☆"})]},p.id)),g.length===0&&s.jsx("div",{className:"nice-station-browser__empty",children:(o==null?void 0:o("no_stations_found"))??"No stations found"})]})]})}function Jp({stations:e,initialStationId:t,autoPlay:n=!1,eqPresets:r=Qp,onStationChange:a,onPlayingChange:o,onMetadata:i,onToggleFavorite:l,onRecordingStart:c,onRecordingStop:d,showBrowser:h=!0,showEqualizer:f=!1,showVisualizer:m=!1,showMetadataHistory:g=!1,showRecording:p=!1,showSleepTimer:v=!1,className:x,style:b}){var T,C;const{t:w}=xe(),[y,k]=Cl(),[M,N]=u.useState(()=>t?e.find(A=>A.id===t)??null:null),[R,_]=u.useState(f),E=u.useRef(null),U=u.useRef(0),[W,j]=u.useState([]),[L,I]=u.useState(!1),q=u.useRef(null),Y=u.useRef([]),[O,Z]=u.useState(0),H=u.useRef(null),[te,G]=u.useState(0),[z,S]=u.useState(null),P=u.useRef(null);u.useEffect(()=>{o==null||o(y.isPlaying)},[y.isPlaying,o]),u.useEffect(()=>{y.metadata&&(i==null||i(y.metadata),(y.metadata.title||y.metadata.artist)&&j(A=>[{time:new Date,meta:y.metadata},...A.slice(0,49)]))},[y.metadata,i]);const $=u.useCallback(A=>{N(A),k.setStation(A),a==null||a(A),n&&setTimeout(()=>k.play(),100)},[k,a,n]);return u.useEffect(()=>{if(t&&!M){const A=e.find(D=>D.id===t);A&&$(A)}},[t,e]),u.useEffect(()=>{if(!m||!E.current)return;const A=E.current,D=A.getContext("2d");if(!D)return;const V=()=>{U.current=requestAnimationFrame(V),D.clearRect(0,0,A.width,A.height);const Q=D.createLinearGradient(0,A.height,0,0);if(Q.addColorStop(0,"var(--nice-accent-tint-80, rgba(99, 102, 241, 0.8))"),Q.addColorStop(.5,"rgba(168,85,247,0.6)"),Q.addColorStop(1,"rgba(236,72,153,0.4)"),!y.isPlaying){const ee=A.width/32;for(let F=0;F<32;F++){const K=4+Math.sin(Date.now()/1e3+F*.3)*3;D.fillStyle=Q,D.fillRect(F*ee+1,A.height-K,ee-2,K)}return}const J=32,ae=A.width/J;for(let re=0;re<J;re++){const ee=re/J,K=(Math.sin(Date.now()/200+re*.5)*.3+.5)*A.height*(1-ee*.5)*(.5+Math.random()*.5);D.fillStyle=Q,D.fillRect(re*ae+1,A.height-K,ae-2,K)}};return V(),()=>cancelAnimationFrame(U.current)},[m,y.isPlaying]),u.useCallback(()=>{if(y.isPlaying)try{const D=new AudioContext().createMediaStreamDestination();Y.current=[];const V=new MediaRecorder(D.stream,{mimeType:"audio/webm"});V.ondataavailable=Q=>{Q.data.size>0&&Y.current.push(Q.data)},V.onstop=()=>{const Q=new Blob(Y.current,{type:"audio/webm"});d==null||d(Q),Z(0),H.current&&window.clearInterval(H.current)},V.start(1e3),q.current=V,I(!0),Z(0),H.current=window.setInterval(()=>{Z(Q=>Q+1)},1e3),c==null||c()}catch{}},[y.isPlaying,c,d]),u.useCallback(()=>{q.current&&L&&(q.current.stop(),I(!1),H.current&&window.clearInterval(H.current))},[L]),u.useCallback(A=>{P.current&&window.clearInterval(P.current),G(A),S(A*60),P.current=window.setInterval(()=>{S(D=>!D||D<=1?(P.current&&window.clearInterval(P.current),P.current=null,k.pause(),null):D-1)},1e3)},[k]),u.useCallback(()=>{P.current&&window.clearInterval(P.current),P.current=null,S(null),G(0)},[]),u.useEffect(()=>()=>{H.current&&window.clearInterval(H.current),P.current&&window.clearInterval(P.current),cancelAnimationFrame(U.current)},[]),s.jsxs("div",{className:`nice-radio-player${x?` ${x}`:""}`,style:b,children:[s.jsx("div",{className:"nice-radio-player__now-playing",children:M?s.jsxs(s.Fragment,{children:[M.logoUrl&&s.jsx("img",{className:"nice-radio-player__cover",src:M.logoUrl,alt:M.name}),s.jsxs("div",{className:"nice-radio-player__info",children:[s.jsx("span",{className:"nice-radio-player__station-name",children:M.name}),((T=y.metadata)==null?void 0:T.title)&&s.jsx("span",{className:"nice-radio-player__track",children:y.metadata.artist?`${y.metadata.artist} — ${y.metadata.title}`:y.metadata.title}),((C=y.metadata)==null?void 0:C.genre)&&s.jsx("span",{className:"nice-radio-player__genre",children:y.metadata.genre}),y.isBuffering&&s.jsx("span",{className:"nice-radio-player__buffering",children:(w==null?void 0:w("buffering"))??"Buffering..."})]})]}):s.jsx("div",{className:"nice-radio-player__placeholder",children:(w==null?void 0:w("select_station"))??"Select a station"})}),s.jsxs("div",{className:"nice-radio-player__controls",children:[s.jsx("button",{className:"nice-radio-player__play-btn",onClick:k.toggle,disabled:!M,"aria-label":y.isPlaying?"Pause":"Play",children:y.isPlaying?"⏸":"▶"}),s.jsxs("div",{className:"nice-radio-player__volume",children:[s.jsx("span",{className:"nice-radio-player__volume-icon",children:"🔊"}),s.jsx("input",{type:"range",min:0,max:1,step:.01,value:y.volume,onChange:A=>k.setVolume(parseFloat(A.target.value)),className:"nice-radio-player__volume-slider","aria-label":"Volume"})]}),s.jsx("button",{className:`nice-radio-player__eq-btn${R?" nice-radio-player__eq-btn--active":""}`,onClick:()=>_(!R),title:"Equalizer",children:"EQ"})]}),y.error&&s.jsx("div",{className:"nice-radio-player__error",children:y.error}),R&&s.jsx("div",{className:"nice-radio-player__equalizer",children:s.jsxs("div",{className:"nice-radio-player__eq-presets",children:[r.map(A=>s.jsx("button",{className:`nice-radio-player__eq-preset${y.activePreset===A.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>k.applyEQPreset(A),children:A.name},A.name)),y.activePreset&&s.jsx("button",{className:"nice-radio-player__eq-preset",onClick:k.clearEQ,children:(w==null?void 0:w("clear"))??"Clear"})]})}),h&&s.jsx(kl,{stations:e,activeStationId:M==null?void 0:M.id,onSelect:$})]})}const e0=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],t0={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class Ml{constructor(t,n={}){this.localStream=null,this.peers=new Map,this.onRemoteStream=null,this.onPeerStateChange=null,this.onSignalingMessage=null,this.localUserId=t,this.config={iceServers:n.iceServers??e0,audioConstraints:{...t0,echoCancellation:n.echoCancellation??!0,noiseSuppression:n.noiseSuppression??!0,autoGainControl:n.autoGainControl??!0}}}async initialize(){return this.localStream?this.localStream:(this.localStream=await navigator.mediaDevices.getUserMedia({audio:this.config.audioConstraints,video:!1}),this.localStream)}getLocalStream(){return this.localStream}getPeerIds(){return Array.from(this.peers.keys())}getPeerState(t){var n;return((n=this.peers.get(t))==null?void 0:n.state)??null}async createOffer(t){if(!this.localStream)throw new Error("WebRTCAudioManager not initialized. Call initialize() first.");const n=this.createPeerConnection(t),r=await n.createOffer();await n.setLocalDescription(r),this.sendSignalingMessage({type:"offer",from:this.localUserId,to:t,payload:r})}async handleSignalingMessage(t){if(t.to===this.localUserId)switch(t.type){case"offer":await this.handleOffer(t.from,t.payload);break;case"answer":await this.handleAnswer(t.from,t.payload);break;case"ice-candidate":await this.handleIceCandidate(t.from,t.payload);break;case"leave":this.removePeer(t.from);break}}removePeer(t){const n=this.peers.get(t);n&&(n.pc.close(),this.peers.delete(t))}disconnect(){for(const t of this.peers.keys())this.sendSignalingMessage({type:"leave",from:this.localUserId,to:t,payload:null});for(const t of this.peers.values())t.pc.close();this.peers.clear(),this.localStream&&(this.localStream.getTracks().forEach(t=>t.stop()),this.localStream=null)}setMuted(t){this.localStream&&this.localStream.getAudioTracks().forEach(n=>{n.enabled=!t})}isMuted(){if(!this.localStream)return!0;const t=this.localStream.getAudioTracks()[0];return t?!t.enabled:!0}createPeerConnection(t){const n=new RTCPeerConnection({iceServers:this.config.iceServers}),r={id:t,pc:n,remoteStream:null,state:n.connectionState};return this.peers.set(t,r),this.localStream&&this.localStream.getTracks().forEach(a=>{n.addTrack(a,this.localStream)}),n.onicecandidate=a=>{a.candidate&&this.sendSignalingMessage({type:"ice-candidate",from:this.localUserId,to:t,payload:a.candidate.toJSON()})},n.ontrack=a=>{var i;const[o]=a.streams;o&&(r.remoteStream=o,(i=this.onRemoteStream)==null||i.call(this,t,o))},n.onconnectionstatechange=()=>{var a;r.state=n.connectionState,(a=this.onPeerStateChange)==null||a.call(this,t,n.connectionState),(n.connectionState==="failed"||n.connectionState==="disconnected")&&this.removePeer(t)},n}async handleOffer(t,n){this.localStream||await this.initialize();const r=this.createPeerConnection(t);await r.setRemoteDescription(new RTCSessionDescription(n));const a=await r.createAnswer();await r.setLocalDescription(a),this.sendSignalingMessage({type:"answer",from:this.localUserId,to:t,payload:a})}async handleAnswer(t,n){const r=this.peers.get(t);r&&await r.pc.setRemoteDescription(new RTCSessionDescription(n))}async handleIceCandidate(t,n){const r=this.peers.get(t);r&&n&&await r.pc.addIceCandidate(new RTCIceCandidate(n))}sendSignalingMessage(t){var n;(n=this.onSignalingMessage)==null||n.call(this,t)}}function n0(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function r0(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function a0(){return new AudioContext({sampleRate:48e3,latencyHint:"interactive"})}const Pa=u.forwardRef(function(t,n){const{mode:r="bars",width:a=300,height:o=100,barCount:i=32,barColor:l="var(--nice-primary, #3b82f6)",backgroundColor:c="transparent",fftSize:d=256,smoothing:h=.8,minDecibels:f=-90,maxDecibels:m=-10,deviceId:g,autoStart:p=!1,onStart:v,onStop:x,onAudioLevel:b,onError:w,className:y,style:k,barBorderRadius:M=2,barGap:N=2,lineWidth:R=2}=t,_=u.useRef(null),E=u.useRef(null),U=u.useRef(null),W=u.useRef(null),j=u.useRef(0),L=u.useRef(null),I=u.useRef(0),[q,Y]=u.useState(!1),O=u.useCallback(($,T,C=!0)=>{const A=C?$.createLinearGradient(0,o,0,0):$.createLinearGradient(0,0,a,0);return T.forEach((D,V)=>{A.addColorStop(V/(T.length-1),D)}),A},[a,o]),Z=u.useCallback(($,T)=>{const A=(a-(i-1)*N)/i,D=Math.floor(T.length/i),V=Array.isArray(l)?l:[l],Q=V.length>1?O($,V):V[0];$.fillStyle=Q;for(let J=0;J<i;J++){const re=T[J*D]/255*o,ee=J*(A+N),F=o-re;M>0?($.beginPath(),$.roundRect(ee,F,A,re,M),$.fill()):$.fillRect(ee,F,A,re)}},[i,l,N,M,a,o,O]),H=u.useCallback(($,T)=>{const C=o/2,D=(a-(i-1)*N)/i,V=Math.floor(T.length/i),Q=Array.isArray(l)?l:[l],J=Q.length>1?O($,Q):Q[0];$.fillStyle=J;for(let ae=0;ae<i;ae++){const ee=T[ae*V]/255*C,F=ae*(D+N);M>0?($.beginPath(),$.roundRect(F,C-ee,D,ee,M),$.fill(),$.beginPath(),$.roundRect(F,C,D,ee,M),$.fill()):($.fillRect(F,C-ee,D,ee),$.fillRect(F,C,D,ee))}},[i,l,N,M,a,o,O]),te=u.useCallback(($,T)=>{const C=Array.isArray(l)?l:[l];$.strokeStyle=C.length>1?O($,C,!1):C[0],$.lineWidth=R,$.lineCap="round",$.lineJoin="round",$.beginPath();const A=a/T.length;let D=0;for(let V=0;V<T.length;V++){const J=T[V]/128*o/2;V===0?$.moveTo(D,J):$.lineTo(D,J),D+=A}$.stroke()},[l,R,a,o,O]),G=u.useCallback(($,T)=>{const C=a/2,A=o/2,D=Math.min(a,o)/3,V=Array.isArray(l)?l:[l];$.strokeStyle=V.length>1?O($,V):V[0],$.lineWidth=R;const Q=Math.floor(T.length/64),J=Math.PI*2/64;$.beginPath();for(let ae=0;ae<64;ae++){const re=T[ae*Q]/255,ee=D+re*D*.5,F=ae*J-Math.PI/2,K=C+Math.cos(F)*ee,se=A+Math.sin(F)*ee;ae===0?$.moveTo(K,se):$.lineTo(K,se)}$.closePath(),$.stroke()},[l,R,a,o,O]),z=u.useCallback(()=>{const $=_.current,T=U.current,C=L.current;if(!$||!T||!C)return;const A=$.getContext("2d");if(!A)return;r==="waveform"?T.getByteTimeDomainData(C):T.getByteFrequencyData(C);let D=0;for(let V=0;V<C.length;V++)D+=C[V];switch(I.current=D/(C.length*255),b==null||b(I.current),A.clearRect(0,0,a,o),c!=="transparent"&&(A.fillStyle=c,A.fillRect(0,0,a,o)),r){case"bars":Z(A,C);break;case"mirror-bars":H(A,C);break;case"waveform":te(A,C);break;case"circle":G(A,C);break}j.current=requestAnimationFrame(z)},[r,a,o,c,Z,H,te,G,b]),S=u.useCallback(async()=>{try{if(q)return;const $=await navigator.mediaDevices.getUserMedia({audio:g?{deviceId:{exact:g}}:!0,video:!1});W.current=$;const T=new AudioContext;E.current=T;const C=T.createMediaStreamSource($),A=T.createAnalyser();A.fftSize=d,A.smoothingTimeConstant=h,A.minDecibels=f,A.maxDecibels=m,C.connect(A),U.current=A,L.current=new Uint8Array(A.frequencyBinCount),Y(!0),v==null||v(),z()}catch($){w==null||w($ instanceof Error?$:new Error(String($)))}},[q,g,d,h,f,m,v,w,z]),P=u.useCallback(()=>{cancelAnimationFrame(j.current),W.current&&(W.current.getTracks().forEach(T=>T.stop()),W.current=null),E.current&&(E.current.close(),E.current=null),U.current=null,L.current=null,I.current=0,Y(!1),x==null||x();const $=_.current;if($){const T=$.getContext("2d");T&&(T.clearRect(0,0,a,o),c!=="transparent"&&(T.fillStyle=c,T.fillRect(0,0,a,o)))}},[a,o,c,x]);return u.useImperativeHandle(n,()=>({start:S,stop:P,isCapturing:()=>q,getAudioLevel:()=>I.current}),[S,P,q]),u.useEffect(()=>(p&&S(),()=>{P()}),[p]),s.jsx("canvas",{ref:_,width:a,height:o,className:y,style:{display:"block",...k},"aria-label":"Audio visualizer"})}),Rs=e=>{switch(e){case"top-left":return{top:16,left:16};case"top-right":return{top:16,right:16};case"bottom-left":return{bottom:16,left:16};case"bottom-right":default:return{bottom:16,right:16}}},s0={position:"fixed",display:"flex",flexDirection:"column",gap:8,padding:12,borderRadius:12,boxShadow:"0 4px 20px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:14,minWidth:200,maxWidth:280,transition:"all 0.2s ease"},o0={background:"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",text:"var(--nice-bg, #1a1a1a)",textSecondary:"var(--nice-text-secondary, #666)",border:"var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-bg, #fee2e2)",mutedIcon:"var(--nice-danger, #ef4444)",activeBg:"var(--nice-success-bg, #dcfce7)",activeIcon:"var(--nice-success, #22c55e)",hoverBg:"var(--nice-overlay-5, rgba(0, 0, 0, 0.05))"},i0={background:"rgba(30, 30, 30, 0.95)",text:"var(--nice-bg, #fff)",textSecondary:"var(--nice-text-muted, #a0a0a0)",border:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-dark, #7f1d1d)",mutedIcon:"var(--nice-danger-bg, #fca5a5)",activeBg:"#14532d",activeIcon:"var(--nice-success-light, #86efac)",hoverBg:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))"},jl=u.forwardRef(function(t,n){const{userId:r,userName:a,userAvatarUrl:o,participants:i=[],rtcConfig:l,position:c="bottom-right",expanded:d=!0,onSignalingMessage:h,onMuteToggle:f,onLeave:m,onSpeakingChange:g,speakingThreshold:p=.1,theme:v="auto",className:x,style:b,zIndex:w=1e3}=t,y=u.useRef(null),k=u.useRef(null),M=u.useRef(new Map);u.useRef(new Map);const[N,R]=u.useState(!1),[_,E]=u.useState(!1),[U,W]=u.useState(!1),[j,L]=u.useState(d),q=u.useMemo(()=>v==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":v,[v])==="dark"?i0:o0;u.useEffect(()=>{const z=new Ml(r,l);return z.onRemoteStream=(S,P)=>{let $=M.current.get(S);$||($=new Audio,$.autoplay=!0,M.current.set(S,$)),$.srcObject=P},z.onSignalingMessage=S=>{h==null||h(S)},z.onPeerStateChange=(S,P)=>{P==="connected"&&E(!0)},y.current=z,z.initialize().then(()=>{var S;(S=k.current)==null||S.start()}),()=>{z.disconnect(),M.current.forEach(S=>{S.srcObject=null}),M.current.clear()}},[r,l,h]);const Y=u.useCallback(()=>{var S;const z=!N;R(z),(S=y.current)==null||S.setMuted(z),f==null||f(z)},[N,f]),O=u.useCallback(()=>{var z,S;(z=y.current)==null||z.disconnect(),(S=k.current)==null||S.stop(),E(!1),m==null||m()},[m]),Z=u.useCallback(z=>{const S=z>p;S!==U&&(W(S),g==null||g(r,S))},[p,U,r,g]),H=u.useCallback(async z=>{var S;await((S=y.current)==null?void 0:S.createOffer(z))},[]),te=u.useCallback(async z=>{var S;await((S=y.current)==null?void 0:S.handleSignalingMessage(z))},[]);u.useImperativeHandle(n,()=>({connectToPeer:H,handleSignalingMessage:te,toggleMute:Y,isMuted:()=>N,leave:O,getManager:()=>y.current}),[H,te,Y,N,O]);const G=({participant:z,isLocal:S,isSpeaking:P})=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 0"},children:[s.jsx("div",{style:{width:32,height:32,borderRadius:"50%",backgroundColor:q.hoverBg,border:`2px solid ${P?q.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:q.text,transition:"border-color 0.15s ease"},children:z.avatarUrl?s.jsx("img",{src:z.avatarUrl,alt:z.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):z.name.charAt(0).toUpperCase()}),s.jsx("div",{style:{flex:1,minWidth:0},children:s.jsxs("div",{style:{color:q.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[z.name,S&&s.jsx("span",{style:{color:q.textSecondary,fontWeight:400},children:" (You)"})]})}),z.isMuted&&s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:q.mutedIcon,strokeWidth:"2",children:[s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),s.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),s.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),s.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),s.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})]});return j?s.jsxs("div",{className:x,style:{...s0,...Rs(c),backgroundColor:q.background,border:`1px solid ${q.border}`,zIndex:w,...b},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${q.border}`},children:[s.jsx("span",{style:{color:q.text,fontWeight:600},children:"Voice Chat"}),s.jsx("button",{onClick:()=>L(!1),style:{background:"none",border:"none",cursor:"pointer",padding:4,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:4},"aria-label":"Collapse",children:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:q.textSecondary,strokeWidth:"2",children:[s.jsx("polyline",{points:"4 14 10 14 10 20"}),s.jsx("polyline",{points:"20 10 14 10 14 4"}),s.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),s.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx(G,{participant:{id:r,name:a,avatarUrl:o,isMuted:N},isLocal:!0,isSpeaking:U&&!N}),i.map(z=>s.jsx(G,{participant:z,isSpeaking:z.isSpeaking},z.id))]}),s.jsx(Pa,{ref:k,mode:"bars",width:256,height:32,barCount:24,barColor:N?"var(--nice-text-muted, #9ca3af)":["var(--nice-primary, #3b82f6)","var(--nice-accent, #8b5cf6)"],barGap:3,barBorderRadius:2,autoStart:!1,onAudioLevel:Z,style:{borderRadius:4,opacity:N?.5:1}}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{onClick:Y,style:{flex:1,padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:N?q.mutedBg:q.activeBg,color:N?q.mutedIcon:q.activeIcon,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":N?"Unmute":"Mute",children:N?s.jsxs(s.Fragment,{children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),s.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),s.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),s.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),s.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Muted"]}):s.jsxs(s.Fragment,{children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),s.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),s.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),s.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Mic On"]})}),s.jsx("button",{onClick:O,style:{padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:"var(--nice-danger-bg, #fef2f2)",color:"var(--nice-danger-dark, #dc2626)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":"Leave voice chat",children:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),s.jsx("polyline",{points:"16 17 21 12 16 7"}),s.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]})]}):s.jsx("div",{className:x,style:{position:"fixed",...Rs(c),zIndex:w,...b},children:s.jsxs("button",{onClick:()=>L(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:q.background,boxShadow:"0 4px 12px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":"Expand voice chat",children:[s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:q.text,strokeWidth:"2",children:[s.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),s.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),s.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),s.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),i.length>0&&s.jsx("span",{style:{position:"absolute",top:-4,right:-4,width:20,height:20,borderRadius:"50%",backgroundColor:q.speakingRing,color:"var(--nice-bg, #fff)",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:i.length+1})]})})});function l0(e,t){const n={...t,id:`op_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now()},r=e.operations.slice(0,e.undoIndex+1);return r.push(n),{...e,operations:r,undoIndex:r.length-1}}function c0(e){return e.undoIndex<0?e:{...e,undoIndex:e.undoIndex-1}}function d0(e){return e.undoIndex>=e.operations.length-1?e:{...e,undoIndex:e.undoIndex+1}}function u0(e,t,n){const a=({"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":.6666666666666666,"1/8T":.3333333333333333,"1/16T":.16666666666666666,"1/4D":1.5,"1/8D":.75}[t.grid]??1)*n,o=t.strength/100;return e.map(i=>{const l=Math.round(i.startTick/a)*a,c=i.startTick+(l-i.startTick)*o,d=(Math.random()-.5)*2*t.humanize;return{...i,startTick:Math.max(0,Math.round(c+d))}})}function h0(e){if(e.length<2)return null;const t=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],n=[...new Set(e.map(a=>a%12))].sort((a,o)=>a-o),r=[{intervals:[0,4,7],quality:"maj"},{intervals:[0,3,7],quality:"min"},{intervals:[0,4,7,11],quality:"maj7"},{intervals:[0,3,7,10],quality:"min7"},{intervals:[0,4,7,10],quality:"7"},{intervals:[0,3,6],quality:"dim"},{intervals:[0,4,8],quality:"aug"},{intervals:[0,3,6,9],quality:"dim7"},{intervals:[0,2,7],quality:"sus2"},{intervals:[0,5,7],quality:"sus4"},{intervals:[0,4,7,9],quality:"6"},{intervals:[0,3,7,9],quality:"min6"}];for(const a of n){const o=n.map(i=>(i-a+12)%12).sort((i,l)=>i-l);for(const i of r)if(i.intervals.length===o.length&&i.intervals.every((l,c)=>l===o[c])){const l=t[a],c=t[e[0]%12];return{root:l,quality:i.quality,bass:c!==l?c:void 0,symbol:`${l}${i.quality==="maj"?"":i.quality}${c!==l?`/${c}`:""}`,intervals:i.intervals}}}return null}const Rl={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],aeolian:[0,2,3,5,7,8,10],locrian:[0,1,3,5,6,8,10],"harmonic-minor":[0,2,3,5,7,8,11],"melodic-minor":[0,2,3,5,7,9,11],"pentatonic-major":[0,2,4,7,9],"pentatonic-minor":[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11],"whole-tone":[0,2,4,6,8,10]};function f0(e,t,n){const r=Rl[n],a=(e-t+120)%12;let o=r[0],i=999;for(const c of r){const d=Math.min(Math.abs(a-c),12-Math.abs(a-c));d<i&&(i=d,o=c)}const l=Math.floor((e-t)/12);return t+l*12+o}function p0(e,t){switch(t.type){case"transpose":return e.map(n=>({...n,pitch:Math.max(0,Math.min(127,n.pitch+(t.params.semitones??0)))}));case"invert":{const n=t.params.axis??60;return e.map(r=>({...r,pitch:Math.max(0,Math.min(127,Math.round(2*n-r.pitch)))}))}case"retrograde":{if(e.length===0)return e;const n=Math.max(...e.map(r=>r.startTick+r.durationTicks));return e.map(r=>({...r,startTick:n-r.startTick-r.durationTicks}))}case"randomize-velocity":return e.map(n=>({...n,velocity:Math.max(1,Math.min(127,n.velocity+Math.round((Math.random()-.5)*2*(t.params.range??20))))}));default:return e}}function m0(e){return e>=95?"S":e>=85?"A":e>=70?"B":e>=55?"C":e>=40?"D":"F"}const g0={"guitar-standard":{instrument:"guitar-6",stringPitches:[40,45,50,55,59,64]},"guitar-drop-d":{instrument:"guitar-6",stringPitches:[38,45,50,55,59,64]},"bass-standard":{instrument:"bass-4",stringPitches:[28,33,38,43]},"ukulele-standard":{instrument:"ukulele",stringPitches:[67,60,64,69]}},y0={"Bass Drum":{staffLine:4,noteHead:"normal",stem:"down"},Snare:{staffLine:2,noteHead:"normal",stem:"up"},"Hi-Hat Closed":{staffLine:0,noteHead:"x",stem:"up"},"Hi-Hat Open":{staffLine:0,noteHead:"diamond",stem:"up"},Ride:{staffLine:-1,noteHead:"x",stem:"up"},Crash:{staffLine:-2,noteHead:"x",stem:"up"},"High Tom":{staffLine:1,noteHead:"normal",stem:"up"},"Mid Tom":{staffLine:2,noteHead:"normal",stem:"down"},"Low Tom":{staffLine:3,noteHead:"normal",stem:"down"}};exports.ALL_CAP_STYLES=Cn;exports.ALL_EFFECTS=dp;exports.ALL_TEXTURES=ko;exports.ARTNET_PORT=Bp;exports.ASYMMETRIC_CAPS=po;exports.ArpeggiatorPanel=Vs;exports.AudioEffectType=yl;exports.AudioPitchAnalyzer=jo;exports.AudioPlaybackEngine=Kh;exports.AudioRecorder=Js;exports.AudioTimeline=Ls;exports.AutoSavePanel=Ks;exports.BarFillEditor=Mo;exports.CCAutomationLaneEditor=zs;exports.CCLane=Es;exports.CONTROLLER_PROFILES=Ci;exports.ChaseRunner=Kp;exports.CollaboratorPermission=bl;exports.DEFAULT_ARP_CONFIG=Ar;exports.DEFAULT_BAR_FILL=At;exports.DEFAULT_CAP_STYLE=go;exports.DEFAULT_EMPTY_BAR_FILL=lr;exports.DEFAULT_FONT_SETTINGS=ur;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=cr;exports.DEFAULT_GOLD_FILLED_BAR_FILL=dr;exports.DEFAULT_KARAOKE_SETTINGS=yo;exports.DEFAULT_PLAYER_BAR_STYLE=Xt;exports.DEFAULT_SEED_CONFIG=mi;exports.DMXEngine=wl;exports.DRUM_PATTERN_NAMES=cf;exports.DefaultScoringPresets=ta;exports.DmxChannelControl=Ta;exports.DmxChannelType=kt;exports.DmxEditor=xl;exports.DmxOptionsControl=$a;exports.DmxSliderControl=kn;exports.DynamicRuleEditor=Zo;exports.DynamicRuleField=Ye;exports.DynamicRuleOperator=Ze;exports.EditorTrackProvider=Qr;exports.EditorUndoManager=ed;exports.FIXTURE_PROFILES=Sl;exports.GENERIC_PROFILE=Sa;exports.GM_DRUM_MAP=y0;exports.GRADIENT_PRESETS=Ro;exports.GROOVE_TEMPLATES=Ma;exports.GenericPlayer=Do;exports.GenericPlayerControls=_o;exports.GenericPlayerStage=zo;exports.GenericPlayerStageVisualizer=Go;exports.GenericPlaylist=Wo;exports.GenericPlaylistItem=pa;exports.KARAOKE_FONT_OPTIONS=Hd;exports.KEY_MAPS=Po;exports.KaraokeEditorManager=Io;exports.KaraokeFormat=gl;exports.KaraokeLyrics=ao;exports.KaraokePhaserRenderer=Lo;exports.KaraokeTimeline=wo;exports.LANE_COLORS=yn;exports.LAUNCH_CONTROL_PROFILE=wi;exports.LAYER_COLORS=Lp;exports.LFOPanel=qs;exports.MINILAB_PROFILE=Si;exports.MPK_MINI_PROFILE=xi;exports.MasterFXPanel=Xs;exports.MidiCCMapper=uf;exports.ModeSwitcher=ha;exports.NOTE_NAMES=nf;exports.NiceArpeggiatorPanel=Vs;exports.NiceAudioErrorBoundary=Ol;exports.NiceAudioPitchAnalyzer=jo;exports.NiceAudioTimeline=Ls;exports.NiceAutoSavePanel=Ks;exports.NiceBarFillEditor=Mo;exports.NiceCCAutomationLaneEditor=zs;exports.NiceCCLane=Es;exports.NiceDMXTimeline=Yp;exports.NiceDmxChannelControl=Ta;exports.NiceDmxEditor=xl;exports.NiceDmxOptionsControl=$a;exports.NiceDmxSliderControl=kn;exports.NiceDynamicRuleEditor=Zo;exports.NiceEditorTrackProvider=Qr;exports.NiceGenericPlayer=Do;exports.NiceGenericPlayerControls=_o;exports.NiceGenericPlayerStage=zo;exports.NiceGenericPlayerStageVisualizer=Go;exports.NiceGenericPlaylist=Wo;exports.NiceGenericPlaylistItem=pa;exports.NiceI18nProvider=Dl;exports.NiceKaraokeEditorManager=Io;exports.NiceKaraokeLyrics=ao;exports.NiceKaraokePhaserRenderer=Lo;exports.NiceKaraokeTimeline=wo;exports.NiceLFOPanel=qs;exports.NiceMasterFXPanel=Xs;exports.NiceModeSwitcher=ha;exports.NiceNoteParticles=fi;exports.NiceNoteRiver=hi;exports.NicePianoRoll=Ps;exports.NicePlaylistBrowser=ei;exports.NicePlaylistDualPane=Xo;exports.NicePlaylistGridView=ri;exports.NicePlaylistImportWizard=ii;exports.NicePlaylistList=ba;exports.NicePlaylistOverview=ai;exports.NicePlaylistSearchBar=si;exports.NicePlaylistSidebar=ni;exports.NicePlaylistTagEditor=Uo;exports.NicePlaylistTrackList=ga;exports.NiceRadioPlayer=Jp;exports.NiceRecordingOptionsPanel=Qs;exports.NiceStageVisualizer=fa;exports.NiceStationBrowser=kl;exports.NiceStepSequencerPanel=Hs;exports.NiceStreamingVisualizer=Pa;exports.NiceUndoRedoPanel=Ys;exports.NiceVoiceChatOverlay=jl;exports.NiceWaveform=Ts;exports.NiceYouTubePlayer=Bo;exports.NiceZoomSnapControls=Zs;exports.NoteParticles=fi;exports.NoteRiver=hi;exports.OVERLAY_PATTERNS=nr;exports.OXYGEN25_PROFILE=vi;exports.PLAYER_COLORS=Pt;exports.PLAYER_COLOR_VARS=Zn;exports.PROGRESSION_NAMES=lf;exports.PadNotePlayer=Xd;exports.PaneSide=qo;exports.PianoRoll=Ps;exports.PlaylistBrowser=ei;exports.PlaylistDualPane=Xo;exports.PlaylistGridView=ri;exports.PlaylistImportWizard=ii;exports.PlaylistList=ba;exports.PlaylistOverview=ai;exports.PlaylistSearchBar=si;exports.PlaylistSidebar=ni;exports.PlaylistTagEditor=Uo;exports.PlaylistTrackList=ga;exports.PlaylistType=ma;exports.RecordingOptionsPanel=Qs;exports.SACN_PORT=Vp;exports.SCALE_INTERVALS=Rl;exports.SCALE_NAMES=of;exports.SKEW_CAPS=mo;exports.STANDARD_TUNINGS=g0;exports.SYMMETRIC_CAPS=ia;exports.ShortcutManager=pl;exports.SimpleSynth=pi;exports.SortDirection=qt;exports.SortField=Ho;exports.StageVisualizer=fa;exports.StepSequencerPanel=Hs;exports.StreamingVisualizer=Pa;exports.TEXTURE_CATEGORIES=ca;exports.TrackSource=lt;exports.UndoRedoPanel=Ys;exports.ViewMode=Vo;exports.VocalEffectsEngine=up;exports.VoiceChatOverlay=jl;exports.Waveform=Ts;exports.WebRTCAudioManager=Ml;exports.YouTubePlayer=Bo;exports.ZoomSnapControls=Zs;exports.addEffectToLayer=Gf;exports.addMidiNote=Vf;exports.analyzeAudioFileWithAlgorithm=ep;exports.applyGroove=ip;exports.applyGrooveTemplate=dl;exports.applyHumanize=cl;exports.applyKaraokeDisplayVars=ua;exports.applyMidiTransform=p0;exports.applySwing=ll;exports.arrow_L=Mt;exports.arrow_R=gt;exports.autoCorrelate=Ef;exports.bracket_L=ra;exports.bracket_R=ho;exports.buildArpSequence=Bs;exports.buildLanes=Eo;exports.buildNoteDescriptors=Af;exports.buildPadNoteEvents=No;exports.buildSegmentScores=Nf;exports.canRedo=Ti;exports.canUndo=$i;exports.chamfer_L=Qn;exports.chamfer_R=Zt;exports.clearMidiNotes=Hf;exports.clearPattern=Hi;exports.computeGrade=m0;exports.computeTheoreticalMax=al;exports.computeVocalPerformanceReport=hp;exports.convertBrowserSongToKaraokeSongFile=zf;exports.copyCCEvents=qr;exports.createAnalyserNode=Qi;exports.createArpPattern=bf;exports.createArtNetPacket=Up;exports.createBasslinePattern=vf;exports.createCCHistory=ki;exports.createCompressorNode=el;exports.createDefaultLFO=ir;exports.createDefaultShortcuts=Mp;exports.createDropZoneHandlers=Np;exports.createEmptyPattern=Nt;exports.createEmptyStep=wa;exports.createGainNode=Ji;exports.createHiHatPattern=yf;exports.createKickPattern=mf;exports.createLoopRegion=vp;exports.createSACNPacket=qp;exports.createSnarePattern=gf;exports.createVocoderNode=tl;exports.createVoiceChatAudioContext=a0;exports.cutCCEvents=Ei;exports.deleteCCEventsInRange=Ai;exports.deserializeLFO=dc;exports.deserializePattern=Sf;exports.detectChord=h0;exports.downsampleAndQuantizePitchPoints=If;exports.drawGlossyBarOnCanvas=hn;exports.drawTimeline=Dr;exports.estimateLatencyMs=Lf;exports.estimateLatencyMsFromRecording=mp;exports.evaluateLFO=Zr;exports.evaluateLFOAsCC=Xr;exports.exportCCLane=Li;exports.extractBpmFromNotes=so;exports.findTextureByUrl=Ud;exports.formatShortcut=jp;exports.generateArpEvents=fc;exports.generatePlaceholderWaveform=sp;exports.generateSeed=bi;exports.generateUltrastarText=tp;exports.getActiveGradient=To;exports.getActiveLyrics=od;exports.getActiveWords=id;exports.getAlgorithmColor=Df;exports.getAlgorithmCssVar=Of;exports.getAlgorithmLabel=Ff;exports.getArpModes=Ws;exports.getArpRates=Us;exports.getAudioContext=tn;exports.getAudioInputDevices=r0;exports.getAudioWorkletProcessorCode=Zi;exports.getBackgroundUrl=Pf;exports.getCachedImage=Gd;exports.getCapStyleByName=dn;exports.getComboMultiplier=rl;exports.getCoverUrl=Tf;exports.getGrooveTemplate=lp;exports.getGrooveTemplateNames=cp;exports.getLaneForPitch=Ao;exports.getNextPlayerColor=Fp;exports.getNextPlayerColorCss=Dp;exports.getOverlayCanvasPattern=gn;exports.getPatternByName=un;exports.getSACNMulticastAddress=Hp;exports.getScoringPreset=lo;exports.getTexturePattern=pn;exports.getVerseRatingLabel=nl;exports.handleAddCCEvent=Yf;exports.handleRedo=Jc;exports.handleRemoveCCEvent=Xf;exports.handleSelectCCLane=Kf;exports.handleUndo=Qc;exports.handleUpdateCCEvent=Zf;exports.hexToHsl=rr;exports.humanizeMidiNotes=bp;exports.hydrateKaraokeDisplayFromBackend=Kd;exports.hydratePlayerKaraokeSettingsFromBackend=vd;exports.hzToUltrastarPitch=oo;exports.importCCLane=Fi;exports.initKaraokeDisplaySettings=Zd;exports.instrumentPresets=Yh;exports.isAudioContextRunning=As;exports.isInLoopRegion=wp;exports.isWebRTCSupported=n0;exports.loadAllKaraokeSettings=xd;exports.loadAudioWorkletModule=Xi;exports.loadKaraokeDisplaySettings=$o;exports.loadKaraokeSettings=bo;exports.loadPlayerBarStyle=vo;exports.loadPlayerBarStyles=wd;exports.loadRemoteScoringPresets=md;exports.makeClickReference=hl;exports.makeClipSelectionId=np;exports.mergeWaveforms=ap;exports.midiSeedGenerator=df;exports.midiToHz=Or;exports.normalizeHex=ar;exports.openAudioFilePicker=Ip;exports.ornate_L=sa;exports.ornate_R=tr;exports.parseLyrics=ad;exports.parseNotes=ea;exports.parseVersesWithSyllables=ro;exports.parseVersesWithWords=sd;exports.parseVideoMetadata=ol;exports.pasteCCEvents=Pi;exports.pill_L=$t;exports.pill_R=Ct;exports.preloadTexture=la;exports.preloadTextures=Bd;exports.probeAudioFile=ml;exports.pushCCState=Mi;exports.pushOperation=l0;exports.quantizeMidiNotes=gp;exports.quantizeNotes=u0;exports.quantizeStepInBeats=fl;exports.quantizeStepInSeconds=ja;exports.randomizeVelocity=qi;exports.recordCCEvent=Ni;exports.redoCC=Ri;exports.redoOperation=d0;exports.removeEffectFromLayer=Bf;exports.removeMidiNote=qf;exports.renderGlossyBarSvg=xo;exports.resumeAudioContext=Et;exports.reversePattern=Ui;exports.sampleLFOForDisplay=_s;exports.sampleLFOToCCEvents=Os;exports.saveKaraokeDisplaySettings=Yd;exports.saveKaraokeSettings=bd;exports.savePlayerBarStyle=Sd;exports.scaleResult=$f;exports.scaleTo10k=sl;exports.scoreNotesWithPitchPoints=Rf;exports.selectCCEventsInRange=hf;exports.serializeLFO=cc;exports.serializePattern=xf;exports.setLoopFromSelection=xp;exports.setProjectWithUndo=to;exports.setStepGate=zi;exports.setStepNote=Oi;exports.setStepProbability=Gi;exports.setStepVelocity=_i;exports.sharp_L=Kt;exports.sharp_R=Yt;exports.shield_L=Jn;exports.shield_R=uo;exports.shiftPattern=Vi;exports.shouldTrigger=Yi;exports.skewTL_L=Un;exports.skewTL_R=Fr;exports.skewTR_L=Lr;exports.skewTR_R=Vn;exports.snapLoopToGrid=Sp;exports.snapTimeToQuantize=Hr;exports.snapToGrid=rp;exports.snapToScale=f0;exports.soft_L=na;exports.soft_R=co;exports.stepDuration=Ca;exports.stepTimeOffset=Ki;exports.syncDivisionToHz=Fs;exports.tab_L=aa;exports.tab_R=fo;exports.thinCCEvents=Ii;exports.toTrack=_f;exports.toggleEffectBypass=Wf;exports.toggleStep=Di;exports.toggleStepSlide=Bi;exports.transposePattern=Wi;exports.undoCC=ji;exports.undoOperation=c0;exports.updateEffectParams=Uf;exports.useAudioWorklet=jf;exports.useAutoSave=Kc;exports.useCCAutomation=pf;exports.useDMXAudioSync=Xp;exports.useDMXEngine=Zp;exports.useEditorTrack=rd;exports.useLocalPlaylists=ya;exports.useMPE=Jh;exports.useMidiLearn=Xh;exports.useNiceTranslation=xe;exports.useOxygen25=tf;exports.usePitchWorker=Cf;exports.usePlaybackEngine=Yc;exports.useProjectCRUD=nd;exports.useRadioStream=Cl;exports.useRecording=Zc;exports.useScoringWorker=kf;exports.useStepSequencer=wf;exports.useWebMidi=pr;exports.useWorker=ka;exports.validateAudioFiles=Ra;exports.wave_L=er;exports.wave_R=oa;exports.waveformValue=Ds;exports.wrapTimeInLoop=Cp;
412
+ E`}}function np(e,t){return`${e}:${t}`}function rp(e,t,n,r=1){if(t==="off")return e;const a=60/n;if(t==="beat")return Math.round(e/(a/r))*(a/r);if(t==="bar"){const o=a*4;return Math.round(e/o)*o}return e}function ap(e){return e.length===0?[]:e.flat()}function sp(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const Ma=[{id:"mpc-60-tight",name:"MPC 60 Tight",stepsPerBar:16,timingOffsets:[0,.02,0,.01,0,.03,0,.01,0,.02,0,.01,0,.03,0,.01],velocityScales:[1.1,.85,.95,.8,1.05,.85,.9,.8,1.1,.85,.95,.8,1.05,.85,.9,.8],durationScales:[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]},{id:"mpc-60-swing",name:"MPC 60 Swing",stepsPerBar:16,timingOffsets:[0,.06,0,.04,0,.07,0,.04,0,.06,0,.04,0,.07,0,.04],velocityScales:[1.15,.7,.9,.75,1.1,.7,.85,.75,1.15,.7,.9,.75,1.1,.7,.85,.75],durationScales:[1.05,.9,1,.95,1.05,.9,1,.95,1.05,.9,1,.95,1.05,.9,1,.95]},{id:"hip-hop-lazy",name:"Hip-Hop Lazy",stepsPerBar:16,timingOffsets:[0,.04,.01,.05,0,.04,.02,.06,0,.04,.01,.05,0,.04,.02,.06],velocityScales:[1.2,.65,.85,.6,1.1,.65,.8,.6,1.2,.65,.85,.6,1.1,.65,.8,.6],durationScales:[1.1,1,1,.9,1.1,1,1,.9,1.1,1,1,.9,1.1,1,1,.9]},{id:"funk-pocket",name:"Funk Pocket",stepsPerBar:16,timingOffsets:[0,-.01,.03,0,0,-.01,.04,0,0,-.01,.03,0,0,-.01,.04,0],velocityScales:[1.2,.9,.7,1.05,.85,.9,.7,1,1.15,.9,.7,1.05,.85,.9,.7,1],durationScales:[1,.95,1.1,1,1,.95,1.1,1,1,.95,1.1,1,1,.95,1.1,1]},{id:"shuffle-blues",name:"Shuffle / Blues",stepsPerBar:8,timingOffsets:[0,.11,0,.11,0,.11,0,.11],velocityScales:[1.2,.8,1.1,.8,1.2,.8,1.1,.8],durationScales:[1.1,.8,1.1,.8,1.1,.8,1.1,.8]},{id:"reggaeton",name:"Reggaeton",stepsPerBar:16,timingOffsets:[0,0,0,.03,0,0,0,.03,0,0,0,.03,0,0,0,.03],velocityScales:[1.3,.6,.9,1.1,.7,.6,.9,1.1,1.3,.6,.9,1.1,.7,.6,.9,1.1],durationScales:[1,1,1,.9,1,1,1,.9,1,1,1,.9,1,1,1,.9]}];function op(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function ll(e,t){return t.amount===0?e:e.map(n=>{const r=n.time/t.grid;if(Math.round(r)%2===1){const i=t.grid*t.amount*.5;return{...n,time:n.time+i}}return{...n}})}function cl(e,t){const n=t.seed!=null?op(t.seed):Math.random;return e.map(r=>{const a=(n()-.5)*2*t.timingAmount,o=Math.round((n()-.5)*2*t.velocityAmount),i=(n()-.5)*2*t.durationAmount;return{...r,time:Math.max(0,r.time+a),velocity:Math.max(1,Math.min(127,r.velocity+o)),duration:Math.max(.01,r.duration+i)}})}function dl(e,t,n=1){const r=4/t.stepsPerBar;return e.map(a=>{const o=a.time/r,i=Math.round(o)%t.stepsPerBar,l=t.timingOffsets[i]*r*n,c=1+(t.velocityScales[i]-1)*n,d=1+(t.durationScales[i]-1)*n;return{...a,time:Math.max(0,a.time+l),velocity:Math.max(1,Math.min(127,Math.round(a.velocity*c))),duration:Math.max(.01,a.duration*d)}})}function ip(e,t){let n=[...e.map(r=>({...r}))];return t.template&&t.grooveStrength>0&&(n=dl(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=ll(n,t.swing)),t.humanize&&(n=cl(n,t.humanize)),n}function lp(e){return Ma.find(t=>t.id===e)}function cp(){return Ma.map(({id:e,name:t})=>({id:e,name:t}))}const dp=[{type:"chipmunk",enabled:!1,intensity:60,label:"Chipmunk",icon:"🐿️"},{type:"helium",enabled:!1,intensity:80,label:"Helium",icon:"🎈"},{type:"deep",enabled:!1,intensity:50,label:"Deep Voice",icon:"🎸"},{type:"demon",enabled:!1,intensity:70,label:"Demon",icon:"😈"},{type:"robot",enabled:!1,intensity:50,label:"Robot",icon:"🤖"},{type:"alien",enabled:!1,intensity:60,label:"Alien",icon:"👽"},{type:"echo",enabled:!1,intensity:50,label:"Echo",icon:"🏔️"},{type:"cave",enabled:!1,intensity:60,label:"Cave",icon:"🕳️"},{type:"reverb",enabled:!1,intensity:50,label:"Reverb",icon:"⛪"},{type:"chorus",enabled:!1,intensity:50,label:"Chorus",icon:"🎵"},{type:"flanger",enabled:!1,intensity:50,label:"Flanger",icon:"🌊"},{type:"distortion",enabled:!1,intensity:40,label:"Distortion",icon:"🔥"},{type:"telephone",enabled:!1,intensity:80,label:"Telephone",icon:"📞"},{type:"megaphone",enabled:!1,intensity:60,label:"Megaphone",icon:"📢"},{type:"radio",enabled:!1,intensity:70,label:"AM Radio",icon:"📻"},{type:"underwater",enabled:!1,intensity:50,label:"Underwater",icon:"🌊"},{type:"whisper",enabled:!1,intensity:60,label:"Whisper",icon:"🤫"},{type:"tremolo",enabled:!1,intensity:50,label:"Tremolo",icon:"〰️"},{type:"autotune",enabled:!1,intensity:60,label:"Auto-Tune",icon:"🎤"},{type:"vocoder",enabled:!1,intensity:50,label:"Vocoder",icon:"🔊"}];function Ms(e,t,n){const r=e.sampleRate,a=Math.round(r*t),o=e.createBuffer(2,a,r);for(let i=0;i<2;i++){const l=o.getChannelData(i);for(let c=0;c<a;c++)l[c]=(Math.random()*2-1)*Math.pow(1-c/a,n)}return o}function Bn(e){const t=Math.max(1,e),n=44100,r=new Float32Array(n),a=Math.PI/180;for(let o=0;o<n;o++){const i=o*2/n-1;r[o]=(3+t)*i*20*a/(Math.PI+t*Math.abs(i))}return r}class up{constructor(){this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.activeEffects=new Map,this.effectOrder=[],this.monitoring=!0,this._volume=1,this._inputVolume=1,this.started=!1,this.externalStream=!1,this.analyser=null}get isStarted(){return this.started}get context(){return this.audioCtx}get activeEffectTypes(){return[...this.effectOrder]}async start(t){this.started||(this.audioCtx=new AudioContext,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),this.sourceNode=this.audioCtx.createMediaStreamSource(this.mediaStream),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}async startWithStream(t){this.started||(this.externalStream=!0,this.audioCtx=new AudioContext,this.mediaStream=t,this.sourceNode=this.audioCtx.createMediaStreamSource(t),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}stop(){var t,n,r,a,o,i;this.clearAllEffects();try{(t=this.analyser)==null||t.disconnect()}catch{}try{(n=this.outputGain)==null||n.disconnect()}catch{}try{(r=this.inputGain)==null||r.disconnect()}catch{}try{(a=this.sourceNode)==null||a.disconnect()}catch{}try{(o=this.audioCtx)==null||o.close()}catch{}if(!this.externalStream)try{(i=this.mediaStream)==null||i.getTracks().forEach(l=>l.stop())}catch{}this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.analyser=null,this.started=!1}setMonitoring(t){this.monitoring=t,this.outputGain&&(this.outputGain.gain.value=t?this._volume:0)}setVolume(t){this._volume=Math.max(0,Math.min(2,t)),this.outputGain&&this.monitoring&&(this.outputGain.gain.value=this._volume)}setInputGain(t){this._inputVolume=Math.max(0,Math.min(3,t)),this.inputGain&&(this.inputGain.gain.value=this._inputVolume)}getLevel(){if(!this.analyser)return 0;const t=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(t);let n=0;for(let r=0;r<t.length;r++){const a=(t[r]-128)/128;n+=a*a}return Math.sqrt(n/t.length)}addEffect(t,n=50){if(!this.audioCtx||!this.inputGain||!this.outputGain||this.activeEffects.has(t))return;const r=this.buildEffectChain(t,n);r&&(this.activeEffects.set(t,r),this.effectOrder.push(t),this.reconnectChain())}removeEffect(t){const n=this.activeEffects.get(t);if(n){for(const r of n.nodes)try{r.disconnect()}catch{}this.activeEffects.delete(t),this.effectOrder=this.effectOrder.filter(r=>r!==t),this.reconnectChain()}}toggleEffect(t,n=50){return this.activeEffects.has(t)?(this.removeEffect(t),!1):(this.addEffect(t,n),!0)}updateIntensity(t,n){this.activeEffects.has(t)&&(this.removeEffect(t),this.addEffect(t,n))}clearAllEffects(){for(const[t]of this.activeEffects){const n=this.activeEffects.get(t);if(n)for(const r of n.nodes)try{r.disconnect()}catch{}}this.activeEffects.clear(),this.effectOrder=[],this.reconnectChain()}reconnectChain(){if(!this.inputGain||!this.outputGain)return;try{this.inputGain.disconnect()}catch{}for(const[,n]of this.activeEffects)try{n.output.disconnect()}catch{}if(this.effectOrder.length===0){this.inputGain.connect(this.outputGain);return}let t=this.inputGain;for(const n of this.effectOrder){const r=this.activeEffects.get(n);r&&(t.connect(r.input),t=r.output)}t.connect(this.outputGain)}buildEffectChain(t,n){const r=this.audioCtx,a=n/100;switch(t){case"chipmunk":return this.buildPitchShift(r,1+a*.8,a);case"helium":return this.buildPitchShift(r,1.5+a*1,a);case"deep":return this.buildPitchShift(r,1/(1+a*.5),a);case"demon":return this.buildDemon(r,a);case"robot":return this.buildRobot(r,a);case"alien":return this.buildAlien(r,a);case"echo":return this.buildDelay(r,.15+a*.35,.3+a*.4,a);case"cave":return this.buildCave(r,a);case"reverb":return this.buildReverb(r,1.5+a*3,2+a*4,a);case"chorus":return this.buildChorus(r,a);case"flanger":return this.buildFlanger(r,a);case"distortion":return this.buildDistortion(r,20+a*100,a);case"telephone":return this.buildBandpass(r,400,3500,a);case"megaphone":return this.buildMegaphone(r,a);case"radio":return this.buildRadio(r,a);case"underwater":return this.buildUnderwater(r,a);case"whisper":return this.buildWhisper(r,a);case"tremolo":return this.buildTremolo(r,a);case"autotune":return this.buildAutotune(r,a);case"vocoder":return this.buildVocoder(r,a);default:return null}}buildPitchShift(t,n,r){const a=t.createGain();a.gain.value=1;const o=t.createGain();o.gain.value=1;const i=t.createGain();i.gain.value=.7+r*.3;const l=t.createGain();l.gain.value=1-r*.5;const c=t.createDelay(1),d=t.createDelay(1),h=t.createOscillator(),f=t.createOscillator(),m=t.createGain(),g=t.createGain(),p=n-1,v=Math.abs(p)*5+2,x=Math.abs(p)*.015;h.type="sawtooth",h.frequency.value=v,m.gain.value=x,h.connect(m),m.connect(c.delayTime),c.delayTime.value=.02,f.type="sawtooth",f.frequency.value=v,g.gain.value=x,f.connect(g),g.connect(d.delayTime),d.delayTime.value=.02+x;const b=t.createGain();b.gain.value=.5;const w=t.createGain();return w.gain.value=.5,a.connect(c),a.connect(d),c.connect(b),d.connect(w),b.connect(i),w.connect(i),a.connect(l),i.connect(o),l.connect(o),h.start(),f.start(),{type:"chipmunk",nodes:[a,c,d,h,f,m,g,b,w,i,l,o],input:a,output:o}}buildRobot(t,n){const r=t.createGain(),a=t.createGain(),o=t.createGain();o.gain.value=.6+n*.4;const i=t.createGain();i.gain.value=1-n*.6;const l=t.createOscillator();l.type="square",l.frequency.value=50+n*200;const c=t.createGain();return c.gain.value=0,l.connect(c.gain),r.connect(c),c.connect(o),r.connect(i),o.connect(a),i.connect(a),l.start(),{type:"robot",nodes:[r,l,c,o,i,a],input:r,output:a}}buildAlien(t,n){const r=t.createGain(),a=t.createGain(),o=t.createOscillator();o.type="sine",o.frequency.value=300+n*700;const i=t.createGain();i.gain.value=0,o.connect(i.gain),r.connect(i);const l=t.createDelay(.1);l.delayTime.value=.005;const c=t.createOscillator();c.type="sine",c.frequency.value=3+n*10;const d=t.createGain();d.gain.value=.004,c.connect(d),d.connect(l.delayTime),i.connect(l),l.connect(a);const h=t.createGain();return h.gain.value=.3,r.connect(h),h.connect(a),o.start(),c.start(),{type:"alien",nodes:[r,o,i,l,c,d,h,a],input:r,output:a}}buildDelay(t,n,r,a){const o=t.createGain(),i=t.createGain(),l=t.createDelay(2);l.delayTime.value=n;const c=t.createGain();c.gain.value=Math.min(.85,r);const d=t.createGain();d.gain.value=.5+a*.5;const h=t.createGain();return h.gain.value=1,o.connect(l),l.connect(c),c.connect(l),l.connect(d),o.connect(h),d.connect(i),h.connect(i),{type:"echo",nodes:[o,l,c,d,h,i],input:o,output:i}}buildCave(t,n){const r=t.createGain(),a=t.createGain(),o=t.createDelay(2);o.delayTime.value=.2+n*.3;const i=t.createDelay(2);i.delayTime.value=.35+n*.25;const l=t.createDelay(2);l.delayTime.value=.55+n*.3;const c=t.createGain();c.gain.value=.5;const d=t.createGain();d.gain.value=.35;const h=t.createGain();h.gain.value=.25;const f=t.createConvolver();f.buffer=Ms(t,2+n*3,3);const m=t.createGain();m.gain.value=.3+n*.3,r.connect(o),o.connect(c),c.connect(o),r.connect(i),i.connect(d),d.connect(i),r.connect(l),l.connect(h),h.connect(l),o.connect(m),i.connect(m),l.connect(m),r.connect(f),f.connect(m);const g=t.createGain();return g.gain.value=.7,r.connect(g),g.connect(a),m.connect(a),{type:"cave",nodes:[r,o,i,l,c,d,h,f,m,g,a],input:r,output:a}}buildReverb(t,n,r,a){const o=t.createGain(),i=t.createGain(),l=t.createConvolver();l.buffer=Ms(t,n,r);const c=t.createGain();c.gain.value=.4+a*.5;const d=t.createGain();return d.gain.value=1,o.connect(l),l.connect(c),o.connect(d),c.connect(i),d.connect(i),{type:"reverb",nodes:[o,l,c,d,i],input:o,output:i}}buildChorus(t,n){const r=t.createGain(),a=t.createGain(),o=[{delayMs:20,lfoFreq:.5,depth:.003},{delayMs:25,lfoFreq:.7,depth:.004},{delayMs:30,lfoFreq:1.1,depth:.005}],i=[r,a],l=t.createGain();l.gain.value=.7,r.connect(l),l.connect(a),i.push(l);for(const c of o){const d=t.createDelay(.1);d.delayTime.value=c.delayMs/1e3;const h=t.createOscillator();h.type="sine",h.frequency.value=c.lfoFreq;const f=t.createGain();f.gain.value=c.depth*(.5+n),h.connect(f),f.connect(d.delayTime);const m=t.createGain();m.gain.value=.3+n*.2,r.connect(d),d.connect(m),m.connect(a),h.start(),i.push(d,h,f,m)}return{type:"chorus",nodes:i,input:r,output:a}}buildFlanger(t,n){const r=t.createGain(),a=t.createGain(),o=t.createDelay(.02);o.delayTime.value=.005;const i=t.createOscillator();i.type="sine",i.frequency.value=.2+n*2;const l=t.createGain();l.gain.value=.003+n*.002,i.connect(l),l.connect(o.delayTime);const c=t.createGain();c.gain.value=.5+n*.35;const d=t.createGain();d.gain.value=.5+n*.3;const h=t.createGain();return h.gain.value=1,r.connect(o),o.connect(c),c.connect(o),o.connect(d),r.connect(h),d.connect(a),h.connect(a),i.start(),{type:"flanger",nodes:[r,o,i,l,c,d,h,a],input:r,output:a}}buildDistortion(t,n,r){const a=t.createGain(),o=t.createGain(),i=t.createWaveShaper();i.curve=Bn(n),i.oversample="4x";const l=t.createGain();l.gain.value=.6+r*.4;const c=t.createGain();return c.gain.value=1-r*.4,a.connect(i),i.connect(l),a.connect(c),l.connect(o),c.connect(o),{type:"distortion",nodes:[a,i,l,c,o],input:a,output:o}}buildBandpass(t,n,r,a){const o=t.createGain(),i=t.createGain(),l=t.createBiquadFilter();l.type="highpass",l.frequency.value=n,l.Q.value=.7;const c=t.createBiquadFilter();return c.type="lowpass",c.frequency.value=r,c.Q.value=.7,o.connect(l),l.connect(c),c.connect(i),{type:"telephone",nodes:[o,l,c,i],input:o,output:i}}buildMegaphone(t,n){const r=t.createGain(),a=t.createGain(),o=t.createBiquadFilter();o.type="highpass",o.frequency.value=500;const i=t.createBiquadFilter();i.type="lowpass",i.frequency.value=4e3;const l=t.createWaveShaper();l.curve=Bn(15+n*30),l.oversample="2x";const c=t.createBiquadFilter();return c.type="peaking",c.frequency.value=2e3,c.gain.value=6+n*6,c.Q.value=1,r.connect(o),o.connect(i),i.connect(l),l.connect(c),c.connect(a),{type:"megaphone",nodes:[r,o,i,l,c,a],input:r,output:a}}buildRadio(t,n){const r=t.createGain(),a=t.createGain(),o=t.createBiquadFilter();o.type="highpass",o.frequency.value=300+n*200;const i=t.createBiquadFilter();i.type="lowpass",i.frequency.value=3e3-n*500;const l=t.createBiquadFilter();l.type="peaking",l.frequency.value=1500,l.gain.value=8,l.Q.value=2;const c=t.createWaveShaper();return c.curve=Bn(10),r.connect(o),o.connect(i),i.connect(l),l.connect(c),c.connect(a),{type:"radio",nodes:[r,o,i,l,c,a],input:r,output:a}}buildUnderwater(t,n){const r=t.createGain(),a=t.createGain(),o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=300+(1-n)*400,o.Q.value=5+n*10;const i=t.createOscillator();i.type="sine",i.frequency.value=.5+n*2;const l=t.createGain();l.gain.value=100+n*200,i.connect(l),l.connect(o.frequency);const c=t.createGain();c.gain.value=.7+n*.3;const d=t.createGain();return d.gain.value=.3-n*.2,r.connect(o),o.connect(c),r.connect(d),c.connect(a),d.connect(a),i.start(),{type:"underwater",nodes:[r,o,i,l,c,d,a],input:r,output:a}}buildWhisper(t,n){const r=t.createGain(),a=t.createGain(),o=t.createBiquadFilter();o.type="highpass",o.frequency.value=500+n*500,o.Q.value=.5;const i=t.createWaveShaper(),l=new Float32Array(256);for(let d=0;d<256;d++){const h=d/255*2-1;l[d]=Math.sign(h)*Math.pow(Math.abs(h),.3+n*.5)}i.curve=l;const c=t.createBiquadFilter();return c.type="highshelf",c.frequency.value=3e3,c.gain.value=6+n*6,r.connect(o),o.connect(i),i.connect(c),c.connect(a),{type:"whisper",nodes:[r,o,i,c,a],input:r,output:a}}buildDemon(t,n){const r=t.createGain(),a=t.createGain(),o=t.createDelay(.1);o.delayTime.value=.03;const i=t.createOscillator();i.type="sawtooth",i.frequency.value=2+n*3;const l=t.createGain();l.gain.value=.02+n*.015,i.connect(l),l.connect(o.delayTime);const c=t.createWaveShaper();c.curve=Bn(20+n*50),c.oversample="2x";const d=t.createBiquadFilter();d.type="lowshelf",d.frequency.value=200,d.gain.value=8+n*8;const h=t.createGain();h.gain.value=.7+n*.3;const f=t.createGain();return f.gain.value=.3,r.connect(o),o.connect(c),c.connect(d),d.connect(h),r.connect(f),h.connect(a),f.connect(a),i.start(),{type:"demon",nodes:[r,o,i,l,c,d,h,f,a],input:r,output:a}}buildTremolo(t,n){const r=t.createGain(),a=t.createGain(),o=t.createGain();o.gain.value=1;const i=t.createOscillator();i.type="sine",i.frequency.value=3+n*12;const l=t.createGain();return l.gain.value=.3+n*.5,i.connect(l),l.connect(o.gain),r.connect(o),o.connect(a),i.start(),{type:"tremolo",nodes:[r,o,i,l,a],input:r,output:a}}buildAutotune(t,n){const r=t.createGain(),a=t.createGain(),o=t.createDelay(.05);o.delayTime.value=.005;const i=t.createOscillator();i.type="sine",i.frequency.value=6+n*8;const l=t.createGain();l.gain.value=.002+n*.002,i.connect(l),l.connect(o.delayTime);const c=[],d=[261.6,293.7,329.6,349.2,392,440,493.9,523.3],h=t.createGain();h.gain.value=.15;for(const g of d){const p=t.createBiquadFilter();p.type="peaking",p.frequency.value=g,p.Q.value=8+n*15,p.gain.value=4+n*8,r.connect(p),p.connect(h),c.push(p)}const f=t.createGain();f.gain.value=.7;const m=t.createGain();return m.gain.value=.5+n*.3,r.connect(o),o.connect(m),h.connect(m),r.connect(f),m.connect(a),f.connect(a),i.start(),{type:"autotune",nodes:[r,o,i,l,...c,h,m,f,a],input:r,output:a}}buildVocoder(t,n){const r=t.createGain(),a=t.createGain(),o=t.createOscillator();o.type="sawtooth",o.frequency.value=110+n*110;const i=t.createGain();i.gain.value=0;const l=8,c=[r,a,o,i],d=t.createGain();d.gain.value=.5+n*.5,c.push(d);for(let f=0;f<l;f++){const m=200*Math.pow(2,f*.5),g=t.createBiquadFilter();g.type="bandpass",g.frequency.value=m,g.Q.value=4;const p=t.createBiquadFilter();p.type="bandpass",p.frequency.value=m,p.Q.value=4;const v=t.createGain();v.gain.value=0,r.connect(g),g.connect(v.gain),o.connect(p),p.connect(v),v.connect(d),c.push(g,p,v)}d.connect(a);const h=t.createGain();return h.gain.value=.3-n*.2,r.connect(h),h.connect(a),c.push(h),o.start(),{type:"vocoder",nodes:c,input:r,output:a}}}const ul=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Ut(e){return 12*Math.log2(e/440)+69}function Wn(e){const t=ul[Math.round(e)%12],n=Math.floor(Math.round(e)/12)-1;return`${t}${n}`}function $r(e,t){if(e.length===0)return 0;const n=t/100*(e.length-1),r=Math.floor(n),a=Math.ceil(n);return r===a?e[r]:e[r]+(e[a]-e[r])*(n-r)}function hp(e){const{playerName:t,playerColor:n,songTitle:r,songArtist:a,songBpm:o,difficulty:i,pitchPoints:l,notes:c,verseRatings:d,combo:h,classicScore:f,bonusScore:m,totalScore:g,micSettings:p}=e,v=l.filter(ne=>ne.hz>0),x=v.map(ne=>Ut(ne.hz)),b=[],w=[],y=[],k=[...c].sort((ne,oe)=>ne.startTime-oe.startTime);function M(ne){let oe=0,Ne=k.length-1;for(;oe<=Ne;){const De=oe+Ne>>>1,Pe=k[De];if(ne<Pe.startTime)Ne=De-1;else if(ne>Pe.startTime+Pe.duration)oe=De+1;else return Pe.pitch}return 0}for(const ne of l){const oe=ne.hz>0?Ut(ne.hz):0,Ne=M(ne.t);if(w.push({t:ne.t,sung:oe,expected:Ne}),oe>0&&Ne>0){const De=(oe-Ne)*100;b.push(De)}}let N=0;for(const ne of k){const oe=ne.startTime-.3,Ne=ne.startTime+ne.duration;for(;N<v.length&&v[N].t<oe;)N++;N<v.length&&v[N].t<=Ne&&y.push((v[N].t-ne.startTime)*1e3)}const R=b.map(Math.abs),_=[...R].sort((ne,oe)=>ne-oe),E=R.length>0?R.reduce((ne,oe)=>ne+oe,0)/R.length:0,U=$r(_,50),W=R.length>1?Math.sqrt(R.reduce((ne,oe)=>ne+(oe-E)**2,0)/(R.length-1)):0,j=R.filter(ne=>ne<=50).length,L=R.filter(ne=>ne<=15).length,I=R.length>0?j/R.length*100:0,q=R.length>0?L/R.length*100:0,Y=["< −100","−100 to −50","−50 to −25","−25 to −15","−15 to 0","0 to +15","+15 to +25","+25 to +50","+50 to +100","> +100"],O=new Array(10).fill(0);for(const ne of b){const oe=ne<-100?0:ne<-50?1:ne<-25?2:ne<-15?3:ne<0?4:ne<15?5:ne<25?6:ne<50?7:ne<100?8:9;O[oe]++}const Z=Y.map((ne,oe)=>({centRange:ne,count:O[oe],pct:b.length>0?O[oe]/b.length*100:0})),H=v.map(ne=>ne.hz).sort((ne,oe)=>ne-oe),te=H.length>0?H[0]:0,G=H.length>0?H[H.length-1]:0,z=te>0?Ut(te):0,S=G>0?Ut(G):0,P=S-z,$=[...x].sort((ne,oe)=>ne-oe),T=$r($,10),C=$r($,90),A=new Array(12).fill(0);for(const ne of x){const oe=Math.round(ne)%12;oe>=0&&oe<12&&A[oe]++}const D=A.reduce((ne,oe)=>ne+oe,0),V=ul.map((ne,oe)=>({note:ne,count:A[oe],pct:D>0?A[oe]/D*100:0})),Q=fp(v),J=y.length>0?y.reduce((ne,oe)=>ne+oe,0)/y.length:0,ae=y.length>1?Math.sqrt(y.reduce((ne,oe)=>ne+(oe-J)**2,0)/(y.length-1)):0,re=ae>0?Math.max(0,Math.min(100,100-ae/2)):100;let ee=0,F=0;for(let ne=1;ne<x.length;ne++){const oe=Math.abs(x[ne]-x[ne-1]);ee+=oe,F++}const K=F>0?ee/F*100/12:0,se=l.filter(ne=>ne.hz<=0).length,ce=l.length>0?(1-se/l.length)*100:0,fe=new Map;for(const ne of c){const oe=ne.line??0;fe.has(oe)||fe.set(oe,[]),fe.get(oe).push(ne)}const X=new Map;for(const ne of v){const oe=M(ne.t);if(oe<=0)continue;let Ne=0,De=k.length-1,Pe=-1;for(;Ne<=De;){const we=Ne+De>>>1,dt=k[we];if(ne.t<dt.startTime)De=we-1;else if(ne.t>dt.startTime+dt.duration)Ne=we+1;else{Pe=dt.line??0;break}}if(Pe<0)continue;const tt=Math.abs((Ut(ne.hz)-oe)*100);X.has(Pe)||X.set(Pe,[]),X.get(Pe).push(tt)}const ue=d.map(ne=>{const oe=fe.get(ne.verseIndex)??[],Ne=X.get(ne.verseIndex)??[],De=Ne.length>0?Ne.reduce((Pe,tt)=>Pe+tt,0)/Ne.length:0;return{verseIndex:ne.verseIndex,label:ne.label,hitFraction:ne.hitFraction,avgCentDeviation:Math.round(De*10)/10,noteCount:oe.length,notesHit:Math.round(ne.hitFraction*oe.length),comboBonus:ne.comboBonus}}),ye=2,je=.5,Fe=l.length>0?l[l.length-1].t:0,Re=[],Se=w.filter(ne=>ne.sung>0&&ne.expected>0);if(Se.length>0){let ne=0,oe=0,Ne=0;for(let De=0;De<=Fe;De+=je){const Pe=De-ye/2,tt=De+ye/2;for(;oe<Se.length&&Se[oe].t<tt;)Math.abs(Se[oe].sung-Se[oe].expected)<=.5&&Ne++,oe++;for(;ne<oe&&Se[ne].t<Pe;)Math.abs(Se[ne].sung-Se[ne].expected)<=.5&&Ne--,ne++;const we=oe-ne;Re.push({t:De,accuracy:we>0?Ne/we*100:0})}}else for(let ne=0;ne<=Fe;ne+=je)Re.push({t:ne,accuracy:0});return{playerName:t,playerColor:n,songTitle:r,songArtist:a,songBpm:o,difficulty:i,timestamp:new Date().toISOString(),classicScore:f,bonusScore:m,totalScore:g,maxCombo:(h==null?void 0:h.maxCombo)??0,totalComboBonus:(h==null?void 0:h.totalComboBonus)??0,totalPitchPoints:l.length,avgCentDeviation:Math.round(E*10)/10,medianCentDeviation:Math.round(U*10)/10,stdDevCents:Math.round(W*10)/10,intonationAccuracyPct:Math.round(I*10)/10,perfectHitPct:Math.round(q*10)/10,pitchDeviationHistogram:Z,lowestHz:Math.round(te*10)/10,highestHz:Math.round(G*10)/10,lowestNote:z>0?Wn(z):"—",highestNote:S>0?Wn(S):"—",rangeInSemitones:Math.round(P*10)/10,tessituraLow:T>0?Wn(T):"—",tessituraHigh:C>0?Wn(C):"—",pitchClassDistribution:V,vibrato:Q,avgOnsetDeviationMs:Math.round(J*10)/10,rhythmStabilityPct:Math.round(re*10)/10,jitterPct:Math.round(K*100)/100,shimmerProxy:Math.round(ce*10)/10,verseMetrics:ue,micSettings:p,pitchOverTime:w,accuracyOverTime:Re}}function fp(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(g=>Ut(g.hz)),n=e.map(g=>g.t),r=.5,a=[],o=[];let i=0,l=0,c=0;for(let g=0;g<e.length;g++){for(l+=t[g],c++;i<g&&n[g]-n[i]>=r;)l-=t[i],c--,i++;if(c<6||(g-i)%10!==0)continue;const p=l/c;let v=0,x=t[i]-p,b=Math.abs(x);for(let k=i+1;k<=g;k++){const M=t[k]-p;M*x<0&&v++,x=M;const N=Math.abs(M);N>b&&(b=N)}const w=n[g]-n[i];if(w<=0)continue;const y=v/2/w;y>=3&&y<=12&&(a.push(y),o.push(b*100))}if(a.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const d=a.reduce((g,p)=>g+p,0)/a.length,h=o.reduce((g,p)=>g+p,0)/o.length,f=Math.sqrt(a.reduce((g,p)=>g+(p-d)**2,0)/a.length),m=Math.max(0,Math.min(100,100-f*20));return{detected:!0,avgRateHz:Math.round(d*10)/10,avgExtentCents:Math.round(h*10)/10,regularityPct:Math.round(m)}}function hl(e,t,n=50,r=30){const a=Math.round(e/1e3*t),o=Math.round(n/1e3*t),i=Math.max(1,Math.round(r/1e3*t)),l=new Float32Array(a);for(let c=0;c<i;c++){const d=.5*(1-Math.cos(2*Math.PI*c/(i-1))),h=o+c-Math.floor(i/2);h>=0&&h<a&&(l[h]=d)}return l}function js(e,t,n=1e3){const r=Math.max(1,Math.round(t/n)),a=Math.ceil(e.length/r),o=new Float32Array(a);for(let l=0;l<a;l++){const c=l*r,d=Math.min(e.length,c+r);let h=0;for(let f=c;f<d;f++)h+=Math.abs(e[f]);o[l]=h/(d-c||1)}let i=0;for(let l=0;l<o.length;l++)o[l]>i&&(i=o[l]);if(i>0)for(let l=0;l<o.length;l++)o[l]=o[l]/i;return{env:o,factor:r}}function pp(e,t){const n=e.length,r=t.length;if(n===0||r===0)return 0;let a={lag:0,score:-1/0};const o=Math.min(2e3,r);for(let i=-o;i<=o;i++){let l=0,c=0,d=0;for(let m=0;m<n;m++){const g=m+i+Math.floor((r-n)/2);if(g<0||g>=r)continue;const p=e[m],v=t[g];l+=p*v,c+=p*p,d+=v*v}const h=Math.sqrt(Math.max(1e-9,c*d)),f=l/h;f>a.score&&(a={lag:i,score:f})}return a.lag}function mp(e,t,n=50,r=30){try{const a=Math.max(300,Math.round(e.length/t*1e3)),o=hl(a,t,n,r),i=js(e,t,1e3),l=js(o,t,1e3),d=pp(l.env,i.env)*1e3/1e3;return Math.round(d)}catch{return null}}function fl(e){switch(e){case"1/4":return 1;case"1/8":return .5;case"1/16":return .25;case"1/32":return .125;case"1/4T":return 2/3;case"1/8T":return 1/3;case"1/16T":return 1/6}}function ja(e,t){return fl(e)*60/t}function Hr(e,t,n){const r=ja(t,n);return Math.round(e/r)*r}function gp(e,t){const{value:n,bpm:r,strength:a=1,quantizeStarts:o=!0,quantizeDurations:i=!1}=t,l=ja(n,r);return e.map(c=>{let{start:d,duration:h}=c;if(o){const f=Math.round(d/l)*l;d=d+(f-d)*a}if(i){const f=Math.max(l,Math.round(h/l)*l);h=h+(f-h)*a}return d===c.start&&h===c.duration?c:{...c,start:d,duration:h}})}function yp(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function bp(e,t={}){const{timingRange:n=.02,velocityRange:r=10,seed:a}=t,o=a!=null?yp(a):Math.random;return e.map(i=>{const l=(o()*2-1)*n,c=Math.round((o()*2-1)*r);return{...i,start:Math.max(0,i.start+l),velocity:i.velocity!=null?Math.max(1,Math.min(127,(i.velocity??100)+c)):void 0}})}function vp(){return{start:0,end:0,enabled:!1}}function xp(e,t){return{...e<t?{start:e,end:t}:{start:t,end:e},enabled:!0}}function Sp(e,t,n){return{start:Hr(e.start,t,n),end:Hr(e.end,t,n),enabled:e.enabled}}function wp(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function Cp(e,t){if(!t.enabled||t.end<=t.start||e<t.start)return e;if(e>=t.end){const n=t.end-t.start;return t.start+(e-t.start)%n}return e}function Kr(e){return e.length===1?e.toLowerCase():e}function Yn(e){var n,r,a,o;const t=[];return(n=e.modifiers)!=null&&n.ctrl&&t.push("Ctrl"),(r=e.modifiers)!=null&&r.shift&&t.push("Shift"),(a=e.modifiers)!=null&&a.alt&&t.push("Alt"),(o=e.modifiers)!=null&&o.meta&&t.push("Meta"),t.push(Kr(e.key)),t.join("+")}function kp(e,t){var l,c,d,h;const n=Kr(e.key)===Kr(t.key),r=!!e.ctrlKey==!!((l=t.modifiers)!=null&&l.ctrl),a=!!e.shiftKey==!!((c=t.modifiers)!=null&&c.shift),o=!!e.altKey==!!((d=t.modifiers)!=null&&d.alt),i=!!e.metaKey==!!((h=t.modifiers)!=null&&h.meta);return n&&r&&a&&o&&i}class pl{constructor(){this.actions=new Map,this.activeScopes=new Set(["global"]),this.enabled=!0,this.listener=null}register(t){this.actions.set(t.id,{...t,enabled:t.enabled??!0})}unregister(t){this.actions.delete(t)}rebind(t,n){const r=this.actions.get(t);r&&(r.binding=n)}setActiveScopes(t){this.activeScopes.clear(),this.activeScopes.add("global");for(const n of t)this.activeScopes.add(n)}setEnabled(t){this.enabled=t}setActionEnabled(t,n){const r=this.actions.get(t);r&&(r.enabled=n)}findConflicts(){const t=[],n=[...this.actions.values()];for(let r=0;r<n.length;r++)for(let a=r+1;a<n.length;a++){const o=n[r],i=n[a];Yn(o.binding)===Yn(i.binding)&&(o.scope===i.scope||o.scope==="global"||i.scope==="global")&&t.push([o,i])}return t}getGrouped(){const t={};for(const n of this.actions.values())t[n.group]||(t[n.group]=[]),t[n.group].push(n);return t}getAll(){return[...this.actions.values()]}exportConfig(){return[...this.actions.values()].map(t=>({id:t.id,binding:t.binding}))}importConfig(t){for(const n of t)this.rebind(n.id,n.binding)}formatBinding(t){const n=this.actions.get(t);return n?Yn(n.binding):""}handleKeyDown(t){if(!this.enabled)return!1;for(const n of this.actions.values())if(n.enabled&&this.activeScopes.has(n.scope)&&kp(t,n.binding))return t.preventDefault(),t.stopPropagation(),n.callback(),!0;return!1}attach(){this.listener||(this.listener=t=>{const n=t.target;n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable||this.handleKeyDown(t)},window.addEventListener("keydown",this.listener,!0))}detach(){this.listener&&(window.removeEventListener("keydown",this.listener,!0),this.listener=null)}destroy(){this.detach(),this.actions.clear()}}function Mp(e={}){const t=new pl,n=()=>{},r=[{id:"transport.play",label:"Play / Pause",group:"Transport",scope:"global",binding:{key:" "}},{id:"transport.stop",label:"Stop",group:"Transport",scope:"global",binding:{key:"Escape"}},{id:"transport.record",label:"Record",group:"Transport",scope:"global",binding:{key:"r",modifiers:{ctrl:!0}}},{id:"transport.rewind",label:"Rewind",group:"Transport",scope:"global",binding:{key:"Home"}},{id:"transport.forward",label:"Forward",group:"Transport",scope:"global",binding:{key:"End"}},{id:"transport.loopToggle",label:"Toggle Loop",group:"Transport",scope:"global",binding:{key:"l"}},{id:"edit.undo",label:"Undo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0}}},{id:"edit.redo",label:"Redo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0,shift:!0}}},{id:"edit.cut",label:"Cut",group:"Edit",scope:"editor",binding:{key:"x",modifiers:{ctrl:!0}}},{id:"edit.copy",label:"Copy",group:"Edit",scope:"editor",binding:{key:"c",modifiers:{ctrl:!0}}},{id:"edit.paste",label:"Paste",group:"Edit",scope:"editor",binding:{key:"v",modifiers:{ctrl:!0}}},{id:"edit.delete",label:"Delete",group:"Edit",scope:"editor",binding:{key:"Delete"}},{id:"edit.selectAll",label:"Select All",group:"Edit",scope:"editor",binding:{key:"a",modifiers:{ctrl:!0}}},{id:"edit.duplicate",label:"Duplicate",group:"Edit",scope:"editor",binding:{key:"d",modifiers:{ctrl:!0}}},{id:"view.zoomIn",label:"Zoom In",group:"View",scope:"global",binding:{key:"=",modifiers:{ctrl:!0}}},{id:"view.zoomOut",label:"Zoom Out",group:"View",scope:"global",binding:{key:"-",modifiers:{ctrl:!0}}},{id:"view.zoomFit",label:"Zoom to Fit",group:"View",scope:"global",binding:{key:"0",modifiers:{ctrl:!0}}},{id:"view.toggleMixer",label:"Toggle Mixer",group:"View",scope:"global",binding:{key:"m"}},{id:"view.togglePianoRoll",label:"Toggle Piano Roll",group:"View",scope:"global",binding:{key:"p"}},{id:"pianoRoll.quantize",label:"Quantize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"q"}},{id:"pianoRoll.humanize",label:"Humanize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"h"}},{id:"pianoRoll.velocityUp",label:"Velocity +10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{shift:!0}}},{id:"pianoRoll.velocityDown",label:"Velocity -10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{shift:!0}}},{id:"pianoRoll.octaveUp",label:"Octave Up",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{ctrl:!0,shift:!0}}},{id:"pianoRoll.octaveDown",label:"Octave Down",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{ctrl:!0,shift:!0}}},{id:"timeline.split",label:"Split at Cursor",group:"Timeline",scope:"timeline",binding:{key:"s"}},{id:"timeline.mute",label:"Mute Track",group:"Timeline",scope:"timeline",binding:{key:"m",modifiers:{ctrl:!0}}},{id:"timeline.solo",label:"Solo Track",group:"Timeline",scope:"timeline",binding:{key:"s",modifiers:{ctrl:!0}}},{id:"timeline.addTrack",label:"Add Track",group:"Timeline",scope:"timeline",binding:{key:"t",modifiers:{ctrl:!0}}},{id:"mixer.resetFader",label:"Reset Fader",group:"Mixer",scope:"mixer",binding:{key:"0"}},{id:"mixer.bypassFx",label:"Bypass All FX",group:"Mixer",scope:"mixer",binding:{key:"b"}}];for(const a of r)t.register({...a,callback:e[a.id]??n});return t}function jp(e){return Yn(e)}const Rp=["audio/mpeg","audio/wav","audio/ogg","audio/flac","audio/aac","audio/webm","audio/mp4","audio/x-m4a","audio/x-wav","audio/x-aiff","audio/aiff","audio/midi","audio/x-midi"],$p=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],Tp=500*1024*1024,Pp=20;function jt(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function Ep(e,t){return!!(e.type&&t.some(n=>e.type.startsWith(n.replace("*","")))||e.type.startsWith("audio/"))}function Ap(e,t){const n=jt(e.name);return n!==""&&t.includes(n)}function Ra(e,t={}){const n=t.maxSize??Tp,r=t.allowedTypes??Rp,a=t.allowedExtensions??$p,o=t.maxFiles??Pp,i=[],l=[];for(let c=0;c<e.length;c++){const d=e[c];if(c>=o){l.push({file:d,reason:"limit",message:`Exceeded maximum of ${o} files`});continue}if(d.size>n){l.push({file:d,reason:"size",message:`File exceeds ${Math.round(n/1024/1024)}MB limit`});continue}if(!Ep(d,r)&&!Ap(d,a)){l.push({file:d,reason:"type",message:`Unsupported file type: ${d.type||jt(d.name)}`});continue}i.push(d)}return{valid:i,errors:l}}async function ml(e){const t={file:e,name:e.name.replace(/\.[^.]+$/,""),extension:jt(e.name),sizeBytes:e.size,mimeType:e.type||`audio/${jt(e.name)}`};try{const n=await e.arrayBuffer(),a=await new OfflineAudioContext(1,1,44100).decodeAudioData(n);t.duration=a.duration,t.sampleRate=a.sampleRate,t.channels=a.numberOfChannels}catch{}return t}function Np(e){let t=0;return{onDragEnter:n=>{var r;n.preventDefault(),n.stopPropagation(),t++,t===1&&((r=e.onDragEnter)==null||r.call(e))},onDragOver:n=>{n.preventDefault(),n.stopPropagation(),(n instanceof DragEvent&&n.dataTransfer||"dataTransfer"in n&&n.dataTransfer)&&(n.dataTransfer.dropEffect="copy")},onDragLeave:n=>{var r;n.preventDefault(),n.stopPropagation(),t--,t===0&&((r=e.onDragLeave)==null||r.call(e))},onDrop:async n=>{var d,h;n.preventDefault(),n.stopPropagation(),t=0,(d=e.onDragLeave)==null||d.call(e);const r="dataTransfer"in n?n.dataTransfer:null;if(!((h=r==null?void 0:r.files)!=null&&h.length))return;const a=Array.from(r.files),{valid:o,errors:i}=Ra(a,e.validation),l=[],c=[...i];for(const f of o)if(e.probe)try{l.push(await ml(f))}catch{c.push({file:f,reason:"decode",message:"Failed to decode audio"})}else l.push({file:f,name:f.name.replace(/\.[^.]+$/,""),extension:jt(f.name),sizeBytes:f.size,mimeType:f.type||`audio/${jt(f.name)}`});e.onDrop({accepted:l,rejected:c})}}}function Ip(e={}){return new Promise(t=>{const n=document.createElement("input");n.type="file",n.accept="audio/*,.mid,.midi",n.multiple=e.multiple??!0,n.onchange=async()=>{var l;if(!((l=n.files)!=null&&l.length)){t({accepted:[],rejected:[]});return}const r=Array.from(n.files),{valid:a,errors:o}=Ra(r,e.validation),i=a.map(c=>({file:c,name:c.name.replace(/\.[^.]+$/,""),extension:jt(c.name),sizeBytes:c.size,mimeType:c.type||`audio/${jt(c.name)}`}));t({accepted:i,rejected:o})},n.click()})}var gl=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(gl||{}),kt=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(kt||{}),yl=(e=>(e[e.Equalizer=0]="Equalizer",e[e.Compressor=1]="Compressor",e[e.Reverb=2]="Reverb",e[e.Delay=3]="Delay",e[e.Distortion=4]="Distortion",e[e.Chorus=5]="Chorus",e[e.Flanger=6]="Flanger",e[e.Phaser=7]="Phaser",e))(yl||{}),bl=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(bl||{});const Lp=["var(--nice-success, #4caf50)","var(--nice-primary, #2196f3)","var(--nice-warning, #ff9800)","var(--nice-accent-pink, #e91e63)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-success, #8bc34a)","var(--nice-warning, #ffc107)"],Pt=["var(--nice-primary, #2196f3)","var(--nice-danger, #e53935)","var(--nice-warning, #ffeb3b)","var(--nice-success, #43a047)","var(--nice-warning, #ff9800)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-warning, #ffc107)","var(--nice-success, #8bc34a)","var(--nice-danger, #f44336)","var(--nice-accent, #3f51b5)","var(--nice-text-secondary, #607d8b)","var(--nice-warning-dark, #795548)","var(--nice-warning, #cddc39)","var(--nice-accent, #673ab7)","#009688"];function Fp(e){for(const t of Pt)if(!e.includes(t))return t;return Pt[Math.floor(Math.random()*Pt.length)]}const Zn=Pt.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function Dp(e){for(let t=0;t<Pt.length;t++){const n=Pt[t],r=Zn[t];if(!e.includes(n)&&!e.includes(r))return r}return Zn[Math.floor(Math.random()*Zn.length)]}const or=["off","no function","brak"],Op=e=>e.segments.some(t=>t.isOff||or.some(n=>t.name.toLowerCase().includes(n))),_p=e=>e.segments.find(t=>t.isOff||or.some(n=>t.name.toLowerCase().includes(n))),vl=e=>Math.floor((e.valueFrom+e.valueTo)/2),zp=e=>{const t=_p(e);return t?vl(t):0},Gp=(e,t)=>e.segments.find(n=>t>=n.valueFrom&&t<=n.valueTo),cn=(e,t=0,n=255)=>Math.max(t,Math.min(n,Math.round(e))),kn=({channel:e,value:t,onChange:n,onCommit:r,showDirectionHint:a})=>{const[o,i]=u.useState(cn(t)),l=u.useMemo(()=>Gp(e,o),[e,o]);u.useEffect(()=>i(cn(t)),[t]);const c=d=>{const h=cn(d);i(h),n(h),r==null||r(h)};return s.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:6},children:[s.jsxs("strong",{children:[e.channel,". ",e.name]}),a&&l&&s.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:l.name})]}),s.jsx("input",{type:"range",min:0,max:255,value:o,onChange:d=>{const h=cn(Number(d.target.value));i(h),n(h)},onMouseUp:()=>r==null?void 0:r(o),onTouchEnd:()=>r==null?void 0:r(o),style:{width:"100%"}}),s.jsx("div",{style:{marginTop:6},children:s.jsx("input",{type:"number",min:0,max:255,value:o,onChange:d=>{const h=cn(Number(d.target.value));i(h),n(h)},onBlur:()=>r==null?void 0:r(o),style:{width:80,padding:6,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:6}})}),Op(e)&&s.jsx("button",{type:"button",onClick:()=>c(zp(e)),style:{width:"100%",marginTop:8,padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)",cursor:"pointer"},children:"OFF"})]})},$a=({channel:e,value:t,onChange:n,onCommit:r})=>{const a=u.useMemo(()=>{const i=[...e.segments];return i.sort((l,c)=>{const d=(l.isOff?-1:0)+(or.some(f=>l.name.toLowerCase().includes(f))?-1:0),h=(c.isOff?-1:0)+(or.some(f=>c.name.toLowerCase().includes(f))?-1:0);return d!==h?d-h:l.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),i},[e]),o=i=>{const l=vl(i);n(l),r==null||r(l)};return s.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[s.jsxs("strong",{children:[e.channel,". ",e.name]}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(120px, 1fr))",gap:8,marginTop:8,maxHeight:220,overflowY:"auto"},children:a.map((i,l)=>{const c=t>=i.valueFrom&&t<=i.valueTo;return s.jsx("button",{type:"button",onClick:()=>o(i),style:{padding:"8px 10px",borderRadius:8,border:c?"2px solid var(--nice-primary-hover, #2563eb)":"1px solid var(--nice-border, #d1d5db)",background:c?"var(--nice-primary-bg, #eff6ff)":"var(--nice-bg, #fff)",textAlign:"left",cursor:"pointer",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:`${i.name} [${i.valueFrom}..${i.valueTo}]`,children:i.name},`${i.name}-${l}`)})})]})},Ta=e=>{switch(e.channel.type){case kt.Dimmer:case kt.DimmerWithOff:return s.jsx(kn,{...e});case kt.RotationWithOff:case kt.RotationWithOffAndCcw:return s.jsx(kn,{...e,showDirectionHint:!0});case kt.Options:return s.jsx($a,{...e});default:return s.jsx(kn,{...e})}},Tr=e=>Math.max(0,Math.min(255,Math.round(e)));function xl({service:e,pollInterval:t=500,className:n,style:r,channels:a,onChannelChange:o,fixtures:i}){if(!e)return s.jsx("div",{className:n,style:r,children:s.jsx("small",{children:"Provide a `service` prop (DmxService) to control hardware."})});const[l,c]=u.useState([]),[d,h]=u.useState(null),[f,m]=u.useState(()=>Array(513).fill(0)),[g,p]=u.useState(30),[v,x]=u.useState(0),[b,w]=u.useState(!1),y=u.useRef(null);u.useEffect(()=>{let j=!1;return e.getDevices().then(L=>{j||(c(L),L.length>0&&h(L[0]))}).catch(()=>{}),()=>{j=!0}},[e]),u.useEffect(()=>{if(y.current&&window.clearInterval(y.current),!(t<=0))return y.current=window.setInterval(async()=>{try{const j=await e.getState();Array.isArray(j.frontSnapshot)&&j.frontSnapshot.length>=513&&m(j.frontSnapshot.slice(0,513)),typeof j.fps=="number"&&p(j.fps),typeof j.startCode=="number"&&x(j.startCode)}catch{}},t),()=>{y.current&&window.clearInterval(y.current)}},[e,t]);const k=async()=>{d&&(await e.openPort(d.serialNumber||d.description),w(!0))},M=async()=>{await e.closePort(),w(!1)},N=async()=>{await e.blackout(),m(j=>{const L=[...j];for(let I=1;I<L.length;I++)L[I]=0;return L})},R=()=>e.configure(g,v),_=(j,L)=>{const I=Tr(L);m(q=>{const Y=[...q];return Y[j]=I,Y})},E=(j,L)=>e.setChannel(j,Tr(L)),U=(d==null?void 0:d.deviceInfo)??null,W=u.useMemo(()=>{var j;return(j=U==null?void 0:U.channels)!=null&&j.length?U.channels:Array.from({length:16},(L,I)=>({channel:I+1,name:`Channel ${I+1}`,type:kt.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[U]);return s.jsxs("div",{className:`ntd-dmx-editor ${n??""}`,style:{padding:16,display:"grid",gap:16,...r},children:[s.jsxs("section",{style:{display:"grid",gap:12,gridTemplateColumns:"1fr auto auto auto",alignItems:"end"},children:[s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FTDI Device"}),s.jsx("select",{value:(d==null?void 0:d.serialNumber)||"",onChange:j=>h(l.find(L=>L.serialNumber===j.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"},children:l.map(j=>{var L,I;return s.jsxs("option",{value:j.serialNumber,children:[((L=j.deviceInfo)==null?void 0:L.manufacturer)??""," ",((I=j.deviceInfo)==null?void 0:I.model)??j.description," (",j.serialNumber||j.description,")"]},j.serialNumber||j.description)})}),U&&s.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:["Mode: ",s.jsx("b",{children:U.modeName}),", footprint: ",s.jsx("b",{children:U.footprint})]})]}),s.jsx("button",{onClick:k,disabled:!d||b,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-success, #10b981)",background:"var(--nice-success-bg, #ecfdf5)",cursor:"pointer"},children:"Open port"}),s.jsx("button",{onClick:M,disabled:!b,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-danger, #ef4444)",background:"var(--nice-danger-bg, #fef2f2)",cursor:"pointer"},children:"Close port"}),s.jsx("button",{onClick:N,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-text-secondary, #4b5563)",background:"var(--nice-bg-secondary, #f3f4f6)",cursor:"pointer"},children:"Blackout"})]}),s.jsxs("section",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(160px, 100%), 1fr))",gap:12,alignItems:"end"},children:[s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FPS"}),s.jsx("input",{type:"number",min:10,max:44,value:g,onChange:j=>p(Number(j.target.value)),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"Start Code"}),s.jsx("input",{type:"number",min:0,max:255,value:v,onChange:j=>x(Tr(Number(j.target.value))),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),s.jsx("div",{children:s.jsx("button",{onClick:R,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-primary, #3b82f6)",background:"var(--nice-primary-bg, #eff6ff)",cursor:"pointer"},children:"Apply configuration"})})]}),s.jsxs("section",{children:[s.jsx("h3",{style:{margin:"8px 0 12px",fontSize:16},children:"Channels"}),s.jsx("div",{style:{display:"grid",gap:12,gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))"},children:W.map(j=>s.jsx(Ta,{channel:j,value:f[j.channel]??0,onChange:L=>_(j.channel,L),onCommit:L=>E(j.channel,L)},j.channel))})]})]})}const Sl=[{id:"generic-dimmer-1ch",name:"Generic Dimmer",manufacturer:"Generic",type:"dimmer",channelCount:1,channels:[{name:"Dimmer",type:"dimmer",defaultValue:0}]},{id:"generic-rgb-3ch",name:"Generic RGB",manufacturer:"Generic",type:"rgb",channelCount:3,channels:[{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0}]},{id:"generic-rgbw-4ch",name:"Generic RGBW",manufacturer:"Generic",type:"rgbw",channelCount:4,channels:[{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0}]},{id:"generic-rgbw-dimmer-5ch",name:"Generic RGBW+D",manufacturer:"Generic",type:"rgbw",channelCount:5,channels:[{name:"Dimmer",type:"dimmer",defaultValue:255},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0}]},{id:"generic-par-7ch",name:"Generic PAR 7ch",manufacturer:"Generic",type:"par",channelCount:7,channels:[{name:"Dimmer",type:"dimmer",defaultValue:255},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0},{name:"Strobe",type:"strobe",defaultValue:0},{name:"Function",type:"function",defaultValue:0}]},{id:"generic-moving-head-16ch",name:"Generic Moving Head 16ch",manufacturer:"Generic",type:"moving_head",channelCount:16,channels:[{name:"Pan",type:"pan",defaultValue:128,min:0,max:255},{name:"Pan Fine",type:"pan",defaultValue:0},{name:"Tilt",type:"tilt",defaultValue:128,min:0,max:255},{name:"Tilt Fine",type:"tilt",defaultValue:0},{name:"Pan/Tilt Speed",type:"speed",defaultValue:0},{name:"Dimmer",type:"dimmer",defaultValue:0},{name:"Strobe",type:"strobe",defaultValue:0},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0},{name:"Color Wheel",type:"function",defaultValue:0},{name:"Gobo",type:"gobo",defaultValue:0},{name:"Gobo Rotation",type:"speed",defaultValue:128},{name:"Prism",type:"function",defaultValue:0},{name:"Function",type:"function",defaultValue:0}]},{id:"generic-strobe-2ch",name:"Generic Strobe",manufacturer:"Generic",type:"strobe",channelCount:2,channels:[{name:"Dimmer",type:"dimmer",defaultValue:0},{name:"Strobe Speed",type:"strobe",defaultValue:0}]},{id:"generic-fog-2ch",name:"Generic Fog Machine",manufacturer:"Generic",type:"fog",channelCount:2,channels:[{name:"Output",type:"dimmer",defaultValue:0},{name:"Fan",type:"speed",defaultValue:128}]}];class wl{constructor(){this.universes=new Map,this.fixtures=new Map,this.profiles=new Map,this.outputCallback=null,this.running=!1,this.frameRate=44,this.intervalId=null,Sl.forEach(t=>this.profiles.set(t.id,t)),this.createUniverse(1,"Universe 1")}createUniverse(t,n){const r={id:String(t),name:n,channels:new Uint8Array(512)};return this.universes.set(t,r),r}getUniverse(t){return this.universes.get(t)}addFixture(t){this.fixtures.set(t.id,t)}removeFixture(t){this.fixtures.delete(t)}getFixture(t){return this.fixtures.get(t)}getAllFixtures(){return Array.from(this.fixtures.values())}getProfile(t){return this.profiles.get(t)}registerProfile(t){this.profiles.set(t.id,t)}setChannel(t,n,r){const a=this.universes.get(t);a&&n>=1&&n<=512&&(a.channels[n-1]=Math.max(0,Math.min(255,r)))}getChannel(t,n){const r=this.universes.get(t);return r&&n>=1&&n<=512?r.channels[n-1]:0}setFixtureValues(t,n){const r=this.fixtures.get(t);if(!r)return;const a=this.profiles.get(r.profileId);if(a)for(let o=0;o<Math.min(n.length,a.channelCount);o++)r.values[o]=n[o],this.setChannel(r.universe,r.startChannel+o,n[o])}setFixtureColor(t,n,r,a,o=0){const i=this.fixtures.get(t);if(!i)return;const l=this.profiles.get(i.profileId);if(!l)return;const c=[...i.values];l.channels.forEach((d,h)=>{d.name.toLowerCase().includes("red")?c[h]=n:d.name.toLowerCase().includes("green")?c[h]=r:d.name.toLowerCase().includes("blue")?c[h]=a:d.name.toLowerCase().includes("white")&&(c[h]=o)}),this.setFixtureValues(t,c)}setFixtureDimmer(t,n){const r=this.fixtures.get(t);if(!r)return;const a=this.profiles.get(r.profileId);a&&a.channels.forEach((o,i)=>{o.type==="dimmer"&&(r.values[i]=Math.max(0,Math.min(255,Math.round(n*255))),this.setChannel(r.universe,r.startChannel+i,r.values[i]))})}fadeFixture(t,n,r,a="linear"){return new Promise(o=>{const i=this.fixtures.get(t);if(!i){o();return}const l=[...i.values],c=performance.now(),d=()=>{const h=performance.now()-c,f=Math.min(1,h/r);let m=f;switch(a){case"ease-in":m=f*f;break;case"ease-out":m=1-(1-f)*(1-f);break;case"ease-in-out":m=f<.5?2*f*f:1-Math.pow(-2*f+2,2)/2;break}const g=l.map((p,v)=>{const x=n[v]??p;return Math.round(p+(x-p)*m)});this.setFixtureValues(t,g),f<1?requestAnimationFrame(d):o()};d()})}setOutputCallback(t){this.outputCallback=t}start(){this.running||(this.running=!0,this.intervalId=window.setInterval(()=>{this.sendOutput()},1e3/this.frameRate))}stop(){this.running=!1,this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null)}sendOutput(){this.outputCallback&&this.universes.forEach((t,n)=>{this.outputCallback(n,t.channels)})}blackout(){this.universes.forEach(t=>{t.channels.fill(0)}),this.fixtures.forEach(t=>{t.values.fill(0)})}fullOn(){this.fixtures.forEach(t=>{this.setFixtureDimmer(t.id,1)})}}const Bp=6454,Wp=new Uint8Array([65,114,116,45,78,101,116,0]);function Up(e,t){const n=new Uint8Array(18+t.length);return n.set(Wp,0),n[8]=0,n[9]=80,n[10]=0,n[11]=14,n[12]=0,n[13]=0,n[14]=e&255,n[15]=e>>8&255,n[16]=t.length>>8&255,n[17]=t.length&255,n.set(t.slice(0,512),18),n}const Vp=5568;function qp(e,t,n,r=100,a="Nice2Dev DMX"){const o=Math.min(t.length,512),i=126+o,l=new Uint8Array(i),c=new DataView(l.buffer);c.setUint16(0,16,!1),c.setUint16(2,0,!1);const d=[65,83,67,45,69,49,46,49,55,0,0,0];for(let p=0;p<d.length;p++)l[4+p]=d[p];const h=i-16;c.setUint16(16,28672|h&4095,!1),c.setUint32(18,4,!1);for(let p=0;p<16;p++)l[22+p]=p+1;const f=i-38;c.setUint16(38,28672|f&4095,!1),c.setUint32(40,2,!1);const m=new TextEncoder().encode(a.slice(0,63));l.set(m,44),l[108]=r,c.setUint16(109,0,!1),l[111]=n&255,l[112]=0,c.setUint16(113,e,!1);const g=o+11;return c.setUint16(115,28672|g&4095,!1),l[117]=2,l[118]=161,c.setUint16(119,0,!1),c.setUint16(121,1,!1),c.setUint16(123,o+1,!1),l[125]=0,l.set(t.slice(0,o),126),l}function Hp(e){const t=e>>8&255,n=e&255;return`239.255.${t}.${n}`}class Kp{constructor(t,n){this.config=t,this.scenes=n,this.currentStep=0,this.direction=1,this.isRunning=!1,this.timer=null,this.fadeStartTime=0,this.fadeFromValues=new Uint8Array(512),this.fadeToValues=new Uint8Array(512),this.onOutput=null}setOutputCallback(t){this.onOutput=t}start(){this.isRunning||(this.isRunning=!0,this.currentStep=this.config.direction==="backward"?this.config.steps.length-1:0,this.direction=this.config.direction==="backward"?-1:1,this.executeStep())}stop(){this.isRunning=!1,this.timer&&(clearTimeout(this.timer),this.timer=null)}executeStep(){var i;if(!this.isRunning)return;const t=this.config.steps[this.currentStep];if(!t)return;const n=this.scenes.get(t.sceneId);if(!n){this.advanceStep();return}const r=new Uint8Array(512);if(n.channels)for(const l of n.channels)l.channel>=1&&l.channel<=512&&(r[l.channel-1]=l.value);this.fadeFromValues.set(this.fadeToValues),this.fadeToValues.set(r),this.fadeStartTime=performance.now();const a=t.fadeTime/this.config.speed,o=t.holdTime/this.config.speed;a>0?this.runFade(a,()=>{var l;(l=this.onOutput)==null||l.call(this,this.fadeToValues),this.timer=setTimeout(()=>this.advanceStep(),o)}):((i=this.onOutput)==null||i.call(this,r),this.timer=setTimeout(()=>this.advanceStep(),o))}runFade(t,n){const r=performance.now(),a=new Uint8Array(512),o=()=>{var c;if(!this.isRunning)return;const i=performance.now()-r,l=Math.min(i/t,1);for(let d=0;d<512;d++)a[d]=Math.round(this.fadeFromValues[d]+(this.fadeToValues[d]-this.fadeFromValues[d])*l);(c=this.onOutput)==null||c.call(this,a),l<1?requestAnimationFrame(o):n()};requestAnimationFrame(o)}advanceStep(){if(!this.isRunning)return;const{steps:t,loop:n,direction:r}=this.config;if(this.currentStep+=this.direction,r==="bounce"){if(this.currentStep>=t.length?(this.direction=-1,this.currentStep=t.length-2):this.currentStep<0&&(this.direction=1,this.currentStep=1),this.currentStep<0||this.currentStep>=t.length){if(!n){this.stop();return}this.currentStep=0,this.direction=1}}else if(this.currentStep>=t.length||this.currentStep<0){if(!n){this.stop();return}this.currentStep=r==="backward"?t.length-1:0}this.executeStep()}}const Yp=({engine:e,tracks:t=[],scenes:n=[],duration:r=3e5,currentTime:a=0,bpm:o=120,onTimeChange:i,onCueAdd:l,onCueUpdate:c,onCueDelete:d,onTrackAdd:h,onTrackUpdate:f,onPlay:m,onPause:g,onStop:p,className:v=""})=>{const[x,b]=u.useState(1),[w,y]=u.useState(0),[k,M]=u.useState(!1),[N,R]=u.useState(null),[_,E]=u.useState(null),[U,W]=u.useState(!0),[j,L]=u.useState(1e3),I=u.useRef(null),q=u.useRef(null),Y=u.useRef(0),O=u.useMemo(()=>.1*x,[x]),Z=u.useCallback(C=>C*O,[O]),H=u.useCallback(C=>C/O,[O]),te=u.useCallback(C=>{if(!U)return C;const A=6e4/o;return Math.round(C/A)*A},[U,o]);u.useEffect(()=>{if(k){const C=performance.now(),A=a,D=()=>{const V=performance.now()-C,Q=A+V;if(Q>=r){M(!1),i==null||i(0),p==null||p();return}G(Q),i==null||i(Q),q.current=requestAnimationFrame(D)};q.current=requestAnimationFrame(D),m==null||m()}else q.current!==null&&(cancelAnimationFrame(q.current),q.current=null),g==null||g();return()=>{q.current!==null&&cancelAnimationFrame(q.current)}},[k,a,r,i,m,g,p]);const G=u.useCallback(C=>{t.forEach(A=>{A.muted||A.cues.forEach(D=>{const V=D.startTime,Q=V+D.duration;if(C>=V&&C<Q&&Y.current<V){const J=n.find(ae=>ae.id===D.sceneId);J&&J.fixtures.forEach(ae=>{D.fadeIn&&D.fadeIn>0?e.fadeFixture(ae.fixtureId,ae.values,D.fadeIn):e.setFixtureValues(ae.fixtureId,ae.values)})}if(Y.current<Q&&C>=Q){const J=n.find(ae=>ae.id===D.sceneId);J&&J.fixtures.forEach(ae=>{if(e.getFixture(ae.fixtureId)&&D.fadeOut&&D.fadeOut>0){const ee=new Array(ae.values.length).fill(0);e.fadeFixture(ae.fixtureId,ee,D.fadeOut)}})}})}),Y.current=C},[t,n,e]),z=C=>{const A=Math.floor(C/1e3),D=Math.floor(A/60),V=A%60,Q=Math.floor(C%1e3/(1e3/30));return`${D}:${V.toString().padStart(2,"0")}:${Q.toString().padStart(2,"0")}`},S=u.useCallback(C=>{if(!I.current)return;const A=I.current.getBoundingClientRect(),D=C.clientX-A.left+w,V=te(H(D));i==null||i(Math.max(0,Math.min(r,V)))},[w,H,te,r,i]),P=u.useCallback((C,A,D)=>{const V=t.find(ae=>ae.id===A),Q=V==null?void 0:V.cues.find(ae=>ae.id===C);if(!Q)return;const J=te(Math.max(0,Q.startTime+H(D)));c==null||c({...Q,startTime:J})},[t,H,te,c]),$=()=>{const C=6e4/o,A=Math.ceil(r/C),D=[];for(let V=0;V<=A;V++){const Q=V*C,J=Z(Q),ae=V%4===0;D.push(s.jsx("div",{className:`nice-dmx-timeline__beat ${ae?"nice-dmx-timeline__beat--measure":""}`,style:{left:J},children:ae&&s.jsx("span",{className:"nice-dmx-timeline__beat-label",children:V/4+1})},V))}return D},T=(C,A)=>{const D=Z(C.startTime),V=Z(C.duration),Q=n.find(J=>J.id===C.sceneId);return s.jsxs("div",{className:`nice-dmx-timeline__cue ${N===C.id?"nice-dmx-timeline__cue--selected":""}`,style:{left:D,width:V,backgroundColor:(Q==null?void 0:Q.color)||A.color||"var(--nice-accent, #8b5cf6)"},onClick:J=>{J.stopPropagation(),R(C.id)},draggable:!A.locked,onDragEnd:J=>{var re;const ae=(re=J.target.parentElement)==null?void 0:re.getBoundingClientRect();ae&&P(C.id,A.id,J.clientX-ae.left-D)},children:[s.jsx("span",{className:"nice-dmx-timeline__cue-name",children:C.name||(Q==null?void 0:Q.name)}),C.fadeIn&&C.fadeIn>0&&s.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--in",style:{width:Z(C.fadeIn)}}),C.fadeOut&&C.fadeOut>0&&s.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--out",style:{width:Z(C.fadeOut)}})]},C.id)};return s.jsxs("div",{className:`nice-dmx-timeline ${v}`,children:[s.jsxs("div",{className:"nice-dmx-timeline__toolbar",children:[s.jsxs("div",{className:"nice-dmx-timeline__transport",children:[s.jsx("button",{type:"button",onClick:()=>i==null?void 0:i(0),title:"Go to start",children:"⏮"}),s.jsx("button",{type:"button",onClick:()=>M(!k),title:k?"Pause":"Play",children:k?"⏸":"▶"}),s.jsx("button",{type:"button",onClick:()=>{M(!1),i==null||i(0),e.blackout(),p==null||p()},title:"Stop",children:"⏹"})]}),s.jsx("div",{className:"nice-dmx-timeline__time",children:z(a)}),s.jsxs("div",{className:"nice-dmx-timeline__tools",children:[s.jsx("button",{type:"button",className:U?"active":"",onClick:()=>W(!U),title:"Snap to grid",children:"⊞"}),s.jsx("button",{type:"button",onClick:()=>b(Math.max(.25,x-.25)),title:"Zoom out",children:"−"}),s.jsxs("span",{className:"nice-dmx-timeline__zoom",children:[Math.round(x*100),"%"]}),s.jsx("button",{type:"button",onClick:()=>b(Math.min(4,x+.25)),title:"Zoom in",children:"+"})]}),s.jsxs("div",{className:"nice-dmx-timeline__bpm",children:[s.jsx("label",{children:"BPM:"}),s.jsx("span",{children:o})]}),s.jsx("button",{type:"button",className:"nice-dmx-timeline__blackout",onClick:()=>e.blackout(),title:"Blackout",children:"⬛"})]}),s.jsxs("div",{className:"nice-dmx-timeline__content",children:[s.jsxs("div",{className:"nice-dmx-timeline__headers",children:[t.map(C=>s.jsxs("div",{className:`nice-dmx-timeline__header ${_===C.id?"nice-dmx-timeline__header--selected":""}`,onClick:()=>E(C.id),children:[s.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:C.color||"var(--nice-accent, #8b5cf6)"}}),s.jsx("span",{className:"nice-dmx-timeline__track-name",children:C.name}),s.jsxs("div",{className:"nice-dmx-timeline__track-controls",children:[s.jsx("button",{type:"button",className:C.muted?"active":"",onClick:A=>{A.stopPropagation(),f==null||f({...C,muted:!C.muted})},title:"Mute",children:"M"}),s.jsx("button",{type:"button",className:C.locked?"active":"",onClick:A=>{A.stopPropagation(),f==null||f({...C,locked:!C.locked})},title:"Lock",children:"🔒"})]})]},C.id)),s.jsx("button",{type:"button",className:"nice-dmx-timeline__add-track",onClick:()=>{h==null||h({id:`track-${Date.now()}`,name:`Track ${t.length+1}`,fixtureIds:[],cues:[]})},children:"+ Add Track"})]}),s.jsxs("div",{className:"nice-dmx-timeline__tracks",ref:I,onClick:S,onScroll:C=>y(C.currentTarget.scrollLeft),children:[s.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:Z(r)},children:$()}),t.map(C=>s.jsx("div",{className:`nice-dmx-timeline__track ${C.muted?"nice-dmx-timeline__track--muted":""}`,style:{width:Z(r)},children:C.cues.map(A=>T(A,C))},C.id)),s.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:Z(a)}})]})]})]})};function Zp(){const[e]=u.useState(()=>new wl);return u.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function Xp(e,t,n=120){const[r,a]=u.useState(0),o=u.useRef(0);return u.useEffect(()=>{if(!t)return;const i=60/n,l=()=>{const c=t.currentTime,d=Math.floor(c/i);d!==o.current&&(o.current=d,a(d))};return t.addEventListener("timeupdate",l),()=>t.removeEventListener("timeupdate",l)},[t,n]),{currentBeat:r}}const Qp=[{name:"Flat",bands:[{frequency:60,gain:0},{frequency:250,gain:0},{frequency:1e3,gain:0},{frequency:4e3,gain:0},{frequency:16e3,gain:0}]},{name:"Bass Boost",bands:[{frequency:60,gain:8},{frequency:250,gain:4},{frequency:1e3,gain:0},{frequency:4e3,gain:-2},{frequency:16e3,gain:-4}]},{name:"Treble Boost",bands:[{frequency:60,gain:-4},{frequency:250,gain:-2},{frequency:1e3,gain:0},{frequency:4e3,gain:4},{frequency:16e3,gain:8}]},{name:"Voice",bands:[{frequency:60,gain:-6},{frequency:250,gain:2},{frequency:1e3,gain:6},{frequency:4e3,gain:4},{frequency:16e3,gain:-2}]},{name:"Rock",bands:[{frequency:60,gain:4},{frequency:250,gain:2},{frequency:1e3,gain:-2},{frequency:4e3,gain:4},{frequency:16e3,gain:6}]}];function Cl(){const[e,t]=u.useState(!1),[n,r]=u.useState(.8),[a,o]=u.useState(!1),[i,l]=u.useState(null),[c,d]=u.useState(null),[h,f]=u.useState(null),m=u.useRef(null),g=u.useRef(null),p=u.useRef(null),v=u.useRef(null),x=u.useRef([]),b=u.useRef(null),w=u.useRef(null),y=u.useCallback(()=>{if(g.current)return;const I=new AudioContext;g.current=I;const q=I.createGain();q.gain.value=n,v.current=q;const Y=I.createAnalyser();Y.fftSize=256,b.current=Y,q.connect(Y).connect(I.destination)},[]),k=u.useCallback(()=>{const I=m.current,q=g.current,Y=v.current;if(!I||!q||!Y||p.current)return;const O=q.createMediaElementSource(I);p.current=O,x.current.length>0?(O.connect(x.current[0]),x.current[x.current.length-1].connect(Y)):O.connect(Y)},[]),M=u.useCallback(()=>{var q;const I=m.current;!I||!w.current||(Et(),y(),k(),((q=g.current)==null?void 0:q.state)==="suspended"&&g.current.resume(),I.play().catch(Y=>d(String(Y))))},[y,k]),N=u.useCallback(()=>{var I;(I=m.current)==null||I.pause()},[]),R=u.useCallback(()=>{e?N():M()},[e,M,N]),_=u.useCallback(I=>{const q=Math.max(0,Math.min(1,I));r(q),v.current&&(v.current.gain.value=q),m.current&&(m.current.volume=q)},[]),E=u.useCallback(I=>{w.current=I,d(null),l(null),o(!0),p.current&&(p.current.disconnect(),p.current=null),m.current||(m.current=new Audio,m.current.crossOrigin="anonymous",m.current.addEventListener("playing",()=>{t(!0),o(!1)}),m.current.addEventListener("pause",()=>t(!1)),m.current.addEventListener("waiting",()=>o(!0)),m.current.addEventListener("canplay",()=>o(!1)),m.current.addEventListener("error",()=>d("Failed to load stream"))),m.current.src=I.streamUrl,m.current.load(),l({genre:I.genre,bitrate:I.bitrate})},[]),U=u.useCallback(I=>{g.current||y();const Y=g.current;x.current.forEach(Z=>Z.disconnect());const O=I.bands.map(Z=>{const H=Y.createBiquadFilter();return H.type="peaking",H.frequency.value=Z.frequency,H.gain.value=Z.gain,H.Q.value=Z.Q??1.4,H});for(let Z=0;Z<O.length-1;Z++)O[Z].connect(O[Z+1]);x.current=O,p.current&&v.current&&(p.current.disconnect(),p.current.connect(O[0]),O[O.length-1].connect(v.current)),f(I.name)},[y]),W=u.useCallback(()=>{x.current.forEach(I=>I.disconnect()),x.current=[],p.current&&v.current&&(p.current.disconnect(),p.current.connect(v.current)),f(null)},[]);return u.useEffect(()=>()=>{var I,q,Y;(I=m.current)==null||I.pause(),m.current=null,x.current.forEach(O=>O.disconnect()),(q=p.current)==null||q.disconnect(),(Y=g.current)==null||Y.close()},[]),[{isPlaying:e,volume:n,isBuffering:a,metadata:i,error:c,activePreset:h},{play:M,pause:N,toggle:R,setVolume:_,setStation:E,applyEQPreset:U,clearEQ:W}]}function kl({stations:e,activeStationId:t,onSelect:n,onToggleFavorite:r,className:a}){const{t:o}=xe(),[i,l]=u.useState(""),[c,d]=u.useState(null),[h,f]=u.useState(!1),m=u.useMemo(()=>[...new Set(e.map(p=>p.genre).filter(Boolean))],[e]),g=u.useMemo(()=>e.filter(p=>{var v,x;if(h&&!p.isFavorite||c&&p.genre!==c)return!1;if(i){const b=i.toLowerCase();return p.name.toLowerCase().includes(b)||(((v=p.genre)==null?void 0:v.toLowerCase().includes(b))??!1)||(((x=p.country)==null?void 0:x.toLowerCase().includes(b))??!1)}return!0}),[e,i,c,h]);return s.jsxs("div",{className:`nice-station-browser${a?` ${a}`:""}`,children:[s.jsxs("div",{className:"nice-station-browser__toolbar",children:[s.jsx("input",{type:"text",className:"nice-station-browser__search",placeholder:(o==null?void 0:o("search_stations"))??"Search stations...",value:i,onChange:p=>l(p.target.value)}),s.jsxs("select",{className:"nice-station-browser__genre-filter",value:c??"",onChange:p=>d(p.target.value||null),children:[s.jsx("option",{value:"",children:(o==null?void 0:o("all_genres"))??"All Genres"}),m.map(p=>s.jsx("option",{value:p,children:p},p))]}),s.jsx("button",{className:`nice-station-browser__fav-toggle${h?" nice-station-browser__fav-toggle--active":""}`,onClick:()=>f(!h),title:(o==null?void 0:o("favorites"))??"Favorites",children:"★"})]}),s.jsxs("div",{className:"nice-station-browser__list",children:[g.map(p=>s.jsxs("div",{className:`nice-station-browser__item${p.id===t?" nice-station-browser__item--active":""}`,onClick:()=>n(p),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&n(p)},children:[p.logoUrl&&s.jsx("img",{className:"nice-station-browser__logo",src:p.logoUrl,alt:p.name,loading:"lazy"}),s.jsxs("div",{className:"nice-station-browser__info",children:[s.jsx("span",{className:"nice-station-browser__name",children:p.name}),p.genre&&s.jsx("span",{className:"nice-station-browser__genre",children:p.genre}),p.country&&s.jsx("span",{className:"nice-station-browser__country",children:p.country})]}),p.bitrate&&s.jsxs("span",{className:"nice-station-browser__bitrate",children:[p.bitrate,"kbps"]}),r&&s.jsx("button",{className:`nice-station-browser__fav${p.isFavorite?" nice-station-browser__fav--active":""}`,onClick:v=>{v.stopPropagation(),r(p.id)},children:p.isFavorite?"★":"☆"})]},p.id)),g.length===0&&s.jsx("div",{className:"nice-station-browser__empty",children:(o==null?void 0:o("no_stations_found"))??"No stations found"})]})]})}function Jp({stations:e,initialStationId:t,autoPlay:n=!1,eqPresets:r=Qp,onStationChange:a,onPlayingChange:o,onMetadata:i,onToggleFavorite:l,onRecordingStart:c,onRecordingStop:d,showBrowser:h=!0,showEqualizer:f=!1,showVisualizer:m=!1,showMetadataHistory:g=!1,showRecording:p=!1,showSleepTimer:v=!1,className:x,style:b}){var T,C;const{t:w}=xe(),[y,k]=Cl(),[M,N]=u.useState(()=>t?e.find(A=>A.id===t)??null:null),[R,_]=u.useState(f),E=u.useRef(null),U=u.useRef(0),[W,j]=u.useState([]),[L,I]=u.useState(!1),q=u.useRef(null),Y=u.useRef([]),[O,Z]=u.useState(0),H=u.useRef(null),[te,G]=u.useState(0),[z,S]=u.useState(null),P=u.useRef(null);u.useEffect(()=>{o==null||o(y.isPlaying)},[y.isPlaying,o]),u.useEffect(()=>{y.metadata&&(i==null||i(y.metadata),(y.metadata.title||y.metadata.artist)&&j(A=>[{time:new Date,meta:y.metadata},...A.slice(0,49)]))},[y.metadata,i]);const $=u.useCallback(A=>{N(A),k.setStation(A),a==null||a(A),n&&setTimeout(()=>k.play(),100)},[k,a,n]);return u.useEffect(()=>{if(t&&!M){const A=e.find(D=>D.id===t);A&&$(A)}},[t,e]),u.useEffect(()=>{if(!m||!E.current)return;const A=E.current,D=A.getContext("2d");if(!D)return;const V=()=>{U.current=requestAnimationFrame(V),D.clearRect(0,0,A.width,A.height);const Q=D.createLinearGradient(0,A.height,0,0);if(Q.addColorStop(0,"var(--nice-accent-tint-80, rgba(99, 102, 241, 0.8))"),Q.addColorStop(.5,"rgba(168,85,247,0.6)"),Q.addColorStop(1,"rgba(236,72,153,0.4)"),!y.isPlaying){const ee=A.width/32;for(let F=0;F<32;F++){const K=4+Math.sin(Date.now()/1e3+F*.3)*3;D.fillStyle=Q,D.fillRect(F*ee+1,A.height-K,ee-2,K)}return}const J=32,ae=A.width/J;for(let re=0;re<J;re++){const ee=re/J,K=(Math.sin(Date.now()/200+re*.5)*.3+.5)*A.height*(1-ee*.5)*(.5+Math.random()*.5);D.fillStyle=Q,D.fillRect(re*ae+1,A.height-K,ae-2,K)}};return V(),()=>cancelAnimationFrame(U.current)},[m,y.isPlaying]),u.useCallback(()=>{if(y.isPlaying)try{const D=new AudioContext().createMediaStreamDestination();Y.current=[];const V=new MediaRecorder(D.stream,{mimeType:"audio/webm"});V.ondataavailable=Q=>{Q.data.size>0&&Y.current.push(Q.data)},V.onstop=()=>{const Q=new Blob(Y.current,{type:"audio/webm"});d==null||d(Q),Z(0),H.current&&window.clearInterval(H.current)},V.start(1e3),q.current=V,I(!0),Z(0),H.current=window.setInterval(()=>{Z(Q=>Q+1)},1e3),c==null||c()}catch{}},[y.isPlaying,c,d]),u.useCallback(()=>{q.current&&L&&(q.current.stop(),I(!1),H.current&&window.clearInterval(H.current))},[L]),u.useCallback(A=>{P.current&&window.clearInterval(P.current),G(A),S(A*60),P.current=window.setInterval(()=>{S(D=>!D||D<=1?(P.current&&window.clearInterval(P.current),P.current=null,k.pause(),null):D-1)},1e3)},[k]),u.useCallback(()=>{P.current&&window.clearInterval(P.current),P.current=null,S(null),G(0)},[]),u.useEffect(()=>()=>{H.current&&window.clearInterval(H.current),P.current&&window.clearInterval(P.current),cancelAnimationFrame(U.current)},[]),s.jsxs("div",{className:`nice-radio-player${x?` ${x}`:""}`,style:b,children:[s.jsx("div",{className:"nice-radio-player__now-playing",children:M?s.jsxs(s.Fragment,{children:[M.logoUrl&&s.jsx("img",{className:"nice-radio-player__cover",src:M.logoUrl,alt:M.name}),s.jsxs("div",{className:"nice-radio-player__info",children:[s.jsx("span",{className:"nice-radio-player__station-name",children:M.name}),((T=y.metadata)==null?void 0:T.title)&&s.jsx("span",{className:"nice-radio-player__track",children:y.metadata.artist?`${y.metadata.artist} — ${y.metadata.title}`:y.metadata.title}),((C=y.metadata)==null?void 0:C.genre)&&s.jsx("span",{className:"nice-radio-player__genre",children:y.metadata.genre}),y.isBuffering&&s.jsx("span",{className:"nice-radio-player__buffering",children:(w==null?void 0:w("buffering"))??"Buffering..."})]})]}):s.jsx("div",{className:"nice-radio-player__placeholder",children:(w==null?void 0:w("select_station"))??"Select a station"})}),s.jsxs("div",{className:"nice-radio-player__controls",children:[s.jsx("button",{className:"nice-radio-player__play-btn",onClick:k.toggle,disabled:!M,"aria-label":y.isPlaying?"Pause":"Play",children:y.isPlaying?"⏸":"▶"}),s.jsxs("div",{className:"nice-radio-player__volume",children:[s.jsx("span",{className:"nice-radio-player__volume-icon",children:"🔊"}),s.jsx("input",{type:"range",min:0,max:1,step:.01,value:y.volume,onChange:A=>k.setVolume(parseFloat(A.target.value)),className:"nice-radio-player__volume-slider","aria-label":"Volume"})]}),s.jsx("button",{className:`nice-radio-player__eq-btn${R?" nice-radio-player__eq-btn--active":""}`,onClick:()=>_(!R),title:"Equalizer",children:"EQ"})]}),y.error&&s.jsx("div",{className:"nice-radio-player__error",children:y.error}),R&&s.jsx("div",{className:"nice-radio-player__equalizer",children:s.jsxs("div",{className:"nice-radio-player__eq-presets",children:[r.map(A=>s.jsx("button",{className:`nice-radio-player__eq-preset${y.activePreset===A.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>k.applyEQPreset(A),children:A.name},A.name)),y.activePreset&&s.jsx("button",{className:"nice-radio-player__eq-preset",onClick:k.clearEQ,children:(w==null?void 0:w("clear"))??"Clear"})]})}),h&&s.jsx(kl,{stations:e,activeStationId:M==null?void 0:M.id,onSelect:$})]})}const e0=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],t0={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class Ml{constructor(t,n={}){this.localStream=null,this.peers=new Map,this.onRemoteStream=null,this.onPeerStateChange=null,this.onSignalingMessage=null,this.localUserId=t,this.config={iceServers:n.iceServers??e0,audioConstraints:{...t0,echoCancellation:n.echoCancellation??!0,noiseSuppression:n.noiseSuppression??!0,autoGainControl:n.autoGainControl??!0}}}async initialize(){return this.localStream?this.localStream:(this.localStream=await navigator.mediaDevices.getUserMedia({audio:this.config.audioConstraints,video:!1}),this.localStream)}getLocalStream(){return this.localStream}getPeerIds(){return Array.from(this.peers.keys())}getPeerState(t){var n;return((n=this.peers.get(t))==null?void 0:n.state)??null}async createOffer(t){if(!this.localStream)throw new Error("WebRTCAudioManager not initialized. Call initialize() first.");const n=this.createPeerConnection(t),r=await n.createOffer();await n.setLocalDescription(r),this.sendSignalingMessage({type:"offer",from:this.localUserId,to:t,payload:r})}async handleSignalingMessage(t){if(t.to===this.localUserId)switch(t.type){case"offer":await this.handleOffer(t.from,t.payload);break;case"answer":await this.handleAnswer(t.from,t.payload);break;case"ice-candidate":await this.handleIceCandidate(t.from,t.payload);break;case"leave":this.removePeer(t.from);break}}removePeer(t){const n=this.peers.get(t);n&&(n.pc.close(),this.peers.delete(t))}disconnect(){for(const t of this.peers.keys())this.sendSignalingMessage({type:"leave",from:this.localUserId,to:t,payload:null});for(const t of this.peers.values())t.pc.close();this.peers.clear(),this.localStream&&(this.localStream.getTracks().forEach(t=>t.stop()),this.localStream=null)}setMuted(t){this.localStream&&this.localStream.getAudioTracks().forEach(n=>{n.enabled=!t})}isMuted(){if(!this.localStream)return!0;const t=this.localStream.getAudioTracks()[0];return t?!t.enabled:!0}createPeerConnection(t){const n=new RTCPeerConnection({iceServers:this.config.iceServers}),r={id:t,pc:n,remoteStream:null,state:n.connectionState};return this.peers.set(t,r),this.localStream&&this.localStream.getTracks().forEach(a=>{n.addTrack(a,this.localStream)}),n.onicecandidate=a=>{a.candidate&&this.sendSignalingMessage({type:"ice-candidate",from:this.localUserId,to:t,payload:a.candidate.toJSON()})},n.ontrack=a=>{var i;const[o]=a.streams;o&&(r.remoteStream=o,(i=this.onRemoteStream)==null||i.call(this,t,o))},n.onconnectionstatechange=()=>{var a;r.state=n.connectionState,(a=this.onPeerStateChange)==null||a.call(this,t,n.connectionState),(n.connectionState==="failed"||n.connectionState==="disconnected")&&this.removePeer(t)},n}async handleOffer(t,n){this.localStream||await this.initialize();const r=this.createPeerConnection(t);await r.setRemoteDescription(new RTCSessionDescription(n));const a=await r.createAnswer();await r.setLocalDescription(a),this.sendSignalingMessage({type:"answer",from:this.localUserId,to:t,payload:a})}async handleAnswer(t,n){const r=this.peers.get(t);r&&await r.pc.setRemoteDescription(new RTCSessionDescription(n))}async handleIceCandidate(t,n){const r=this.peers.get(t);r&&n&&await r.pc.addIceCandidate(new RTCIceCandidate(n))}sendSignalingMessage(t){var n;(n=this.onSignalingMessage)==null||n.call(this,t)}}function n0(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function r0(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function a0(){return new AudioContext({sampleRate:48e3,latencyHint:"interactive"})}const Pa=u.forwardRef(function(t,n){const{mode:r="bars",width:a=300,height:o=100,barCount:i=32,barColor:l="var(--nice-primary, #3b82f6)",backgroundColor:c="transparent",fftSize:d=256,smoothing:h=.8,minDecibels:f=-90,maxDecibels:m=-10,deviceId:g,autoStart:p=!1,onStart:v,onStop:x,onAudioLevel:b,onError:w,className:y,style:k,barBorderRadius:M=2,barGap:N=2,lineWidth:R=2}=t,_=u.useRef(null),E=u.useRef(null),U=u.useRef(null),W=u.useRef(null),j=u.useRef(0),L=u.useRef(null),I=u.useRef(0),[q,Y]=u.useState(!1),O=u.useCallback(($,T,C=!0)=>{const A=C?$.createLinearGradient(0,o,0,0):$.createLinearGradient(0,0,a,0);return T.forEach((D,V)=>{A.addColorStop(V/(T.length-1),D)}),A},[a,o]),Z=u.useCallback(($,T)=>{const A=(a-(i-1)*N)/i,D=Math.floor(T.length/i),V=Array.isArray(l)?l:[l],Q=V.length>1?O($,V):V[0];$.fillStyle=Q;for(let J=0;J<i;J++){const re=T[J*D]/255*o,ee=J*(A+N),F=o-re;M>0?($.beginPath(),$.roundRect(ee,F,A,re,M),$.fill()):$.fillRect(ee,F,A,re)}},[i,l,N,M,a,o,O]),H=u.useCallback(($,T)=>{const C=o/2,D=(a-(i-1)*N)/i,V=Math.floor(T.length/i),Q=Array.isArray(l)?l:[l],J=Q.length>1?O($,Q):Q[0];$.fillStyle=J;for(let ae=0;ae<i;ae++){const ee=T[ae*V]/255*C,F=ae*(D+N);M>0?($.beginPath(),$.roundRect(F,C-ee,D,ee,M),$.fill(),$.beginPath(),$.roundRect(F,C,D,ee,M),$.fill()):($.fillRect(F,C-ee,D,ee),$.fillRect(F,C,D,ee))}},[i,l,N,M,a,o,O]),te=u.useCallback(($,T)=>{const C=Array.isArray(l)?l:[l];$.strokeStyle=C.length>1?O($,C,!1):C[0],$.lineWidth=R,$.lineCap="round",$.lineJoin="round",$.beginPath();const A=a/T.length;let D=0;for(let V=0;V<T.length;V++){const J=T[V]/128*o/2;V===0?$.moveTo(D,J):$.lineTo(D,J),D+=A}$.stroke()},[l,R,a,o,O]),G=u.useCallback(($,T)=>{const C=a/2,A=o/2,D=Math.min(a,o)/3,V=Array.isArray(l)?l:[l];$.strokeStyle=V.length>1?O($,V):V[0],$.lineWidth=R;const Q=Math.floor(T.length/64),J=Math.PI*2/64;$.beginPath();for(let ae=0;ae<64;ae++){const re=T[ae*Q]/255,ee=D+re*D*.5,F=ae*J-Math.PI/2,K=C+Math.cos(F)*ee,se=A+Math.sin(F)*ee;ae===0?$.moveTo(K,se):$.lineTo(K,se)}$.closePath(),$.stroke()},[l,R,a,o,O]),z=u.useCallback(()=>{const $=_.current,T=U.current,C=L.current;if(!$||!T||!C)return;const A=$.getContext("2d");if(!A)return;r==="waveform"?T.getByteTimeDomainData(C):T.getByteFrequencyData(C);let D=0;for(let V=0;V<C.length;V++)D+=C[V];switch(I.current=D/(C.length*255),b==null||b(I.current),A.clearRect(0,0,a,o),c!=="transparent"&&(A.fillStyle=c,A.fillRect(0,0,a,o)),r){case"bars":Z(A,C);break;case"mirror-bars":H(A,C);break;case"waveform":te(A,C);break;case"circle":G(A,C);break}j.current=requestAnimationFrame(z)},[r,a,o,c,Z,H,te,G,b]),S=u.useCallback(async()=>{try{if(q)return;const $=await navigator.mediaDevices.getUserMedia({audio:g?{deviceId:{exact:g}}:!0,video:!1});W.current=$;const T=new AudioContext;E.current=T;const C=T.createMediaStreamSource($),A=T.createAnalyser();A.fftSize=d,A.smoothingTimeConstant=h,A.minDecibels=f,A.maxDecibels=m,C.connect(A),U.current=A,L.current=new Uint8Array(A.frequencyBinCount),Y(!0),v==null||v(),z()}catch($){w==null||w($ instanceof Error?$:new Error(String($)))}},[q,g,d,h,f,m,v,w,z]),P=u.useCallback(()=>{cancelAnimationFrame(j.current),W.current&&(W.current.getTracks().forEach(T=>T.stop()),W.current=null),E.current&&(E.current.close(),E.current=null),U.current=null,L.current=null,I.current=0,Y(!1),x==null||x();const $=_.current;if($){const T=$.getContext("2d");T&&(T.clearRect(0,0,a,o),c!=="transparent"&&(T.fillStyle=c,T.fillRect(0,0,a,o)))}},[a,o,c,x]);return u.useImperativeHandle(n,()=>({start:S,stop:P,isCapturing:()=>q,getAudioLevel:()=>I.current}),[S,P,q]),u.useEffect(()=>(p&&S(),()=>{P()}),[p]),s.jsx("canvas",{ref:_,width:a,height:o,className:y,style:{display:"block",...k},"aria-label":"Audio visualizer"})}),Rs=e=>{switch(e){case"top-left":return{top:16,left:16};case"top-right":return{top:16,right:16};case"bottom-left":return{bottom:16,left:16};case"bottom-right":default:return{bottom:16,right:16}}},s0={position:"fixed",display:"flex",flexDirection:"column",gap:8,padding:12,borderRadius:12,boxShadow:"0 4px 20px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:14,minWidth:200,maxWidth:280,transition:"all 0.2s ease"},o0={background:"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",text:"var(--nice-bg, #1a1a1a)",textSecondary:"var(--nice-text-secondary, #666)",border:"var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-bg, #fee2e2)",mutedIcon:"var(--nice-danger, #ef4444)",activeBg:"var(--nice-success-bg, #dcfce7)",activeIcon:"var(--nice-success, #22c55e)",hoverBg:"var(--nice-overlay-5, rgba(0, 0, 0, 0.05))"},i0={background:"rgba(30, 30, 30, 0.95)",text:"var(--nice-bg, #fff)",textSecondary:"var(--nice-text-muted, #a0a0a0)",border:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-dark, #7f1d1d)",mutedIcon:"var(--nice-danger-bg, #fca5a5)",activeBg:"#14532d",activeIcon:"var(--nice-success-light, #86efac)",hoverBg:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))"},jl=u.forwardRef(function(t,n){const{userId:r,userName:a,userAvatarUrl:o,participants:i=[],rtcConfig:l,position:c="bottom-right",expanded:d=!0,onSignalingMessage:h,onMuteToggle:f,onLeave:m,onSpeakingChange:g,speakingThreshold:p=.1,theme:v="auto",className:x,style:b,zIndex:w=1e3}=t,y=u.useRef(null),k=u.useRef(null),M=u.useRef(new Map);u.useRef(new Map);const[N,R]=u.useState(!1),[_,E]=u.useState(!1),[U,W]=u.useState(!1),[j,L]=u.useState(d),q=u.useMemo(()=>v==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":v,[v])==="dark"?i0:o0;u.useEffect(()=>{const z=new Ml(r,l);return z.onRemoteStream=(S,P)=>{let $=M.current.get(S);$||($=new Audio,$.autoplay=!0,M.current.set(S,$)),$.srcObject=P},z.onSignalingMessage=S=>{h==null||h(S)},z.onPeerStateChange=(S,P)=>{P==="connected"&&E(!0)},y.current=z,z.initialize().then(()=>{var S;(S=k.current)==null||S.start()}),()=>{z.disconnect();const S=M.current;S.forEach(P=>{P.srcObject=null}),S.clear()}},[r,l,h]);const Y=u.useCallback(()=>{var S;const z=!N;R(z),(S=y.current)==null||S.setMuted(z),f==null||f(z)},[N,f]),O=u.useCallback(()=>{var z,S;(z=y.current)==null||z.disconnect(),(S=k.current)==null||S.stop(),E(!1),m==null||m()},[m]),Z=u.useCallback(z=>{const S=z>p;S!==U&&(W(S),g==null||g(r,S))},[p,U,r,g]),H=u.useCallback(async z=>{var S;await((S=y.current)==null?void 0:S.createOffer(z))},[]),te=u.useCallback(async z=>{var S;await((S=y.current)==null?void 0:S.handleSignalingMessage(z))},[]);u.useImperativeHandle(n,()=>({connectToPeer:H,handleSignalingMessage:te,toggleMute:Y,isMuted:()=>N,leave:O,getManager:()=>y.current}),[H,te,Y,N,O]);const G=({participant:z,isLocal:S,isSpeaking:P})=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 0"},children:[s.jsx("div",{style:{width:32,height:32,borderRadius:"50%",backgroundColor:q.hoverBg,border:`2px solid ${P?q.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:q.text,transition:"border-color 0.15s ease"},children:z.avatarUrl?s.jsx("img",{src:z.avatarUrl,alt:z.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):z.name.charAt(0).toUpperCase()}),s.jsx("div",{style:{flex:1,minWidth:0},children:s.jsxs("div",{style:{color:q.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[z.name,S&&s.jsx("span",{style:{color:q.textSecondary,fontWeight:400},children:" (You)"})]})}),z.isMuted&&s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:q.mutedIcon,strokeWidth:"2",children:[s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),s.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),s.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),s.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),s.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})]});return j?s.jsxs("div",{className:x,style:{...s0,...Rs(c),backgroundColor:q.background,border:`1px solid ${q.border}`,zIndex:w,...b},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${q.border}`},children:[s.jsx("span",{style:{color:q.text,fontWeight:600},children:"Voice Chat"}),s.jsx("button",{onClick:()=>L(!1),style:{background:"none",border:"none",cursor:"pointer",padding:4,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:4},"aria-label":"Collapse",children:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:q.textSecondary,strokeWidth:"2",children:[s.jsx("polyline",{points:"4 14 10 14 10 20"}),s.jsx("polyline",{points:"20 10 14 10 14 4"}),s.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),s.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx(G,{participant:{id:r,name:a,avatarUrl:o,isMuted:N},isLocal:!0,isSpeaking:U&&!N}),i.map(z=>s.jsx(G,{participant:z,isSpeaking:z.isSpeaking},z.id))]}),s.jsx(Pa,{ref:k,mode:"bars",width:256,height:32,barCount:24,barColor:N?"var(--nice-text-muted, #9ca3af)":["var(--nice-primary, #3b82f6)","var(--nice-accent, #8b5cf6)"],barGap:3,barBorderRadius:2,autoStart:!1,onAudioLevel:Z,style:{borderRadius:4,opacity:N?.5:1}}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{onClick:Y,style:{flex:1,padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:N?q.mutedBg:q.activeBg,color:N?q.mutedIcon:q.activeIcon,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":N?"Unmute":"Mute",children:N?s.jsxs(s.Fragment,{children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),s.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),s.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),s.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),s.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Muted"]}):s.jsxs(s.Fragment,{children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),s.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),s.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),s.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Mic On"]})}),s.jsx("button",{onClick:O,style:{padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:"var(--nice-danger-bg, #fef2f2)",color:"var(--nice-danger-dark, #dc2626)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":"Leave voice chat",children:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),s.jsx("polyline",{points:"16 17 21 12 16 7"}),s.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]})]}):s.jsx("div",{className:x,style:{position:"fixed",...Rs(c),zIndex:w,...b},children:s.jsxs("button",{onClick:()=>L(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:q.background,boxShadow:"0 4px 12px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":"Expand voice chat",children:[s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:q.text,strokeWidth:"2",children:[s.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),s.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),s.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),s.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),i.length>0&&s.jsx("span",{style:{position:"absolute",top:-4,right:-4,width:20,height:20,borderRadius:"50%",backgroundColor:q.speakingRing,color:"var(--nice-bg, #fff)",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:i.length+1})]})})});function l0(e,t){const n={...t,id:`op_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now()},r=e.operations.slice(0,e.undoIndex+1);return r.push(n),{...e,operations:r,undoIndex:r.length-1}}function c0(e){return e.undoIndex<0?e:{...e,undoIndex:e.undoIndex-1}}function d0(e){return e.undoIndex>=e.operations.length-1?e:{...e,undoIndex:e.undoIndex+1}}function u0(e,t,n){const a=({"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":.6666666666666666,"1/8T":.3333333333333333,"1/16T":.16666666666666666,"1/4D":1.5,"1/8D":.75}[t.grid]??1)*n,o=t.strength/100;return e.map(i=>{const l=Math.round(i.startTick/a)*a,c=i.startTick+(l-i.startTick)*o,d=(Math.random()-.5)*2*t.humanize;return{...i,startTick:Math.max(0,Math.round(c+d))}})}function h0(e){if(e.length<2)return null;const t=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],n=[...new Set(e.map(a=>a%12))].sort((a,o)=>a-o),r=[{intervals:[0,4,7],quality:"maj"},{intervals:[0,3,7],quality:"min"},{intervals:[0,4,7,11],quality:"maj7"},{intervals:[0,3,7,10],quality:"min7"},{intervals:[0,4,7,10],quality:"7"},{intervals:[0,3,6],quality:"dim"},{intervals:[0,4,8],quality:"aug"},{intervals:[0,3,6,9],quality:"dim7"},{intervals:[0,2,7],quality:"sus2"},{intervals:[0,5,7],quality:"sus4"},{intervals:[0,4,7,9],quality:"6"},{intervals:[0,3,7,9],quality:"min6"}];for(const a of n){const o=n.map(i=>(i-a+12)%12).sort((i,l)=>i-l);for(const i of r)if(i.intervals.length===o.length&&i.intervals.every((l,c)=>l===o[c])){const l=t[a],c=t[e[0]%12];return{root:l,quality:i.quality,bass:c!==l?c:void 0,symbol:`${l}${i.quality==="maj"?"":i.quality}${c!==l?`/${c}`:""}`,intervals:i.intervals}}}return null}const Rl={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],aeolian:[0,2,3,5,7,8,10],locrian:[0,1,3,5,6,8,10],"harmonic-minor":[0,2,3,5,7,8,11],"melodic-minor":[0,2,3,5,7,9,11],"pentatonic-major":[0,2,4,7,9],"pentatonic-minor":[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11],"whole-tone":[0,2,4,6,8,10]};function f0(e,t,n){const r=Rl[n],a=(e-t+120)%12;let o=r[0],i=999;for(const c of r){const d=Math.min(Math.abs(a-c),12-Math.abs(a-c));d<i&&(i=d,o=c)}const l=Math.floor((e-t)/12);return t+l*12+o}function p0(e,t){switch(t.type){case"transpose":return e.map(n=>({...n,pitch:Math.max(0,Math.min(127,n.pitch+(t.params.semitones??0)))}));case"invert":{const n=t.params.axis??60;return e.map(r=>({...r,pitch:Math.max(0,Math.min(127,Math.round(2*n-r.pitch)))}))}case"retrograde":{if(e.length===0)return e;const n=Math.max(...e.map(r=>r.startTick+r.durationTicks));return e.map(r=>({...r,startTick:n-r.startTick-r.durationTicks}))}case"randomize-velocity":return e.map(n=>({...n,velocity:Math.max(1,Math.min(127,n.velocity+Math.round((Math.random()-.5)*2*(t.params.range??20))))}));default:return e}}function m0(e){return e>=95?"S":e>=85?"A":e>=70?"B":e>=55?"C":e>=40?"D":"F"}const g0={"guitar-standard":{instrument:"guitar-6",stringPitches:[40,45,50,55,59,64]},"guitar-drop-d":{instrument:"guitar-6",stringPitches:[38,45,50,55,59,64]},"bass-standard":{instrument:"bass-4",stringPitches:[28,33,38,43]},"ukulele-standard":{instrument:"ukulele",stringPitches:[67,60,64,69]}},y0={"Bass Drum":{staffLine:4,noteHead:"normal",stem:"down"},Snare:{staffLine:2,noteHead:"normal",stem:"up"},"Hi-Hat Closed":{staffLine:0,noteHead:"x",stem:"up"},"Hi-Hat Open":{staffLine:0,noteHead:"diamond",stem:"up"},Ride:{staffLine:-1,noteHead:"x",stem:"up"},Crash:{staffLine:-2,noteHead:"x",stem:"up"},"High Tom":{staffLine:1,noteHead:"normal",stem:"up"},"Mid Tom":{staffLine:2,noteHead:"normal",stem:"down"},"Low Tom":{staffLine:3,noteHead:"normal",stem:"down"}};exports.ALL_CAP_STYLES=Cn;exports.ALL_EFFECTS=dp;exports.ALL_TEXTURES=ko;exports.ARTNET_PORT=Bp;exports.ASYMMETRIC_CAPS=po;exports.ArpeggiatorPanel=Vs;exports.AudioEffectType=yl;exports.AudioPitchAnalyzer=jo;exports.AudioPlaybackEngine=Kh;exports.AudioRecorder=Js;exports.AudioTimeline=Ls;exports.AutoSavePanel=Ks;exports.BarFillEditor=Mo;exports.CCAutomationLaneEditor=zs;exports.CCLane=Es;exports.CONTROLLER_PROFILES=Ci;exports.ChaseRunner=Kp;exports.CollaboratorPermission=bl;exports.DEFAULT_ARP_CONFIG=Ar;exports.DEFAULT_BAR_FILL=At;exports.DEFAULT_CAP_STYLE=go;exports.DEFAULT_EMPTY_BAR_FILL=lr;exports.DEFAULT_FONT_SETTINGS=ur;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=cr;exports.DEFAULT_GOLD_FILLED_BAR_FILL=dr;exports.DEFAULT_KARAOKE_SETTINGS=yo;exports.DEFAULT_PLAYER_BAR_STYLE=Xt;exports.DEFAULT_SEED_CONFIG=mi;exports.DMXEngine=wl;exports.DRUM_PATTERN_NAMES=cf;exports.DefaultScoringPresets=ta;exports.DmxChannelControl=Ta;exports.DmxChannelType=kt;exports.DmxEditor=xl;exports.DmxOptionsControl=$a;exports.DmxSliderControl=kn;exports.DynamicRuleEditor=Zo;exports.DynamicRuleField=Ye;exports.DynamicRuleOperator=Ze;exports.EditorTrackProvider=Qr;exports.EditorUndoManager=ed;exports.FIXTURE_PROFILES=Sl;exports.GENERIC_PROFILE=Sa;exports.GM_DRUM_MAP=y0;exports.GRADIENT_PRESETS=Ro;exports.GROOVE_TEMPLATES=Ma;exports.GenericPlayer=Do;exports.GenericPlayerControls=_o;exports.GenericPlayerStage=zo;exports.GenericPlayerStageVisualizer=Go;exports.GenericPlaylist=Wo;exports.GenericPlaylistItem=pa;exports.KARAOKE_FONT_OPTIONS=Hd;exports.KEY_MAPS=Po;exports.KaraokeEditorManager=Io;exports.KaraokeFormat=gl;exports.KaraokeLyrics=ao;exports.KaraokePhaserRenderer=Lo;exports.KaraokeTimeline=wo;exports.LANE_COLORS=yn;exports.LAUNCH_CONTROL_PROFILE=wi;exports.LAYER_COLORS=Lp;exports.LFOPanel=qs;exports.MINILAB_PROFILE=Si;exports.MPK_MINI_PROFILE=xi;exports.MasterFXPanel=Xs;exports.MidiCCMapper=uf;exports.ModeSwitcher=ha;exports.NOTE_NAMES=nf;exports.NiceArpeggiatorPanel=Vs;exports.NiceAudioErrorBoundary=Ol;exports.NiceAudioPitchAnalyzer=jo;exports.NiceAudioTimeline=Ls;exports.NiceAutoSavePanel=Ks;exports.NiceBarFillEditor=Mo;exports.NiceCCAutomationLaneEditor=zs;exports.NiceCCLane=Es;exports.NiceDMXTimeline=Yp;exports.NiceDmxChannelControl=Ta;exports.NiceDmxEditor=xl;exports.NiceDmxOptionsControl=$a;exports.NiceDmxSliderControl=kn;exports.NiceDynamicRuleEditor=Zo;exports.NiceEditorTrackProvider=Qr;exports.NiceGenericPlayer=Do;exports.NiceGenericPlayerControls=_o;exports.NiceGenericPlayerStage=zo;exports.NiceGenericPlayerStageVisualizer=Go;exports.NiceGenericPlaylist=Wo;exports.NiceGenericPlaylistItem=pa;exports.NiceI18nProvider=Dl;exports.NiceKaraokeEditorManager=Io;exports.NiceKaraokeLyrics=ao;exports.NiceKaraokePhaserRenderer=Lo;exports.NiceKaraokeTimeline=wo;exports.NiceLFOPanel=qs;exports.NiceMasterFXPanel=Xs;exports.NiceModeSwitcher=ha;exports.NiceNoteParticles=fi;exports.NiceNoteRiver=hi;exports.NicePianoRoll=Ps;exports.NicePlaylistBrowser=ei;exports.NicePlaylistDualPane=Xo;exports.NicePlaylistGridView=ri;exports.NicePlaylistImportWizard=ii;exports.NicePlaylistList=ba;exports.NicePlaylistOverview=ai;exports.NicePlaylistSearchBar=si;exports.NicePlaylistSidebar=ni;exports.NicePlaylistTagEditor=Uo;exports.NicePlaylistTrackList=ga;exports.NiceRadioPlayer=Jp;exports.NiceRecordingOptionsPanel=Qs;exports.NiceStageVisualizer=fa;exports.NiceStationBrowser=kl;exports.NiceStepSequencerPanel=Hs;exports.NiceStreamingVisualizer=Pa;exports.NiceUndoRedoPanel=Ys;exports.NiceVoiceChatOverlay=jl;exports.NiceWaveform=Ts;exports.NiceYouTubePlayer=Bo;exports.NiceZoomSnapControls=Zs;exports.NoteParticles=fi;exports.NoteRiver=hi;exports.OVERLAY_PATTERNS=nr;exports.OXYGEN25_PROFILE=vi;exports.PLAYER_COLORS=Pt;exports.PLAYER_COLOR_VARS=Zn;exports.PROGRESSION_NAMES=lf;exports.PadNotePlayer=Xd;exports.PaneSide=qo;exports.PianoRoll=Ps;exports.PlaylistBrowser=ei;exports.PlaylistDualPane=Xo;exports.PlaylistGridView=ri;exports.PlaylistImportWizard=ii;exports.PlaylistList=ba;exports.PlaylistOverview=ai;exports.PlaylistSearchBar=si;exports.PlaylistSidebar=ni;exports.PlaylistTagEditor=Uo;exports.PlaylistTrackList=ga;exports.PlaylistType=ma;exports.RecordingOptionsPanel=Qs;exports.SACN_PORT=Vp;exports.SCALE_INTERVALS=Rl;exports.SCALE_NAMES=of;exports.SKEW_CAPS=mo;exports.STANDARD_TUNINGS=g0;exports.SYMMETRIC_CAPS=ia;exports.ShortcutManager=pl;exports.SimpleSynth=pi;exports.SortDirection=qt;exports.SortField=Ho;exports.StageVisualizer=fa;exports.StepSequencerPanel=Hs;exports.StreamingVisualizer=Pa;exports.TEXTURE_CATEGORIES=ca;exports.TrackSource=lt;exports.UndoRedoPanel=Ys;exports.ViewMode=Vo;exports.VocalEffectsEngine=up;exports.VoiceChatOverlay=jl;exports.Waveform=Ts;exports.WebRTCAudioManager=Ml;exports.YouTubePlayer=Bo;exports.ZoomSnapControls=Zs;exports.addEffectToLayer=Gf;exports.addMidiNote=Vf;exports.analyzeAudioFileWithAlgorithm=ep;exports.applyGroove=ip;exports.applyGrooveTemplate=dl;exports.applyHumanize=cl;exports.applyKaraokeDisplayVars=ua;exports.applyMidiTransform=p0;exports.applySwing=ll;exports.arrow_L=Mt;exports.arrow_R=gt;exports.autoCorrelate=Ef;exports.bracket_L=ra;exports.bracket_R=ho;exports.buildArpSequence=Bs;exports.buildLanes=Eo;exports.buildNoteDescriptors=Af;exports.buildPadNoteEvents=No;exports.buildSegmentScores=Nf;exports.canRedo=Ti;exports.canUndo=$i;exports.chamfer_L=Qn;exports.chamfer_R=Zt;exports.clearMidiNotes=Hf;exports.clearPattern=Hi;exports.computeGrade=m0;exports.computeTheoreticalMax=al;exports.computeVocalPerformanceReport=hp;exports.convertBrowserSongToKaraokeSongFile=zf;exports.copyCCEvents=qr;exports.createAnalyserNode=Qi;exports.createArpPattern=bf;exports.createArtNetPacket=Up;exports.createBasslinePattern=vf;exports.createCCHistory=ki;exports.createCompressorNode=el;exports.createDefaultLFO=ir;exports.createDefaultShortcuts=Mp;exports.createDropZoneHandlers=Np;exports.createEmptyPattern=Nt;exports.createEmptyStep=wa;exports.createGainNode=Ji;exports.createHiHatPattern=yf;exports.createKickPattern=mf;exports.createLoopRegion=vp;exports.createSACNPacket=qp;exports.createSnarePattern=gf;exports.createVocoderNode=tl;exports.createVoiceChatAudioContext=a0;exports.cutCCEvents=Ei;exports.deleteCCEventsInRange=Ai;exports.deserializeLFO=dc;exports.deserializePattern=Sf;exports.detectChord=h0;exports.downsampleAndQuantizePitchPoints=If;exports.drawGlossyBarOnCanvas=hn;exports.drawTimeline=Dr;exports.estimateLatencyMs=Lf;exports.estimateLatencyMsFromRecording=mp;exports.evaluateLFO=Zr;exports.evaluateLFOAsCC=Xr;exports.exportCCLane=Li;exports.extractBpmFromNotes=so;exports.findTextureByUrl=Ud;exports.formatShortcut=jp;exports.generateArpEvents=fc;exports.generatePlaceholderWaveform=sp;exports.generateSeed=bi;exports.generateUltrastarText=tp;exports.getActiveGradient=To;exports.getActiveLyrics=od;exports.getActiveWords=id;exports.getAlgorithmColor=Df;exports.getAlgorithmCssVar=Of;exports.getAlgorithmLabel=Ff;exports.getArpModes=Ws;exports.getArpRates=Us;exports.getAudioContext=tn;exports.getAudioInputDevices=r0;exports.getAudioWorkletProcessorCode=Zi;exports.getBackgroundUrl=Pf;exports.getCachedImage=Gd;exports.getCapStyleByName=dn;exports.getComboMultiplier=rl;exports.getCoverUrl=Tf;exports.getGrooveTemplate=lp;exports.getGrooveTemplateNames=cp;exports.getLaneForPitch=Ao;exports.getNextPlayerColor=Fp;exports.getNextPlayerColorCss=Dp;exports.getOverlayCanvasPattern=gn;exports.getPatternByName=un;exports.getSACNMulticastAddress=Hp;exports.getScoringPreset=lo;exports.getTexturePattern=pn;exports.getVerseRatingLabel=nl;exports.handleAddCCEvent=Yf;exports.handleRedo=Jc;exports.handleRemoveCCEvent=Xf;exports.handleSelectCCLane=Kf;exports.handleUndo=Qc;exports.handleUpdateCCEvent=Zf;exports.hexToHsl=rr;exports.humanizeMidiNotes=bp;exports.hydrateKaraokeDisplayFromBackend=Kd;exports.hydratePlayerKaraokeSettingsFromBackend=vd;exports.hzToUltrastarPitch=oo;exports.importCCLane=Fi;exports.initKaraokeDisplaySettings=Zd;exports.instrumentPresets=Yh;exports.isAudioContextRunning=As;exports.isInLoopRegion=wp;exports.isWebRTCSupported=n0;exports.loadAllKaraokeSettings=xd;exports.loadAudioWorkletModule=Xi;exports.loadKaraokeDisplaySettings=$o;exports.loadKaraokeSettings=bo;exports.loadPlayerBarStyle=vo;exports.loadPlayerBarStyles=wd;exports.loadRemoteScoringPresets=md;exports.makeClickReference=hl;exports.makeClipSelectionId=np;exports.mergeWaveforms=ap;exports.midiSeedGenerator=df;exports.midiToHz=Or;exports.normalizeHex=ar;exports.openAudioFilePicker=Ip;exports.ornate_L=sa;exports.ornate_R=tr;exports.parseLyrics=ad;exports.parseNotes=ea;exports.parseVersesWithSyllables=ro;exports.parseVersesWithWords=sd;exports.parseVideoMetadata=ol;exports.pasteCCEvents=Pi;exports.pill_L=$t;exports.pill_R=Ct;exports.preloadTexture=la;exports.preloadTextures=Bd;exports.probeAudioFile=ml;exports.pushCCState=Mi;exports.pushOperation=l0;exports.quantizeMidiNotes=gp;exports.quantizeNotes=u0;exports.quantizeStepInBeats=fl;exports.quantizeStepInSeconds=ja;exports.randomizeVelocity=qi;exports.recordCCEvent=Ni;exports.redoCC=Ri;exports.redoOperation=d0;exports.removeEffectFromLayer=Bf;exports.removeMidiNote=qf;exports.renderGlossyBarSvg=xo;exports.resumeAudioContext=Et;exports.reversePattern=Ui;exports.sampleLFOForDisplay=_s;exports.sampleLFOToCCEvents=Os;exports.saveKaraokeDisplaySettings=Yd;exports.saveKaraokeSettings=bd;exports.savePlayerBarStyle=Sd;exports.scaleResult=$f;exports.scaleTo10k=sl;exports.scoreNotesWithPitchPoints=Rf;exports.selectCCEventsInRange=hf;exports.serializeLFO=cc;exports.serializePattern=xf;exports.setLoopFromSelection=xp;exports.setProjectWithUndo=to;exports.setStepGate=zi;exports.setStepNote=Oi;exports.setStepProbability=Gi;exports.setStepVelocity=_i;exports.sharp_L=Kt;exports.sharp_R=Yt;exports.shield_L=Jn;exports.shield_R=uo;exports.shiftPattern=Vi;exports.shouldTrigger=Yi;exports.skewTL_L=Un;exports.skewTL_R=Fr;exports.skewTR_L=Lr;exports.skewTR_R=Vn;exports.snapLoopToGrid=Sp;exports.snapTimeToQuantize=Hr;exports.snapToGrid=rp;exports.snapToScale=f0;exports.soft_L=na;exports.soft_R=co;exports.stepDuration=Ca;exports.stepTimeOffset=Ki;exports.syncDivisionToHz=Fs;exports.tab_L=aa;exports.tab_R=fo;exports.thinCCEvents=Ii;exports.toTrack=_f;exports.toggleEffectBypass=Wf;exports.toggleStep=Di;exports.toggleStepSlide=Bi;exports.transposePattern=Wi;exports.undoCC=ji;exports.undoOperation=c0;exports.updateEffectParams=Uf;exports.useAudioWorklet=jf;exports.useAutoSave=Kc;exports.useCCAutomation=pf;exports.useDMXAudioSync=Xp;exports.useDMXEngine=Zp;exports.useEditorTrack=rd;exports.useLocalPlaylists=ya;exports.useMPE=Jh;exports.useMidiLearn=Xh;exports.useNiceTranslation=xe;exports.useOxygen25=tf;exports.usePitchWorker=Cf;exports.usePlaybackEngine=Yc;exports.useProjectCRUD=nd;exports.useRadioStream=Cl;exports.useRecording=Zc;exports.useScoringWorker=kf;exports.useStepSequencer=wf;exports.useWebMidi=pr;exports.useWorker=ka;exports.validateAudioFiles=Ra;exports.wave_L=er;exports.wave_R=oa;exports.waveformValue=Ds;exports.wrapTimeInLoop=Cp;