itube-modern-player 0.4.2 → 0.4.4

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.
@@ -1,5 +1,5 @@
1
- var ITubePlayer=(function(){"use strict";function o(l,e,t){const i=document.createElement(l);if(e&&(i.className=e),t)for(const[s,n]of Object.entries(t))i.setAttribute(s,n);return i}function y(l,e,t){const i=o("button",`imp-btn ${l}`,{type:"button","aria-label":e,title:e});return i.innerHTML=t,i}function A(l,e,t){l.innerHTML=e,t!==void 0&&(l.setAttribute("aria-label",t),l.setAttribute("title",t))}function w(l,e,t){return Math.min(t,Math.max(e,l))}function x(l){if(!Number.isFinite(l)||l<0)return"0:00";const e=Math.floor(l%60),t=Math.floor(l/60%60),i=Math.floor(l/3600),s=i>0?String(t).padStart(2,"0"):String(t),n=String(e).padStart(2,"0");return i>0?`${i}:${s}:${n}`:`${s}:${n}`}function P(l){const e=l.trim().match(/^(?:(\d+):)?(\d{1,2}):(\d{2})(?:[.,](\d{1,3}))?$/);if(!e)return null;const t=e[1]?Number(e[1]):0,i=Number(e[2]),s=Number(e[3]),n=e[4]?Number(e[4].padEnd(3,"0")):0;return t*3600+i*60+s+n/1e3}function F(l){const e=[],t=l.replace(/\r\n?/g,`
1
+ var ITubePlayer=(function(){"use strict";function o(l,e,t){const i=document.createElement(l);if(e&&(i.className=e),t)for(const[s,n]of Object.entries(t))i.setAttribute(s,n);return i}function y(l,e,t){const i=o("button",`imp-btn ${l}`,{type:"button","aria-label":e,title:e});return i.innerHTML=t,i}function F(l,e){const t=o("div",`${e}__meta`);return l.forEach((i,s)=>{s>0&&t.append(document.createTextNode(" "));const n=typeof i=="string"?i:i.text,r=typeof i=="string"?void 0:i.icon,a=o("span",`${e}__meta-chunk`);if(r){const h=o("span",`${e}__meta-icon`);h.innerHTML=r,a.append(h)}a.append(document.createTextNode(n)),t.append(a)}),t}function A(l,e,t){l.innerHTML=e,t!==void 0&&(l.setAttribute("aria-label",t),l.setAttribute("title",t))}function w(l,e,t){return Math.min(t,Math.max(e,l))}function x(l){if(!Number.isFinite(l)||l<0)return"0:00";const e=Math.floor(l%60),t=Math.floor(l/60%60),i=Math.floor(l/3600),s=i>0?String(t).padStart(2,"0"):String(t),n=String(e).padStart(2,"0");return i>0?`${i}:${s}:${n}`:`${s}:${n}`}function P(l){const e=l.trim().match(/^(?:(\d+):)?(\d{1,2}):(\d{2})(?:[.,](\d{1,3}))?$/);if(!e)return null;const t=e[1]?Number(e[1]):0,i=Number(e[2]),s=Number(e[3]),n=e[4]?Number(e[4].padEnd(3,"0")):0;return t*3600+i*60+s+n/1e3}function $(l){const e=[],t=l.replace(/\r\n?/g,`
2
2
  `).split(/\n\n+/);for(const i of t){const s=i.split(`
3
- `).filter(v=>v.trim()!=="");if(s.length===0)continue;let n=s.findIndex(v=>v.includes("-->"));if(n===-1)continue;const[r,a]=s[n].split("-->"),h=P(r),c=P((a??"").split(" ")[1]??a??"")??P(a??"");if(h===null||c===null)continue;const u=s.slice(n+1).join(`
4
- `).trim();u&&e.push({start:h,end:c,text:u})}return e}function j(l,e){try{return new URL(l,new URL(e,window.location.href)).toString()}catch{return l}}class K{constructor(){this.listeners=new Map}on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>this.off(e,t)}once(e,t){const i=this.on(e,s=>{i(),t(s)});return i}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){const i=this.listeners.get(e);if(i)for(const s of[...i])try{s(t)}catch(n){console.error("[itube-player] listener error",n)}}removeAll(){this.listeners.clear()}}const m=(l,e="0 0 24 24")=>`<svg viewBox="${e}" fill="currentColor" aria-hidden="true" focusable="false">${l}</svg>`,X={play:m('<path d="M8 5.14v13.72c0 .8.87 1.3 1.56.88l10.54-6.86a1.05 1.05 0 0 0 0-1.76L9.56 4.26C8.87 3.84 8 4.34 8 5.14Z"/>'),pause:m('<rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/>'),replay:m('<path d="M12 5V2.5L7.5 6 12 9.5V7a5 5 0 1 1-5 5H5a7 7 0 1 0 7-7Z"/>'),bigPlay:m('<path d="M8 5.14v13.72c0 .8.87 1.3 1.56.88l10.54-6.86a1.05 1.05 0 0 0 0-1.76L9.56 4.26C8.87 3.84 8 4.34 8 5.14Z"/>'),volumeHigh:m('<path d="M4 9v6h3.5L12 19.5v-15L7.5 9H4Z"/><path d="M14.5 8.6a4.5 4.5 0 0 1 0 6.8v-1.9a2.5 2.5 0 0 0 0-3v-1.9Z"/><path d="M14.5 5.2a8 8 0 0 1 0 13.6v-2a6 6 0 0 0 0-9.6v-2Z"/>'),volumeLow:m('<path d="M4 9v6h3.5L12 19.5v-15L7.5 9H4Z"/><path d="M14.5 8.6a4.5 4.5 0 0 1 0 6.8v-1.9a2.5 2.5 0 0 0 0-3v-1.9Z"/>'),volumeMute:m('<path d="M4 9v6h3.5L12 19.5v-15L7.5 9H4Z"/><path d="m15.3 9.3 1.4 1.4 1.4-1.4 1.4 1.4-1.4 1.4 1.4 1.4-1.4 1.4-1.4-1.4-1.4 1.4-1.4-1.4 1.4-1.4-1.4-1.4 1.4-1.4Z"/>'),fullscreen:m('<path d="M5 5h5v2H7v3H5V5Zm9 0h5v5h-2V7h-3V5ZM5 14h2v3h3v2H5v-5Zm12 0h2v5h-5v-2h3v-3Z"/>'),fullscreenExit:m('<path d="M10 10H5V8h3V5h2v5Zm4 0V5h2v3h3v2h-5Zm-4 4v5H8v-3H5v-2h5Zm4 0h5v2h-3v3h-2v-5Z"/>'),pip:m('<path d="M3 5h18v14H3V5Zm2 2v10h14V7H5Z"/><rect x="12" y="11" width="6" height="4"/>'),settings:m('<path d="M12 8.5A3.5 3.5 0 1 0 12 15.5 3.5 3.5 0 0 0 12 8.5Zm0 2a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3Z"/><path d="M10.3 2.8 9.9 5.1a7 7 0 0 0-1.5.86l-2.2-.8-1.7 3 1.8 1.5a7 7 0 0 0 0 1.7l-1.8 1.5 1.7 3 2.2-.8c.46.36.97.65 1.5.86l.4 2.3h3.4l.4-2.3a7 7 0 0 0 1.5-.86l2.2.8 1.7-3-1.8-1.5a7 7 0 0 0 0-1.7l1.8-1.5-1.7-3-2.2.8a7 7 0 0 0-1.5-.86l-.4-2.3h-3.4Zm1.7 5.7a3.5 3.5 0 1 1 0 7 3.5 3.5 0 0 1 0-7Z"/>'),speed:m('<path d="M12 4a9 9 0 0 0-9 9 8.96 8.96 0 0 0 1.62 5.16l1.64-1.15A7 7 0 0 1 5 13a7 7 0 1 1 12.74 4.01l1.64 1.15A8.96 8.96 0 0 0 21 13a9 9 0 0 0-9-9Z"/><path d="m15.6 8.3-3.95 3.13a1.5 1.5 0 1 0 1.92 1.92L16.7 9.4a.78.78 0 0 0-1.1-1.1Z"/>'),scenes:m('<path d="M3 5h18v14H3V5Zm2 2v10h3V7H5Zm5 0v10h9V7h-9Zm-5 3h3v1H5v-1Zm0 3h3v1H5v-1Z"/>'),shuffle:m('<path d="M4 6h2.6c1.5 0 2.9.7 3.8 1.9l4.1 5.4a2.75 2.75 0 0 0 2.2 1.1H19l-1.8-1.8 1.4-1.4 4.2 4.2-4.2 4.2-1.4-1.4L19 16.4h-2.3a4.75 4.75 0 0 1-3.8-1.9L8.8 9.1A2.75 2.75 0 0 0 6.6 8H4V6Z"/><path d="M19 7.6h-2.3c-.86 0-1.67.41-2.18 1.1l-.93 1.23-1.25-1.65.58-.77A4.75 4.75 0 0 1 16.7 5.6H19L17.2 3.8l1.4-1.4 4.2 4.2-4.2 4.2-1.4-1.4L19 7.6Z" transform="translate(0 1.2)"/>'),repeat:m('<path d="M7 7h10v2.5L21 6l-4-3.5V5H5v6h2V7Zm10 10H7v-2.5L3 18l4 3.5V19h12v-6h-2v4Z"/>'),subtitles:m('<path d="M3 5h18v14H3V5Zm2 2v10h14V7H5Zm2 3h6v2H7v-2Zm8 0h2v2h-2v-2ZM7 14h2v2H7v-2Zm4 0h6v2h-6v-2Z"/>'),list:m('<path d="M4 6h2v2H4V6Zm4 0h12v2H8V6ZM4 11h2v2H4v-2Zm4 0h12v2H8v-2ZM4 16h2v2H4v-2Zm4 0h12v2H8v-2Z"/>'),next:m('<path d="M6 5.5v13c0 .77.84 1.25 1.5.85l9-6.5a1 1 0 0 0 0-1.7l-9-6.5c-.66-.4-1.5.08-1.5.85Z"/><rect x="17" y="5" width="2.5" height="14" rx="1"/>'),previous:m('<path d="M18 5.5v13c0 .77-.84 1.25-1.5.85l-9-6.5a1 1 0 0 1 0-1.7l9-6.5c.66-.4 1.5.08 1.5.85Z"/><rect x="4.5" y="5" width="2.5" height="14" rx="1"/>'),seekForward:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>',seekBack:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg>',like:m('<path d="M9 21H5a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h4v11Zm2 0h7.1a2 2 0 0 0 2-1.6l1.3-7a2 2 0 0 0-2-2.4H14V5.5A2.5 2.5 0 0 0 11.5 3l-.5.1V10h-.9L11 21Z"/>'),dislike:m('<path d="M15 3h4a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2h-4V3Zm-2 0H5.9a2 2 0 0 0-2 1.6l-1.3 7a2 2 0 0 0 2 2.4H10v4.5A2.5 2.5 0 0 0 12.5 21l.5-.1V14h.9L13 3Z"/>'),addTo:m('<path d="M4 6h12v2H4V6Zm0 4h12v2H4v-2Zm0 4h8v2H4v-2Zm14 0v-4h2v4h4v2h-4v4h-2v-4h-4v-2h4Z"/>'),share:m('<path d="M18 8a3 3 0 1 0-2.83-4H15a3 3 0 0 0 .14 1.06L8.4 8.94a3 3 0 1 0 0 6.12l6.74 3.88A3 3 0 1 0 16 16.6l-6.74-3.88a3.03 3.03 0 0 0 0-1.44L16 7.4c.55.38 1.24.6 2 .6Z"/>'),report:m('<path d="M5 3h2v18H5V3Zm4 1h10l-2.5 4L19 12H9V4Z"/>'),more:m('<circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/>'),close:m('<path d="m6.4 5 5.6 5.6L17.6 5 19 6.4 13.4 12l5.6 5.6-1.4 1.4-5.6-5.6L6.4 19 5 17.6 10.6 12 5 6.4 6.4 5Z"/>'),user:m('<path d="M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm0 2c-3.6 0-8 1.8-8 4.4V21h16v-2.6c0-2.6-4.4-4.4-8-4.4Z"/>'),channel:m('<path d="M3 5h18a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm7 3.5v7l6-3.5-6-3.5Z"/>')},C={play:"Play",pause:"Pause",replay:"Replay",mute:"Mute",unmute:"Unmute",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",pip:"Picture-in-picture",settings:"Playback speed",scenes:"Scenes",sceneTypes:"Scene type",autoplay:"Autoplay",playNext:"Play next",shuffle:"Shuffle",repeat:"Repeat",subtitles:"Subtitles",subtitlesOff:"Off",speed:"Speed",quality:"Quality",qualityAuto:"Auto",next:"Next",nextVideo:"Next video",previous:"Previous",playlist:"Playlist",like:"Like",dislike:"Dislike",addTo:"Save to…",share:"Share",report:"Report",more:"More actions",seekForward:"Seek forward",seekBack:"Seek back",secondsShort:"s",live:"LIVE",related:"More videos",adLabel:"Ad",skipAd:"Skip ad",skipAdIn:"Skip in",visitAdvertiser:"Visit advertiser",sponsored:"Sponsored"},$={en:C};function J(l){for(const[e,t]of Object.entries(l))t&&($[e]=t)}function Y(l){return l&&$[l]||C}function ee(l,e,t=100){if(l.length===0||!Number.isFinite(e)||e<=0)return[];const i=new Array(t).fill(0);let s=!1;for(const c of l){if(!Number.isFinite(c.time)||c.time<0||c.time>e)continue;const u=Math.max(0,c.value);if(u===0)continue;const v=Math.min(t-1,Math.floor(c.time/e*t));i[v]+=u,s=!0}if(!s)return[];const n=[.06,.24,.4,.24,.06],r=i.map((c,u)=>n.reduce((v,p,f)=>v+p*(i[u+f-2]??0),0)),a=Math.max(...r);if(a<=0)return[];const h=.08;return r.map(c=>h+(1-h)*(c/a))}function te(l,e=1e3,t=100){if(l.length===0)return"";const i=e/(l.length-1||1);let s=`M 0 ${t}`;return l.forEach((n,r)=>{s+=` L ${(r*i).toFixed(1)} ${(t-n*t).toFixed(1)}`}),s+=` L ${e} ${t} Z`,s}async function ie(l,e){if(l.src)return{roll:l.roll,mediaUrl:l.src,clickThrough:l.clickUrl,impressions:[],tracking:{}};if(!l.vastTag)throw new Error('Ad roll has neither "vastTag" nor "src"');return O(l,l.vastTag,e,0,{impressions:[],tracking:{}})}async function O(l,e,t,i,s){if(i>t.maxWrapperDepth)throw new Error("VAST wrapper depth limit exceeded");const n=new AbortController,r=setTimeout(()=>n.abort(),t.requestTimeout);let a;try{const g=await fetch(e,{signal:n.signal,credentials:"omit"});if(!g.ok)throw new Error(`VAST request failed (${g.status})`);a=await g.text()}finally{clearTimeout(r)}const h=new DOMParser().parseFromString(a,"text/xml");if(h.querySelector("parsererror"))throw new Error("VAST response is not valid XML");const c=h.querySelector("VAST > Ad");if(!c)throw new Error("VAST response contains no ads");se(c,s);const u=c.querySelector(":scope > Wrapper");if(u){const g=S(u.querySelector("VASTAdTagURI"));if(!g)throw new Error("VAST wrapper without VASTAdTagURI");return O(l,g,t,i+1,s)}const v=c.querySelector(":scope > InLine");if(!v)throw new Error("VAST ad has neither InLine nor Wrapper");const p=v.querySelector("Creatives > Creative > Linear");if(!p)throw new Error("VAST ad has no Linear creative");const f=ne(p);if(!f)throw new Error("VAST ad has no playable MediaFile");return{roll:l.roll,mediaUrl:f.url,mediaType:f.type,clickThrough:S(p.querySelector("VideoClicks > ClickThrough"))??l.clickUrl,duration:I(S(p.querySelector(":scope > Duration"))),skipOffset:re(p.getAttribute("skipoffset"),I(S(p.querySelector(":scope > Duration")))),impressions:s.impressions,tracking:s.tracking,adTitle:S(v.querySelector(":scope > AdTitle"))??void 0}}function se(l,e){var t,i;for(const s of l.querySelectorAll("Impression")){const n=S(s);n&&e.impressions.push(n)}for(const s of l.querySelectorAll("Linear > TrackingEvents > Tracking")){const n=s.getAttribute("event"),r=S(s);!n||!r||["start","firstQuartile","midpoint","thirdQuartile","complete","skip","pause","resume"].includes(n)&&((t=e.tracking)[n]??(t[n]=[])).push(r)}for(const s of l.querySelectorAll("Linear > VideoClicks > ClickTracking")){const n=S(s);n&&((i=e.tracking).click??(i.click=[])).push(n)}}function ne(l){const t=[...l.querySelectorAll("MediaFiles > MediaFile")].map(r=>({url:S(r)??"",type:r.getAttribute("type")??void 0,delivery:r.getAttribute("delivery")??"",bitrate:Number(r.getAttribute("bitrate")??0),apiFramework:r.getAttribute("apiFramework")??""})).filter(r=>r.url&&r.apiFramework.toUpperCase()!=="VPAID").filter(r=>!r.type||/(video\/(mp4|webm|ogg)|application\/(x-mpegurl|vnd\.apple\.mpegurl))/i.test(r.type));if(t.length===0)return null;t.sort((r,a)=>r.bitrate-a.bitrate);const i=t.filter(r=>r.delivery!=="streaming"),s=i.length>0?i:t,n=s[Math.floor(s.length/2)];return{url:n.url,type:n.type}}function I(l){if(!l)return;const e=l.trim().match(/^(?:(\d+):)?(\d{1,2}):(\d{2})(?:\.(\d{1,3}))?$/);if(e)return(e[1]?Number(e[1])*3600:0)+Number(e[2])*60+Number(e[3])+(e[4]?Number(e[4].padEnd(3,"0"))/1e3:0)}function re(l,e){if(!l)return;const t=l.trim().match(/^(\d+(?:\.\d+)?)%$/);return t?e!==void 0?Number(t[1])/100*e:void 0:I(l)}function E(l){if(l)for(const e of l)try{new Image().src=e}catch{}}function S(l){return l?.textContent?.trim().replace(/^<!\[CDATA\[|\]\]>$/g,"").trim()||null}class oe{constructor(e,t){this.host=e,this.playedRolls=new Set,this.sourcesSeen=0,this.activeBreak=null,this.layer=null,this.adVideo=null,this.destroyed=!1,this.opts={skipDelay:5,maxWrapperDepth:3,requestTimeout:8e3,mediaTimeout:1e4,playOn:"every",...t}}ensureAdVideo(){if(!this.adVideo){this.adVideo=o("video","imp-ad__video",{playsinline:""});try{this.adVideo.load()}catch{}}return this.adVideo}get adPlaying(){return this.activeBreak!==null}get hasPendingPreRoll(){return this.pending("preRoll").length>0}resetForNewSource(){if(this.sourcesSeen++,this.opts.playOn==="first"&&this.sourcesSeen>1){for(const e of this.opts.adList)this.playedRolls.add(e);return}this.playedRolls.clear()}async playPreRoll(){await this.playRolls(this.pending("preRoll"))}async playPostRoll(){await this.playRolls(this.pending("postRoll"))}checkMidRolls(e){if(this.adPlaying)return;const t=this.pending("midRoll").filter(i=>i.timer!==void 0&&e>=i.timer);t.length>0&&this.playRolls(t)}pending(e){return this.opts.adList.filter(t=>t.roll===e&&!this.playedRolls.has(t))}async playRolls(e){if(e.length===0||this.destroyed)return;if(this.activeBreak)return this.activeBreak;this.ensureAdVideo();const t=(async()=>{const i=this.host.contentVideo,s=!i.paused&&!i.ended;i.pause();for(const n of e){this.playedRolls.add(n);try{const r=await ie(n,this.opts);await this.playAd(r)}catch(r){const a=r instanceof Error?r:new Error(String(r));this.host.emitter.emit("aderror",{roll:n,error:a})}if(this.destroyed)return}(s||e[0].roll==="preRoll")&&i.play().catch(()=>{})})();return this.activeBreak=t.finally(()=>{this.activeBreak=null}),this.activeBreak}playAd(e){return new Promise(t=>{const{labels:i}=this.host,s=o("div","imp-ad"),n=this.ensureAdVideo(),r=new AbortController,a=r.signal;n.src=e.mediaUrl,n.muted=this.host.contentVideo.muted,n.volume=this.host.contentVideo.volume;const h=o("div","imp-spinner imp-ad__spinner"),c=o("div","imp-ad__hud"),u=o("span","imp-ad__badge");u.textContent=e.adTitle?`${i.adLabel} · ${e.adTitle}`:i.adLabel;const v=o("span","imp-ad__countdown");c.append(u,v);const p=o("div","imp-ad__actions");let f=null;e.clickThrough&&(f=o("button","imp-ad__visit",{type:"button"}),f.textContent=i.visitAdvertiser,p.append(f));const g=o("button","imp-ad__skip",{type:"button"});g.hidden=!0,p.append(g),s.append(n,h,c,p),this.host.container.append(s),this.layer=s;const B=e.skipOffset??this.opts.skipDelay,d=new Set,b=k=>{d.has(k)||(d.add(k),E(e.tracking[k]))};let N=Date.now(),W=-1;const Le=setInterval(()=>{if(n.paused){N=Date.now();return}if(n.currentTime!==W){W=n.currentTime,N=Date.now();return}Date.now()-N>=this.opts.mediaTimeout&&(this.host.emitter.emit("aderror",{roll:{roll:e.roll},error:new Error(`Ad media stalled for ${this.opts.mediaTimeout} ms — skipping`)}),q())},500),q=()=>{clearInterval(Le),r.abort(),n.pause(),n.removeAttribute("src"),n.load(),s.remove(),this.layer=null,t()},z=k=>{k?(b("skip"),this.host.emitter.emit("adskip",{ad:e})):b("complete"),this.host.emitter.emit("adend",{ad:e}),q()};n.addEventListener("playing",()=>{E(e.impressions),b("start"),this.host.emitter.emit("adstart",{ad:e})},{once:!0,signal:a}),n.addEventListener("playing",()=>{h.hidden=!0},{signal:a}),n.addEventListener("waiting",()=>{h.hidden=!1},{signal:a}),n.addEventListener("timeupdate",()=>{const k=n.currentTime,T=n.duration;if(Number.isFinite(T)&&T>0&&(v.textContent=x(Math.max(0,T-k)),k/T>=.25&&b("firstQuartile"),k/T>=.5&&b("midpoint"),k/T>=.75&&b("thirdQuartile")),B>=0){const U=Math.ceil(B-k);U>0?(g.hidden=!1,g.disabled=!0,g.textContent=`${i.skipAdIn} ${U}`):(g.hidden=!1,g.disabled=!1,g.textContent=i.skipAd)}},{signal:a}),n.addEventListener("ended",()=>z(!1),{signal:a}),n.addEventListener("error",()=>{this.host.emitter.emit("aderror",{roll:{roll:e.roll},error:new Error("Ad media failed to play")}),q()},{signal:a}),g.addEventListener("click",()=>z(!0));const G=()=>{e.clickThrough&&(b("click"),this.host.emitter.emit("adclick",{ad:e}),window.open(e.clickThrough,"_blank","noopener"),n.pause())};n.addEventListener("click",G,{signal:a}),f?.addEventListener("click",G);let Q=!1,M=!1;n.addEventListener("playing",()=>{Q=!0},{once:!0,signal:a}),n.addEventListener("pause",()=>{n.ended||!s.isConnected||(s.classList.add("imp-ad--paused"),Q&&!M&&(M=!0,E(e.tracking.pause),this.host.emitter.emit("adpause",{ad:e})))},{signal:a}),n.addEventListener("play",()=>{s.classList.remove("imp-ad--paused"),M&&(M=!1,E(e.tracking.resume),this.host.emitter.emit("adresume",{ad:e}))},{signal:a}),s.addEventListener("click",k=>{(k.target===s||s.classList.contains("imp-ad--paused"))&&n.paused&&n.play().catch(()=>{})}),n.play().catch(()=>{s.classList.add("imp-ad--paused")})})}get closeIcon(){return this.host.closeIcon}destroy(){this.destroyed=!0,this.adVideo?.pause(),this.layer?.remove(),this.layer=null,this.adVideo=null}}function H(l,e){const t=[...l].sort((s,n)=>s.start-n.start),i=[];for(let s=0;s<t.length;s++){const n=Math.max(0,t[s].start);if(Number.isFinite(e)&&n>=e)continue;let r=t[s].end??t[s+1]?.start??e;Number.isFinite(e)&&(r=Math.min(r,e)),!(r<=n)&&i.push({start:n,end:r,title:t[s].title})}return i}async function ae(l){const e=await fetch(l);if(!e.ok)throw new Error(`Failed to load chapters VTT (${e.status})`);const t=await e.text();return F(t).map(i=>({start:i.start,end:i.end,title:i.text}))}function Z(l,e){for(const t of l)if(e>=t.start&&e<t.end)return t;return null}function le(l,e){return e?/application\/(x-mpegurl|vnd\.apple\.mpegurl)/i.test(e):/\.m3u8(\?|#|$)/i.test(l)}let L;async function he(){if(L!==void 0)return L;const l=globalThis.Hls;if(l)return L=l,L;try{L=(await import("hls.js/light")).default}catch{L=null}return L}async function ce(l,e,t,i){if(le(e,t)){const s=l.canPlayType("application/vnd.apple.mpegurl"),n=s?null:await he();return n&&n.isSupported()?de(n,l,e,i):s?(l.src=e,V(l)):(i.onError("HLS is not supported in this browser and hls.js could not be loaded."),V(l))}return l.src=e,V(l)}function V(l){return{kind:"native",levels:[],selected:-1,setLevel(){},destroy(){l.removeAttribute("src"),l.load()}}}function de(l,e,t,i){const s=new l({enableWorker:!0}),n={kind:"hls",levels:[],selected:-1,setLevel(h){n.selected=h,s.currentLevel=h},destroy(){s.destroy(),e.removeAttribute("src"),e.load()}};s.on(l.Events.MANIFEST_PARSED,()=>{n.levels=s.levels.map((h,c)=>({index:c,label:h.height?`${h.height}p`:`${Math.round(h.bitrate/1e3)} kbps`})).reverse(),i.onLevels(n.levels)}),s.on(l.Events.LEVEL_SWITCHED,(h,c)=>{const u=s.levels[c.level];u&&i.onLevelSwitch(u.height?`${u.height}p`:`${Math.round(u.bitrate/1e3)} kbps`)});let r=0,a=!1;return s.on(l.Events.ERROR,(h,c)=>{if(c.fatal)switch(c.type){case l.ErrorTypes.NETWORK_ERROR:s.startLoad();break;case l.ErrorTypes.MEDIA_ERROR:r<3?(r++,s.recoverMediaError()):(i.onError(`HLS media error: ${c.details}`,c),s.destroy());break;default:if(a)i.onError(`HLS fatal error: ${c.details}`,c),s.destroy();else{a=!0;try{s.loadSource(t),s.startLoad()}catch{i.onError(`HLS fatal error: ${c.details}`,c),s.destroy()}}}}),s.loadSource(t),s.attachMedia(e),n}class R{constructor(e){this.cues=e}static async load(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to load thumbnails VTT (${t.status})`);const i=await t.text(),s=[];for(const n of F(i)){const[r,a]=n.text.trim().split("#");if(!r)continue;const h={start:n.start,end:n.end,src:j(r,e)},c=a?.match(/xywh=(\d+),(\d+),(\d+),(\d+)/);c&&(h.xywh={x:Number(c[1]),y:Number(c[2]),w:Number(c[3]),h:Number(c[4])}),s.push(h)}return s.sort((n,r)=>n.start-r.start),new R(s)}cueAt(e){let t=0,i=this.cues.length-1;for(;t<=i;){const s=t+i>>1,n=this.cues[s];if(e<n.start)i=s-1;else if(e>=n.end)t=s+1;else return n}return null}}const ue='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 6 6 6-6 6"/></svg>',pe='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 6-6 6 6 6"/></svg>';class _{constructor(e){this.anchor=e,this.outsideListener=null,this.root=o("div","imp-menu"),this.root.hidden=!0,this.backdrop=o("div","imp-menu__backdrop"),this.backdrop.hidden=!0,this.backdrop.addEventListener("pointerdown",t=>{t.preventDefault(),this.close()}),e.append(this.backdrop)}get open(){return!this.root.hidden}toggle(e){this.open?this.close():this.show(e)}show(e){this.root.textContent="";for(const t of e)t.items.length!==0&&this.root.append(this.renderSection(t));this.reveal()}toggleSettings(e,t){this.open?this.close():this.showSettings(e,t)}showSettings(e,t){this.root.classList.add("imp-menu--wide"),this.renderSettingsRoot(t),this.reveal()}renderSettingsRoot(e){this.root.textContent="";const t=o("div","imp-menu__section");for(const i of e){if(i.toggle){t.append(this.buildToggleRow(i,i.toggle));continue}const s=o("button","imp-menu__item imp-menu__row",{type:"button"}),n=o("span","imp-menu__label");n.textContent=i.label;const r=o("span","imp-menu__value");r.textContent=i.value??"";const a=o("span","imp-menu__chevron");a.innerHTML=ue,s.append(n,r,a),s.addEventListener("click",()=>this.renderSettingsDetail(e,i)),t.append(s)}this.root.append(t)}buildToggleRow(e,t){const i=o("button","imp-menu__item imp-menu__row imp-menu__toggle",{type:"button",role:"switch","aria-checked":String(t.value)}),s=o("span","imp-menu__label");s.textContent=e.label;const n=o("span","imp-switch");return n.append(o("span","imp-switch__knob")),i.classList.toggle("imp-menu__toggle--on",t.value),i.append(s,n),i.addEventListener("click",()=>{const r=i.getAttribute("aria-checked")!=="true";i.setAttribute("aria-checked",String(r)),i.classList.toggle("imp-menu__toggle--on",r),t.onChange(r)}),i}renderSettingsDetail(e,t){if(!t.section)return;this.root.textContent="";const i=o("button","imp-menu__item imp-menu__back",{type:"button"}),s=o("span","imp-menu__chevron");s.innerHTML=pe;const n=o("span","imp-menu__label");n.textContent=t.label,i.append(s,n),i.addEventListener("click",()=>this.renderSettingsRoot(e)),this.root.append(i),this.root.append(this.renderSection(t.section())),this.root.scrollTop=0}renderSection(e){const t=o("div","imp-menu__section");if(e.title){const i=o("div","imp-menu__title");i.textContent=e.title,t.append(i)}for(const i of e.items){const s=o("button","imp-menu__item",{type:"button",role:"menuitemradio"});if(s.setAttribute("aria-checked",String(i.active)),i.active&&s.classList.add("imp-menu__item--active"),i.icon){const r=o("span","imp-menu__icon");i.icon.trimStart().startsWith("<svg")?r.innerHTML=i.icon:r.append(o("img","",{src:i.icon,alt:""})),s.append(r)}const n=o("span","imp-menu__label");n.textContent=i.label,s.append(n),s.addEventListener("click",()=>{e.onSelect(i.value),this.close()}),t.append(s)}return t}reveal(){this.root.hidden=!1,this.backdrop.hidden=!1,this.outsideListener=e=>{const t=e.target;!this.root.contains(t)&&!this.anchor.contains(t)&&this.close()},setTimeout(()=>{this.outsideListener&&document.addEventListener("pointerdown",this.outsideListener)},0)}close(){this.root.hidden=!0,this.root.classList.remove("imp-menu--wide"),this.backdrop.hidden=!0,this.outsideListener&&(document.removeEventListener("pointerdown",this.outsideListener),this.outsideListener=null)}destroy(){this.close(),this.root.remove()}}class me{constructor(e){this.cb=e,this.segments=[],this.duration=0,this.chapters=[],this.thumbnails=null,this.scrubbing=!1,this.root=o("div","imp-progress",{role:"slider","aria-label":"Seek",tabindex:"-1"}),this.buffered=o("div","imp-progress__buffered"),this.track=o("div","imp-progress__track"),this.handle=o("div","imp-progress__handle"),this.tooltipThumb=o("div","imp-progress__thumb"),this.tooltipChapter=o("div","imp-progress__tooltip-chapter"),this.tooltipTime=o("div","imp-progress__tooltip-time"),this.tooltip=o("div","imp-progress__tooltip"),this.tooltip.append(this.tooltipThumb,this.tooltipChapter,this.tooltipTime),this.heatmap=o("div","imp-progress__heatmap"),this.heatmap.hidden=!0,this.root.append(this.heatmap,this.buffered,this.track,this.handle,this.tooltip),this.setChapters([]),this.bindPointer()}setHeatmap(e){if(e.length===0){this.heatmap.hidden=!0,this.heatmap.textContent="";return}this.heatmap.innerHTML=`<svg viewBox="0 0 1000 100" preserveAspectRatio="none" aria-hidden="true"><path d="${te(e)}"/></svg>`,this.heatmap.hidden=!1}setDuration(e){this.duration=Number.isFinite(e)?e:0,this.root.classList.toggle("imp-progress--live",!Number.isFinite(e)),this.chapters.length===0&&this.setChapters([])}setChapters(e){this.chapters=e,this.track.textContent="",this.segments=[];const t=e.length>0?e:[{start:0,end:this.duration||1,title:""}],i=[];let s=0;for(const n of t)n.start>s&&i.push({start:s,end:n.start,title:""}),i.push(n),s=n.end;this.duration>0&&s<this.duration&&i.push({start:s,end:this.duration,title:""});for(const n of i){const r=o("div","imp-progress__segment");r.style.flexGrow=String(Math.max(n.end-n.start,.01));const a=o("div","imp-progress__fill");r.append(a),this.track.append(r),this.segments.push({chapter:n,root:r,fill:a})}}setThumbnails(e){this.thumbnails=e}update(e,t,i){if(t!==this.duration&&Number.isFinite(t)&&this.setDuration(t),this.scrubbing)return;this.render(e);const s=this.duration>0?w(i/this.duration,0,1):0;this.buffered.style.width=`${s*100}%`,this.root.setAttribute("aria-valuemin","0"),this.root.setAttribute("aria-valuemax",String(Math.round(this.duration))),this.root.setAttribute("aria-valuenow",String(Math.round(e))),this.root.setAttribute("aria-valuetext",`${x(e)} / ${x(this.duration)}`)}render(e){for(const{chapter:i,fill:s}of this.segments){const n=i.end-i.start,r=n>0?w((e-i.start)/n,0,1):0;s.style.transform=`scaleX(${r})`}const t=this.duration>0?w(e/this.duration,0,1):0;this.handle.style.left=`${t*100}%`}timeFromEvent(e){const t=this.root.getBoundingClientRect();return(t.width>0?w((e.clientX-t.left)/t.width,0,1):0)*this.duration}bindPointer(){this.root.addEventListener("pointerdown",e=>{this.duration<=0||(e.preventDefault(),this.scrubbing=!0,this.root.classList.add("imp-progress--scrubbing"),this.root.setPointerCapture(e.pointerId),this.cb.onScrubStart(),this.render(this.timeFromEvent(e)),this.showTooltip(e))}),this.root.addEventListener("pointermove",e=>{this.duration<=0||(this.showTooltip(e),this.scrubbing&&this.render(this.timeFromEvent(e)))}),this.root.addEventListener("pointerup",e=>{this.scrubbing&&(this.scrubbing=!1,this.root.classList.remove("imp-progress--scrubbing"),this.cb.onSeek(this.timeFromEvent(e)),this.cb.onScrubEnd())}),this.root.addEventListener("pointercancel",()=>{this.scrubbing=!1,this.root.classList.remove("imp-progress--scrubbing"),this.cb.onScrubEnd()}),this.root.addEventListener("pointerleave",()=>this.hideTooltip())}showTooltip(e){const t=this.timeFromEvent(e);this.tooltipTime.textContent=x(t);const i=Z(this.chapters,t);this.tooltipChapter.textContent=i?.title??"",this.tooltipChapter.hidden=!i?.title;const s=this.thumbnails?.cueAt(t)??null;s?(this.tooltipThumb.hidden=!1,this.tooltipThumb.style.backgroundImage=`url("${s.src}")`,s.xywh?(this.tooltipThumb.style.width=`${s.xywh.w}px`,this.tooltipThumb.style.height=`${s.xywh.h}px`,this.tooltipThumb.style.backgroundPosition=`-${s.xywh.x}px -${s.xywh.y}px`,this.tooltipThumb.style.backgroundSize="auto"):(this.tooltipThumb.style.width="160px",this.tooltipThumb.style.height="90px",this.tooltipThumb.style.backgroundPosition="center",this.tooltipThumb.style.backgroundSize="cover")):this.tooltipThumb.hidden=!0,this.tooltip.classList.add("imp-progress__tooltip--visible");const n=this.root.getBoundingClientRect(),r=w(e.clientX-n.left,0,n.width),a=this.tooltip.offsetWidth/2;this.tooltip.style.left=`${w(r,a,Math.max(a,n.width-a))}px`}hideTooltip(){this.tooltip.classList.remove("imp-progress__tooltip--visible")}}class ve{constructor(e){this.player=e,this.rightItems=new Map,this.subtitlesBtn=null,this.settingsBtn=null,this.settingsMenu=null,this.subtitlesMenu=null,this.moreMenu=null,this.moreWrap=null,this.qualityBtn=null,this.qualityMenu=null,this.gearBtn=null,this.gearMenu=null,this.gear={speed:!1,quality:!1,subtitles:!1},this.nextPreviewEl=null,this.nextPreviewOpts=null,this.scenesBtn=null,this.sceneTypeBtn=null,this.sceneTypeMenu=null,this.likeBtn=null,this.dislikeBtn=null,this.likeCountEl=null,this.dislikeCountEl=null,this.prevBtn=null,this.nextBtn=null,this.seekBackBtn=null,this.seekFwdBtn=null,this.centerPlayBtn=null,this.centerPrevBtn=null,this.centerNextBtn=null,this.collapsibles=[],this.overflowed=new Set,this.resizeObserver=null,this.reflowScheduled=!1,this.actionItems=[],this.wasPlayingBeforeScrub=!1,this.disposers=[],this.onWindowResize=null;const{labels:t,icons:i}=e,s=e.controlsOptions;this.root=o("div","imp-controls"),this.progress=new me({onSeek:d=>e.seek(d),onScrubStart:()=>{this.wasPlayingBeforeScrub=!e.paused,e.pause()},onScrubEnd:()=>{this.wasPlayingBeforeScrub&&e.play()}}),s.progress&&this.root.append(this.progress.root);const n=o("div","imp-controls__row");this.row=n,this.root.append(n);const r=o("div","imp-controls__group"),a=o("div","imp-controls__group");this.rightGroup=a;const h=o("div","imp-controls__spacer");this.chapterLabel=o("div","imp-controls__chapter"),n.append(r,h,a),h.append(this.chapterLabel);const c=typeof s.seekButtons=="object"?s.seekButtons:{},u=c.back??e.seekStep,v=c.forward??e.seekStep;if(this.seekLabelFn=c.label,s.playlist&&e.hasPlaylist&&!s.hidePrev&&(this.prevBtn=y("imp-btn--prev",t.previous,i.previous),this.prevBtn.addEventListener("click",()=>e.previous()),r.append(this.prevBtn)),s.seekButtons&&(this.seekBackBtn=y("imp-btn--seek-back",`${t.seekBack} ${u}s`,i.seekBack),this.addStepBadge(this.seekBackBtn,u,"back"),this.seekBackBtn.addEventListener("click",()=>e.skip(-u)),r.append(this.seekBackBtn)),s.play&&(this.playBtn=y("imp-btn--play",t.play,i.play),this.playBtn.addEventListener("click",()=>e.togglePlay()),r.append(this.playBtn)),s.seekButtons&&(this.seekFwdBtn=y("imp-btn--seek-forward",`${t.seekForward} ${v}s`,i.seekForward),this.addStepBadge(this.seekFwdBtn,v,"forward"),this.seekFwdBtn.addEventListener("click",()=>e.skip(v)),r.append(this.seekFwdBtn)),s.playlist&&e.hasPlaylist&&(this.nextBtn=y("imp-btn--next",t.next,i.next),this.nextBtn.addEventListener("click",()=>e.next()),r.append(this.nextBtn)),s.volume){const d=o("div","imp-volume");this.muteBtn=y("imp-btn--mute",t.mute,i.volumeHigh),this.muteBtn.addEventListener("click",()=>e.toggleMute()),this.volumeSlider=o("input","imp-volume__slider",{type:"range",min:"0",max:"1",step:"0.05","aria-label":"Volume"}),this.volumeSlider.addEventListener("input",()=>{e.setVolume(Number(this.volumeSlider.value))}),d.append(this.muteBtn,this.volumeSlider),r.append(d)}s.time&&(this.timeLabel=o("div","imp-controls__time"),this.liveBadge=o("span","imp-controls__live"),this.liveBadge.textContent=t.live,this.liveBadge.hidden=!0,r.append(this.timeLabel,this.liveBadge)),this.buildLikeDislike();for(const d of(e.actionsOptions.custom??[]).filter(b=>b.placement==="bar")){const b=y(`imp-btn--custom imp-btn--custom-${d.id}`,d.title,d.icon??i.more);b.addEventListener("click",()=>e.emit("customaction",{id:d.id})),this.rightItems.set(`custom:${d.id}`,b),this.registerCollapsible({key:`custom:${d.id}`,el:b,priority:55,available:()=>!0,section:()=>this.simpleSection(`custom:${d.id}`,d.title,d.icon??i.more,()=>e.emit("customaction",{id:d.id}))})}const p=d=>d===!1?"off":d==="bar"?"bar":"gear",f=p(s.subtitles),g=p(s.quality),B=p(s.speed);if(this.gear={speed:B==="gear",quality:g==="gear",subtitles:f==="gear"},f==="bar"){this.subtitlesBtn=y("imp-btn--subtitles",t.subtitles,i.subtitles),this.subtitlesMenu=new _(this.subtitlesBtn);const d=o("div","imp-controls__menu-anchor");d.append(this.subtitlesBtn,this.subtitlesMenu.root),this.subtitlesBtn.addEventListener("click",()=>this.toggleSubtitlesMenu()),this.rightItems.set("subtitles",d),this.registerCollapsible({key:"subtitles",el:d,priority:30,available:()=>e.subtitleTracks.length>0,section:()=>this.subtitlesSection()})}if(g==="bar"){this.qualityBtn=y("imp-btn--quality",t.quality,i.settings),this.qualityMenu=new _(this.qualityBtn);const d=o("div","imp-controls__menu-anchor");d.append(this.qualityBtn,this.qualityMenu.root),this.qualityBtn.addEventListener("click",()=>this.toggleQualityMenu()),this.rightItems.set("quality",d),this.registerCollapsible({key:"quality",el:d,priority:10,available:()=>e.qualityLevels.length>0,section:()=>this.qualitySection()})}if(B==="bar"){this.settingsBtn=y("imp-btn--speed",t.speed,i.speed),this.settingsMenu=new _(this.settingsBtn);const d=o("div","imp-controls__menu-anchor");d.append(this.settingsBtn,this.settingsMenu.root),this.settingsBtn.addEventListener("click",()=>this.toggleSettingsMenu()),this.rightItems.set("speed",d),this.registerCollapsible({key:"speed",el:d,priority:40,available:()=>!0,section:()=>this.speedSection()})}if(s.scenes&&(this.scenesBtn=y("imp-btn--scenes",t.scenes,i.scenes),this.scenesBtn.addEventListener("click",()=>e.toggleScenesPanel()),this.rightItems.set("scenes",this.scenesBtn),this.registerCollapsible({key:"scenes",el:this.scenesBtn,priority:25,available:()=>e.chapterList.length>0,section:()=>this.simpleSection("scenes",t.scenes,i.scenes,()=>e.toggleScenesPanel())})),s.sceneTypes!==!1){this.sceneTypeBtn=o("button","imp-btn imp-btn--scene-types",{type:"button"}),this.sceneTypeMenu=new _(this.sceneTypeBtn);const d=o("div","imp-controls__menu-anchor");d.append(this.sceneTypeBtn,this.sceneTypeMenu.root),this.sceneTypeBtn.addEventListener("click",()=>this.toggleSceneTypeMenu()),this.rightItems.set("sceneTypes",d),this.refreshSceneTypeButton(),this.registerCollapsible({key:"sceneTypes",el:d,priority:26,available:()=>e.sceneTypes.length>0,section:()=>this.sceneTypeSection()})}if(s.playlist&&e.hasPlaylist){const d=y("imp-btn--list",t.playlist,i.list);d.addEventListener("click",()=>e.togglePlaylistPanel()),this.rightItems.set("playlist",d),this.registerCollapsible({key:"list",el:d,priority:50,available:()=>!0,section:()=>this.simpleSection("list",t.playlist,i.list,()=>e.togglePlaylistPanel())})}if(s.pip&&"requestPictureInPicture"in HTMLVideoElement.prototype){const d=y("imp-btn--pip",t.pip,i.pip);d.addEventListener("click",()=>void e.togglePip()),this.rightItems.set("pip",d),this.registerCollapsible({key:"pip",el:d,priority:20,available:()=>!0,section:()=>this.simpleSection("pip",t.pip,i.pip,()=>void e.togglePip())})}if(s.fullscreen&&(this.fullscreenBtn=y("imp-btn--fullscreen",t.fullscreen,i.fullscreen),this.fullscreenBtn.addEventListener("click",()=>void e.toggleFullscreen()),this.rightItems.set("fullscreen",this.fullscreenBtn)),this.prevBtn&&this.registerCollapsible({key:"prev",el:this.prevBtn,priority:70,available:()=>!0,section:()=>e.hasPrevious?this.simpleSection("prev",t.previous,i.previous,()=>e.previous()):null}),this.nextBtn&&this.registerCollapsible({key:"next",el:this.nextBtn,priority:72,available:()=>!0,section:()=>e.hasNext?this.simpleSection("next",t.next,i.next,()=>e.next()):null}),this.seekBackBtn){const d=this.seekBackBtn;this.registerCollapsible({key:"seekBack",el:d,priority:80,available:()=>Number.isFinite(e.duration)&&e.duration>0,section:()=>this.simpleSection("seekBack",`${t.seekBack} ${u}s`,i.seekBack,()=>e.skip(-u))})}if(this.seekFwdBtn){const d=this.seekFwdBtn;this.registerCollapsible({key:"seekFwd",el:d,priority:82,available:()=>Number.isFinite(e.duration)&&e.duration>0,section:()=>this.simpleSection("seekFwd",`${t.seekForward} ${v}s`,i.seekForward,()=>e.skip(v))})}if(this.center=o("div","imp-center-controls"),s.playlist&&e.hasPlaylist&&(this.centerPrevBtn=this.makeCenterButton("prev",t.previous,i.previous),this.centerPrevBtn.addEventListener("click",()=>e.previous()),this.center.append(this.centerPrevBtn)),s.seekButtons){const d=this.makeCenterButton("seek-back",`${t.seekBack} ${u}s`,i.seekBack);this.addStepBadge(d,u,"back"),d.addEventListener("click",()=>e.skip(-u)),this.center.append(d)}if(s.play&&(this.centerPlayBtn=this.makeCenterButton("play",t.play,i.play),this.centerPlayBtn.addEventListener("click",()=>e.togglePlay()),this.center.append(this.centerPlayBtn)),s.seekButtons){const d=this.makeCenterButton("seek-forward",`${t.seekForward} ${v}s`,i.seekForward);this.addStepBadge(d,v,"forward"),d.addEventListener("click",()=>e.skip(v)),this.center.append(d)}if(s.playlist&&e.hasPlaylist&&(this.centerNextBtn=this.makeCenterButton("next",t.next,i.next),this.centerNextBtn.addEventListener("click",()=>e.next()),this.center.append(this.centerNextBtn)),this.center.style.display="none",this.setupNextPreview(),this.gear.speed||this.gear.quality||this.gear.subtitles){this.gearBtn=y("imp-btn--settings",t.settings,i.settings),this.gearMenu=new _(this.gearBtn);const d=o("div","imp-controls__menu-anchor");d.append(this.gearBtn,this.gearMenu.root),this.gearBtn.addEventListener("click",()=>this.toggleGearMenu()),this.rightItems.set("gear",d),this.registerCollapsible({key:"gear",el:d,priority:40,available:()=>this.gearSections().length>0,section:()=>this.gearSections()})}this.layoutRightCluster(a),this.buildMoreDropdown(a),this.bind(),this.syncVolume(),this.syncPlayState(),this.setLikeState(e.actionsOptions.likeState??null),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.scheduleReflow()),this.resizeObserver.observe(e.container)),this.onWindowResize=()=>this.scheduleReflow(),window.addEventListener("resize",this.onWindowResize)}registerCollapsible(e){this.collapsibles.push(e)}layoutRightCluster(e){const t=[...this.rightItems.keys()],i=this.player.controlsOptions.order;let s=t;if(i.length>0){const n=new Set;s=[];for(const r of i)this.rightItems.has(r)&&!n.has(r)&&(s.push(r),n.add(r));for(const r of t)n.has(r)||s.push(r)}for(const n of s){const r=this.rightItems.get(n);r&&e.append(r)}}makeCenterButton(e,t,i){const s=o("button",`imp-center-btn imp-center-btn--${e}`,{type:"button","aria-label":t,title:t});return s.innerHTML=i,s}addStepBadge(e,t,i){const s=o("span","imp-seek-num");s.textContent=this.seekLabelFn?this.seekLabelFn(t,i):`${i==="back"?"−":"+"}${t}${this.player.labels.secondsShort}`,e.append(s)}gearSections(){const e=this.player,t=[];return this.gear.quality&&e.qualityLevels.length>0&&t.push(this.qualitySection()),this.gear.speed&&t.push(this.speedSection()),this.gear.subtitles&&e.subtitleTracks.length>0&&t.push(this.subtitlesSection()),t}gearEntries(){const e=this.player,t=[];if(e.hasPlaylist&&t.push({key:"autoplay",label:e.labels.autoplay,toggle:{value:e.autoAdvance,onChange:i=>e.setAutoAdvance(i)}}),this.gear.quality&&e.qualityLevels.length>0){const i=e.currentQuality===-1?e.labels.qualityAuto:e.qualityLevels.find(s=>s.index===e.currentQuality)?.label??e.labels.qualityAuto;t.push({key:"quality",label:e.labels.quality,value:i,section:()=>this.qualitySection()})}if(this.gear.speed){const i=e.playbackRate;t.push({key:"speed",label:e.labels.speed,value:i===1?"1×":`${i}×`,section:()=>this.speedSection()})}if(this.gear.subtitles&&e.subtitleTracks.length>0){const i=e.activeSubtitle===-1?e.labels.subtitlesOff:e.subtitleTracks[e.activeSubtitle]?.label??e.labels.subtitlesOff;t.push({key:"subtitles",label:e.labels.subtitles,value:i,section:()=>this.subtitlesSection()})}return t}refreshSceneTypeButton(){const e=this.sceneTypeBtn;if(!e)return;const t=this.player.activeSceneType;if(e.textContent="",!t)return;if(t.icon){const s=o("span","imp-scene-type__icon");t.icon.trimStart().startsWith("<svg")?s.innerHTML=t.icon:s.append(o("img","",{src:t.icon,alt:""})),e.append(s)}const i=o("span","imp-scene-type__label");i.textContent=t.title,e.append(i),e.setAttribute("aria-label",`${this.player.labels.sceneTypes}: ${t.title}`),e.title=t.title}sceneTypeSection(){const e=this.player;return{title:e.labels.sceneTypes,items:e.sceneTypes.map(t=>({label:t.title,value:t.id,icon:t.icon,active:t.id===(e.activeSceneType?.id??"")})),onSelect:t=>{e.setSceneGroup(t),this.refreshSceneTypeButton()}}}toggleSceneTypeMenu(){!this.sceneTypeMenu||this.player.sceneTypes.length===0||(this.closeMenus(this.sceneTypeMenu),this.sceneTypeMenu.toggle([this.sceneTypeSection()]))}toggleGearMenu(){if(!this.gearMenu)return;const e=this.gearEntries();e.length!==0&&(this.closeMenus(this.gearMenu),this.gearMenu.toggleSettings(this.player.labels.settings,e))}setupNextPreview(){const e=this.player,t=e.controlsOptions;if(t.nextPreview===!1||!t.playlist||!e.hasPlaylist)return;const i=typeof t.nextPreview=="object"?t.nextPreview:{};this.nextPreviewOpts={thumbnail:i.thumbnail??!0,title:i.title??!0,duration:i.duration??!0,meta:i.meta??!0},this.nextPreviewEl=o("div","imp-next-preview"),this.nextPreviewEl.hidden=!0,e.container.append(this.nextPreviewEl),this.nextBtn&&this.bindNextPreview(this.nextBtn),this.centerNextBtn&&this.bindNextPreview(this.centerNextBtn)}bindNextPreview(e){e.addEventListener("pointerenter",t=>{t.pointerType==="mouse"&&this.showNextPreview(e)}),e.addEventListener("pointerleave",()=>this.hideNextPreview()),e.addEventListener("click",()=>this.hideNextPreview())}showNextPreview(e){const t=this.nextPreviewEl,i=this.nextPreviewOpts;if(!t||!i)return;const s=this.player.nextSource;if(!s)return;t.textContent="";const n=o("div","imp-next-preview__kicker");if(n.textContent=this.player.labels.next,t.append(n),i.thumbnail&&s.poster){const p=o("div","imp-next-preview__thumb");if(p.style.backgroundImage=`url("${s.poster}")`,i.duration&&s.duration){const f=o("span","imp-next-preview__duration");f.textContent=x(s.duration),p.append(f)}t.append(p)}if(i.title&&s.title){const p=o("div","imp-next-preview__title");p.textContent=s.title,t.append(p)}if(i.meta&&s.previewMeta?.length){const p=o("div","imp-next-preview__meta");p.textContent=s.previewMeta.join(" · "),t.append(p)}t.hidden=!1;const r=this.player.container.getBoundingClientRect(),a=e.getBoundingClientRect(),h=8,c=t.offsetWidth,u=a.left-r.left+a.width/2-c/2,v=Math.max(h,Math.min(u,r.width-c-h));t.style.left=`${v}px`,t.style.bottom=`${r.height-(a.top-r.top)+10}px`}hideNextPreview(){this.nextPreviewEl&&(this.nextPreviewEl.hidden=!0)}buildLikeDislike(){const e=this.player,t=e.actionsOptions,{labels:i,icons:s}=e;if(t.like){this.likeBtn=y("imp-btn--like",i.like,s.like),this.likeBtn.addEventListener("click",()=>e.emit("action",{id:"like"})),this.likeCountEl=this.attachCountTooltip(this.likeBtn,t.likeCount);const n=this.wrapWithTooltip(this.likeBtn,this.likeCountEl);this.rightItems.set("like",n),this.registerCollapsible({key:"like",el:n,priority:62,available:()=>!0,section:()=>this.simpleSection("like",i.like,s.like,()=>e.emit("action",{id:"like"}))})}if(t.dislike){this.dislikeBtn=y("imp-btn--dislike",i.dislike,s.dislike),this.dislikeBtn.addEventListener("click",()=>e.emit("action",{id:"dislike"})),this.dislikeCountEl=this.attachCountTooltip(this.dislikeBtn,t.dislikeCount);const n=this.wrapWithTooltip(this.dislikeBtn,this.dislikeCountEl);this.rightItems.set("dislike",n),this.registerCollapsible({key:"dislike",el:n,priority:60,available:()=>!0,section:()=>this.simpleSection("dislike",i.dislike,s.dislike,()=>e.emit("action",{id:"dislike"}))})}}attachCountTooltip(e,t){const i=o("span","imp-count-tooltip");return this.setCountText(i,t),i}wrapWithTooltip(e,t){const i=o("div","imp-action");return i.append(e,t),i}setCountText(e,t){const i=t==null||t===""?"":String(t);e.textContent=i,e.hidden=i===""}setLikeCounts(e,t){this.likeCountEl&&e!==void 0&&this.setCountText(this.likeCountEl,e),this.dislikeCountEl&&t!==void 0&&this.setCountText(this.dislikeCountEl,t)}setLikeState(e){this.likeBtn?.classList.toggle("imp-btn--active",e==="like"),this.dislikeBtn?.classList.toggle("imp-btn--active",e==="dislike")}buildMoreDropdown(e){const t=this.player,i=t.actionsOptions,{labels:s,icons:n}=t;i.addTo&&this.actionItems.push({value:"addTo",label:s.addTo,icon:n.addTo,run:()=>t.emit("action",{id:"addTo"})}),i.share&&this.actionItems.push({value:"share",label:s.share,icon:n.share,run:()=>void t.share()}),i.report&&this.actionItems.push({value:"report",label:s.report,icon:n.report,run:()=>t.emit("action",{id:"report"})});for(const h of(i.custom??[]).filter(c=>c.placement!=="bar"))this.actionItems.push({value:`custom:${h.id}`,label:h.title,icon:h.icon,run:()=>t.emit("customaction",{id:h.id})});const r=y("imp-btn--more",s.more,n.more);this.moreMenu=new _(r);const a=o("div","imp-controls__menu-anchor imp-controls__more");a.append(r,this.moreMenu.root),r.addEventListener("click",()=>{this.closeMenus(this.moreMenu),this.moreMenu?.toggle(this.buildMoreSections())}),e.append(a),this.moreWrap=a}buildMoreSections(){const e=[],t=new Map,i=[],s=["prev","next","seekBack","seekFwd","like","dislike","scenes","sceneTypes","pip","list","subtitles","speed","quality","gear"],n=a=>{const h=s.indexOf(a);return h===-1?s.length:h},r=this.collapsibles.filter(a=>this.overflowed.has(a.key)&&a.available()).sort((a,h)=>n(a.key)-n(h.key));for(const a of r){const h=a.section();if(h)for(const c of Array.isArray(h)?h:[h])if(!c.title&&c.items.length===1){const u=c.items[0];i.push(u),t.set(u.value,()=>c.onSelect(u.value))}else e.push(c)}if(i.length>0&&e.unshift({title:"",items:i,onSelect:a=>t.get(a)?.()}),this.actionItems.length>0){const a=new Map(this.actionItems.map(h=>[h.value,h.run]));e.push({title:"",items:this.actionItems.map(({value:h,label:c,icon:u})=>({value:h,label:c,icon:u,active:!1})),onSelect:h=>a.get(h)?.()})}return e}simpleSection(e,t,i,s){return{title:"",items:[{value:e,label:t,icon:i,active:!1}],onSelect:()=>s()}}speedSection(){const e=this.player;return{title:e.labels.speed,items:e.playbackRates.map(t=>({label:t===1?"1× (normal)":`${t}×`,value:String(t),active:e.playbackRate===t})),onSelect:t=>e.setPlaybackRate(Number(t))}}qualitySection(){const e=this.player;return{title:e.labels.quality,items:[...e.qualityAutoAvailable?[{label:e.labels.qualityAuto,value:"-1",active:e.currentQuality===-1}]:[],...e.qualityLevels.map(t=>({label:t.label,value:String(t.index),active:e.currentQuality===t.index}))],onSelect:t=>e.setQuality(Number(t))}}subtitlesSection(){const e=this.player;return{title:e.labels.subtitles,items:[{label:e.labels.subtitlesOff,value:"-1",active:e.activeSubtitle===-1},...e.subtitleTracks.map((t,i)=>({label:t.label,value:String(i),active:e.activeSubtitle===i}))],onSelect:t=>e.setSubtitle(Number(t))}}scheduleReflow(){this.reflowScheduled||(this.reflowScheduled=!0,requestAnimationFrame(()=>{this.reflowScheduled=!1,this.reflow()}))}reflow(){const e=window.innerWidth<=767,i=this.player.controlsOptions.seekPlacement!=="bar"||e;this.center.style.display=i?"flex":"none",this.centerPrevBtn&&(this.centerPrevBtn.style.display=e?"":"none"),this.centerNextBtn&&(this.centerNextBtn.style.display=e?"":"none"),this.playBtn&&(this.playBtn.style.display=e?"none":"");const s=a=>a==="seekBack"||a==="seekFwd"?i:a==="prev"||a==="next"?e:!1;this.overflowed.clear();for(const a of this.collapsibles){if(s(a.key)){a.el.style.display="none";continue}const h=a.available();a.el.style.display=h?"":"none",a.el.classList.remove("imp-collapsed")}const n=this.collapsibles.filter(a=>a.available()&&!s(a.key)).sort((a,h)=>a.priority-h.priority);let r=n.length;for(;r-- >0&&this.overflowsRow();){const a=n.find(h=>!this.overflowed.has(h.key));if(!a)break;a.el.style.display="none",a.el.classList.add("imp-collapsed"),this.overflowed.add(a.key)}if(this.moreWrap){const a=this.actionItems.length>0||this.overflowed.size>0;this.moreWrap.style.display=a?"":"none"}}overflowsRow(){const e=this.row.getBoundingClientRect().right;return this.rightGroup.getBoundingClientRect().right>e+1}bind(){const e=this.player;this.disposers.push(e.on("timeupdate",({currentTime:t,duration:i})=>{this.progress.update(t,i,e.bufferedEnd),this.timeLabel&&(e.live?(this.timeLabel.hidden=!0,this.liveBadge.hidden=!1):(this.timeLabel.hidden=!1,this.liveBadge.hidden=!0,this.timeLabel.textContent=`${x(t)} / ${x(i)}`))}),e.on("play",()=>this.syncPlayState()),e.on("pause",()=>this.syncPlayState()),e.on("ended",()=>this.syncPlayState()),e.on("volumechange",()=>this.syncVolume()),e.on("chapterchange",({chapter:t})=>{this.chapterLabel.textContent=t?.title??""}),e.on("fullscreenchange",({active:t})=>{this.fullscreenBtn&&A(this.fullscreenBtn,t?e.icons.fullscreenExit:e.icons.fullscreen,t?e.labels.exitFullscreen:e.labels.fullscreen),this.scheduleReflow()}),e.on("playlistitemchange",()=>{this.syncPlaylistButtons(),this.scheduleReflow()}),e.on("sourcechange",()=>{this.syncPlaylistButtons(),this.scheduleReflow()})),this.syncPlaylistButtons(),this.reflow()}syncPlayState(){const e=this.player,[t,i]=e.ended?[e.icons.replay,e.labels.replay]:e.paused?[e.icons.play,e.labels.play]:[e.icons.pause,e.labels.pause];this.playBtn&&A(this.playBtn,t,i),this.centerPlayBtn&&A(this.centerPlayBtn,t,i)}syncVolume(){if(!this.muteBtn)return;const e=this.player,t=e.muted?0:e.volume,i=t===0?e.icons.volumeMute:t<.5?e.icons.volumeLow:e.icons.volumeHigh;A(this.muteBtn,i,e.muted?e.labels.unmute:e.labels.mute),this.volumeSlider.value=String(t),this.volumeSlider.style.setProperty("--imp-volume-fill",`${t*100}%`)}syncFeatureButtons(){this.refreshSceneTypeButton(),this.scheduleReflow()}syncPlaylistButtons(){const e=this.player;this.prevBtn&&(this.prevBtn.disabled=!e.hasPrevious),this.nextBtn&&(this.nextBtn.disabled=!e.hasNext),this.centerPrevBtn&&(this.centerPrevBtn.disabled=!e.hasPrevious),this.centerNextBtn&&(this.centerNextBtn.disabled=!e.hasNext)}closeMenus(e){for(const t of[this.gearMenu,this.settingsMenu,this.subtitlesMenu,this.qualityMenu,this.sceneTypeMenu,this.moreMenu])t&&t!==e&&t.close()}toggleSettingsMenu(){this.settingsMenu&&(this.closeMenus(this.settingsMenu),this.settingsMenu.toggle([this.speedSection()]))}toggleQualityMenu(){!this.qualityMenu||this.player.qualityLevels.length===0||(this.closeMenus(this.qualityMenu),this.qualityMenu.toggle([this.qualitySection()]))}toggleSubtitlesMenu(){!this.subtitlesMenu||this.player.subtitleTracks.length===0||(this.closeMenus(this.subtitlesMenu),this.subtitlesMenu.toggle([this.subtitlesSection()]))}destroy(){for(const e of this.disposers)e();this.disposers=[],this.resizeObserver?.disconnect(),this.onWindowResize&&window.removeEventListener("resize",this.onWindowResize),this.gearMenu?.destroy(),this.sceneTypeMenu?.destroy(),this.settingsMenu?.destroy(),this.subtitlesMenu?.destroy(),this.qualityMenu?.destroy(),this.moreMenu?.destroy(),this.nextPreviewEl?.remove(),this.root.remove()}}class fe{constructor(e){this.root=o("div","imp-poster"),this.image=o("img","imp-poster__image",{alt:"",decoding:"async"}),this.image.hidden=!0;const t=y("imp-poster__play",e.labels.play,e.icons.bigPlay);t.addEventListener("click",()=>void e.play()),this.root.append(this.image,t),this.root.addEventListener("click",i=>{(i.target===this.root||i.target===this.image)&&e.play()})}setSource(e){e?.poster?(this.image.src=e.poster,this.image.fetchPriority="high",this.image.hidden=!1):(this.image.removeAttribute("src"),this.image.hidden=!0)}show(){this.root.hidden=!1}hide(){this.root.hidden=!0}}class ye{constructor(e){this.labels=e,this.channelUrl=null,this.custom=null,this.visible={title:!0,description:!0,sponsor:!0},this.root=o("div","imp-pause-screen"),this.root.hidden=!0,this.defaultContent=o("div","imp-pause-screen__default"),this.channel=o("button","imp-channel",{type:"button"}),this.channel.hidden=!0,this.channelAvatar=o("div","imp-channel__avatar"),this.channelName=o("div","imp-channel__name"),this.channel.append(this.channelName,this.channelAvatar),this.channel.addEventListener("click",()=>{this.channelUrl&&window.open(this.channelUrl,"_blank","noopener")});const t=o("div","imp-pause-screen__heading");this.title=o("div","imp-pause-screen__title"),this.description=o("div","imp-pause-screen__description"),this.sponsor=o("a","imp-sponsor",{target:"_blank",rel:"nofollow noopener"}),this.sponsor.hidden=!0,this.sponsorLabel=o("span","imp-sponsor__label"),this.sponsorText=o("span","imp-sponsor__text"),this.sponsor.append(this.sponsorLabel,this.sponsorText),this.sponsor.addEventListener("click",i=>i.stopPropagation()),t.append(this.sponsor,this.title,this.description),this.defaultContent.append(t,this.channel),this.root.append(this.defaultContent)}setCustomContent(e){this.custom?.remove(),this.custom=e,e&&(e.classList.add("imp-pause-screen__custom"),this.root.append(e)),this.defaultContent.hidden=e!==null,this.root.classList.toggle("imp-pause-screen--custom",e!==null)}get hasCustom(){return this.custom!==null}setVisibility(e){this.visible={title:e.title??this.visible.title,description:e.description??this.visible.description,sponsor:e.sponsor??this.visible.sponsor}}setSource(e){this.title.textContent=e?.title??"",this.description.textContent=e?.description??"",this.title.hidden=!this.visible.title||!e?.title,this.description.hidden=!this.visible.description||!e?.description;const t=this.visible.sponsor?e?.sponsor:void 0;this.sponsor.hidden=!t,t&&(this.sponsor.href=t.url,this.sponsorText.textContent=t.text,this.sponsorLabel.textContent=t.label??this.labels.sponsored);const i=e?.channel;this.channel.hidden=!i,this.channelUrl=i?.url??null,this.channel.classList.toggle("imp-channel--link",!!i?.url),i&&(this.channelName.textContent=i.name,this.channelAvatar.className=`imp-channel__avatar imp-channel__avatar--${i.avatarShape??"circle"}`,i.avatar?(this.channelAvatar.textContent="",this.channelAvatar.style.backgroundImage=`url("${i.avatar}")`):(this.channelAvatar.style.backgroundImage="",this.channelAvatar.textContent=(i.name.trim()[0]??"?").toUpperCase()))}show(){this.root.hidden=!1}hide(){this.root.hidden=!0}}class ge{constructor(e){this.player=e,this.clickBehavior="player",this.root=o("div","imp-related"),this.root.hidden=!0,this.heading=o("div","imp-related__title"),this.grid=o("div","imp-related__grid");const t=y("imp-related__close","Close",e.icons.close);t.addEventListener("click",()=>this.hide()),this.root.append(t,this.heading,this.grid)}setOptions(e){if(this.grid.textContent="",!!e){this.clickBehavior=e.clickBehavior??"player",this.heading.textContent=e.title??this.player.labels.related;for(const t of e.items)this.grid.append(this.buildCard(t))}}buildCard(e){const t=o("button","imp-related__card",{type:"button"}),i=o("div","imp-related__thumb");if(e.poster&&(i.style.backgroundImage=`url("${e.poster}")`),e.duration){const n=o("span","imp-related__duration");n.textContent=e.duration,i.append(n)}const s=o("div","imp-related__card-title");return s.textContent=e.title,t.append(i,s),t.addEventListener("click",()=>{this.player.emit("relatedclick",{item:e}),this.hide(),this.activate(e)}),t}activate(e){const t=e.url??e.source?.src;switch(this.clickBehavior){case"newWindow":t&&window.open(t,"_blank","noopener");break;case"currentTab":t&&(window.location.href=t);break;case"player":default:e.source?(this.player.load(e.source),this.player.play()):e.url&&window.open(e.url,"_blank","noopener")}}get visible(){return!this.root.hidden}show(){this.grid.childElementCount!==0&&(this.root.hidden=!1,this.player.emit("relatedshow",void 0))}hide(){this.root.hidden=!0}}class be{constructor(e){this.player=e,this.root=o("div","imp-upnext"),this.root.hidden=!0}get visible(){return!this.root.hidden}show(){const e=this.player.nextSource;if(!e)return;const{labels:t}=this.player;this.root.textContent="";const i=o("div","imp-upnext__card"),s=o("div","imp-upnext__kicker");if(s.textContent=t.nextVideo,i.append(s),e.poster){const r=o("button","imp-upnext__thumb",{type:"button","aria-label":t.playNext});if(r.style.backgroundImage=`url("${e.poster}")`,e.duration){const h=o("span","imp-upnext__duration");h.textContent=x(e.duration),r.append(h)}const a=o("span","imp-upnext__thumb-play");a.innerHTML=this.player.icons.bigPlay,r.append(a),r.addEventListener("click",()=>this.player.next()),i.append(r)}if(e.title){const r=o("div","imp-upnext__title");r.textContent=e.title,i.append(r)}if(e.previewMeta?.length){const r=o("div","imp-upnext__meta"),a=o("span","imp-upnext__meta-icon");a.innerHTML=e.metaIcon??(e.channel?this.player.icons.channel:this.player.icons.user);const h=o("span","imp-upnext__meta-text");h.textContent=e.previewMeta.join(" · "),r.append(a,h),i.append(r)}const n=o("button","imp-upnext__btn",{type:"button"});n.textContent=t.playNext,n.addEventListener("click",()=>this.player.next()),i.append(n),this.root.append(i),this.root.hidden=!1}hide(){this.root.hidden=!0}}class ke{constructor(e,t="sidebar",i){this.player=e,this.root=o("div",`imp-playlist imp-playlist--${t}`),this.root.hidden=!0;const s=o("div","imp-playlist__header"),n=o("div","imp-playlist__heading");if(i){const h=o("div","imp-playlist__kicker");h.textContent=e.labels.playlist;const c=o("div","imp-playlist__name");c.textContent=i,n.append(h,c)}else n.textContent=e.labels.playlist;const r=o("div","imp-playlist__tools");this.shuffleBtn=y("imp-playlist__shuffle",e.labels.shuffle,e.icons.shuffle),this.shuffleBtn.addEventListener("click",()=>{e.setShuffle(!e.shuffle),this.syncModes()}),this.repeatBtn=y("imp-playlist__repeat",e.labels.repeat,e.icons.repeat),this.repeatBtn.addEventListener("click",()=>{e.setRepeat(!e.repeat),this.syncModes()});const a=y("imp-playlist__close","Close",e.icons.close);a.addEventListener("click",()=>this.hide()),r.append(this.shuffleBtn,this.repeatBtn,a),s.append(n,r),this.list=o("div","imp-playlist__list"),this.root.append(s,this.list),this.rebuild(),this.syncModes()}syncModes(){this.shuffleBtn.classList.toggle("imp-btn--active",this.player.shuffle),this.repeatBtn.classList.toggle("imp-btn--active",this.player.repeat)}rebuild(){this.list.textContent="",this.player.playlist.forEach((e,t)=>{const i=o("button","imp-playlist__item",{type:"button"});t===this.player.index&&i.classList.add("imp-playlist__item--active");const s=o("div","imp-playlist__thumb");e.poster&&(s.style.backgroundImage=`url("${e.poster}")`);const n=o("div","imp-playlist__meta"),r=o("div","imp-playlist__title");if(r.textContent=e.title??`#${t+1}`,n.append(r),e.duration){const a=o("div","imp-playlist__duration");a.textContent=x(e.duration),n.append(a)}i.append(s,n),i.addEventListener("click",()=>{this.player.playItem(t),window.innerWidth<=767&&this.hide()}),this.list.append(i)})}get visible(){return!this.root.hidden}show(){this.rebuild(),this.root.hidden=!1}hide(){this.root.hidden=!0}toggle(){this.visible?this.hide():this.show()}}class we{constructor(e,t="bottom"){this.player=e,this.items=[],this.root=o("div",`imp-playlist imp-scenes imp-playlist--${t}`),this.root.hidden=!0;const i=o("div","imp-playlist__header"),s=o("span");s.textContent=e.labels.scenes;const n=y("imp-playlist__close","Close",e.icons.close);n.addEventListener("click",()=>this.hide()),i.append(s,n),this.list=o("div","imp-playlist__list"),this.root.append(i,this.list),e.on("chapterchange",()=>this.syncActive())}rebuild(){this.list.textContent="",this.items=[];const e=this.player.thumbnails;for(const t of this.player.chapterList){const i=o("button","imp-playlist__item",{type:"button"}),s=o("div","imp-playlist__thumb"),n=e?.cueAt(t.start+.01)??null;if(n?.xywh){const c=o("div","imp-scenes__sprite");c.style.width=`${n.xywh.w}px`,c.style.height=`${n.xywh.h}px`,c.style.backgroundImage=`url("${n.src}")`,c.style.backgroundPosition=`-${n.xywh.x}px -${n.xywh.y}px`,c.style.setProperty("--imp-sprite-w",String(n.xywh.w)),s.append(c)}else n&&(s.style.backgroundImage=`url("${n.src}")`);const r=o("div","imp-playlist__meta"),a=o("div","imp-playlist__title");a.textContent=t.title||x(t.start);const h=o("div","imp-playlist__duration");h.textContent=x(t.start),r.append(a,h),i.append(s,r),i.addEventListener("click",()=>{this.player.seek(t.start),this.player.play(),window.innerWidth<=767&&this.hide()}),this.list.append(i),this.items.push(i)}this.syncActive()}syncActive(){const e=this.player.chapter,t=this.player.chapterList;this.items.forEach((i,s)=>{i.classList.toggle("imp-playlist__item--active",e!==null&&t[s]===e)})}get visible(){return!this.root.hidden}show(){this.rebuild(),this.root.hidden=!1}hide(){this.root.hidden=!0}toggle(){this.visible?this.hide():this.show()}}function D(l){return l?typeof l=="string"?[{src:l,label:"Subtitles"}]:Array.isArray(l)?l:[l]:[]}const xe={play:!0,progress:!0,time:!0,volume:!0,fullscreen:!0,pip:!0,speed:"gear",settings:"gear",quality:"gear",scenes:!0,sceneTypes:!0,heatmap:!0,subtitles:"gear",seekButtons:!0,seekPlacement:"overlay",order:[],playlist:!0,hidePrev:!0,nextPreview:!0,hideDelay:2500};class Se{constructor(e,t={}){this.scrubbing=!1,this.emitter=new K,this.abort=new AbortController,this.sources=[],this.currentIndex=-1,this.sourceController=null,this.loadToken=0,this.chapters=[],this.currentChapter=null,this.sceneGroupList=[],this.activeSceneGroupId="",this.progressiveQuality=-1,this.thumbTrack=null,this.shuffleMode=!1,this.autoAdvanceEnabled=!0,this.persistKey=null,this.persistVolume=!1,this.persistAutoAdvance=!1,this.decodeRecoveries=0,this.adManager=null,this.playedOnce=!1,this.idleTimer=null,this.destroyed=!1;const i=typeof e=="string"?document.querySelector(e):e;if(!i)throw new Error(`[itube-player] mount target not found: ${String(e)}`);this.mount=i,this.options=t,this.labels={...C,...Y(t.language),...t.labels},this.icons={...X,...t.icons};const s=t.controls??{},n=s.speed??s.settings??"gear";if(this.controlsOptions={...xe,...s,speed:n,settings:n},this.actionsOptions=t.actions??{},this.playbackRates=t.playbackRates??[.5,.75,1,1.25,1.5,2],this.seekStep=t.seekStep??15,this.playlistOptions={title:"",autoAdvance:!0,loop:!1,shuffle:!1,startIndex:0,layout:"sidebar",...t.playlist},this.shuffleMode=this.playlistOptions.shuffle,t.persist){const f=t.persist===!0?{}:t.persist;this.persistKey=f.key??"itube-player",this.persistVolume=f.volume!==!1,this.persistAutoAdvance=f.autoAdvance!==!1}const r=this.readPersisted();this.autoAdvanceEnabled=this.persistAutoAdvance&&typeof r?.autoAdvance=="boolean"?r.autoAdvance:this.playlistOptions.autoAdvance,this.sources=t.source?Array.isArray(t.source)?[...t.source]:[t.source]:[],this.container=o("div","imp-player",{tabindex:"0"}),t.className&&this.container.classList.add(t.className);const a=t.styling;if(a?.themeColor&&this.container.style.setProperty("--imp-accent",a.themeColor),a?.likeColor&&this.container.style.setProperty("--imp-like",a.likeColor),a?.dislikeColor&&this.container.style.setProperty("--imp-dislike",a.dislikeColor),a?.borderRadius!==void 0){const f=typeof a.borderRadius=="number"?`${a.borderRadius}px`:a.borderRadius;this.container.style.setProperty("--imp-radius",f)}a?.playButtonStyle==="inverted"&&this.container.classList.add("imp-player--play-inverted"),this.video=o("video","imp-video"),t.playsInline!==!1&&this.video.setAttribute("playsinline",""),t.crossOrigin!==void 0&&(this.video.crossOrigin=t.crossOrigin),this.video.preload="metadata",t.loop&&(this.video.loop=!0);const h=this.persistVolume?r:null;this.video.volume=w(h?.volume??t.volume??1,0,1),(h?.muted??t.muted)&&(this.video.muted=!0);const c=o("div","imp-layer");this.spinner=o("div","imp-spinner"),this.spinner.hidden=!0,this.errorBox=o("div","imp-error"),this.errorBox.hidden=!0,this.pauseScreen=new ye(this.labels),this.poster=new fe(this),this.related=new ge(this),this.related.setOptions(t.related),this.upNext=new be(this),this.controls=new ve(this),this.playlistPanel=new ke(this,this.playlistOptions.layout,this.playlistOptions.title||void 0),this.scenesPanel=new we(this,t.scenes?.layout??"bottom");const u=o("div","imp-layer__middle");u.append(this.spinner,this.errorBox,this.controls.center);const v=o("div","imp-layer__bottom");v.append(this.controls.root),c.append(this.pauseScreen.root,this.related.root,this.upNext.root,u,v),this.container.append(this.video,c,this.poster.root,this.playlistPanel.root,this.scenesPanel.root),this.mount.append(this.container),t.pauseScreen instanceof HTMLElement?this.pauseScreen.setCustomContent(t.pauseScreen):typeof t.pauseScreen=="function"?this.pauseScreen.setCustomContent(t.pauseScreen(this)):t.pauseScreen&&typeof t.pauseScreen=="object"&&this.pauseScreen.setVisibility(t.pauseScreen);const p=t.adConfig??t.ads;p&&p.adList.length>0&&(this.adManager=new oe({container:this.container,contentVideo:this.video,emitter:this.emitter,labels:this.labels,closeIcon:this.icons.close},p)),this.emitter.on("error",({message:f})=>{this.errorBox.textContent=f,this.errorBox.hidden=!1,this.spinner.hidden=!0,this.poster.hide()}),this.bindVideoEvents(),this.bindIdleHide(),t.keyboard!==!1&&this.bindKeyboard(),this.video.addEventListener("pointerup",f=>{if(!(this.adPlaying||!this.playedOnce)){if(f.pointerType==="mouse"){this.togglePlay();return}this.container.classList.contains("imp-player--idle")?(this.showControlsNow(),this.scheduleIdle()):this.video.paused||this.container.classList.add("imp-player--idle")}},{signal:this.abort.signal}),this.pauseScreen.root.addEventListener("click",f=>{this.pauseScreen.hasCustom||f.target===this.pauseScreen.root&&this.togglePlay()},{signal:this.abort.signal}),this.sources.length>0&&this.loadItem(w(this.playlistOptions.startIndex,0,this.sources.length-1),!!t.autoplay),this.emitter.emit("ready",{player:this})}on(e,t){return this.emitter.on(e,t)}once(e,t){return this.emitter.once(e,t)}off(e,t){this.emitter.off(e,t)}emit(e,t){this.emitter.emit(e,t)}get paused(){return this.video.paused}get ended(){return this.video.ended}get currentTime(){return this.video.currentTime}get duration(){return this.video.duration||0}get live(){return this.video.duration===1/0}get bufferedEnd(){const e=this.video.buffered;return e.length>0?e.end(e.length-1):0}get adPlaying(){return this.adManager?.adPlaying??!1}async play(){this.destroyed||this.adPlaying||this.adManager&&(await this.adManager.playPreRoll(),this.destroyed||!this.video.paused)||await this.video.play()}pause(){this.adPlaying||this.video.pause()}togglePlay(){this.video.paused||this.video.ended?this.play():this.pause()}seek(e){Number.isFinite(this.video.duration)&&(this.video.currentTime=w(e,0,this.video.duration))}skip(e){this.seek(this.video.currentTime+e)}get volume(){return this.video.volume}get muted(){return this.video.muted}setVolume(e){this.video.volume=w(e,0,1),e>0&&(this.video.muted=!1)}setMuted(e){this.video.muted=e}toggleMute(){this.video.muted=!this.video.muted}readPersisted(){if(!this.persistKey)return null;try{const e=localStorage.getItem(this.persistKey),t=e?JSON.parse(e):null;return t&&typeof t=="object"?t:null}catch{return null}}persistState(){if(this.persistKey)try{const e={};this.persistVolume&&(e.volume=this.video.volume,e.muted=this.video.muted),this.persistAutoAdvance&&(e.autoAdvance=this.autoAdvanceEnabled),localStorage.setItem(this.persistKey,JSON.stringify(e))}catch{}}get playbackRate(){return this.video.playbackRate}setPlaybackRate(e){this.video.playbackRate=e,this.emitter.emit("ratechange",{rate:e})}get qualityLevels(){if(this.sourceController?.kind==="hls")return this.sourceController.levels;const e=this.source?.qualities;return e?e.map((t,i)=>({index:i,label:t.label??String(t.quality??i)})):[]}get qualityAutoAvailable(){return this.sourceController?.kind==="hls"}get currentQuality(){return this.sourceController?.kind==="hls"?this.sourceController.selected:this.progressiveQuality}setQuality(e){if(this.sourceController?.kind==="hls"){this.sourceController.setLevel(e);const n=e===-1?this.labels.qualityAuto:this.sourceController.levels.find(r=>r.index===e)?.label??String(e);this.emitter.emit("qualitychange",{label:n});return}const t=this.source?.qualities;if(!t||!t[e]||e===this.progressiveQuality)return;const i=this.video.currentTime,s=!this.video.paused&&!this.video.ended;this.progressiveQuality=e,this.video.src=t[e].src,this.video.currentTime=i,s&&this.video.play().catch(()=>{}),this.emitter.emit("qualitychange",{label:t[e].label??String(t[e].quality??e)})}get subtitleTracks(){return D(this.source?.subtitles)}get activeSubtitle(){const e=this.video.textTracks;for(let t=0;t<e.length;t++)if(e[t].mode==="showing")return t;return-1}setSubtitle(e){const t=this.video.textTracks;for(let i=0;i<t.length;i++)t[i].mode=i===e?"showing":"disabled";this.emitter.emit("subtitlechange",{track:this.subtitleTracks[e]??null})}get playlist(){return this.sources}get index(){return this.currentIndex}get source(){return this.sources[this.currentIndex]??null}get nextSource(){if(this.shuffleMode||this.sources.length<2)return null;const e=this.currentIndex+1;return e<this.sources.length?this.sources[e]:this.playlistOptions.loop?this.sources[0]??null:null}get hasPlaylist(){return this.sources.length>1}get hasNext(){return this.shuffleMode||this.playlistOptions.loop?this.sources.length>1:this.currentIndex<this.sources.length-1}get hasPrevious(){return this.playlistOptions.loop?this.sources.length>1:this.currentIndex>0}get shuffle(){return this.shuffleMode}setShuffle(e){this.shuffleMode=e}get repeat(){return this.playlistOptions.loop}setRepeat(e){this.playlistOptions.loop=e}next(){if(this.hasNext){if(this.shuffleMode&&this.sources.length>1){let e=this.currentIndex;for(;e===this.currentIndex;)e=Math.floor(Math.random()*this.sources.length);this.playItem(e);return}this.playItem((this.currentIndex+1)%this.sources.length)}}previous(){this.hasPrevious&&this.playItem((this.currentIndex-1+this.sources.length)%this.sources.length)}playItem(e){e<0||e>=this.sources.length||this.loadItem(e,!0).then(()=>{this.emitter.emit("playlistitemchange",{source:this.sources[e],index:e})})}togglePlaylistPanel(){this.scenesPanel.hide(),this.playlistPanel.toggle()}toggleScenesPanel(){this.playlistPanel.hide(),this.scenesPanel.toggle()}get thumbnails(){return this.thumbTrack}load(e,t=0){this.sources=Array.isArray(e)?[...e]:[e],this.playlistPanel.rebuild(),this.loadItem(w(t,0,this.sources.length-1),!1)}get isFullscreen(){return document.fullscreenElement===this.container}async toggleFullscreen(){this.isFullscreen?await document.exitFullscreen():this.container.requestFullscreen?await this.container.requestFullscreen():this.video.webkitEnterFullscreen?.()}async togglePip(){document.pictureInPictureElement===this.video?await document.exitPictureInPicture():await this.video.requestPictureInPicture()}get chapterList(){return this.chapters}get chapter(){return this.currentChapter}get sceneTypes(){return this.sceneGroupList}get activeSceneType(){return this.sceneGroupList.find(e=>e.id===this.activeSceneGroupId)??null}setSceneGroup(e){e===this.activeSceneGroupId||!this.sceneGroupList.some(t=>t.id===e)||(this.activeSceneGroupId=e,this.applyActiveSceneGroup(),this.emitter.emit("scenetypechange",{group:this.activeSceneType}))}applyActiveSceneGroup(){this.chapters=H(this.activeSceneType?.scenes??[],this.video.duration),this.currentChapter=null,this.controls.progress.setChapters(this.chapters),this.controls.syncFeatureButtons(),this.scenesPanel.visible&&this.scenesPanel.rebuild()}async share(){const e={title:this.source?.title??document.title,url:window.location.href};if(typeof navigator.share=="function"){try{await navigator.share(e)}catch{}return}this.emitter.emit("action",{id:"share"})}setLikeState(e){this.controls.setLikeState(e)}setLikeCounts(e,t){this.controls.setLikeCounts(e,t)}setPauseScreenContent(e){this.pauseScreen.setCustomContent(e)}destroy(){this.destroyed||(this.destroyed=!0,this.loadToken++,this.adManager?.destroy(),this.controls.destroy(),this.sourceController?.destroy(),this.abort.abort(),this.idleTimer&&clearTimeout(this.idleTimer),this.container.remove(),this.emitter.emit("destroy",void 0),this.emitter.removeAll())}async loadItem(e,t){const i=++this.loadToken,s=this.sources[e];if(!s)return;this.currentIndex=e,this.sourceController?.destroy(),this.sourceController=null,this.chapters=[],this.currentChapter=null,this.sceneGroupList=[],this.activeSceneGroupId="",this.progressiveQuality=-1,this.playedOnce=!1;for(const h of[...this.video.querySelectorAll("track")])h.remove();this.adManager?.resetForNewSource(),this.related.hide(),this.upNext.hide(),this.pauseScreen.hide(),this.scenesPanel.hide(),this.thumbTrack=null,this.errorBox.hidden=!0,this.decodeRecoveries=0,this.video.poster=s.poster??"",this.poster.setSource(s),this.pauseScreen.setSource(s),this.controls.progress.setChapters([]),this.controls.progress.setThumbnails(null),this.controls.progress.setHeatmap([]),t?this.poster.hide():this.poster.show(),this.playlistPanel.rebuild();for(const h of D(s.subtitles)){const c=o("track","",{kind:"subtitles",src:h.src,label:h.label,...h.srclang?{srclang:h.srclang}:{}});h.default&&c.setAttribute("default",""),this.video.append(c)}let n=s.src,r=s.type;if(s.qualities&&s.qualities.length>0){const h=Math.max(0,s.qualities.findIndex(c=>c.src===s.src));this.progressiveQuality=h,n=s.qualities[h].src,r=s.qualities[h].type??r}this.video.preload=this.adManager?.hasPendingPreRoll?"auto":"metadata";const a=await ce(this.video,n,r,{onLevels:()=>{i===this.loadToken&&this.controls.syncFeatureButtons()},onLevelSwitch:h=>this.emitter.emit("qualitychange",{label:h}),onError:(h,c)=>this.emitter.emit("error",{message:h,cause:c})});if(i!==this.loadToken){a.destroy();return}if(this.sourceController=a,this.emitter.emit("sourcechange",{source:s,index:e}),s.thumbnails&&R.load(s.thumbnails).then(h=>{i===this.loadToken&&(this.thumbTrack=h,this.controls.progress.setThumbnails(h),this.scenesPanel.visible&&this.scenesPanel.rebuild())}).catch(h=>this.emitter.emit("error",{message:"Failed to load thumbnails track",cause:h})),s.sceneGroups&&s.sceneGroups.length>0){this.sceneGroupList=s.sceneGroups,this.activeSceneGroupId=s.sceneGroups[0].id;const h=()=>{i===this.loadToken&&this.applyActiveSceneGroup()};Number.isFinite(this.video.duration)&&this.video.duration>0?h():this.video.addEventListener("loadedmetadata",h,{once:!0,signal:this.abort.signal})}else if(s.chapters){const h=c=>{const u=()=>{i===this.loadToken&&(this.chapters=H(c,this.video.duration),this.controls.progress.setChapters(this.chapters),this.controls.syncFeatureButtons(),this.scenesPanel.visible&&this.scenesPanel.rebuild())};Number.isFinite(this.video.duration)&&this.video.duration>0?u():this.video.addEventListener("loadedmetadata",u,{once:!0,signal:this.abort.signal})};typeof s.chapters=="string"?ae(s.chapters).then(c=>h(c)).catch(c=>this.emitter.emit("error",{message:"Failed to load chapters track",cause:c})):h(s.chapters)}if(s.heatmap&&s.heatmap.length>0&&this.controlsOptions.heatmap){const h=s.heatmap,c=()=>{i===this.loadToken&&this.controls.progress.setHeatmap(ee(h,this.video.duration))};Number.isFinite(this.video.duration)&&this.video.duration>0?c():this.video.addEventListener("loadedmetadata",c,{once:!0,signal:this.abort.signal})}t&&this.play().catch(()=>{i===this.loadToken&&this.poster.show()})}bindVideoEvents(){const{signal:e}=this.abort,t=this.video;t.addEventListener("play",()=>{this.playedOnce=!0,this.poster.hide(),this.pauseScreen.hide(),this.related.visible||this.related.hide(),this.related.hide(),this.upNext.hide(),t.readyState<3&&(this.spinner.hidden=!1),this.emitter.emit("play",void 0),this.scheduleIdle()},{signal:e}),t.addEventListener("pause",()=>{this.spinner.hidden=!0,this.emitter.emit("pause",void 0),this.showControlsNow(),!(this.video.ended||this.scrubbing||this.adPlaying||!this.playedOnce)&&(this.options.pauseScreen!==!1&&this.pauseScreen.show(),this.options.related?.showOn?.includes("pause")&&this.related.show())},{signal:e}),t.addEventListener("ended",()=>{this.handleEnded()},{signal:e}),t.addEventListener("timeupdate",()=>{this.emitter.emit("timeupdate",{currentTime:t.currentTime,duration:t.duration||0}),this.adManager?.checkMidRolls(t.currentTime);const i=Z(this.chapters,t.currentTime);i!==this.currentChapter&&(this.currentChapter=i,this.emitter.emit("chapterchange",{chapter:i}))},{signal:e}),t.addEventListener("progress",()=>{this.emitter.emit("progress",{buffered:this.bufferedEnd})},{signal:e}),t.addEventListener("volumechange",()=>{this.emitter.emit("volumechange",{volume:t.volume,muted:t.muted}),this.persistVolume&&this.persistState()},{signal:e}),t.addEventListener("seeking",()=>this.emitter.emit("seeking",{currentTime:t.currentTime}),{signal:e}),t.addEventListener("seeked",()=>this.emitter.emit("seeked",{currentTime:t.currentTime}),{signal:e}),t.addEventListener("waiting",()=>{this.spinner.hidden=!1},{signal:e});for(const i of["playing","canplay","seeked"])t.addEventListener(i,()=>{this.spinner.hidden=!0,this.errorBox.hidden=!0,this.decodeRecoveries=0},{signal:e});t.addEventListener("error",()=>{const i=t.error;if(!i||this.sourceController?.kind==="hls"||t.getAttribute("src")===null&&!t.currentSrc)return;if((i.code===MediaError.MEDIA_ERR_DECODE||/DEMUXER|PARSE|DECODE/i.test(i.message||""))&&this.decodeRecoveries<2&&Number.isFinite(t.duration)){this.decodeRecoveries++;const n=t.currentTime,r=!t.paused;t.load();const a=()=>{try{t.currentTime=n}catch{}r&&t.play().catch(()=>{})};t.readyState>=1?a():t.addEventListener("loadedmetadata",a,{once:!0,signal:this.abort.signal});return}this.emitter.emit("error",{message:i.message||`Media error (code ${i.code})`,cause:i})},{signal:e}),t.addEventListener("enterpictureinpicture",()=>this.emitter.emit("pipchange",{active:!0}),{signal:e}),t.addEventListener("leavepictureinpicture",()=>this.emitter.emit("pipchange",{active:!1}),{signal:e}),document.addEventListener("fullscreenchange",()=>{this.emitter.emit("fullscreenchange",{active:this.isFullscreen}),this.container.classList.toggle("imp-player--fullscreen",this.isFullscreen)},{signal:e})}async handleEnded(){if(this.emitter.emit("ended",void 0),this.showControlsNow(),!(this.adManager&&(await this.adManager.playPostRoll(),this.destroyed))){if(this.autoAdvanceEnabled&&this.hasNext){this.next();return}if(!this.autoAdvanceEnabled&&this.hasNext){this.upNext.show();return}(this.options.related?.showOn?.includes("ended")??!!this.options.related)&&this.related.show()}}get autoAdvance(){return this.autoAdvanceEnabled}setAutoAdvance(e){this.autoAdvanceEnabled=e,e&&this.upNext.hide(),this.persistAutoAdvance&&this.persistState()}bindIdleHide(){const{signal:e}=this.abort,t=()=>{this.showControlsNow(),this.scheduleIdle()};this.container.addEventListener("pointermove",i=>{i.pointerType!=="touch"&&t()},{signal:e}),this.container.addEventListener("pointerdown",i=>{i.pointerType!=="touch"&&t()},{signal:e}),this.container.addEventListener("keydown",t,{signal:e}),this.container.addEventListener("pointerleave",i=>{i.pointerType!=="touch"&&(this.video.paused||this.container.classList.add("imp-player--idle"))},{signal:e})}showControlsNow(){this.container.classList.remove("imp-player--idle")}scheduleIdle(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{!this.video.paused&&!this.destroyed&&this.container.classList.add("imp-player--idle")},this.controlsOptions.hideDelay)}bindKeyboard(){this.container.addEventListener("keydown",e=>{const t=e.target;if(t.closest("input, select, textarea, [contenteditable]"))return;const s=t.closest("button")!==null;switch(e.key){case" ":case"k":if(e.key===" "&&s)return;e.preventDefault(),this.togglePlay();break;case"ArrowLeft":e.preventDefault(),this.skip(-this.seekStep);break;case"ArrowRight":e.preventDefault(),this.skip(this.seekStep);break;case"ArrowUp":e.preventDefault(),this.setVolume(this.volume+.1);break;case"ArrowDown":e.preventDefault(),this.setVolume(this.volume-.1);break;case"m":this.toggleMute();break;case"f":this.toggleFullscreen();break;case"Home":this.seek(0);break;case"End":this.seek(this.duration);break;default:/^[0-9]$/.test(e.key)&&Number.isFinite(this.video.duration)&&this.seek(Number(e.key)/10*this.video.duration)}},{signal:this.abort.signal})}}return J({en:C,ru:{play:"Воспроизвести",pause:"Пауза",replay:"Смотреть снова",mute:"Выключить звук",unmute:"Включить звук",fullscreen:"Во весь экран",exitFullscreen:"Выйти из полноэкранного режима",pip:"Картинка в картинке",settings:"Скорость воспроизведения",subtitles:"Субтитры",subtitlesOff:"Выкл.",speed:"Скорость",quality:"Качество",qualityAuto:"Авто",next:"Следующее",nextVideo:"Следующее видео",previous:"Предыдущее",playlist:"Плейлист",scenes:"Сцены",sceneTypes:"Тип сцен",autoplay:"Автовоспроизведение",playNext:"Играть дальше",shuffle:"Перемешать",repeat:"Повтор",like:"Нравится",dislike:"Не нравится",addTo:"Сохранить в…",share:"Поделиться",report:"Пожаловаться",more:"Ещё",seekForward:"Перемотать вперёд",seekBack:"Перемотать назад",secondsShort:"с",live:"В ЭФИРЕ",related:"Похожие видео",adLabel:"Реклама",skipAd:"Пропустить рекламу",skipAdIn:"Пропуск через",visitAdvertiser:"Перейти к рекламодателю",sponsored:"Спонсор"},de:{play:"Wiedergabe",pause:"Pause",replay:"Erneut abspielen",mute:"Stummschalten",unmute:"Ton einschalten",fullscreen:"Vollbild",exitFullscreen:"Vollbild beenden",pip:"Bild im Bild",settings:"Wiedergabegeschwindigkeit",subtitles:"Untertitel",subtitlesOff:"Aus",speed:"Geschwindigkeit",quality:"Qualität",qualityAuto:"Automatisch",next:"Weiter",nextVideo:"Nächstes Video",previous:"Zurück",playlist:"Playlist",scenes:"Szenen",sceneTypes:"Szenentyp",autoplay:"Autoplay",playNext:"Weiter abspielen",shuffle:"Zufallswiedergabe",repeat:"Wiederholen",like:"Mag ich",dislike:"Mag ich nicht",addTo:"Speichern in…",share:"Teilen",report:"Melden",more:"Weitere Aktionen",seekForward:"Vorspulen",seekBack:"Zurückspulen",secondsShort:"s",live:"LIVE",related:"Weitere Videos",adLabel:"Anzeige",skipAd:"Werbung überspringen",skipAdIn:"Überspringen in",visitAdvertiser:"Zum Werbetreibenden",sponsored:"Gesponsert"},es:{play:"Reproducir",pause:"Pausa",replay:"Volver a reproducir",mute:"Silenciar",unmute:"Activar sonido",fullscreen:"Pantalla completa",exitFullscreen:"Salir de pantalla completa",pip:"Imagen en imagen",settings:"Velocidad de reproducción",subtitles:"Subtítulos",subtitlesOff:"Desactivados",speed:"Velocidad",quality:"Calidad",qualityAuto:"Automática",next:"Siguiente",nextVideo:"Siguiente vídeo",previous:"Anterior",playlist:"Lista de reproducción",scenes:"Escenas",sceneTypes:"Tipo de escena",autoplay:"Reproducción automática",playNext:"Reproducir siguiente",shuffle:"Aleatorio",repeat:"Repetir",like:"Me gusta",dislike:"No me gusta",addTo:"Guardar en…",share:"Compartir",report:"Denunciar",more:"Más acciones",seekForward:"Avanzar",seekBack:"Retroceder",secondsShort:"s",live:"EN VIVO",related:"Más vídeos",adLabel:"Anuncio",skipAd:"Omitir anuncio",skipAdIn:"Omitir en",visitAdvertiser:"Visitar al anunciante",sponsored:"Patrocinado"},it:{play:"Riproduci",pause:"Pausa",replay:"Riproduci di nuovo",mute:"Disattiva audio",unmute:"Attiva audio",fullscreen:"Schermo intero",exitFullscreen:"Esci da schermo intero",pip:"Picture-in-picture",settings:"Velocità di riproduzione",subtitles:"Sottotitoli",subtitlesOff:"Disattivati",speed:"Velocità",quality:"Qualità",qualityAuto:"Automatica",next:"Successivo",nextVideo:"Prossimo video",previous:"Precedente",playlist:"Playlist",scenes:"Scene",sceneTypes:"Tipo di scena",autoplay:"Riproduzione automatica",playNext:"Riproduci successivo",shuffle:"Casuale",repeat:"Ripeti",like:"Mi piace",dislike:"Non mi piace",addTo:"Salva in…",share:"Condividi",report:"Segnala",more:"Altre azioni",seekForward:"Avanti veloce",seekBack:"Indietro",secondsShort:"s",live:"LIVE",related:"Altri video",adLabel:"Annuncio",skipAd:"Salta annuncio",skipAdIn:"Salta tra",visitAdvertiser:"Visita l'inserzionista",sponsored:"Sponsorizzato"},ja:{play:"再生",pause:"一時停止",replay:"もう一度見る",mute:"ミュート",unmute:"ミュート解除",fullscreen:"全画面",exitFullscreen:"全画面を終了",pip:"ピクチャーインピクチャー",settings:"再生速度",subtitles:"字幕",subtitlesOff:"オフ",speed:"速度",quality:"画質",qualityAuto:"自動",next:"次へ",nextVideo:"次の動画",previous:"前へ",playlist:"プレイリスト",scenes:"シーン",sceneTypes:"シーンタイプ",autoplay:"自動再生",playNext:"次を再生",shuffle:"シャッフル",repeat:"リピート",like:"高く評価",dislike:"低く評価",addTo:"保存…",share:"共有",report:"報告",more:"その他の操作",seekForward:"早送り",seekBack:"巻き戻し",secondsShort:"秒",live:"ライブ",related:"関連動画",adLabel:"広告",skipAd:"広告をスキップ",skipAdIn:"スキップまで",visitAdvertiser:"広告主のサイトへ",sponsored:"スポンサー"},ko:{play:"재생",pause:"일시정지",replay:"다시 보기",mute:"음소거",unmute:"음소거 해제",fullscreen:"전체화면",exitFullscreen:"전체화면 종료",pip:"PIP 모드",settings:"재생 속도",subtitles:"자막",subtitlesOff:"사용 안 함",speed:"속도",quality:"화질",qualityAuto:"자동",next:"다음",nextVideo:"다음 동영상",previous:"이전",playlist:"재생목록",scenes:"장면",sceneTypes:"장면 유형",autoplay:"자동 재생",playNext:"다음 재생",shuffle:"셔플",repeat:"반복",like:"좋아요",dislike:"싫어요",addTo:"저장…",share:"공유",report:"신고",more:"더보기",seekForward:"앞으로 감기",seekBack:"뒤로 감기",secondsShort:"초",live:"실시간",related:"관련 동영상",adLabel:"광고",skipAd:"광고 건너뛰기",skipAdIn:"건너뛰기까지",visitAdvertiser:"광고주 방문",sponsored:"스폰서"},zh:{play:"播放",pause:"暂停",replay:"重新播放",mute:"静音",unmute:"取消静音",fullscreen:"全屏",exitFullscreen:"退出全屏",pip:"画中画",settings:"播放速度",subtitles:"字幕",subtitlesOff:"关闭",speed:"速度",quality:"画质",qualityAuto:"自动",next:"下一个",nextVideo:"下一个视频",previous:"上一个",playlist:"播放列表",scenes:"场景",sceneTypes:"场景类型",autoplay:"自动播放",playNext:"播放下一个",shuffle:"随机播放",repeat:"循环播放",like:"赞",dislike:"踩",addTo:"保存到…",share:"分享",report:"举报",more:"更多操作",seekForward:"快进",seekBack:"快退",secondsShort:"秒",live:"直播",related:"更多视频",adLabel:"广告",skipAd:"跳过广告",skipAdIn:"可跳过",visitAdvertiser:"访问广告主",sponsored:"赞助"},pt:{play:"Reproduzir",pause:"Pausar",replay:"Assistir novamente",mute:"Sem som",unmute:"Ativar som",fullscreen:"Tela cheia",exitFullscreen:"Sair da tela cheia",pip:"Picture-in-picture",settings:"Velocidade de reprodução",subtitles:"Legendas",subtitlesOff:"Desativadas",speed:"Velocidade",quality:"Qualidade",qualityAuto:"Automática",next:"Próximo",nextVideo:"Próximo vídeo",previous:"Anterior",playlist:"Playlist",scenes:"Cenas",sceneTypes:"Tipo de cena",autoplay:"Reprodução automática",playNext:"Reproduzir próximo",shuffle:"Aleatório",repeat:"Repetir",like:"Gostei",dislike:"Não gostei",addTo:"Salvar em…",share:"Compartilhar",report:"Denunciar",more:"Mais ações",seekForward:"Avançar",seekBack:"Retroceder",secondsShort:"s",live:"AO VIVO",related:"Mais vídeos",adLabel:"Anúncio",skipAd:"Pular anúncio",skipAdIn:"Pular em",visitAdvertiser:"Visitar anunciante",sponsored:"Patrocinado"},ar:{play:"تشغيل",pause:"إيقاف مؤقت",replay:"إعادة التشغيل",mute:"كتم الصوت",unmute:"إلغاء كتم الصوت",fullscreen:"ملء الشاشة",exitFullscreen:"الخروج من ملء الشاشة",pip:"صورة داخل صورة",settings:"سرعة التشغيل",subtitles:"الترجمة",subtitlesOff:"إيقاف",speed:"السرعة",quality:"الجودة",qualityAuto:"تلقائي",next:"التالي",nextVideo:"الفيديو التالي",previous:"السابق",playlist:"قائمة التشغيل",scenes:"المشاهد",sceneTypes:"نوع المشهد",autoplay:"تشغيل تلقائي",playNext:"تشغيل التالي",shuffle:"تشغيل عشوائي",repeat:"تكرار",like:"أعجبني",dislike:"لم يعجبني",addTo:"حفظ في…",share:"مشاركة",report:"إبلاغ",more:"المزيد من الإجراءات",seekForward:"تقديم",seekBack:"إرجاع",secondsShort:"ث",live:"مباشر",related:"المزيد من الفيديوهات",adLabel:"إعلان",skipAd:"تخطي الإعلان",skipAdIn:"التخطي بعد",visitAdvertiser:"زيارة المعلن",sponsored:"برعاية"},hi:{play:"चलाएं",pause:"रोकें",replay:"फिर से चलाएं",mute:"म्यूट करें",unmute:"अनम्यूट करें",fullscreen:"फ़ुल स्क्रीन",exitFullscreen:"फ़ुल स्क्रीन से बाहर निकलें",pip:"पिक्चर-इन-पिक्चर",settings:"प्लेबैक गति",subtitles:"सबटाइटल",subtitlesOff:"बंद",speed:"गति",quality:"क्वालिटी",qualityAuto:"ऑटो",next:"अगला",nextVideo:"अगला वीडियो",previous:"पिछला",playlist:"प्लेलिस्ट",scenes:"दृश्य",sceneTypes:"सीन प्रकार",autoplay:"ऑटोप्ले",playNext:"अगला चलाएं",shuffle:"शफ़ल",repeat:"दोहराएं",like:"पसंद",dislike:"नापसंद",addTo:"इसमें सहेजें…",share:"साझा करें",report:"रिपोर्ट करें",more:"अधिक कार्रवाइयां",seekForward:"आगे बढ़ाएं",seekBack:"पीछे करें",secondsShort:"s",live:"लाइव",related:"और वीडियो",adLabel:"विज्ञापन",skipAd:"विज्ञापन छोड़ें",skipAdIn:"छोड़ें",visitAdvertiser:"विज्ञापनदाता देखें",sponsored:"प्रायोजित"}}),Se})();
3
+ `).filter(m=>m.trim()!=="");if(s.length===0)continue;let n=s.findIndex(m=>m.includes("-->"));if(n===-1)continue;const[r,a]=s[n].split("-->"),h=P(r),c=P((a??"").split(" ")[1]??a??"")??P(a??"");if(h===null||c===null)continue;const u=s.slice(n+1).join(`
4
+ `).trim();u&&e.push({start:h,end:c,text:u})}return e}function K(l,e){try{return new URL(l,new URL(e,window.location.href)).toString()}catch{return l}}class X{constructor(){this.listeners=new Map}on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>this.off(e,t)}once(e,t){const i=this.on(e,s=>{i(),t(s)});return i}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){const i=this.listeners.get(e);if(i)for(const s of[...i])try{s(t)}catch(n){console.error("[itube-player] listener error",n)}}removeAll(){this.listeners.clear()}}const p=(l,e="0 0 24 24")=>`<svg viewBox="${e}" fill="currentColor" aria-hidden="true" focusable="false">${l}</svg>`,J={play:p('<path d="M8 5.14v13.72c0 .8.87 1.3 1.56.88l10.54-6.86a1.05 1.05 0 0 0 0-1.76L9.56 4.26C8.87 3.84 8 4.34 8 5.14Z"/>'),pause:p('<rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/>'),replay:p('<path d="M12 5V2.5L7.5 6 12 9.5V7a5 5 0 1 1-5 5H5a7 7 0 1 0 7-7Z"/>'),bigPlay:p('<path d="M8 5.14v13.72c0 .8.87 1.3 1.56.88l10.54-6.86a1.05 1.05 0 0 0 0-1.76L9.56 4.26C8.87 3.84 8 4.34 8 5.14Z"/>'),volumeHigh:p('<path d="M4 9v6h3.5L12 19.5v-15L7.5 9H4Z"/><path d="M14.5 8.6a4.5 4.5 0 0 1 0 6.8v-1.9a2.5 2.5 0 0 0 0-3v-1.9Z"/><path d="M14.5 5.2a8 8 0 0 1 0 13.6v-2a6 6 0 0 0 0-9.6v-2Z"/>'),volumeLow:p('<path d="M4 9v6h3.5L12 19.5v-15L7.5 9H4Z"/><path d="M14.5 8.6a4.5 4.5 0 0 1 0 6.8v-1.9a2.5 2.5 0 0 0 0-3v-1.9Z"/>'),volumeMute:p('<path d="M4 9v6h3.5L12 19.5v-15L7.5 9H4Z"/><path d="m15.3 9.3 1.4 1.4 1.4-1.4 1.4 1.4-1.4 1.4 1.4 1.4-1.4 1.4-1.4-1.4-1.4 1.4-1.4-1.4 1.4-1.4-1.4-1.4 1.4-1.4Z"/>'),fullscreen:p('<path d="M5 5h5v2H7v3H5V5Zm9 0h5v5h-2V7h-3V5ZM5 14h2v3h3v2H5v-5Zm12 0h2v5h-5v-2h3v-3Z"/>'),fullscreenExit:p('<path d="M10 10H5V8h3V5h2v5Zm4 0V5h2v3h3v2h-5Zm-4 4v5H8v-3H5v-2h5Zm4 0h5v2h-3v3h-2v-5Z"/>'),pip:p('<path d="M3 5h18v14H3V5Zm2 2v10h14V7H5Z"/><rect x="12" y="11" width="6" height="4"/>'),settings:p('<path d="M12 8.5A3.5 3.5 0 1 0 12 15.5 3.5 3.5 0 0 0 12 8.5Zm0 2a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3Z"/><path d="M10.3 2.8 9.9 5.1a7 7 0 0 0-1.5.86l-2.2-.8-1.7 3 1.8 1.5a7 7 0 0 0 0 1.7l-1.8 1.5 1.7 3 2.2-.8c.46.36.97.65 1.5.86l.4 2.3h3.4l.4-2.3a7 7 0 0 0 1.5-.86l2.2.8 1.7-3-1.8-1.5a7 7 0 0 0 0-1.7l1.8-1.5-1.7-3-2.2.8a7 7 0 0 0-1.5-.86l-.4-2.3h-3.4Zm1.7 5.7a3.5 3.5 0 1 1 0 7 3.5 3.5 0 0 1 0-7Z"/>'),speed:p('<path d="M12 4a9 9 0 0 0-9 9 8.96 8.96 0 0 0 1.62 5.16l1.64-1.15A7 7 0 0 1 5 13a7 7 0 1 1 12.74 4.01l1.64 1.15A8.96 8.96 0 0 0 21 13a9 9 0 0 0-9-9Z"/><path d="m15.6 8.3-3.95 3.13a1.5 1.5 0 1 0 1.92 1.92L16.7 9.4a.78.78 0 0 0-1.1-1.1Z"/>'),scenes:p('<path d="M3 5h18v14H3V5Zm2 2v10h3V7H5Zm5 0v10h9V7h-9Zm-5 3h3v1H5v-1Zm0 3h3v1H5v-1Z"/>'),shuffle:p('<path d="M4 6h2.6c1.5 0 2.9.7 3.8 1.9l4.1 5.4a2.75 2.75 0 0 0 2.2 1.1H19l-1.8-1.8 1.4-1.4 4.2 4.2-4.2 4.2-1.4-1.4L19 16.4h-2.3a4.75 4.75 0 0 1-3.8-1.9L8.8 9.1A2.75 2.75 0 0 0 6.6 8H4V6Z"/><path d="M19 7.6h-2.3c-.86 0-1.67.41-2.18 1.1l-.93 1.23-1.25-1.65.58-.77A4.75 4.75 0 0 1 16.7 5.6H19L17.2 3.8l1.4-1.4 4.2 4.2-4.2 4.2-1.4-1.4L19 7.6Z" transform="translate(0 1.2)"/>'),repeat:p('<path d="M7 7h10v2.5L21 6l-4-3.5V5H5v6h2V7Zm10 10H7v-2.5L3 18l4 3.5V19h12v-6h-2v4Z"/>'),subtitles:p('<path d="M3 5h18v14H3V5Zm2 2v10h14V7H5Zm2 3h6v2H7v-2Zm8 0h2v2h-2v-2ZM7 14h2v2H7v-2Zm4 0h6v2h-6v-2Z"/>'),list:p('<path d="M4 6h2v2H4V6Zm4 0h12v2H8V6ZM4 11h2v2H4v-2Zm4 0h12v2H8v-2ZM4 16h2v2H4v-2Zm4 0h12v2H8v-2Z"/>'),next:p('<path d="M6 5.5v13c0 .77.84 1.25 1.5.85l9-6.5a1 1 0 0 0 0-1.7l-9-6.5c-.66-.4-1.5.08-1.5.85Z"/><rect x="17" y="5" width="2.5" height="14" rx="1"/>'),previous:p('<path d="M18 5.5v13c0 .77-.84 1.25-1.5.85l-9-6.5a1 1 0 0 1 0-1.7l9-6.5c.66-.4 1.5.08 1.5.85Z"/><rect x="4.5" y="5" width="2.5" height="14" rx="1"/>'),seekForward:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>',seekBack:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg>',like:p('<path d="M9 21H5a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h4v11Zm2 0h7.1a2 2 0 0 0 2-1.6l1.3-7a2 2 0 0 0-2-2.4H14V5.5A2.5 2.5 0 0 0 11.5 3l-.5.1V10h-.9L11 21Z"/>'),dislike:p('<path d="M15 3h4a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2h-4V3Zm-2 0H5.9a2 2 0 0 0-2 1.6l-1.3 7a2 2 0 0 0 2 2.4H10v4.5A2.5 2.5 0 0 0 12.5 21l.5-.1V14h.9L13 3Z"/>'),addTo:p('<path d="M4 6h12v2H4V6Zm0 4h12v2H4v-2Zm0 4h8v2H4v-2Zm14 0v-4h2v4h4v2h-4v4h-2v-4h-4v-2h4Z"/>'),share:p('<path d="M18 8a3 3 0 1 0-2.83-4H15a3 3 0 0 0 .14 1.06L8.4 8.94a3 3 0 1 0 0 6.12l6.74 3.88A3 3 0 1 0 16 16.6l-6.74-3.88a3.03 3.03 0 0 0 0-1.44L16 7.4c.55.38 1.24.6 2 .6Z"/>'),report:p('<path d="M5 3h2v18H5V3Zm4 1h10l-2.5 4L19 12H9V4Z"/>'),more:p('<circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/>'),close:p('<path d="m6.4 5 5.6 5.6L17.6 5 19 6.4 13.4 12l5.6 5.6-1.4 1.4-5.6-5.6L6.4 19 5 17.6 10.6 12 5 6.4 6.4 5Z"/>'),user:p('<path d="M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm0 2c-3.6 0-8 1.8-8 4.4V21h16v-2.6c0-2.6-4.4-4.4-8-4.4Z"/>'),channel:p('<path d="M3 5h18a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm7 3.5v7l6-3.5-6-3.5Z"/>')},C={play:"Play",pause:"Pause",replay:"Replay",mute:"Mute",unmute:"Unmute",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",pip:"Picture-in-picture",settings:"Playback speed",scenes:"Scenes",sceneTypes:"Scene type",autoplay:"Autoplay",playNext:"Play next",shuffle:"Shuffle",repeat:"Repeat",subtitles:"Subtitles",subtitlesOff:"Off",speed:"Speed",quality:"Quality",qualityAuto:"Auto",next:"Next",nextVideo:"Next video",previous:"Previous",playlist:"Playlist",like:"Like",dislike:"Dislike",addTo:"Save to…",share:"Share",report:"Report",more:"More actions",seekForward:"Seek forward",seekBack:"Seek back",secondsShort:"s",live:"LIVE",related:"More videos",adLabel:"Ad",skipAd:"Skip ad",skipAdIn:"Skip in",visitAdvertiser:"Visit advertiser",sponsored:"Sponsored"},O={en:C};function Y(l){for(const[e,t]of Object.entries(l))t&&(O[e]=t)}function ee(l){return l&&O[l]||C}function te(l,e,t=100){if(l.length===0||!Number.isFinite(e)||e<=0)return[];const i=new Array(t).fill(0);let s=!1;for(const c of l){if(!Number.isFinite(c.time)||c.time<0||c.time>e)continue;const u=Math.max(0,c.value);if(u===0)continue;const m=Math.min(t-1,Math.floor(c.time/e*t));i[m]+=u,s=!0}if(!s)return[];const n=[.06,.24,.4,.24,.06],r=i.map((c,u)=>n.reduce((m,f,v)=>m+f*(i[u+v-2]??0),0)),a=Math.max(...r);if(a<=0)return[];const h=.08;return r.map(c=>h+(1-h)*(c/a))}function ie(l,e=1e3,t=100){if(l.length===0)return"";const i=e/(l.length-1||1);let s=`M 0 ${t}`;return l.forEach((n,r)=>{s+=` L ${(r*i).toFixed(1)} ${(t-n*t).toFixed(1)}`}),s+=` L ${e} ${t} Z`,s}async function se(l,e){if(l.src)return{roll:l.roll,mediaUrl:l.src,clickThrough:l.clickUrl,impressions:[],tracking:{}};if(!l.vastTag)throw new Error('Ad roll has neither "vastTag" nor "src"');return H(l,l.vastTag,e,0,{impressions:[],tracking:{}})}async function H(l,e,t,i,s){if(i>t.maxWrapperDepth)throw new Error("VAST wrapper depth limit exceeded");const n=new AbortController,r=setTimeout(()=>n.abort(),t.requestTimeout);let a;try{const g=await fetch(e,{signal:n.signal,credentials:"omit"});if(!g.ok)throw new Error(`VAST request failed (${g.status})`);a=await g.text()}finally{clearTimeout(r)}const h=new DOMParser().parseFromString(a,"text/xml");if(h.querySelector("parsererror"))throw new Error("VAST response is not valid XML");const c=h.querySelector("VAST > Ad");if(!c)throw new Error("VAST response contains no ads");ne(c,s);const u=c.querySelector(":scope > Wrapper");if(u){const g=S(u.querySelector("VASTAdTagURI"));if(!g)throw new Error("VAST wrapper without VASTAdTagURI");return H(l,g,t,i+1,s)}const m=c.querySelector(":scope > InLine");if(!m)throw new Error("VAST ad has neither InLine nor Wrapper");const f=m.querySelector("Creatives > Creative > Linear");if(!f)throw new Error("VAST ad has no Linear creative");const v=re(f);if(!v)throw new Error("VAST ad has no playable MediaFile");return{roll:l.roll,mediaUrl:v.url,mediaType:v.type,clickThrough:S(f.querySelector("VideoClicks > ClickThrough"))??l.clickUrl,duration:V(S(f.querySelector(":scope > Duration"))),skipOffset:oe(f.getAttribute("skipoffset"),V(S(f.querySelector(":scope > Duration")))),impressions:s.impressions,tracking:s.tracking,adTitle:S(m.querySelector(":scope > AdTitle"))??void 0}}function ne(l,e){var t,i;for(const s of l.querySelectorAll("Impression")){const n=S(s);n&&e.impressions.push(n)}for(const s of l.querySelectorAll("Linear > TrackingEvents > Tracking")){const n=s.getAttribute("event"),r=S(s);!n||!r||["start","firstQuartile","midpoint","thirdQuartile","complete","skip","pause","resume"].includes(n)&&((t=e.tracking)[n]??(t[n]=[])).push(r)}for(const s of l.querySelectorAll("Linear > VideoClicks > ClickTracking")){const n=S(s);n&&((i=e.tracking).click??(i.click=[])).push(n)}}function re(l){const t=[...l.querySelectorAll("MediaFiles > MediaFile")].map(r=>({url:S(r)??"",type:r.getAttribute("type")??void 0,delivery:r.getAttribute("delivery")??"",bitrate:Number(r.getAttribute("bitrate")??0),apiFramework:r.getAttribute("apiFramework")??""})).filter(r=>r.url&&r.apiFramework.toUpperCase()!=="VPAID").filter(r=>!r.type||/(video\/(mp4|webm|ogg)|application\/(x-mpegurl|vnd\.apple\.mpegurl))/i.test(r.type));if(t.length===0)return null;t.sort((r,a)=>r.bitrate-a.bitrate);const i=t.filter(r=>r.delivery!=="streaming"),s=i.length>0?i:t,n=s[Math.floor(s.length/2)];return{url:n.url,type:n.type}}function V(l){if(!l)return;const e=l.trim().match(/^(?:(\d+):)?(\d{1,2}):(\d{2})(?:\.(\d{1,3}))?$/);if(e)return(e[1]?Number(e[1])*3600:0)+Number(e[2])*60+Number(e[3])+(e[4]?Number(e[4].padEnd(3,"0"))/1e3:0)}function oe(l,e){if(!l)return;const t=l.trim().match(/^(\d+(?:\.\d+)?)%$/);return t?e!==void 0?Number(t[1])/100*e:void 0:V(l)}function E(l){if(l)for(const e of l)try{new Image().src=e}catch{}}function S(l){return l?.textContent?.trim().replace(/^<!\[CDATA\[|\]\]>$/g,"").trim()||null}class ae{constructor(e,t){this.host=e,this.playedRolls=new Set,this.sourcesSeen=0,this.activeBreak=null,this.layer=null,this.adVideo=null,this.destroyed=!1,this.opts={skipDelay:5,maxWrapperDepth:3,requestTimeout:8e3,mediaTimeout:1e4,playOn:"every",...t}}ensureAdVideo(){if(!this.adVideo){this.adVideo=o("video","imp-ad__video",{playsinline:""});try{this.adVideo.load()}catch{}}return this.adVideo}get adPlaying(){return this.activeBreak!==null}get hasPendingPreRoll(){return this.pending("preRoll").length>0}resetForNewSource(){if(this.sourcesSeen++,this.opts.playOn==="first"&&this.sourcesSeen>1){for(const e of this.opts.adList)this.playedRolls.add(e);return}this.playedRolls.clear()}async playPreRoll(){await this.playRolls(this.pending("preRoll"))}async playPostRoll(){await this.playRolls(this.pending("postRoll"))}checkMidRolls(e){if(this.adPlaying)return;const t=this.pending("midRoll").filter(i=>i.timer!==void 0&&e>=i.timer);t.length>0&&this.playRolls(t)}pending(e){return this.opts.adList.filter(t=>t.roll===e&&!this.playedRolls.has(t))}async playRolls(e){if(e.length===0||this.destroyed)return;if(this.activeBreak)return this.activeBreak;this.ensureAdVideo();const t=(async()=>{const i=this.host.contentVideo,s=!i.paused&&!i.ended;i.pause();for(const n of e){this.playedRolls.add(n);try{const r=await se(n,this.opts);await this.playAd(r)}catch(r){const a=r instanceof Error?r:new Error(String(r));this.host.emitter.emit("aderror",{roll:n,error:a})}if(this.destroyed)return}(s||e[0].roll==="preRoll")&&i.play().catch(()=>{})})();return this.activeBreak=t.finally(()=>{this.activeBreak=null}),this.activeBreak}playAd(e){return new Promise(t=>{const{labels:i}=this.host,s=o("div","imp-ad"),n=this.ensureAdVideo(),r=new AbortController,a=r.signal;n.src=e.mediaUrl,n.muted=this.host.contentVideo.muted,n.volume=this.host.contentVideo.volume;const h=o("div","imp-spinner imp-ad__spinner"),c=o("div","imp-ad__hud"),u=o("span","imp-ad__badge");u.textContent=e.adTitle?`${i.adLabel} · ${e.adTitle}`:i.adLabel;const m=o("span","imp-ad__countdown");c.append(u,m);const f=o("div","imp-ad__actions");let v=null;e.clickThrough&&(v=o("button","imp-ad__visit",{type:"button"}),v.textContent=i.visitAdvertiser,f.append(v));const g=o("button","imp-ad__skip",{type:"button"});g.hidden=!0,f.append(g),s.append(n,h,c,f),this.host.container.append(s),this.layer=s;const B=e.skipOffset??this.opts.skipDelay,d=new Set,b=k=>{d.has(k)||(d.add(k),E(e.tracking[k]))};let N=Date.now(),z=-1;const _e=setInterval(()=>{if(n.paused){N=Date.now();return}if(n.currentTime!==z){z=n.currentTime,N=Date.now();return}Date.now()-N>=this.opts.mediaTimeout&&(this.host.emitter.emit("aderror",{roll:{roll:e.roll},error:new Error(`Ad media stalled for ${this.opts.mediaTimeout} ms — skipping`)}),q())},500),q=()=>{clearInterval(_e),r.abort(),n.pause(),n.removeAttribute("src"),n.load(),s.remove(),this.layer=null,t()},G=k=>{k?(b("skip"),this.host.emitter.emit("adskip",{ad:e})):b("complete"),this.host.emitter.emit("adend",{ad:e}),q()};n.addEventListener("playing",()=>{E(e.impressions),b("start"),this.host.emitter.emit("adstart",{ad:e})},{once:!0,signal:a}),n.addEventListener("playing",()=>{h.hidden=!0},{signal:a}),n.addEventListener("waiting",()=>{h.hidden=!1},{signal:a}),n.addEventListener("timeupdate",()=>{const k=n.currentTime,T=n.duration;if(Number.isFinite(T)&&T>0&&(m.textContent=x(Math.max(0,T-k)),k/T>=.25&&b("firstQuartile"),k/T>=.5&&b("midpoint"),k/T>=.75&&b("thirdQuartile")),B>=0){const j=Math.ceil(B-k);j>0?(g.hidden=!1,g.disabled=!0,g.textContent=`${i.skipAdIn} ${j}`):(g.hidden=!1,g.disabled=!1,g.textContent=i.skipAd)}},{signal:a}),n.addEventListener("ended",()=>G(!1),{signal:a}),n.addEventListener("error",()=>{this.host.emitter.emit("aderror",{roll:{roll:e.roll},error:new Error("Ad media failed to play")}),q()},{signal:a}),g.addEventListener("click",()=>G(!0));const Q=()=>{e.clickThrough&&(b("click"),this.host.emitter.emit("adclick",{ad:e}),window.open(e.clickThrough,"_blank","noopener"),n.pause())};n.addEventListener("click",Q,{signal:a}),v?.addEventListener("click",Q);let U=!1,M=!1;n.addEventListener("playing",()=>{U=!0},{once:!0,signal:a}),n.addEventListener("pause",()=>{n.ended||!s.isConnected||(s.classList.add("imp-ad--paused"),U&&!M&&(M=!0,E(e.tracking.pause),this.host.emitter.emit("adpause",{ad:e})))},{signal:a}),n.addEventListener("play",()=>{s.classList.remove("imp-ad--paused"),M&&(M=!1,E(e.tracking.resume),this.host.emitter.emit("adresume",{ad:e}))},{signal:a}),s.addEventListener("click",k=>{(k.target===s||s.classList.contains("imp-ad--paused"))&&n.paused&&n.play().catch(()=>{})}),n.play().catch(()=>{s.classList.add("imp-ad--paused")})})}get closeIcon(){return this.host.closeIcon}destroy(){this.destroyed=!0,this.adVideo?.pause(),this.layer?.remove(),this.layer=null,this.adVideo=null}}function Z(l,e){const t=[...l].sort((s,n)=>s.start-n.start),i=[];for(let s=0;s<t.length;s++){const n=Math.max(0,t[s].start);if(Number.isFinite(e)&&n>=e)continue;let r=t[s].end??t[s+1]?.start??e;Number.isFinite(e)&&(r=Math.min(r,e)),!(r<=n)&&i.push({start:n,end:r,title:t[s].title})}return i}async function le(l){const e=await fetch(l);if(!e.ok)throw new Error(`Failed to load chapters VTT (${e.status})`);const t=await e.text();return $(t).map(i=>({start:i.start,end:i.end,title:i.text}))}function D(l,e){for(const t of l)if(e>=t.start&&e<t.end)return t;return null}function he(l,e){return e?/application\/(x-mpegurl|vnd\.apple\.mpegurl)/i.test(e):/\.m3u8(\?|#|$)/i.test(l)}let L;async function ce(){if(L!==void 0)return L;const l=globalThis.Hls;if(l)return L=l,L;try{L=(await import("hls.js/light")).default}catch{L=null}return L}async function de(l,e,t,i){if(he(e,t)){const s=l.canPlayType("application/vnd.apple.mpegurl"),n=s?null:await ce();return n&&n.isSupported()?ue(n,l,e,i):s?(l.src=e,I(l)):(i.onError("HLS is not supported in this browser and hls.js could not be loaded."),I(l))}return l.src=e,I(l)}function I(l){return{kind:"native",levels:[],selected:-1,setLevel(){},destroy(){l.removeAttribute("src"),l.load()}}}function ue(l,e,t,i){const s=new l({enableWorker:!0}),n={kind:"hls",levels:[],selected:-1,setLevel(h){n.selected=h,s.currentLevel=h},destroy(){s.destroy(),e.removeAttribute("src"),e.load()}};s.on(l.Events.MANIFEST_PARSED,()=>{n.levels=s.levels.map((h,c)=>({index:c,label:h.height?`${h.height}p`:`${Math.round(h.bitrate/1e3)} kbps`})).reverse(),i.onLevels(n.levels)}),s.on(l.Events.LEVEL_SWITCHED,(h,c)=>{const u=s.levels[c.level];u&&i.onLevelSwitch(u.height?`${u.height}p`:`${Math.round(u.bitrate/1e3)} kbps`)});let r=0,a=!1;return s.on(l.Events.ERROR,(h,c)=>{if(c.fatal)switch(c.type){case l.ErrorTypes.NETWORK_ERROR:s.startLoad();break;case l.ErrorTypes.MEDIA_ERROR:r<3?(r++,s.recoverMediaError()):(i.onError(`HLS media error: ${c.details}`,c),s.destroy());break;default:if(a)i.onError(`HLS fatal error: ${c.details}`,c),s.destroy();else{a=!0;try{s.loadSource(t),s.startLoad()}catch{i.onError(`HLS fatal error: ${c.details}`,c),s.destroy()}}}}),s.loadSource(t),s.attachMedia(e),n}class R{constructor(e){this.cues=e}static async load(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to load thumbnails VTT (${t.status})`);const i=await t.text(),s=[];for(const n of $(i)){const[r,a]=n.text.trim().split("#");if(!r)continue;const h={start:n.start,end:n.end,src:K(r,e)},c=a?.match(/xywh=(\d+),(\d+),(\d+),(\d+)/);c&&(h.xywh={x:Number(c[1]),y:Number(c[2]),w:Number(c[3]),h:Number(c[4])}),s.push(h)}return s.sort((n,r)=>n.start-r.start),new R(s)}cueAt(e){let t=0,i=this.cues.length-1;for(;t<=i;){const s=t+i>>1,n=this.cues[s];if(e<n.start)i=s-1;else if(e>=n.end)t=s+1;else return n}return null}}const pe='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 6 6 6-6 6"/></svg>',me='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 6-6 6 6 6"/></svg>';class _{constructor(e){this.anchor=e,this.outsideListener=null,this.root=o("div","imp-menu"),this.root.hidden=!0,this.backdrop=o("div","imp-menu__backdrop"),this.backdrop.hidden=!0,this.backdrop.addEventListener("pointerdown",t=>{t.preventDefault(),this.close()}),e.append(this.backdrop)}get open(){return!this.root.hidden}toggle(e){this.open?this.close():this.show(e)}show(e){this.root.textContent="";for(const t of e)t.items.length!==0&&this.root.append(this.renderSection(t));this.reveal()}toggleSettings(e,t){this.open?this.close():this.showSettings(e,t)}showSettings(e,t){this.root.classList.add("imp-menu--wide"),this.renderSettingsRoot(t),this.reveal()}renderSettingsRoot(e){this.root.textContent="";const t=o("div","imp-menu__section");for(const i of e){if(i.toggle){t.append(this.buildToggleRow(i,i.toggle));continue}const s=o("button","imp-menu__item imp-menu__row",{type:"button"}),n=o("span","imp-menu__label");n.textContent=i.label;const r=o("span","imp-menu__value");r.textContent=i.value??"";const a=o("span","imp-menu__chevron");a.innerHTML=pe,s.append(n,r,a),s.addEventListener("click",()=>this.renderSettingsDetail(e,i)),t.append(s)}this.root.append(t)}buildToggleRow(e,t){const i=o("button","imp-menu__item imp-menu__row imp-menu__toggle",{type:"button",role:"switch","aria-checked":String(t.value)}),s=o("span","imp-menu__label");s.textContent=e.label;const n=o("span","imp-switch");return n.append(o("span","imp-switch__knob")),i.classList.toggle("imp-menu__toggle--on",t.value),i.append(s,n),i.addEventListener("click",()=>{const r=i.getAttribute("aria-checked")!=="true";i.setAttribute("aria-checked",String(r)),i.classList.toggle("imp-menu__toggle--on",r),t.onChange(r)}),i}renderSettingsDetail(e,t){if(!t.section)return;this.root.textContent="";const i=o("button","imp-menu__item imp-menu__back",{type:"button"}),s=o("span","imp-menu__chevron");s.innerHTML=me;const n=o("span","imp-menu__label");n.textContent=t.label,i.append(s,n),i.addEventListener("click",()=>this.renderSettingsRoot(e)),this.root.append(i),this.root.append(this.renderSection(t.section())),this.root.scrollTop=0}renderSection(e){const t=o("div","imp-menu__section");if(e.title){const i=o("div","imp-menu__title");i.textContent=e.title,t.append(i)}for(const i of e.items){const s=o("button","imp-menu__item",{type:"button",role:"menuitemradio"});if(s.setAttribute("aria-checked",String(i.active)),i.active&&s.classList.add("imp-menu__item--active"),i.icon){const r=o("span","imp-menu__icon");i.icon.trimStart().startsWith("<svg")?r.innerHTML=i.icon:r.append(o("img","",{src:i.icon,alt:""})),s.append(r)}const n=o("span","imp-menu__label");n.textContent=i.label,s.append(n),s.addEventListener("click",()=>{e.onSelect(i.value),this.close()}),t.append(s)}return t}reveal(){this.root.hidden=!1,this.backdrop.hidden=!1,this.outsideListener=e=>{const t=e.target;!this.root.contains(t)&&!this.anchor.contains(t)&&this.close()},setTimeout(()=>{this.outsideListener&&document.addEventListener("pointerdown",this.outsideListener)},0)}close(){this.root.hidden=!0,this.root.classList.remove("imp-menu--wide"),this.backdrop.hidden=!0,this.outsideListener&&(document.removeEventListener("pointerdown",this.outsideListener),this.outsideListener=null)}destroy(){this.close(),this.root.remove()}}class ve{constructor(e){this.cb=e,this.segments=[],this.duration=0,this.chapters=[],this.thumbnails=null,this.scrubbing=!1,this.root=o("div","imp-progress",{role:"slider","aria-label":"Seek",tabindex:"-1"}),this.buffered=o("div","imp-progress__buffered"),this.track=o("div","imp-progress__track"),this.handle=o("div","imp-progress__handle"),this.tooltipThumb=o("div","imp-progress__thumb"),this.tooltipChapter=o("div","imp-progress__tooltip-chapter"),this.tooltipTime=o("div","imp-progress__tooltip-time"),this.tooltip=o("div","imp-progress__tooltip"),this.tooltip.append(this.tooltipThumb,this.tooltipChapter,this.tooltipTime),this.heatmap=o("div","imp-progress__heatmap"),this.heatmap.hidden=!0,this.root.append(this.heatmap,this.buffered,this.track,this.handle,this.tooltip),this.setChapters([]),this.bindPointer()}setHeatmap(e){if(e.length===0){this.heatmap.hidden=!0,this.heatmap.textContent="";return}this.heatmap.innerHTML=`<svg viewBox="0 0 1000 100" preserveAspectRatio="none" aria-hidden="true"><path d="${ie(e)}"/></svg>`,this.heatmap.hidden=!1}setDuration(e){this.duration=Number.isFinite(e)?e:0,this.root.classList.toggle("imp-progress--live",!Number.isFinite(e)),this.chapters.length===0&&this.setChapters([])}setChapters(e){this.chapters=e,this.track.textContent="",this.segments=[];const t=e.length>0?e:[{start:0,end:this.duration||1,title:""}],i=[];let s=0;for(const n of t)n.start>s&&i.push({start:s,end:n.start,title:""}),i.push(n),s=n.end;this.duration>0&&s<this.duration&&i.push({start:s,end:this.duration,title:""});for(const n of i){const r=o("div","imp-progress__segment");r.style.flexGrow=String(Math.max(n.end-n.start,.01));const a=o("div","imp-progress__fill");r.append(a),this.track.append(r),this.segments.push({chapter:n,root:r,fill:a})}}setThumbnails(e){this.thumbnails=e}update(e,t,i){if(t!==this.duration&&Number.isFinite(t)&&this.setDuration(t),this.scrubbing)return;this.render(e);const s=this.duration>0?w(i/this.duration,0,1):0;this.buffered.style.width=`${s*100}%`,this.root.setAttribute("aria-valuemin","0"),this.root.setAttribute("aria-valuemax",String(Math.round(this.duration))),this.root.setAttribute("aria-valuenow",String(Math.round(e))),this.root.setAttribute("aria-valuetext",`${x(e)} / ${x(this.duration)}`)}render(e){for(const{chapter:i,fill:s}of this.segments){const n=i.end-i.start,r=n>0?w((e-i.start)/n,0,1):0;s.style.transform=`scaleX(${r})`}const t=this.duration>0?w(e/this.duration,0,1):0;this.handle.style.left=`${t*100}%`}timeFromEvent(e){const t=this.root.getBoundingClientRect();return(t.width>0?w((e.clientX-t.left)/t.width,0,1):0)*this.duration}bindPointer(){this.root.addEventListener("pointerdown",e=>{this.duration<=0||(e.preventDefault(),this.scrubbing=!0,this.root.classList.add("imp-progress--scrubbing"),this.root.setPointerCapture(e.pointerId),this.cb.onScrubStart(),this.render(this.timeFromEvent(e)),this.showTooltip(e))}),this.root.addEventListener("pointermove",e=>{this.duration<=0||(this.showTooltip(e),this.scrubbing&&this.render(this.timeFromEvent(e)))}),this.root.addEventListener("pointerup",e=>{this.scrubbing&&(this.scrubbing=!1,this.root.classList.remove("imp-progress--scrubbing"),this.cb.onSeek(this.timeFromEvent(e)),this.cb.onScrubEnd())}),this.root.addEventListener("pointercancel",()=>{this.scrubbing=!1,this.root.classList.remove("imp-progress--scrubbing"),this.cb.onScrubEnd()}),this.root.addEventListener("pointerleave",()=>this.hideTooltip())}showTooltip(e){const t=this.timeFromEvent(e);this.tooltipTime.textContent=x(t);const i=D(this.chapters,t);this.tooltipChapter.textContent=i?.title??"",this.tooltipChapter.hidden=!i?.title;const s=this.thumbnails?.cueAt(t)??null;s?(this.tooltipThumb.hidden=!1,this.tooltipThumb.style.backgroundImage=`url("${s.src}")`,s.xywh?(this.tooltipThumb.style.width=`${s.xywh.w}px`,this.tooltipThumb.style.height=`${s.xywh.h}px`,this.tooltipThumb.style.backgroundPosition=`-${s.xywh.x}px -${s.xywh.y}px`,this.tooltipThumb.style.backgroundSize="auto"):(this.tooltipThumb.style.width="160px",this.tooltipThumb.style.height="90px",this.tooltipThumb.style.backgroundPosition="center",this.tooltipThumb.style.backgroundSize="cover")):this.tooltipThumb.hidden=!0,this.tooltip.classList.add("imp-progress__tooltip--visible");const n=this.root.getBoundingClientRect(),r=w(e.clientX-n.left,0,n.width),a=this.tooltip.offsetWidth/2;this.tooltip.style.left=`${w(r,a,Math.max(a,n.width-a))}px`}hideTooltip(){this.tooltip.classList.remove("imp-progress__tooltip--visible")}}class fe{constructor(e){this.player=e,this.rightItems=new Map,this.subtitlesBtn=null,this.settingsBtn=null,this.settingsMenu=null,this.subtitlesMenu=null,this.moreMenu=null,this.moreWrap=null,this.qualityBtn=null,this.qualityMenu=null,this.gearBtn=null,this.gearMenu=null,this.gear={speed:!1,quality:!1,subtitles:!1},this.nextPreviewEl=null,this.nextPreviewOpts=null,this.scenesBtn=null,this.sceneTypeBtn=null,this.sceneTypeMenu=null,this.likeBtn=null,this.dislikeBtn=null,this.likeCountEl=null,this.dislikeCountEl=null,this.prevBtn=null,this.nextBtn=null,this.seekBackBtn=null,this.seekFwdBtn=null,this.centerPlayBtn=null,this.centerPrevBtn=null,this.centerNextBtn=null,this.collapsibles=[],this.overflowed=new Set,this.resizeObserver=null,this.reflowScheduled=!1,this.actionItems=[],this.wasPlayingBeforeScrub=!1,this.disposers=[],this.onWindowResize=null;const{labels:t,icons:i}=e,s=e.controlsOptions;this.root=o("div","imp-controls"),this.progress=new ve({onSeek:d=>e.seek(d),onScrubStart:()=>{this.wasPlayingBeforeScrub=!e.paused,e.pause()},onScrubEnd:()=>{this.wasPlayingBeforeScrub&&e.play()}}),s.progress&&this.root.append(this.progress.root);const n=o("div","imp-controls__row");this.row=n,this.root.append(n);const r=o("div","imp-controls__group"),a=o("div","imp-controls__group");this.rightGroup=a;const h=o("div","imp-controls__spacer");this.chapterLabel=o("div","imp-controls__chapter"),n.append(r,h,a),h.append(this.chapterLabel);const c=typeof s.seekButtons=="object"?s.seekButtons:{},u=c.back??e.seekStep,m=c.forward??e.seekStep;if(this.seekLabelFn=c.label,s.playlist&&e.hasPlaylist&&!s.hidePrev&&(this.prevBtn=y("imp-btn--prev",t.previous,i.previous),this.prevBtn.addEventListener("click",()=>e.previous()),r.append(this.prevBtn)),s.seekButtons&&(this.seekBackBtn=y("imp-btn--seek-back",`${t.seekBack} ${u}s`,i.seekBack),this.addStepBadge(this.seekBackBtn,u,"back"),this.seekBackBtn.addEventListener("click",()=>e.skip(-u)),r.append(this.seekBackBtn)),s.play&&(this.playBtn=y("imp-btn--play",t.play,i.play),this.playBtn.addEventListener("click",()=>e.togglePlay()),r.append(this.playBtn)),s.seekButtons&&(this.seekFwdBtn=y("imp-btn--seek-forward",`${t.seekForward} ${m}s`,i.seekForward),this.addStepBadge(this.seekFwdBtn,m,"forward"),this.seekFwdBtn.addEventListener("click",()=>e.skip(m)),r.append(this.seekFwdBtn)),s.playlist&&e.hasPlaylist&&(this.nextBtn=y("imp-btn--next",t.next,i.next),this.nextBtn.addEventListener("click",()=>e.next()),r.append(this.nextBtn)),s.volume){const d=o("div","imp-volume");this.muteBtn=y("imp-btn--mute",t.mute,i.volumeHigh),this.muteBtn.addEventListener("click",()=>e.toggleMute()),this.volumeSlider=o("input","imp-volume__slider",{type:"range",min:"0",max:"1",step:"0.05","aria-label":"Volume"}),this.volumeSlider.addEventListener("input",()=>{e.setVolume(Number(this.volumeSlider.value))}),d.append(this.muteBtn,this.volumeSlider),r.append(d)}s.time&&(this.timeLabel=o("div","imp-controls__time"),this.timeCurrent=o("span","imp-controls__time-current"),this.timeTotal=o("span","imp-controls__time-total"),this.timeLabel.append(this.timeCurrent,this.timeTotal),this.liveBadge=o("span","imp-controls__live"),this.liveBadge.textContent=t.live,this.liveBadge.hidden=!0,r.append(this.timeLabel,this.liveBadge)),this.buildLikeDislike();for(const d of(e.actionsOptions.custom??[]).filter(b=>b.placement==="bar")){const b=y(`imp-btn--custom imp-btn--custom-${d.id}`,d.title,d.icon??i.more);b.addEventListener("click",()=>e.emit("customaction",{id:d.id})),this.rightItems.set(`custom:${d.id}`,b),this.registerCollapsible({key:`custom:${d.id}`,el:b,priority:55,available:()=>!0,section:()=>this.simpleSection(`custom:${d.id}`,d.title,d.icon??i.more,()=>e.emit("customaction",{id:d.id}))})}const f=d=>d===!1?"off":d==="bar"?"bar":"gear",v=f(s.subtitles),g=f(s.quality),B=f(s.speed);if(this.gear={speed:B==="gear",quality:g==="gear",subtitles:v==="gear"},v==="bar"){this.subtitlesBtn=y("imp-btn--subtitles",t.subtitles,i.subtitles),this.subtitlesMenu=new _(this.subtitlesBtn);const d=o("div","imp-controls__menu-anchor");d.append(this.subtitlesBtn,this.subtitlesMenu.root),this.subtitlesBtn.addEventListener("click",()=>this.toggleSubtitlesMenu()),this.rightItems.set("subtitles",d),this.registerCollapsible({key:"subtitles",el:d,priority:30,available:()=>e.subtitleTracks.length>0,section:()=>this.subtitlesSection()})}if(g==="bar"){this.qualityBtn=y("imp-btn--quality",t.quality,i.settings),this.qualityMenu=new _(this.qualityBtn);const d=o("div","imp-controls__menu-anchor");d.append(this.qualityBtn,this.qualityMenu.root),this.qualityBtn.addEventListener("click",()=>this.toggleQualityMenu()),this.rightItems.set("quality",d),this.registerCollapsible({key:"quality",el:d,priority:10,available:()=>e.qualityLevels.length>0,section:()=>this.qualitySection()})}if(B==="bar"){this.settingsBtn=y("imp-btn--speed",t.speed,i.speed),this.settingsMenu=new _(this.settingsBtn);const d=o("div","imp-controls__menu-anchor");d.append(this.settingsBtn,this.settingsMenu.root),this.settingsBtn.addEventListener("click",()=>this.toggleSettingsMenu()),this.rightItems.set("speed",d),this.registerCollapsible({key:"speed",el:d,priority:40,available:()=>!0,section:()=>this.speedSection()})}if(s.scenes&&(this.scenesBtn=y("imp-btn--scenes",t.scenes,i.scenes),this.scenesBtn.addEventListener("click",()=>e.toggleScenesPanel()),this.rightItems.set("scenes",this.scenesBtn),this.registerCollapsible({key:"scenes",el:this.scenesBtn,priority:25,available:()=>e.chapterList.length>0,section:()=>this.simpleSection("scenes",t.scenes,i.scenes,()=>e.toggleScenesPanel())})),s.sceneTypes!==!1){this.sceneTypeBtn=o("button","imp-btn imp-btn--scene-types",{type:"button"}),this.sceneTypeMenu=new _(this.sceneTypeBtn);const d=o("div","imp-controls__menu-anchor");d.append(this.sceneTypeBtn,this.sceneTypeMenu.root),this.sceneTypeBtn.addEventListener("click",()=>this.toggleSceneTypeMenu()),this.rightItems.set("sceneTypes",d),this.refreshSceneTypeButton(),this.registerCollapsible({key:"sceneTypes",el:d,priority:26,available:()=>e.sceneTypes.length>0,section:()=>this.sceneTypeSection()})}if(s.playlist&&e.hasPlaylist){const d=y("imp-btn--list",t.playlist,i.list);d.addEventListener("click",()=>e.togglePlaylistPanel()),this.rightItems.set("playlist",d),this.registerCollapsible({key:"list",el:d,priority:50,available:()=>!0,section:()=>this.simpleSection("list",t.playlist,i.list,()=>e.togglePlaylistPanel())})}if(s.pip&&"requestPictureInPicture"in HTMLVideoElement.prototype){const d=y("imp-btn--pip",t.pip,i.pip);d.addEventListener("click",()=>void e.togglePip()),this.rightItems.set("pip",d),this.registerCollapsible({key:"pip",el:d,priority:20,available:()=>!0,section:()=>this.simpleSection("pip",t.pip,i.pip,()=>void e.togglePip())})}if(s.fullscreen&&(this.fullscreenBtn=y("imp-btn--fullscreen",t.fullscreen,i.fullscreen),this.fullscreenBtn.addEventListener("click",()=>void e.toggleFullscreen()),this.rightItems.set("fullscreen",this.fullscreenBtn)),this.prevBtn&&this.registerCollapsible({key:"prev",el:this.prevBtn,priority:70,available:()=>!0,section:()=>e.hasPrevious?this.simpleSection("prev",t.previous,i.previous,()=>e.previous()):null}),this.nextBtn&&this.registerCollapsible({key:"next",el:this.nextBtn,priority:72,available:()=>!0,section:()=>e.hasNext?this.simpleSection("next",t.next,i.next,()=>e.next()):null}),this.seekBackBtn){const d=this.seekBackBtn;this.registerCollapsible({key:"seekBack",el:d,priority:80,available:()=>Number.isFinite(e.duration)&&e.duration>0,section:()=>this.simpleSection("seekBack",`${t.seekBack} ${u}s`,i.seekBack,()=>e.skip(-u))})}if(this.seekFwdBtn){const d=this.seekFwdBtn;this.registerCollapsible({key:"seekFwd",el:d,priority:82,available:()=>Number.isFinite(e.duration)&&e.duration>0,section:()=>this.simpleSection("seekFwd",`${t.seekForward} ${m}s`,i.seekForward,()=>e.skip(m))})}if(this.center=o("div","imp-center-controls"),s.playlist&&e.hasPlaylist&&(this.centerPrevBtn=this.makeCenterButton("prev",t.previous,i.previous),this.centerPrevBtn.addEventListener("click",()=>e.previous()),this.center.append(this.centerPrevBtn)),s.seekButtons){const d=this.makeCenterButton("seek-back",`${t.seekBack} ${u}s`,i.seekBack);this.addStepBadge(d,u,"back"),d.addEventListener("click",()=>e.skip(-u)),this.center.append(d)}if(s.play&&(this.centerPlayBtn=this.makeCenterButton("play",t.play,i.play),this.centerPlayBtn.addEventListener("click",()=>e.togglePlay()),this.center.append(this.centerPlayBtn)),s.seekButtons){const d=this.makeCenterButton("seek-forward",`${t.seekForward} ${m}s`,i.seekForward);this.addStepBadge(d,m,"forward"),d.addEventListener("click",()=>e.skip(m)),this.center.append(d)}if(s.playlist&&e.hasPlaylist&&(this.centerNextBtn=this.makeCenterButton("next",t.next,i.next),this.centerNextBtn.addEventListener("click",()=>e.next()),this.center.append(this.centerNextBtn)),this.center.style.display="none",this.setupNextPreview(),this.gear.speed||this.gear.quality||this.gear.subtitles){this.gearBtn=y("imp-btn--settings",t.settings,i.settings),this.gearMenu=new _(this.gearBtn);const d=o("div","imp-controls__menu-anchor");d.append(this.gearBtn,this.gearMenu.root),this.gearBtn.addEventListener("click",()=>this.toggleGearMenu()),this.rightItems.set("gear",d),this.registerCollapsible({key:"gear",el:d,priority:40,available:()=>this.gearSections().length>0,section:()=>this.gearSections()})}this.layoutRightCluster(a),this.buildMoreDropdown(a),this.bind(),this.syncVolume(),this.syncPlayState(),this.setLikeState(e.actionsOptions.likeState??null),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.scheduleReflow()),this.resizeObserver.observe(e.container)),this.onWindowResize=()=>this.scheduleReflow(),window.addEventListener("resize",this.onWindowResize)}registerCollapsible(e){this.collapsibles.push(e)}layoutRightCluster(e){const t=[...this.rightItems.keys()],i=this.player.controlsOptions.order;let s=t;if(i.length>0){const n=new Set;s=[];for(const r of i)this.rightItems.has(r)&&!n.has(r)&&(s.push(r),n.add(r));for(const r of t)n.has(r)||s.push(r)}for(const n of s){const r=this.rightItems.get(n);r&&e.append(r)}}makeCenterButton(e,t,i){const s=o("button",`imp-center-btn imp-center-btn--${e}`,{type:"button","aria-label":t,title:t});return s.innerHTML=i,s}addStepBadge(e,t,i){const s=o("span","imp-seek-num");s.textContent=this.seekLabelFn?this.seekLabelFn(t,i):`${i==="back"?"−":"+"}${t}${this.player.labels.secondsShort}`,e.append(s)}gearSections(){const e=this.player,t=[];return this.gear.quality&&e.qualityLevels.length>0&&t.push(this.qualitySection()),this.gear.speed&&t.push(this.speedSection()),this.gear.subtitles&&e.subtitleTracks.length>0&&t.push(this.subtitlesSection()),t}gearEntries(){const e=this.player,t=[];if(e.hasPlaylist&&t.push({key:"autoplay",label:e.labels.autoplay,toggle:{value:e.autoAdvance,onChange:i=>e.setAutoAdvance(i)}}),this.gear.quality&&e.qualityLevels.length>0){const i=e.currentQuality===-1?e.labels.qualityAuto:e.qualityLevels.find(s=>s.index===e.currentQuality)?.label??e.labels.qualityAuto;t.push({key:"quality",label:e.labels.quality,value:i,section:()=>this.qualitySection()})}if(this.gear.speed){const i=e.playbackRate;t.push({key:"speed",label:e.labels.speed,value:i===1?"1×":`${i}×`,section:()=>this.speedSection()})}if(this.gear.subtitles&&e.subtitleTracks.length>0){const i=e.activeSubtitle===-1?e.labels.subtitlesOff:e.subtitleTracks[e.activeSubtitle]?.label??e.labels.subtitlesOff;t.push({key:"subtitles",label:e.labels.subtitles,value:i,section:()=>this.subtitlesSection()})}return t}refreshSceneTypeButton(){const e=this.sceneTypeBtn;if(!e)return;const t=this.player.activeSceneType;if(e.textContent="",!t)return;if(t.icon){const s=o("span","imp-scene-type__icon");t.icon.trimStart().startsWith("<svg")?s.innerHTML=t.icon:s.append(o("img","",{src:t.icon,alt:""})),e.append(s)}const i=o("span","imp-scene-type__label");i.textContent=t.title,e.append(i),e.setAttribute("aria-label",`${this.player.labels.sceneTypes}: ${t.title}`),e.title=t.title}sceneTypeSection(){const e=this.player;return{title:e.labels.sceneTypes,items:e.sceneTypes.map(t=>({label:t.title,value:t.id,icon:t.icon,active:t.id===(e.activeSceneType?.id??"")})),onSelect:t=>{e.setSceneGroup(t),this.refreshSceneTypeButton()}}}toggleSceneTypeMenu(){!this.sceneTypeMenu||this.player.sceneTypes.length===0||(this.closeMenus(this.sceneTypeMenu),this.sceneTypeMenu.toggle([this.sceneTypeSection()]))}toggleGearMenu(){if(!this.gearMenu)return;const e=this.gearEntries();e.length!==0&&(this.closeMenus(this.gearMenu),this.gearMenu.toggleSettings(this.player.labels.settings,e))}setupNextPreview(){const e=this.player,t=e.controlsOptions;if(t.nextPreview===!1||!t.playlist||!e.hasPlaylist)return;const i=typeof t.nextPreview=="object"?t.nextPreview:{};this.nextPreviewOpts={thumbnail:i.thumbnail??!0,title:i.title??!0,duration:i.duration??!0,meta:i.meta??!0},this.nextPreviewEl=o("div","imp-next-preview"),this.nextPreviewEl.hidden=!0,e.container.append(this.nextPreviewEl),this.nextBtn&&this.bindNextPreview(this.nextBtn),this.centerNextBtn&&this.bindNextPreview(this.centerNextBtn)}bindNextPreview(e){e.addEventListener("pointerenter",t=>{t.pointerType==="mouse"&&this.showNextPreview(e)}),e.addEventListener("pointerleave",()=>this.hideNextPreview()),e.addEventListener("click",()=>this.hideNextPreview())}showNextPreview(e){const t=this.nextPreviewEl,i=this.nextPreviewOpts;if(!t||!i)return;const s=this.player.nextSource;if(!s)return;t.textContent="";const n=o("div","imp-next-preview__kicker");if(n.textContent=this.player.labels.next,t.append(n),i.thumbnail&&s.poster){const f=o("div","imp-next-preview__thumb");if(f.style.backgroundImage=`url("${s.poster}")`,i.duration&&s.duration){const v=o("span","imp-next-preview__duration");v.textContent=x(s.duration),f.append(v)}t.append(f)}if(i.title&&s.title){const f=o("div","imp-next-preview__title");f.textContent=s.title,t.append(f)}i.meta&&s.previewMeta?.length&&t.append(F(s.previewMeta,"imp-next-preview")),t.hidden=!1;const r=this.player.container.getBoundingClientRect(),a=e.getBoundingClientRect(),h=8,c=t.offsetWidth,u=a.left-r.left+a.width/2-c/2,m=Math.max(h,Math.min(u,r.width-c-h));t.style.left=`${m}px`,t.style.bottom=`${r.height-(a.top-r.top)+10}px`}hideNextPreview(){this.nextPreviewEl&&(this.nextPreviewEl.hidden=!0)}buildLikeDislike(){const e=this.player,t=e.actionsOptions,{labels:i,icons:s}=e;if(t.like){this.likeBtn=y("imp-btn--like",i.like,s.like),this.likeBtn.addEventListener("click",()=>e.emit("action",{id:"like"})),this.likeCountEl=this.attachCountTooltip(this.likeBtn,t.likeCount);const n=this.wrapWithTooltip(this.likeBtn,this.likeCountEl);this.rightItems.set("like",n),this.registerCollapsible({key:"like",el:n,priority:62,available:()=>!0,section:()=>this.simpleSection("like",i.like,s.like,()=>e.emit("action",{id:"like"}))})}if(t.dislike){this.dislikeBtn=y("imp-btn--dislike",i.dislike,s.dislike),this.dislikeBtn.addEventListener("click",()=>e.emit("action",{id:"dislike"})),this.dislikeCountEl=this.attachCountTooltip(this.dislikeBtn,t.dislikeCount);const n=this.wrapWithTooltip(this.dislikeBtn,this.dislikeCountEl);this.rightItems.set("dislike",n),this.registerCollapsible({key:"dislike",el:n,priority:60,available:()=>!0,section:()=>this.simpleSection("dislike",i.dislike,s.dislike,()=>e.emit("action",{id:"dislike"}))})}}attachCountTooltip(e,t){const i=o("span","imp-count-tooltip");return this.setCountText(i,t),i}wrapWithTooltip(e,t){const i=o("div","imp-action");return i.append(e,t),i}setCountText(e,t){const i=t==null||t===""?"":String(t);e.textContent=i,e.hidden=i===""}setLikeCounts(e,t){this.likeCountEl&&e!==void 0&&this.setCountText(this.likeCountEl,e),this.dislikeCountEl&&t!==void 0&&this.setCountText(this.dislikeCountEl,t)}setLikeState(e){this.likeBtn?.classList.toggle("imp-btn--active",e==="like"),this.dislikeBtn?.classList.toggle("imp-btn--active",e==="dislike")}buildMoreDropdown(e){const t=this.player,i=t.actionsOptions,{labels:s,icons:n}=t;i.addTo&&this.actionItems.push({value:"addTo",label:s.addTo,icon:n.addTo,run:()=>t.emit("action",{id:"addTo"})}),i.share&&this.actionItems.push({value:"share",label:s.share,icon:n.share,run:()=>void t.share()}),i.report&&this.actionItems.push({value:"report",label:s.report,icon:n.report,run:()=>t.emit("action",{id:"report"})});for(const h of(i.custom??[]).filter(c=>c.placement!=="bar"))this.actionItems.push({value:`custom:${h.id}`,label:h.title,icon:h.icon,run:()=>t.emit("customaction",{id:h.id})});const r=y("imp-btn--more",s.more,n.more);this.moreMenu=new _(r);const a=o("div","imp-controls__menu-anchor imp-controls__more");a.append(r,this.moreMenu.root),r.addEventListener("click",()=>{this.closeMenus(this.moreMenu),this.moreMenu?.toggle(this.buildMoreSections())}),e.append(a),this.moreWrap=a}buildMoreSections(){const e=[],t=new Map,i=[],s=["prev","next","seekBack","seekFwd","like","dislike","scenes","sceneTypes","pip","list","subtitles","speed","quality","gear"],n=a=>{const h=s.indexOf(a);return h===-1?s.length:h},r=this.collapsibles.filter(a=>this.overflowed.has(a.key)&&a.available()).sort((a,h)=>n(a.key)-n(h.key));for(const a of r){const h=a.section();if(h)for(const c of Array.isArray(h)?h:[h])if(!c.title&&c.items.length===1){const u=c.items[0];i.push(u),t.set(u.value,()=>c.onSelect(u.value))}else e.push(c)}if(i.length>0&&e.unshift({title:"",items:i,onSelect:a=>t.get(a)?.()}),this.actionItems.length>0){const a=new Map(this.actionItems.map(h=>[h.value,h.run]));e.push({title:"",items:this.actionItems.map(({value:h,label:c,icon:u})=>({value:h,label:c,icon:u,active:!1})),onSelect:h=>a.get(h)?.()})}return e}simpleSection(e,t,i,s){return{title:"",items:[{value:e,label:t,icon:i,active:!1}],onSelect:()=>s()}}speedSection(){const e=this.player;return{title:e.labels.speed,items:e.playbackRates.map(t=>({label:t===1?"1× (normal)":`${t}×`,value:String(t),active:e.playbackRate===t})),onSelect:t=>e.setPlaybackRate(Number(t))}}qualitySection(){const e=this.player;return{title:e.labels.quality,items:[...e.qualityAutoAvailable?[{label:e.labels.qualityAuto,value:"-1",active:e.currentQuality===-1}]:[],...e.qualityLevels.map(t=>({label:t.label,value:String(t.index),active:e.currentQuality===t.index}))],onSelect:t=>e.setQuality(Number(t))}}subtitlesSection(){const e=this.player;return{title:e.labels.subtitles,items:[{label:e.labels.subtitlesOff,value:"-1",active:e.activeSubtitle===-1},...e.subtitleTracks.map((t,i)=>({label:t.label,value:String(i),active:e.activeSubtitle===i}))],onSelect:t=>e.setSubtitle(Number(t))}}scheduleReflow(){this.reflowScheduled||(this.reflowScheduled=!0,requestAnimationFrame(()=>{this.reflowScheduled=!1,this.reflow()}))}reflow(){const e=window.innerWidth<=767,i=this.player.controlsOptions.seekPlacement!=="bar"||e;this.center.style.display=i?"flex":"none",this.centerPrevBtn&&(this.centerPrevBtn.style.display=e?"":"none"),this.centerNextBtn&&(this.centerNextBtn.style.display=e?"":"none"),this.playBtn&&(this.playBtn.style.display=e?"none":"");const s=a=>a==="seekBack"||a==="seekFwd"?i:a==="prev"||a==="next"?e:!1;this.overflowed.clear();for(const a of this.collapsibles){if(s(a.key)){a.el.style.display="none";continue}const h=a.available();a.el.style.display=h?"":"none",a.el.classList.remove("imp-collapsed")}const n=this.collapsibles.filter(a=>a.available()&&!s(a.key)).sort((a,h)=>a.priority-h.priority);let r=n.length;for(;r-- >0&&this.overflowsRow();){const a=n.find(h=>!this.overflowed.has(h.key));if(!a)break;a.el.style.display="none",a.el.classList.add("imp-collapsed"),this.overflowed.add(a.key)}if(this.moreWrap){const a=this.actionItems.length>0||this.overflowed.size>0;this.moreWrap.style.display=a?"":"none"}}overflowsRow(){const e=this.row.getBoundingClientRect().right;return this.rightGroup.getBoundingClientRect().right>e+1}bind(){const e=this.player;this.disposers.push(e.on("timeupdate",({currentTime:t,duration:i})=>{this.progress.update(t,i,e.bufferedEnd),this.timeLabel&&(e.live?(this.timeLabel.hidden=!0,this.liveBadge.hidden=!1):(this.timeLabel.hidden=!1,this.liveBadge.hidden=!0,this.timeCurrent.textContent=x(t),this.timeTotal.textContent=` / ${x(i)}`))}),e.on("play",()=>this.syncPlayState()),e.on("pause",()=>this.syncPlayState()),e.on("ended",()=>this.syncPlayState()),e.on("volumechange",()=>this.syncVolume()),e.on("chapterchange",({chapter:t})=>{this.chapterLabel.textContent=t?.title??""}),e.on("fullscreenchange",({active:t})=>{this.fullscreenBtn&&A(this.fullscreenBtn,t?e.icons.fullscreenExit:e.icons.fullscreen,t?e.labels.exitFullscreen:e.labels.fullscreen),this.scheduleReflow()}),e.on("playlistitemchange",()=>{this.syncPlaylistButtons(),this.scheduleReflow()}),e.on("sourcechange",()=>{this.syncPlaylistButtons(),this.scheduleReflow()})),this.syncPlaylistButtons(),this.reflow()}syncPlayState(){const e=this.player,[t,i]=e.ended?[e.icons.replay,e.labels.replay]:e.paused?[e.icons.play,e.labels.play]:[e.icons.pause,e.labels.pause];this.playBtn&&A(this.playBtn,t,i),this.centerPlayBtn&&A(this.centerPlayBtn,t,i)}syncVolume(){if(!this.muteBtn)return;const e=this.player,t=e.muted?0:e.volume,i=t===0?e.icons.volumeMute:t<.5?e.icons.volumeLow:e.icons.volumeHigh;A(this.muteBtn,i,e.muted?e.labels.unmute:e.labels.mute),this.volumeSlider.value=String(t),this.volumeSlider.style.setProperty("--imp-volume-fill",`${t*100}%`)}syncFeatureButtons(){this.refreshSceneTypeButton(),this.scheduleReflow()}syncPlaylistButtons(){const e=this.player;this.prevBtn&&(this.prevBtn.disabled=!e.hasPrevious),this.nextBtn&&(this.nextBtn.disabled=!e.hasNext),this.centerPrevBtn&&(this.centerPrevBtn.disabled=!e.hasPrevious),this.centerNextBtn&&(this.centerNextBtn.disabled=!e.hasNext)}closeMenus(e){for(const t of[this.gearMenu,this.settingsMenu,this.subtitlesMenu,this.qualityMenu,this.sceneTypeMenu,this.moreMenu])t&&t!==e&&t.close()}toggleSettingsMenu(){this.settingsMenu&&(this.closeMenus(this.settingsMenu),this.settingsMenu.toggle([this.speedSection()]))}toggleQualityMenu(){!this.qualityMenu||this.player.qualityLevels.length===0||(this.closeMenus(this.qualityMenu),this.qualityMenu.toggle([this.qualitySection()]))}toggleSubtitlesMenu(){!this.subtitlesMenu||this.player.subtitleTracks.length===0||(this.closeMenus(this.subtitlesMenu),this.subtitlesMenu.toggle([this.subtitlesSection()]))}destroy(){for(const e of this.disposers)e();this.disposers=[],this.resizeObserver?.disconnect(),this.onWindowResize&&window.removeEventListener("resize",this.onWindowResize),this.gearMenu?.destroy(),this.sceneTypeMenu?.destroy(),this.settingsMenu?.destroy(),this.subtitlesMenu?.destroy(),this.qualityMenu?.destroy(),this.moreMenu?.destroy(),this.nextPreviewEl?.remove(),this.root.remove()}}class ye{constructor(e){this.root=o("div","imp-poster"),this.image=o("img","imp-poster__image",{alt:"",decoding:"async"}),this.image.hidden=!0;const t=y("imp-poster__play",e.labels.play,e.icons.bigPlay);t.addEventListener("click",()=>void e.play()),this.root.append(this.image,t),this.root.addEventListener("click",i=>{(i.target===this.root||i.target===this.image)&&e.play()})}setSource(e){e?.poster?(this.image.src=e.poster,this.image.fetchPriority="high",this.image.hidden=!1):(this.image.removeAttribute("src"),this.image.hidden=!0)}show(){this.root.hidden=!1}hide(){this.root.hidden=!0}}class ge{constructor(e){this.labels=e,this.channelUrl=null,this.custom=null,this.visible={title:!0,description:!0,sponsor:!0},this.root=o("div","imp-pause-screen"),this.root.hidden=!0,this.defaultContent=o("div","imp-pause-screen__default"),this.channel=o("button","imp-channel",{type:"button"}),this.channel.hidden=!0,this.channelAvatar=o("div","imp-channel__avatar"),this.channelName=o("div","imp-channel__name"),this.channel.append(this.channelName,this.channelAvatar),this.channel.addEventListener("click",()=>{this.channelUrl&&window.open(this.channelUrl,"_blank","noopener")});const t=o("div","imp-pause-screen__heading");this.title=o("div","imp-pause-screen__title"),this.description=o("div","imp-pause-screen__description"),this.sponsor=o("a","imp-sponsor",{target:"_blank",rel:"nofollow noopener"}),this.sponsor.hidden=!0,this.sponsorLabel=o("span","imp-sponsor__label"),this.sponsorText=o("span","imp-sponsor__text"),this.sponsor.append(this.sponsorLabel,this.sponsorText),this.sponsor.addEventListener("click",i=>i.stopPropagation()),t.append(this.sponsor,this.title,this.description),this.defaultContent.append(t,this.channel),this.root.append(this.defaultContent)}setCustomContent(e){this.custom?.remove(),this.custom=e,e&&(e.classList.add("imp-pause-screen__custom"),this.root.append(e)),this.defaultContent.hidden=e!==null,this.root.classList.toggle("imp-pause-screen--custom",e!==null)}get hasCustom(){return this.custom!==null}setVisibility(e){this.visible={title:e.title??this.visible.title,description:e.description??this.visible.description,sponsor:e.sponsor??this.visible.sponsor}}setSource(e){this.title.textContent=e?.title??"",this.description.textContent=e?.description??"",this.title.hidden=!this.visible.title||!e?.title,this.description.hidden=!this.visible.description||!e?.description;const t=this.visible.sponsor?e?.sponsor:void 0;this.sponsor.hidden=!t,t&&(this.sponsor.href=t.url,this.sponsorText.textContent=t.text,this.sponsorLabel.textContent=t.label??this.labels.sponsored);const i=e?.channel;this.channel.hidden=!i,this.channelUrl=i?.url??null,this.channel.classList.toggle("imp-channel--link",!!i?.url),i&&(this.channelName.textContent=i.name,this.channelAvatar.className=`imp-channel__avatar imp-channel__avatar--${i.avatarShape??"circle"}`,i.avatar?(this.channelAvatar.textContent="",this.channelAvatar.style.backgroundImage=`url("${i.avatar}")`):(this.channelAvatar.style.backgroundImage="",this.channelAvatar.textContent=(i.name.trim()[0]??"?").toUpperCase()))}show(){this.root.hidden=!1}hide(){this.root.hidden=!0}}class be{constructor(e){this.player=e,this.clickBehavior="player",this.root=o("div","imp-related"),this.root.hidden=!0,this.heading=o("div","imp-related__title"),this.grid=o("div","imp-related__grid");const t=y("imp-related__close","Close",e.icons.close);t.addEventListener("click",()=>this.hide()),this.root.append(t,this.heading,this.grid)}setOptions(e){if(this.grid.textContent="",!!e){this.clickBehavior=e.clickBehavior??"player",this.heading.textContent=e.title??this.player.labels.related;for(const t of e.items)this.grid.append(this.buildCard(t))}}buildCard(e){const t=o("button","imp-related__card",{type:"button"}),i=o("div","imp-related__thumb");if(e.poster&&(i.style.backgroundImage=`url("${e.poster}")`),e.duration){const n=o("span","imp-related__duration");n.textContent=e.duration,i.append(n)}const s=o("div","imp-related__card-title");return s.textContent=e.title,t.append(i,s),t.addEventListener("click",()=>{this.player.emit("relatedclick",{item:e}),this.hide(),this.activate(e)}),t}activate(e){const t=e.url??e.source?.src;switch(this.clickBehavior){case"newWindow":t&&window.open(t,"_blank","noopener");break;case"currentTab":t&&(window.location.href=t);break;case"player":default:e.source?(this.player.load(e.source),this.player.play()):e.url&&window.open(e.url,"_blank","noopener")}}get visible(){return!this.root.hidden}show(){this.grid.childElementCount!==0&&(this.root.hidden=!1,this.player.emit("relatedshow",void 0))}hide(){this.root.hidden=!0}}class ke{constructor(e){this.player=e,this.root=o("div","imp-upnext"),this.root.hidden=!0}get visible(){return!this.root.hidden}show(){const e=this.player.nextSource;if(!e)return;const{labels:t}=this.player;this.root.textContent="";const i=o("div","imp-upnext__card"),s=o("div","imp-upnext__kicker");if(s.textContent=t.nextVideo,i.append(s),e.poster){const r=o("button","imp-upnext__thumb",{type:"button","aria-label":t.playNext});if(r.style.backgroundImage=`url("${e.poster}")`,e.duration){const h=o("span","imp-upnext__duration");h.textContent=x(e.duration),r.append(h)}const a=o("span","imp-upnext__thumb-play");a.innerHTML=this.player.icons.bigPlay,r.append(a),r.addEventListener("click",()=>this.player.next()),i.append(r)}if(e.title){const r=o("div","imp-upnext__title");r.textContent=e.title,i.append(r)}e.previewMeta?.length&&i.append(F(e.previewMeta,"imp-upnext"));const n=o("button","imp-upnext__btn",{type:"button"});n.textContent=t.playNext,n.addEventListener("click",()=>this.player.next()),i.append(n),this.root.append(i),this.root.hidden=!1}hide(){this.root.hidden=!0}}class we{constructor(e,t="sidebar",i){this.player=e,this.root=o("div",`imp-playlist imp-playlist--${t}`),this.root.hidden=!0;const s=o("div","imp-playlist__header"),n=o("div","imp-playlist__heading");if(i){const h=o("div","imp-playlist__kicker");h.textContent=e.labels.playlist;const c=o("div","imp-playlist__name");c.textContent=i,n.append(h,c)}else n.textContent=e.labels.playlist;const r=o("div","imp-playlist__tools");this.shuffleBtn=y("imp-playlist__shuffle",e.labels.shuffle,e.icons.shuffle),this.shuffleBtn.addEventListener("click",()=>{e.setShuffle(!e.shuffle),this.syncModes()}),this.repeatBtn=y("imp-playlist__repeat",e.labels.repeat,e.icons.repeat),this.repeatBtn.addEventListener("click",()=>{e.setRepeat(!e.repeat),this.syncModes()});const a=y("imp-playlist__close","Close",e.icons.close);a.addEventListener("click",()=>this.hide()),r.append(this.shuffleBtn,this.repeatBtn,a),s.append(n,r),this.list=o("div","imp-playlist__list"),this.root.append(s,this.list),this.rebuild(),this.syncModes()}syncModes(){this.shuffleBtn.classList.toggle("imp-btn--active",this.player.shuffle),this.repeatBtn.classList.toggle("imp-btn--active",this.player.repeat)}rebuild(){this.list.textContent="",this.player.playlist.forEach((e,t)=>{const i=o("button","imp-playlist__item",{type:"button"});t===this.player.index&&i.classList.add("imp-playlist__item--active");const s=o("div","imp-playlist__thumb");e.poster&&(s.style.backgroundImage=`url("${e.poster}")`);const n=o("div","imp-playlist__meta"),r=o("div","imp-playlist__title");if(r.textContent=e.title??`#${t+1}`,n.append(r),e.duration){const a=o("div","imp-playlist__duration");a.textContent=x(e.duration),n.append(a)}i.append(s,n),i.addEventListener("click",()=>{this.player.playItem(t),window.innerWidth<=767&&this.hide()}),this.list.append(i)})}get visible(){return!this.root.hidden}show(){this.rebuild(),this.root.hidden=!1}hide(){this.root.hidden=!0}toggle(){this.visible?this.hide():this.show()}}class xe{constructor(e,t="bottom"){this.player=e,this.items=[],this.root=o("div",`imp-playlist imp-scenes imp-playlist--${t}`),this.root.hidden=!0;const i=o("div","imp-playlist__header"),s=o("span");s.textContent=e.labels.scenes;const n=y("imp-playlist__close","Close",e.icons.close);n.addEventListener("click",()=>this.hide()),i.append(s,n),this.list=o("div","imp-playlist__list"),this.root.append(i,this.list),e.on("chapterchange",()=>this.syncActive())}rebuild(){this.list.textContent="",this.items=[];const e=this.player.thumbnails;for(const t of this.player.chapterList){const i=o("button","imp-playlist__item",{type:"button"}),s=o("div","imp-playlist__thumb"),n=e?.cueAt(t.start+.01)??null;if(n?.xywh){const c=o("div","imp-scenes__sprite");c.style.width=`${n.xywh.w}px`,c.style.height=`${n.xywh.h}px`,c.style.backgroundImage=`url("${n.src}")`,c.style.backgroundPosition=`-${n.xywh.x}px -${n.xywh.y}px`,c.style.setProperty("--imp-sprite-w",String(n.xywh.w)),s.append(c)}else n&&(s.style.backgroundImage=`url("${n.src}")`);const r=o("div","imp-playlist__meta"),a=o("div","imp-playlist__title");a.textContent=t.title||x(t.start);const h=o("div","imp-playlist__duration");h.textContent=x(t.start),r.append(a,h),i.append(s,r),i.addEventListener("click",()=>{this.player.seek(t.start),this.player.play(),window.innerWidth<=767&&this.hide()}),this.list.append(i),this.items.push(i)}this.syncActive()}syncActive(){const e=this.player.chapter,t=this.player.chapterList;this.items.forEach((i,s)=>{i.classList.toggle("imp-playlist__item--active",e!==null&&t[s]===e)})}get visible(){return!this.root.hidden}show(){this.rebuild(),this.root.hidden=!1}hide(){this.root.hidden=!0}toggle(){this.visible?this.hide():this.show()}}function W(l){return l?typeof l=="string"?[{src:l,label:"Subtitles"}]:Array.isArray(l)?l:[l]:[]}const Se={play:!0,progress:!0,time:!0,volume:!0,fullscreen:!0,pip:!0,speed:"gear",settings:"gear",quality:"gear",scenes:!0,sceneTypes:!0,heatmap:!0,subtitles:"gear",seekButtons:!0,seekPlacement:"overlay",order:[],playlist:!0,hidePrev:!0,nextPreview:!0,hideDelay:2500};class Le{constructor(e,t={}){this.scrubbing=!1,this.emitter=new X,this.abort=new AbortController,this.sources=[],this.currentIndex=-1,this.sourceController=null,this.loadToken=0,this.chapters=[],this.currentChapter=null,this.sceneGroupList=[],this.activeSceneGroupId="",this.progressiveQuality=-1,this.thumbTrack=null,this.shuffleMode=!1,this.autoAdvanceEnabled=!0,this.persistKey=null,this.persistVolume=!1,this.persistAutoAdvance=!1,this.decodeRecoveries=0,this.adManager=null,this.playedOnce=!1,this.idleTimer=null,this.destroyed=!1;const i=typeof e=="string"?document.querySelector(e):e;if(!i)throw new Error(`[itube-player] mount target not found: ${String(e)}`);this.mount=i,this.options=t,this.labels={...C,...ee(t.language),...t.labels},this.icons={...J,...t.icons};const s=t.controls??{},n=s.speed??s.settings??"gear";if(this.controlsOptions={...Se,...s,speed:n,settings:n},this.actionsOptions=t.actions??{},this.playbackRates=t.playbackRates??[.5,.75,1,1.25,1.5,2],this.seekStep=t.seekStep??15,this.playlistOptions={title:"",autoAdvance:!0,loop:!1,shuffle:!1,startIndex:0,layout:"sidebar",...t.playlist},this.shuffleMode=this.playlistOptions.shuffle,t.persist){const v=t.persist===!0?{}:t.persist;this.persistKey=v.key??"itube-player",this.persistVolume=v.volume!==!1,this.persistAutoAdvance=v.autoAdvance!==!1}const r=this.readPersisted();this.autoAdvanceEnabled=this.persistAutoAdvance&&typeof r?.autoAdvance=="boolean"?r.autoAdvance:this.playlistOptions.autoAdvance,this.sources=t.source?Array.isArray(t.source)?[...t.source]:[t.source]:[],this.container=o("div","imp-player",{tabindex:"0"}),t.className&&this.container.classList.add(t.className);const a=t.styling;if(a?.themeColor&&this.container.style.setProperty("--imp-accent",a.themeColor),a?.likeColor&&this.container.style.setProperty("--imp-like",a.likeColor),a?.dislikeColor&&this.container.style.setProperty("--imp-dislike",a.dislikeColor),a?.borderRadius!==void 0){const v=typeof a.borderRadius=="number"?`${a.borderRadius}px`:a.borderRadius;this.container.style.setProperty("--imp-radius",v)}a?.playButtonStyle==="inverted"&&this.container.classList.add("imp-player--play-inverted"),this.video=o("video","imp-video"),t.playsInline!==!1&&this.video.setAttribute("playsinline",""),t.crossOrigin!==void 0&&(this.video.crossOrigin=t.crossOrigin),this.video.preload="metadata",t.loop&&(this.video.loop=!0);const h=this.persistVolume?r:null;this.video.volume=w(h?.volume??t.volume??1,0,1),(h?.muted??t.muted)&&(this.video.muted=!0);const c=o("div","imp-layer");this.spinner=o("div","imp-spinner"),this.spinner.hidden=!0,this.errorBox=o("div","imp-error"),this.errorBox.hidden=!0,this.pauseScreen=new ge(this.labels),this.poster=new ye(this),this.related=new be(this),this.related.setOptions(t.related),this.upNext=new ke(this),this.controls=new fe(this),this.playlistPanel=new we(this,this.playlistOptions.layout,this.playlistOptions.title||void 0),this.scenesPanel=new xe(this,t.scenes?.layout??"bottom");const u=o("div","imp-layer__middle");u.append(this.spinner,this.errorBox,this.controls.center);const m=o("div","imp-layer__bottom");m.append(this.controls.root),c.append(this.pauseScreen.root,this.related.root,this.upNext.root,u,m),this.container.append(this.video,c,this.poster.root,this.playlistPanel.root,this.scenesPanel.root),this.mount.append(this.container),t.pauseScreen instanceof HTMLElement?this.pauseScreen.setCustomContent(t.pauseScreen):typeof t.pauseScreen=="function"?this.pauseScreen.setCustomContent(t.pauseScreen(this)):t.pauseScreen&&typeof t.pauseScreen=="object"&&this.pauseScreen.setVisibility(t.pauseScreen);const f=t.adConfig??t.ads;f&&f.adList.length>0&&(this.adManager=new ae({container:this.container,contentVideo:this.video,emitter:this.emitter,labels:this.labels,closeIcon:this.icons.close},f)),this.emitter.on("error",({message:v})=>{this.errorBox.textContent=v,this.errorBox.hidden=!1,this.spinner.hidden=!0,this.poster.hide()}),this.bindVideoEvents(),this.bindIdleHide(),t.keyboard!==!1&&this.bindKeyboard(),this.video.addEventListener("pointerup",v=>{if(!(this.adPlaying||!this.playedOnce)){if(v.pointerType==="mouse"){this.togglePlay();return}this.container.classList.contains("imp-player--idle")?(this.showControlsNow(),this.scheduleIdle()):this.video.paused||this.container.classList.add("imp-player--idle")}},{signal:this.abort.signal}),this.pauseScreen.root.addEventListener("click",v=>{this.pauseScreen.hasCustom||v.target===this.pauseScreen.root&&this.togglePlay()},{signal:this.abort.signal}),this.sources.length>0&&this.loadItem(w(this.playlistOptions.startIndex,0,this.sources.length-1),!!t.autoplay),this.emitter.emit("ready",{player:this})}on(e,t){return this.emitter.on(e,t)}once(e,t){return this.emitter.once(e,t)}off(e,t){this.emitter.off(e,t)}emit(e,t){this.emitter.emit(e,t)}get paused(){return this.video.paused}get ended(){return this.video.ended}get currentTime(){return this.video.currentTime}get duration(){return this.video.duration||0}get live(){return this.video.duration===1/0}get bufferedEnd(){const e=this.video.buffered;return e.length>0?e.end(e.length-1):0}get adPlaying(){return this.adManager?.adPlaying??!1}async play(){this.destroyed||this.adPlaying||this.adManager&&(await this.adManager.playPreRoll(),this.destroyed||!this.video.paused)||await this.video.play()}pause(){this.adPlaying||this.video.pause()}togglePlay(){this.video.paused||this.video.ended?this.play():this.pause()}seek(e){Number.isFinite(this.video.duration)&&(this.video.currentTime=w(e,0,this.video.duration))}skip(e){this.seek(this.video.currentTime+e)}get volume(){return this.video.volume}get muted(){return this.video.muted}setVolume(e){this.video.volume=w(e,0,1),e>0&&(this.video.muted=!1)}setMuted(e){this.video.muted=e}toggleMute(){this.video.muted=!this.video.muted}readPersisted(){if(!this.persistKey)return null;try{const e=localStorage.getItem(this.persistKey),t=e?JSON.parse(e):null;return t&&typeof t=="object"?t:null}catch{return null}}persistState(){if(this.persistKey)try{const e={};this.persistVolume&&(e.volume=this.video.volume,e.muted=this.video.muted),this.persistAutoAdvance&&(e.autoAdvance=this.autoAdvanceEnabled),localStorage.setItem(this.persistKey,JSON.stringify(e))}catch{}}get playbackRate(){return this.video.playbackRate}setPlaybackRate(e){this.video.playbackRate=e,this.emitter.emit("ratechange",{rate:e})}get qualityLevels(){if(this.sourceController?.kind==="hls")return this.sourceController.levels;const e=this.source?.qualities;return e?e.map((t,i)=>({index:i,label:t.label??String(t.quality??i)})):[]}get qualityAutoAvailable(){return this.sourceController?.kind==="hls"}get currentQuality(){return this.sourceController?.kind==="hls"?this.sourceController.selected:this.progressiveQuality}setQuality(e){if(this.sourceController?.kind==="hls"){this.sourceController.setLevel(e);const n=e===-1?this.labels.qualityAuto:this.sourceController.levels.find(r=>r.index===e)?.label??String(e);this.emitter.emit("qualitychange",{label:n});return}const t=this.source?.qualities;if(!t||!t[e]||e===this.progressiveQuality)return;const i=this.video.currentTime,s=!this.video.paused&&!this.video.ended;this.progressiveQuality=e,this.video.src=t[e].src,this.video.currentTime=i,s&&this.video.play().catch(()=>{}),this.emitter.emit("qualitychange",{label:t[e].label??String(t[e].quality??e)})}get subtitleTracks(){return W(this.source?.subtitles)}get activeSubtitle(){const e=this.video.textTracks;for(let t=0;t<e.length;t++)if(e[t].mode==="showing")return t;return-1}setSubtitle(e){const t=this.video.textTracks;for(let i=0;i<t.length;i++)t[i].mode=i===e?"showing":"disabled";this.emitter.emit("subtitlechange",{track:this.subtitleTracks[e]??null})}get playlist(){return this.sources}get index(){return this.currentIndex}get source(){return this.sources[this.currentIndex]??null}get nextSource(){if(this.shuffleMode||this.sources.length<2)return null;const e=this.currentIndex+1;return e<this.sources.length?this.sources[e]:this.playlistOptions.loop?this.sources[0]??null:null}get hasPlaylist(){return this.sources.length>1}get hasNext(){return this.shuffleMode||this.playlistOptions.loop?this.sources.length>1:this.currentIndex<this.sources.length-1}get hasPrevious(){return this.playlistOptions.loop?this.sources.length>1:this.currentIndex>0}get shuffle(){return this.shuffleMode}setShuffle(e){this.shuffleMode=e}get repeat(){return this.playlistOptions.loop}setRepeat(e){this.playlistOptions.loop=e}next(){if(this.hasNext){if(this.shuffleMode&&this.sources.length>1){let e=this.currentIndex;for(;e===this.currentIndex;)e=Math.floor(Math.random()*this.sources.length);this.playItem(e);return}this.playItem((this.currentIndex+1)%this.sources.length)}}previous(){this.hasPrevious&&this.playItem((this.currentIndex-1+this.sources.length)%this.sources.length)}playItem(e){e<0||e>=this.sources.length||this.loadItem(e,!0).then(()=>{this.emitter.emit("playlistitemchange",{source:this.sources[e],index:e})})}togglePlaylistPanel(){this.scenesPanel.hide(),this.playlistPanel.toggle()}toggleScenesPanel(){this.playlistPanel.hide(),this.scenesPanel.toggle()}get thumbnails(){return this.thumbTrack}load(e,t=0){this.sources=Array.isArray(e)?[...e]:[e],this.playlistPanel.rebuild(),this.loadItem(w(t,0,this.sources.length-1),!1)}get isFullscreen(){return document.fullscreenElement===this.container}async toggleFullscreen(){this.isFullscreen?await document.exitFullscreen():this.container.requestFullscreen?await this.container.requestFullscreen():this.video.webkitEnterFullscreen?.()}async togglePip(){document.pictureInPictureElement===this.video?await document.exitPictureInPicture():await this.video.requestPictureInPicture()}get chapterList(){return this.chapters}get chapter(){return this.currentChapter}get sceneTypes(){return this.sceneGroupList}get activeSceneType(){return this.sceneGroupList.find(e=>e.id===this.activeSceneGroupId)??null}setSceneGroup(e){e===this.activeSceneGroupId||!this.sceneGroupList.some(t=>t.id===e)||(this.activeSceneGroupId=e,this.applyActiveSceneGroup(),this.emitter.emit("scenetypechange",{group:this.activeSceneType}))}applyActiveSceneGroup(){this.chapters=Z(this.activeSceneType?.scenes??[],this.video.duration),this.currentChapter=null,this.controls.progress.setChapters(this.chapters),this.controls.syncFeatureButtons(),this.scenesPanel.visible&&this.scenesPanel.rebuild()}async share(){const e={title:this.source?.title??document.title,url:window.location.href};if(typeof navigator.share=="function"){try{await navigator.share(e)}catch{}return}this.emitter.emit("action",{id:"share"})}setLikeState(e){this.controls.setLikeState(e)}setLikeCounts(e,t){this.controls.setLikeCounts(e,t)}setPauseScreenContent(e){this.pauseScreen.setCustomContent(e)}destroy(){this.destroyed||(this.destroyed=!0,this.loadToken++,this.adManager?.destroy(),this.controls.destroy(),this.sourceController?.destroy(),this.abort.abort(),this.idleTimer&&clearTimeout(this.idleTimer),this.container.remove(),this.emitter.emit("destroy",void 0),this.emitter.removeAll())}async loadItem(e,t){const i=++this.loadToken,s=this.sources[e];if(!s)return;this.currentIndex=e,this.sourceController?.destroy(),this.sourceController=null,this.chapters=[],this.currentChapter=null,this.sceneGroupList=[],this.activeSceneGroupId="",this.progressiveQuality=-1,this.playedOnce=!1;for(const h of[...this.video.querySelectorAll("track")])h.remove();this.adManager?.resetForNewSource(),this.related.hide(),this.upNext.hide(),this.pauseScreen.hide(),this.scenesPanel.hide(),this.thumbTrack=null,this.errorBox.hidden=!0,this.decodeRecoveries=0,this.video.poster=s.poster??"",this.poster.setSource(s),this.pauseScreen.setSource(s),this.controls.progress.setChapters([]),this.controls.progress.setThumbnails(null),this.controls.progress.setHeatmap([]),t?this.poster.hide():this.poster.show(),this.playlistPanel.rebuild();for(const h of W(s.subtitles)){const c=o("track","",{kind:"subtitles",src:h.src,label:h.label,...h.srclang?{srclang:h.srclang}:{}});h.default&&c.setAttribute("default",""),this.video.append(c)}let n=s.src,r=s.type;if(s.qualities&&s.qualities.length>0){const h=Math.max(0,s.qualities.findIndex(c=>c.src===s.src));this.progressiveQuality=h,n=s.qualities[h].src,r=s.qualities[h].type??r}this.video.preload=this.adManager?.hasPendingPreRoll?"auto":"metadata";const a=await de(this.video,n,r,{onLevels:()=>{i===this.loadToken&&this.controls.syncFeatureButtons()},onLevelSwitch:h=>this.emitter.emit("qualitychange",{label:h}),onError:(h,c)=>this.emitter.emit("error",{message:h,cause:c})});if(i!==this.loadToken){a.destroy();return}if(this.sourceController=a,this.emitter.emit("sourcechange",{source:s,index:e}),s.thumbnails&&R.load(s.thumbnails).then(h=>{i===this.loadToken&&(this.thumbTrack=h,this.controls.progress.setThumbnails(h),this.scenesPanel.visible&&this.scenesPanel.rebuild())}).catch(h=>this.emitter.emit("error",{message:"Failed to load thumbnails track",cause:h})),s.sceneGroups&&s.sceneGroups.length>0){this.sceneGroupList=s.sceneGroups,this.activeSceneGroupId=s.sceneGroups[0].id;const h=()=>{i===this.loadToken&&this.applyActiveSceneGroup()};Number.isFinite(this.video.duration)&&this.video.duration>0?h():this.video.addEventListener("loadedmetadata",h,{once:!0,signal:this.abort.signal})}else if(s.chapters){const h=c=>{const u=()=>{i===this.loadToken&&(this.chapters=Z(c,this.video.duration),this.controls.progress.setChapters(this.chapters),this.controls.syncFeatureButtons(),this.scenesPanel.visible&&this.scenesPanel.rebuild())};Number.isFinite(this.video.duration)&&this.video.duration>0?u():this.video.addEventListener("loadedmetadata",u,{once:!0,signal:this.abort.signal})};typeof s.chapters=="string"?le(s.chapters).then(c=>h(c)).catch(c=>this.emitter.emit("error",{message:"Failed to load chapters track",cause:c})):h(s.chapters)}if(s.heatmap&&s.heatmap.length>0&&this.controlsOptions.heatmap){const h=s.heatmap,c=()=>{i===this.loadToken&&this.controls.progress.setHeatmap(te(h,this.video.duration))};Number.isFinite(this.video.duration)&&this.video.duration>0?c():this.video.addEventListener("loadedmetadata",c,{once:!0,signal:this.abort.signal})}t&&this.play().catch(()=>{i===this.loadToken&&this.poster.show()})}bindVideoEvents(){const{signal:e}=this.abort,t=this.video;t.addEventListener("play",()=>{this.playedOnce=!0,this.poster.hide(),this.pauseScreen.hide(),this.related.visible||this.related.hide(),this.related.hide(),this.upNext.hide(),t.readyState<3&&(this.spinner.hidden=!1),this.emitter.emit("play",void 0),this.scheduleIdle()},{signal:e}),t.addEventListener("pause",()=>{this.spinner.hidden=!0,this.emitter.emit("pause",void 0),this.showControlsNow(),!(this.video.ended||this.scrubbing||this.adPlaying||!this.playedOnce)&&(this.options.pauseScreen!==!1&&this.pauseScreen.show(),this.options.related?.showOn?.includes("pause")&&this.related.show())},{signal:e}),t.addEventListener("ended",()=>{this.handleEnded()},{signal:e}),t.addEventListener("timeupdate",()=>{this.emitter.emit("timeupdate",{currentTime:t.currentTime,duration:t.duration||0}),this.adManager?.checkMidRolls(t.currentTime);const i=D(this.chapters,t.currentTime);i!==this.currentChapter&&(this.currentChapter=i,this.emitter.emit("chapterchange",{chapter:i}))},{signal:e}),t.addEventListener("progress",()=>{this.emitter.emit("progress",{buffered:this.bufferedEnd})},{signal:e}),t.addEventListener("volumechange",()=>{this.emitter.emit("volumechange",{volume:t.volume,muted:t.muted}),this.persistVolume&&this.persistState()},{signal:e}),t.addEventListener("seeking",()=>this.emitter.emit("seeking",{currentTime:t.currentTime}),{signal:e}),t.addEventListener("seeked",()=>this.emitter.emit("seeked",{currentTime:t.currentTime}),{signal:e}),t.addEventListener("waiting",()=>{this.spinner.hidden=!1},{signal:e});for(const i of["playing","canplay","seeked"])t.addEventListener(i,()=>{this.spinner.hidden=!0,this.errorBox.hidden=!0,this.decodeRecoveries=0},{signal:e});t.addEventListener("error",()=>{const i=t.error;if(!i||this.sourceController?.kind==="hls"||t.getAttribute("src")===null&&!t.currentSrc)return;if((i.code===MediaError.MEDIA_ERR_DECODE||/DEMUXER|PARSE|DECODE/i.test(i.message||""))&&this.decodeRecoveries<2&&Number.isFinite(t.duration)){this.decodeRecoveries++;const n=t.currentTime,r=!t.paused;t.load();const a=()=>{try{t.currentTime=n}catch{}r&&t.play().catch(()=>{})};t.readyState>=1?a():t.addEventListener("loadedmetadata",a,{once:!0,signal:this.abort.signal});return}this.emitter.emit("error",{message:i.message||`Media error (code ${i.code})`,cause:i})},{signal:e}),t.addEventListener("enterpictureinpicture",()=>this.emitter.emit("pipchange",{active:!0}),{signal:e}),t.addEventListener("leavepictureinpicture",()=>this.emitter.emit("pipchange",{active:!1}),{signal:e}),document.addEventListener("fullscreenchange",()=>{this.emitter.emit("fullscreenchange",{active:this.isFullscreen}),this.container.classList.toggle("imp-player--fullscreen",this.isFullscreen)},{signal:e})}async handleEnded(){if(this.emitter.emit("ended",void 0),this.showControlsNow(),!(this.adManager&&(await this.adManager.playPostRoll(),this.destroyed))){if(this.autoAdvanceEnabled&&this.hasNext){this.next();return}if(!this.autoAdvanceEnabled&&this.hasNext){this.upNext.show();return}(this.options.related?.showOn?.includes("ended")??!!this.options.related)&&this.related.show()}}get autoAdvance(){return this.autoAdvanceEnabled}setAutoAdvance(e){this.autoAdvanceEnabled=e,e&&this.upNext.hide(),this.persistAutoAdvance&&this.persistState()}bindIdleHide(){const{signal:e}=this.abort,t=()=>{this.showControlsNow(),this.scheduleIdle()};this.container.addEventListener("pointermove",i=>{i.pointerType!=="touch"&&t()},{signal:e}),this.container.addEventListener("pointerdown",i=>{i.pointerType!=="touch"&&t()},{signal:e}),this.container.addEventListener("keydown",t,{signal:e}),this.container.addEventListener("pointerleave",i=>{i.pointerType!=="touch"&&(this.video.paused||this.container.classList.add("imp-player--idle"))},{signal:e})}showControlsNow(){this.container.classList.remove("imp-player--idle")}scheduleIdle(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{!this.video.paused&&!this.destroyed&&this.container.classList.add("imp-player--idle")},this.controlsOptions.hideDelay)}bindKeyboard(){this.container.addEventListener("keydown",e=>{const t=e.target;if(t.closest("input, select, textarea, [contenteditable]"))return;const s=t.closest("button")!==null;switch(e.key){case" ":case"k":if(e.key===" "&&s)return;e.preventDefault(),this.togglePlay();break;case"ArrowLeft":e.preventDefault(),this.skip(-this.seekStep);break;case"ArrowRight":e.preventDefault(),this.skip(this.seekStep);break;case"ArrowUp":e.preventDefault(),this.setVolume(this.volume+.1);break;case"ArrowDown":e.preventDefault(),this.setVolume(this.volume-.1);break;case"m":this.toggleMute();break;case"f":this.toggleFullscreen();break;case"Home":this.seek(0);break;case"End":this.seek(this.duration);break;default:/^[0-9]$/.test(e.key)&&Number.isFinite(this.video.duration)&&this.seek(Number(e.key)/10*this.video.duration)}},{signal:this.abort.signal})}}return Y({en:C,ru:{play:"Воспроизвести",pause:"Пауза",replay:"Смотреть снова",mute:"Выключить звук",unmute:"Включить звук",fullscreen:"Во весь экран",exitFullscreen:"Выйти из полноэкранного режима",pip:"Картинка в картинке",settings:"Скорость воспроизведения",subtitles:"Субтитры",subtitlesOff:"Выкл.",speed:"Скорость",quality:"Качество",qualityAuto:"Авто",next:"Следующее",nextVideo:"Следующее видео",previous:"Предыдущее",playlist:"Плейлист",scenes:"Сцены",sceneTypes:"Тип сцен",autoplay:"Автовоспроизведение",playNext:"Играть дальше",shuffle:"Перемешать",repeat:"Повтор",like:"Нравится",dislike:"Не нравится",addTo:"Сохранить в…",share:"Поделиться",report:"Пожаловаться",more:"Ещё",seekForward:"Перемотать вперёд",seekBack:"Перемотать назад",secondsShort:"с",live:"В ЭФИРЕ",related:"Похожие видео",adLabel:"Реклама",skipAd:"Пропустить рекламу",skipAdIn:"Пропуск через",visitAdvertiser:"Перейти к рекламодателю",sponsored:"Спонсор"},de:{play:"Wiedergabe",pause:"Pause",replay:"Erneut abspielen",mute:"Stummschalten",unmute:"Ton einschalten",fullscreen:"Vollbild",exitFullscreen:"Vollbild beenden",pip:"Bild im Bild",settings:"Wiedergabegeschwindigkeit",subtitles:"Untertitel",subtitlesOff:"Aus",speed:"Geschwindigkeit",quality:"Qualität",qualityAuto:"Automatisch",next:"Weiter",nextVideo:"Nächstes Video",previous:"Zurück",playlist:"Playlist",scenes:"Szenen",sceneTypes:"Szenentyp",autoplay:"Autoplay",playNext:"Weiter abspielen",shuffle:"Zufallswiedergabe",repeat:"Wiederholen",like:"Mag ich",dislike:"Mag ich nicht",addTo:"Speichern in…",share:"Teilen",report:"Melden",more:"Weitere Aktionen",seekForward:"Vorspulen",seekBack:"Zurückspulen",secondsShort:"s",live:"LIVE",related:"Weitere Videos",adLabel:"Anzeige",skipAd:"Werbung überspringen",skipAdIn:"Überspringen in",visitAdvertiser:"Zum Werbetreibenden",sponsored:"Gesponsert"},es:{play:"Reproducir",pause:"Pausa",replay:"Volver a reproducir",mute:"Silenciar",unmute:"Activar sonido",fullscreen:"Pantalla completa",exitFullscreen:"Salir de pantalla completa",pip:"Imagen en imagen",settings:"Velocidad de reproducción",subtitles:"Subtítulos",subtitlesOff:"Desactivados",speed:"Velocidad",quality:"Calidad",qualityAuto:"Automática",next:"Siguiente",nextVideo:"Siguiente vídeo",previous:"Anterior",playlist:"Lista de reproducción",scenes:"Escenas",sceneTypes:"Tipo de escena",autoplay:"Reproducción automática",playNext:"Reproducir siguiente",shuffle:"Aleatorio",repeat:"Repetir",like:"Me gusta",dislike:"No me gusta",addTo:"Guardar en…",share:"Compartir",report:"Denunciar",more:"Más acciones",seekForward:"Avanzar",seekBack:"Retroceder",secondsShort:"s",live:"EN VIVO",related:"Más vídeos",adLabel:"Anuncio",skipAd:"Omitir anuncio",skipAdIn:"Omitir en",visitAdvertiser:"Visitar al anunciante",sponsored:"Patrocinado"},it:{play:"Riproduci",pause:"Pausa",replay:"Riproduci di nuovo",mute:"Disattiva audio",unmute:"Attiva audio",fullscreen:"Schermo intero",exitFullscreen:"Esci da schermo intero",pip:"Picture-in-picture",settings:"Velocità di riproduzione",subtitles:"Sottotitoli",subtitlesOff:"Disattivati",speed:"Velocità",quality:"Qualità",qualityAuto:"Automatica",next:"Successivo",nextVideo:"Prossimo video",previous:"Precedente",playlist:"Playlist",scenes:"Scene",sceneTypes:"Tipo di scena",autoplay:"Riproduzione automatica",playNext:"Riproduci successivo",shuffle:"Casuale",repeat:"Ripeti",like:"Mi piace",dislike:"Non mi piace",addTo:"Salva in…",share:"Condividi",report:"Segnala",more:"Altre azioni",seekForward:"Avanti veloce",seekBack:"Indietro",secondsShort:"s",live:"LIVE",related:"Altri video",adLabel:"Annuncio",skipAd:"Salta annuncio",skipAdIn:"Salta tra",visitAdvertiser:"Visita l'inserzionista",sponsored:"Sponsorizzato"},ja:{play:"再生",pause:"一時停止",replay:"もう一度見る",mute:"ミュート",unmute:"ミュート解除",fullscreen:"全画面",exitFullscreen:"全画面を終了",pip:"ピクチャーインピクチャー",settings:"再生速度",subtitles:"字幕",subtitlesOff:"オフ",speed:"速度",quality:"画質",qualityAuto:"自動",next:"次へ",nextVideo:"次の動画",previous:"前へ",playlist:"プレイリスト",scenes:"シーン",sceneTypes:"シーンタイプ",autoplay:"自動再生",playNext:"次を再生",shuffle:"シャッフル",repeat:"リピート",like:"高く評価",dislike:"低く評価",addTo:"保存…",share:"共有",report:"報告",more:"その他の操作",seekForward:"早送り",seekBack:"巻き戻し",secondsShort:"秒",live:"ライブ",related:"関連動画",adLabel:"広告",skipAd:"広告をスキップ",skipAdIn:"スキップまで",visitAdvertiser:"広告主のサイトへ",sponsored:"スポンサー"},ko:{play:"재생",pause:"일시정지",replay:"다시 보기",mute:"음소거",unmute:"음소거 해제",fullscreen:"전체화면",exitFullscreen:"전체화면 종료",pip:"PIP 모드",settings:"재생 속도",subtitles:"자막",subtitlesOff:"사용 안 함",speed:"속도",quality:"화질",qualityAuto:"자동",next:"다음",nextVideo:"다음 동영상",previous:"이전",playlist:"재생목록",scenes:"장면",sceneTypes:"장면 유형",autoplay:"자동 재생",playNext:"다음 재생",shuffle:"셔플",repeat:"반복",like:"좋아요",dislike:"싫어요",addTo:"저장…",share:"공유",report:"신고",more:"더보기",seekForward:"앞으로 감기",seekBack:"뒤로 감기",secondsShort:"초",live:"실시간",related:"관련 동영상",adLabel:"광고",skipAd:"광고 건너뛰기",skipAdIn:"건너뛰기까지",visitAdvertiser:"광고주 방문",sponsored:"스폰서"},zh:{play:"播放",pause:"暂停",replay:"重新播放",mute:"静音",unmute:"取消静音",fullscreen:"全屏",exitFullscreen:"退出全屏",pip:"画中画",settings:"播放速度",subtitles:"字幕",subtitlesOff:"关闭",speed:"速度",quality:"画质",qualityAuto:"自动",next:"下一个",nextVideo:"下一个视频",previous:"上一个",playlist:"播放列表",scenes:"场景",sceneTypes:"场景类型",autoplay:"自动播放",playNext:"播放下一个",shuffle:"随机播放",repeat:"循环播放",like:"赞",dislike:"踩",addTo:"保存到…",share:"分享",report:"举报",more:"更多操作",seekForward:"快进",seekBack:"快退",secondsShort:"秒",live:"直播",related:"更多视频",adLabel:"广告",skipAd:"跳过广告",skipAdIn:"可跳过",visitAdvertiser:"访问广告主",sponsored:"赞助"},pt:{play:"Reproduzir",pause:"Pausar",replay:"Assistir novamente",mute:"Sem som",unmute:"Ativar som",fullscreen:"Tela cheia",exitFullscreen:"Sair da tela cheia",pip:"Picture-in-picture",settings:"Velocidade de reprodução",subtitles:"Legendas",subtitlesOff:"Desativadas",speed:"Velocidade",quality:"Qualidade",qualityAuto:"Automática",next:"Próximo",nextVideo:"Próximo vídeo",previous:"Anterior",playlist:"Playlist",scenes:"Cenas",sceneTypes:"Tipo de cena",autoplay:"Reprodução automática",playNext:"Reproduzir próximo",shuffle:"Aleatório",repeat:"Repetir",like:"Gostei",dislike:"Não gostei",addTo:"Salvar em…",share:"Compartilhar",report:"Denunciar",more:"Mais ações",seekForward:"Avançar",seekBack:"Retroceder",secondsShort:"s",live:"AO VIVO",related:"Mais vídeos",adLabel:"Anúncio",skipAd:"Pular anúncio",skipAdIn:"Pular em",visitAdvertiser:"Visitar anunciante",sponsored:"Patrocinado"},ar:{play:"تشغيل",pause:"إيقاف مؤقت",replay:"إعادة التشغيل",mute:"كتم الصوت",unmute:"إلغاء كتم الصوت",fullscreen:"ملء الشاشة",exitFullscreen:"الخروج من ملء الشاشة",pip:"صورة داخل صورة",settings:"سرعة التشغيل",subtitles:"الترجمة",subtitlesOff:"إيقاف",speed:"السرعة",quality:"الجودة",qualityAuto:"تلقائي",next:"التالي",nextVideo:"الفيديو التالي",previous:"السابق",playlist:"قائمة التشغيل",scenes:"المشاهد",sceneTypes:"نوع المشهد",autoplay:"تشغيل تلقائي",playNext:"تشغيل التالي",shuffle:"تشغيل عشوائي",repeat:"تكرار",like:"أعجبني",dislike:"لم يعجبني",addTo:"حفظ في…",share:"مشاركة",report:"إبلاغ",more:"المزيد من الإجراءات",seekForward:"تقديم",seekBack:"إرجاع",secondsShort:"ث",live:"مباشر",related:"المزيد من الفيديوهات",adLabel:"إعلان",skipAd:"تخطي الإعلان",skipAdIn:"التخطي بعد",visitAdvertiser:"زيارة المعلن",sponsored:"برعاية"},hi:{play:"चलाएं",pause:"रोकें",replay:"फिर से चलाएं",mute:"म्यूट करें",unmute:"अनम्यूट करें",fullscreen:"फ़ुल स्क्रीन",exitFullscreen:"फ़ुल स्क्रीन से बाहर निकलें",pip:"पिक्चर-इन-पिक्चर",settings:"प्लेबैक गति",subtitles:"सबटाइटल",subtitlesOff:"बंद",speed:"गति",quality:"क्वालिटी",qualityAuto:"ऑटो",next:"अगला",nextVideo:"अगला वीडियो",previous:"पिछला",playlist:"प्लेलिस्ट",scenes:"दृश्य",sceneTypes:"सीन प्रकार",autoplay:"ऑटोप्ले",playNext:"अगला चलाएं",shuffle:"शफ़ल",repeat:"दोहराएं",like:"पसंद",dislike:"नापसंद",addTo:"इसमें सहेजें…",share:"साझा करें",report:"रिपोर्ट करें",more:"अधिक कार्रवाइयां",seekForward:"आगे बढ़ाएं",seekBack:"पीछे करें",secondsShort:"s",live:"लाइव",related:"और वीडियो",adLabel:"विज्ञापन",skipAd:"विज्ञापन छोड़ें",skipAdIn:"छोड़ें",visitAdvertiser:"विज्ञापनदाता देखें",sponsored:"प्रायोजित"}}),Le})();
5
5
  //# sourceMappingURL=itube-modern-player.iife.js.map