import{a as e,o as t,t as n}from"./i18n-CjHYiQIU.js";import{r}from"./channel-ByUzMNR5.js";import{B as i,F as a,I as o,N as s,R as c}from"./index-D2kkGKae.js";var l=t(),u=e(),d=[`pointerdown`,`touchstart`,`click`,`keydown`],f=5;function p({trackIndex:e,volume:t,onEnded:p,paused:m=!1}){let{ambientLoop:h}=n().strings,g=(0,l.useRef)(null),_=(0,l.useRef)(null),v=(0,l.useRef)(null),y=(0,l.useRef)(m),b=r(`music-soft-transition`),x=Math.min(1,Math.max(0,t)),S=(0,l.useRef)(x),C=i[e]??i[0],w=(0,l.useCallback)(()=>{v.current!==null&&(clearInterval(v.current),v.current=null)},[]),T=(0,l.useCallback)((e,t)=>{let n=g.current;if(!n)return;w();let r=Math.max(1,Math.round(t/50)),i=n.volume,a=0;v.current=setInterval(()=>{a+=1,n.volume=Math.min(1,Math.max(0,i+(e-i)*(a/r))),a>=r&&w()},50)},[w]);return(0,l.useEffect)(()=>{y.current=m},[m]),(0,l.useEffect)(()=>{S.current=x},[x]),(0,l.useEffect)(()=>a(e=>{g.current&&(g.current.muted=e)}),[]),(0,l.useEffect)(()=>{o(C?.src)},[C?.src]),(0,l.useEffect)(()=>{let e=0,t=!1,n=!1,r=()=>{if(!n){n=!0;for(let e of d)document.removeEventListener(e,i)}};function i(){let i=g.current;n||!i||y.current||!i.paused||t||(t=!0,e+=1,i.play().then(()=>{r()},()=>{e>=f&&r()}).finally(()=>{t=!1}))}for(let e of d)document.addEventListener(e,i);return r},[]),(0,l.useEffect)(()=>{let e=g.current;e&&(w(),e.volume=x)},[w,x]),(0,l.useEffect)(()=>{let e=g.current;if(e)return w(),y.current||(b?(e.volume=0,e.play().catch(()=>void 0),T(S.current,900)):e.play().catch(()=>void 0)),()=>{e.pause(),w(),_.current!==null&&(clearTimeout(_.current),_.current=null)}},[C?.src,b,T,w]),(0,l.useEffect)(()=>{let e=g.current;e&&(m?(w(),e.pause()):(b&&v.current===null&&(e.volume=S.current),e.play().catch(()=>void 0)))},[m,b,w]),C&&x>0?(0,u.jsx)(`audio`,{ref:g,src:C.src,preload:s(),onEnded:()=>{if(b){p();return}_.current!==null&&clearTimeout(_.current),_.current=setTimeout(()=>{_.current=null,p()},c)},onTimeUpdate:()=>{if(!b||y.current||v.current!==null)return;let e=g.current;if(!e||!e.duration||Number.isNaN(e.duration))return;let t=e.duration-e.currentTime;t<=900/1e3&&e.volume>.01&&T(0,Math.max(50,t*1e3))},"aria-label":h.puzzleAmbience}):null}export{p as AmbientLoop};