ts-video-player 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cdn.min.js CHANGED
@@ -1,6 +1,6 @@
1
- function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown",streamType:"unknown",providerType:"unknown",loadingState:"idle",preload:"metadata",canPlay:!1,canPlayThrough:!1,error:null,playbackState:"idle",paused:!0,playing:!1,started:!1,ended:!1,seeking:!1,waiting:!1,currentTime:0,duration:0,playbackRate:1,loop:!1,autoplay:!1,playsinline:!0,muted:!1,volume:1,buffered:[],bufferedAmount:0,seekable:[],videoWidth:0,videoHeight:0,aspectRatio:1.7777777777777777,qualities:[],autoQuality:!0,audioTracks:[],textTracks:[],fullscreen:!1,pictureInPicture:!1,canFullscreen:!1,canPictureInPicture:!1,volumeAvailability:"unavailable",fullscreenAvailability:"unavailable",pipAvailability:"unavailable",controlsVisible:!0,userActive:!0,pointerOver:!1,title:"",poster:""}}class _{state;listeners=new Map;_pendingKeys=null;_flushScheduled=!1;constructor(e){this.state={...Be(),...e}}getState(){return this.state}get(e){return this.state[e]}set(e,t){if(this.state[e]===t)return;this.state={...this.state,[e]:t},this.scheduleNotify(e)}batch(e){for(let[t,i]of Object.entries(e))if(this.state[t]!==i)this.state[t]=i,this.scheduleNotify(t)}subscribe(e,t){if(typeof e==="function"){if(!this.listeners.has("*"))this.listeners.set("*",new Set);return this.listeners.get("*").add(e),()=>this.listeners.get("*")?.delete(e)}let i=e;if(!t)return()=>{};if(!this.listeners.has(i))this.listeners.set(i,new Set);return this.listeners.get(i).add(t),()=>this.listeners.get(i)?.delete(t)}reset(){this.state=Be(),this._pendingKeys=null,this._flushScheduled=!1,this.notifyAll()}flush(){if(this._pendingKeys){let e=this._pendingKeys;this._pendingKeys=null,this._flushScheduled=!1;for(let t of e)this.notifyKey(t);this.notifyAll()}}scheduleNotify(e){if(!this._pendingKeys)this._pendingKeys=new Set;if(this._pendingKeys.add(e),!this._flushScheduled)this._flushScheduled=!0,queueMicrotask(()=>this.flush())}notifyKey(e){this.listeners.get(e)?.forEach((t)=>t(this.state,e))}notifyAll(){this.listeners.get("*")?.forEach((e)=>e(this.state))}}function $e(e){if(e.duration===0||e.buffered.length===0)return 0;let t=0;for(let i of e.buffered)t+=i.end-i.start;return Math.min(t/e.duration,1)}var Fe="ts-video-player";function qe(e=localStorage){try{let t=e.getItem(Fe);if(t)return JSON.parse(t)}catch{}return{}}function Lt(e,t=localStorage){try{let i=qe(t);t.setItem(Fe,JSON.stringify({...i,...e}))}catch{}}function Oe(e,t=["volume","muted","playbackRate"],i=localStorage){let n=qe(i);if(n.volume!==void 0)e.set("volume",n.volume);if(n.muted!==void 0)e.set("muted",n.muted);if(n.playbackRate!==void 0)e.set("playbackRate",n.playbackRate);let s=t.map((r)=>e.subscribe(r,(a)=>{let o=a[r];Lt({[r]:o},i)}));return()=>s.forEach((r)=>r())}class S{listeners=new Map;onceListeners=new Map;on(e,t){if(!this.listeners.has(e))this.listeners.set(e,new Set);return this.listeners.get(e).add(t),()=>this.off(e,t)}once(e,t){if(!this.onceListeners.has(e))this.onceListeners.set(e,new Set);return this.onceListeners.get(e).add(t),()=>this.onceListeners.get(e)?.delete(t)}off(e,t){this.listeners.get(e)?.delete(t),this.onceListeners.get(e)?.delete(t)}emit(e,...t){this.listeners.get(e)?.forEach((n)=>{try{n(...t)}catch(s){console.error(`[ts-video-player] Error in event handler for "${String(e)}":`,s)}});let i=this.onceListeners.get(e);if(i)i.forEach((n)=>{try{n(...t)}catch(s){console.error(`[ts-video-player] Error in once handler for "${String(e)}":`,s)}}),i.clear()}removeAllListeners(e){if(e)this.listeners.delete(e),this.onceListeners.delete(e);else this.listeners.clear(),this.onceListeners.clear()}listenerCount(e){return(this.listeners.get(e)?.size||0)+(this.onceListeners.get(e)?.size||0)}}class M{media;emitter;listeners=[];constructor(e,t){this.media=e,this.emitter=t,this.attachListeners()}attachListeners(){let e=(t,i)=>{this.media.addEventListener(t,i),this.listeners.push(()=>this.media.removeEventListener(t,i))};e("loadstart",()=>this.emitter.emit("loadstart")),e("loadedmetadata",()=>this.emitter.emit("loadedmetadata")),e("loadeddata",()=>this.emitter.emit("loadeddata")),e("canplay",()=>this.emitter.emit("canplay")),e("canplaythrough",()=>this.emitter.emit("canplaythrough")),e("play",()=>this.emitter.emit("play")),e("pause",()=>this.emitter.emit("pause")),e("playing",()=>this.emitter.emit("playing")),e("waiting",()=>this.emitter.emit("waiting")),e("ended",()=>this.emitter.emit("ended")),e("seeking",()=>this.emitter.emit("seeking")),e("seeked",()=>this.emitter.emit("seeked")),e("timeupdate",()=>this.emitter.emit("timeupdate",this.media.currentTime)),e("durationchange",()=>this.emitter.emit("durationchange",this.media.duration)),e("volumechange",()=>this.emitter.emit("volumechange",this.media.volume,this.media.muted)),e("ratechange",()=>this.emitter.emit("ratechange",this.media.playbackRate)),e("progress",()=>{let t=this.getTimeRanges(this.media.buffered);this.emitter.emit("progress",t)}),e("error",()=>{let t=this.normalizeError(this.media.error);this.emitter.emit("error",t)})}getTimeRanges(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}normalizeError(e){if(!e)return{code:0,message:"Unknown error"};let t={1:"The fetching of the media resource was aborted by the user agent.",2:"A network error occurred while fetching the media resource.",3:"An error occurred while decoding the media resource.",4:"The media resource is not supported."};return{code:e.code,message:t[e.code]||e.message||"Unknown error"}}destroy(){this.listeners.forEach((e)=>e()),this.listeners=[]}}function N(e){let t=["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],i=()=>{let n=!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement);e(n)};return t.forEach((n)=>document.addEventListener(n,i)),()=>{t.forEach((n)=>document.removeEventListener(n,i))}}function z(e,t){let i=()=>t(!0),n=()=>t(!1);return e.addEventListener("enterpictureinpicture",i),e.addEventListener("leavepictureinpicture",n),()=>{e.removeEventListener("enterpictureinpicture",i),e.removeEventListener("leavepictureinpicture",n)}}var Ct={" ":"togglePlay",k:"togglePlay",m:"toggleMute",f:"toggleFullscreen",i:"togglePiP",c:"toggleCaptions",ArrowLeft:"seekBackward",ArrowRight:"seekForward",j:"seekBackward",l:"seekForward",ArrowUp:"volumeUp",ArrowDown:"volumeDown",">":"speedUp","<":"speedDown",Home:"seekStart",End:"seekEnd","0":"seek0","1":"seek10","2":"seek20","3":"seek30","4":"seek40","5":"seek50","6":"seek60","7":"seek70","8":"seek80","9":"seek90"};function Ne(e,t={}){let{seekStep:i=5,volumeStep:n=0.1,speedStep:s=0.25}=t;return(r)=>{if(r.target instanceof HTMLInputElement||r.target instanceof HTMLTextAreaElement||r.target instanceof HTMLSelectElement||r.target?.isContentEditable)return;let a=r.key,o=Ct[a];if(!o)return;switch(r.preventDefault(),o){case"togglePlay":e.togglePlay();break;case"toggleMute":e.toggleMute();break;case"toggleFullscreen":e.toggleFullscreen();break;case"togglePiP":e.togglePiP();break;case"toggleCaptions":e.toggleCaptions();break;case"seekBackward":e.seekBackward();break;case"seekForward":e.seekForward();break;case"volumeUp":e.volumeUp();break;case"volumeDown":e.volumeDown();break;case"speedUp":e.speedUp();break;case"speedDown":e.speedDown();break;case"seekStart":e.seekStart();break;case"seekEnd":e.seekEnd();break;default:if(o.startsWith("seek")){let l=parseInt(o.replace("seek",""),10);if(!isNaN(l))e.seekPercent(l)}}}}function ze(e,t={}){let{timeout:i=3000,onActive:n,onInactive:s}=t,r=null,a=!0,o=()=>{if(!a)a=!0,n?.();d()},l=()=>{if(a)a=!1,s?.()},d=()=>{if(r)clearTimeout(r);r=setTimeout(l,i)},c=["mousemove","mouseenter","mouseleave","mousedown","keydown","touchstart","touchmove"];return c.forEach((u)=>e.addEventListener(u,o)),d(),()=>{if(r)clearTimeout(r);c.forEach((u)=>e.removeEventListener(u,o))}}function Ue(){return typeof navigator<"u"&&"mediaSession"in navigator}function Qe(e,t,i){if(!Ue())return()=>{};let n=navigator.mediaSession;if(i)Rt(i);let s=[["play",()=>t.play()],["pause",()=>t.pause()],["stop",()=>t.stop()],["seekbackward",(d)=>{let c=d.seekOffset||-10;t.seekBy(c)}],["seekforward",(d)=>{let c=d.seekOffset||10;t.seekBy(c)}],["seekto",(d)=>{let c=d.seekTime;if(c!==void 0)t.seekTo(c)}]];for(let[d,c]of s)try{n.setActionHandler(d,c)}catch{}let r=e.subscribe("paused",(d)=>{n.playbackState=d.paused?"paused":"playing"}),a=null,o=()=>{let d=e.getState();if(!isFinite(d.duration)||d.duration<=0)return;try{n.setPositionState({duration:d.duration,playbackRate:d.playbackRate,position:Math.min(d.currentTime,d.duration)})}catch{}},l=e.subscribe("playing",(d)=>{if(d.playing){if(o(),!a)a=setInterval(o,1000)}else{if(a)clearInterval(a),a=null;o()}});return()=>{if(a)clearInterval(a);r(),l();for(let[d]of s)try{n.setActionHandler(d,null)}catch{}}}function Rt(e){if(!Ue())return;navigator.mediaSession.metadata=new MediaMetadata({title:e.title||"",artist:e.artist||"",album:e.album||"",artwork:e.artwork||[]})}function Ke(){return typeof screen<"u"&&"orientation"in screen&&typeof screen.orientation.lock==="function"}function We(e){if(!Ke())return;let t={landscape:"landscape",portrait:"portrait",any:"any"};screen.orientation.lock(t[e]).catch(()=>{})}function je(){if(!Ke())return;try{screen.orientation.unlock()}catch{}}function It(){if(typeof navigator>"u")return!1;let e=navigator.userAgent;if(/iPad|iPhone|iPod/.test(e)&&!window.MSStream)return!0;if(navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1)return!0;return!1}function Ht(){if(typeof navigator>"u")return!1;return/^(?:(?!chrome|android).)*safari/i.test(navigator.userAgent)}function Ye(){if(typeof window>"u")return!1;return navigator.standalone===!0||window.matchMedia("(display-mode: standalone)").matches}function Xe(e){if(It())return"unsupported";if(!e)return"unavailable";return"available"}async function Ge(e){let t=e.volume;try{let i=t===1?0.5:1;e.volume=i,await new Promise((s)=>setTimeout(s,0));let n=e.volume!==t;return e.volume=t,n?"available":"unsupported"}catch{try{e.volume=t}catch{}return"unsupported"}}function Je(e,t){let i=typeof document<"u"?document:null;if(!i)return"unsupported";if(i.fullscreenEnabled||i.webkitFullscreenEnabled)return"available";if(i.mozFullScreenEnabled||i.msFullscreenEnabled)return"available";if(t){let n=t;if(n.webkitSupportsFullscreen===!0)return"available";if(typeof n.webkitEnterFullscreen==="function")return"available"}if(!e&&!t)return"unavailable";return"unsupported"}async function Ze(e,t){let i=t;if(e){let n=e;if(typeof n.requestFullscreen==="function")return n.requestFullscreen();if(typeof n.webkitRequestFullscreen==="function")return n.webkitRequestFullscreen();if(typeof n.webkitRequestFullScreen==="function")return n.webkitRequestFullScreen()}if(i&&typeof i.webkitEnterFullscreen==="function"){i.webkitEnterFullscreen();return}if(t&&typeof t.requestFullscreen==="function")return t.requestFullscreen()}async function et(e){let t=document,i=e;if(typeof t.exitFullscreen==="function")return t.exitFullscreen();if(typeof t.webkitExitFullscreen==="function")return t.webkitExitFullscreen();if(typeof t.webkitCancelFullScreen==="function")return t.webkitCancelFullScreen();if(i&&typeof i.webkitExitFullscreen==="function")i.webkitExitFullscreen()}function tt(e){if(!e)return"unavailable";if("requestPictureInPicture"in e){if(typeof document<"u"&&document.pictureInPictureEnabled===!1)return"unavailable";if(Ht()&&Ye())return"unavailable";return"available"}let t=e;if(typeof t.webkitSetPresentationMode==="function"){if(Ye())return"unavailable";if(typeof t.webkitSupportsPresentationMode==="function")return t.webkitSupportsPresentationMode("picture-in-picture")?"available":"unsupported";return"available"}return"unsupported"}async function it(e){let t=e;if(typeof t.requestPictureInPicture==="function"){await t.requestPictureInPicture();return}if(typeof t.webkitSetPresentationMode==="function")t.webkitSetPresentationMode("picture-in-picture")}async function nt(e){if(document.pictureInPictureElement&&typeof document.exitPictureInPicture==="function"){await document.exitPictureInPicture();return}if(e){let t=e;if(t.webkitPresentationMode==="picture-in-picture"&&typeof t.webkitSetPresentationMode==="function")t.webkitSetPresentationMode("inline")}}class b{container=null;options={};events=new S;_ready=!1;get mediaElement(){return null}get ready(){return this._ready}async setup(e,t){this.container=e,this.options=t,await this.initialize(),this._ready=!0,this.events.emit("ready")}destroy(){this._ready=!1,this.cleanup(),this.events.removeAllListeners()}stop(){this.pause(),this.seekTo(0)}getQualities(){return[]}setQuality(e){}getTextTracks(){return[]}setTextTrackMode(e,t){}getAudioTracks(){return[]}setAudioTrack(e){}getFeatureAvailability(e){let t=this.mediaElement,i=t instanceof HTMLMediaElement?t:null,n=t instanceof HTMLVideoElement?t:null;switch(e){case"volume":return t&&!(t instanceof HTMLMediaElement)?"available":Xe(i);case"fullscreen":return Je(this.container,n);case"pip":return t&&!(t instanceof HTMLMediaElement)?"unsupported":tt(n);default:return"unsupported"}}async enterFullscreen(){await Ze(this.container,this.mediaElement)}async exitFullscreen(){await et(this.mediaElement)}getFullscreenElement(){return this.container}async enterPiP(){let e=this.mediaElement;if(!e)return;await it(e)}async exitPiP(){await nt(this.mediaElement)}on(e,t){this.events.on(e,t)}off(e,t){this.events.off(e,t)}emitError(e,t,i){let n={code:e,message:t,details:i};this.events.emit("error",n)}}function ve(e){if(typeof e==="string"){let t=ge(e);if(t==="mp4"||t==="webm"||t==="ogg"||t==="ogv"||t==="mov"||t==="mp3"||t==="wav"||t==="flac"||t==="m4a"||t==="aac"||t==="oga"||t==="opus")return!0;return!1}if(typeof e==="object"&&"type"in e){let t=e.type?.toLowerCase()||"";return t.startsWith("video/")||t.startsWith("audio/")||t==="application/ogg"}return!1}function ge(e){let t=e.split(/[?#]/,1)[0];return t.slice(t.lastIndexOf(".")+1).toLowerCase()}function U(e){let t=ge(e);return{mp4:"video/mp4",webm:"video/webm",ogg:"video/ogg",ogv:"video/ogg",mov:"video/quicktime",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",m4a:"audio/mp4",aac:"audio/aac",oga:"audio/ogg",opus:"audio/ogg; codecs=opus"}[t||""]||"video/mp4"}class L extends b{name="html5";type="video";media=null;eventsNormalizer=null;cleanupFullscreen=null;cleanupPiP=null;isAudio=!1;get mediaElement(){return this.media}async initialize(){if(!this.container)throw Error("Container element is required");if(this.isAudio=this.options.mediaType==="audio",this.media=document.createElement(this.isAudio?"audio":"video"),this.media.className="ts-video-player__media",this.options.autoplay)this.media.autoplay=!0;if(this.options.loop)this.media.loop=!0;if(this.options.muted)this.media.muted=!0;if(this.options.playsinline&&!this.isAudio)this.media.playsInline=!0;if(this.options.preload)this.media.preload=this.options.preload;if(this.options.crossorigin)this.media.crossOrigin=this.options.crossorigin;if(this.options.controlsList?.length)this.media.setAttribute("controlslist",this.options.controlsList.join(" "));if(!this.isAudio&&this.options.disablePictureInPicture)this.media.disablePictureInPicture=!0;if(this.options.poster&&!this.isAudio)this.media.poster=this.options.poster;if(this.options.volume!==void 0)this.media.volume=this.options.volume;this.container.appendChild(this.media);for(let e of this.options.tracks??[])this.addTextTrack(e);if(this.eventsNormalizer=new M(this.media,this.events),this.cleanupFullscreen=N((e)=>{this.events.emit("fullscreenchange",e)}),!this.isAudio&&this.media instanceof HTMLVideoElement)this.cleanupPiP=z(this.media,(e)=>{this.events.emit("pipchange",e)});if(!this.isAudio)this.media.addEventListener("loadedmetadata",()=>{let e=this.media,t=this.getFeatureAvailability("fullscreen"),i=this.getFeatureAvailability("pip"),n=this.getFeatureAvailability("volume");this.events.emit("statechange",{videoWidth:e.videoWidth,videoHeight:e.videoHeight,aspectRatio:(e.videoHeight>0?e.videoWidth/e.videoHeight:0)||1.7777777777777777,canFullscreen:t==="available",canPictureInPicture:i==="available",fullscreenAvailability:t,pipAvailability:i,volumeAvailability:n}),this.events.emit("availabilitychange","fullscreen",t),this.events.emit("availabilitychange","pip",i),this.events.emit("availabilitychange","volume",n)});if(this.media.addEventListener("loadeddata",()=>{if(!this.media)return;Ge(this.media).then((e)=>{this.events.emit("statechange",{volumeAvailability:e}),this.events.emit("availabilitychange","volume",e)}).catch(()=>{})}),!this.isAudio&&this.media instanceof HTMLVideoElement)this.media.addEventListener("webkitpresentationmodechanged",()=>{let e=this.media;if(e?.webkitPresentationMode){let t=e.webkitPresentationMode==="picture-in-picture";this.events.emit("pipchange",t)}})}cleanup(){if(this.eventsNormalizer?.destroy(),this.cleanupFullscreen?.(),this.cleanupPiP?.(),this.media)this.media.pause(),this.media.removeAttribute("src"),this.media.load(),this.media.remove(),this.media=null}canPlay(e){return ve(e)}async load(e){if(!this.media)return;this.media.innerHTML="",this.media.removeAttribute("src");let t=Array.isArray(e)?e:[e];for(let i of t)if(typeof i==="string"){let n=document.createElement("source");n.src=i,n.type=U(i),this.media.appendChild(n)}else if("src"in i&&typeof i.src==="string"){let n=i,s=document.createElement("source");s.src=n.src,s.type=n.type||U(n.src),this.media.appendChild(s)}this.media.load()}async play(){if(!this.media)return;try{await this.media.play()}catch(e){if(e.name==="NotAllowedError")this.emitError(1,"Playback was blocked. User interaction required.",e);else throw e}}pause(){this.media?.pause()}seekTo(e){if(this.media)this.media.currentTime=Math.max(0,Math.min(e,this.getDuration()))}getCurrentTime(){return this.media?.currentTime||0}getDuration(){return this.media?.duration||0}setVolume(e){if(this.media)this.media.volume=Math.max(0,Math.min(1,e))}getVolume(){return this.media?.volume||1}setMuted(e){if(this.media)this.media.muted=e}getMuted(){return this.media?.muted||!1}setPlaybackRate(e){if(this.media)this.media.playbackRate=Math.max(0.25,Math.min(4,e))}getPlaybackRate(){return this.media?.playbackRate||1}getTextTracks(){if(!this.media)return[];let e=[],t=this.media.textTracks;for(let i=0;i<t.length;i++){let n=t[i];e.push({id:String(i),kind:n.kind,label:n.label||`Track ${i+1}`,language:n.language||"",mode:n.mode,cues:this.getTrackCues(n)})}return e}getTrackCues(e){if(!e.cues)return[];let t=[];for(let i=0;i<e.cues.length;i++){let n=e.cues[i];t.push({id:n.id||String(i),startTime:n.startTime,endTime:n.endTime,text:n.text})}return t}setTextTrackMode(e,t){if(!this.media)return;let i=parseInt(e,10),n=this.media.textTracks[i];if(n)n.mode=t,this.events.emit("texttrackchange",t==="showing"?this.getTextTracks()[i]:null)}getAudioTracks(){if(!this.media||this.isAudio)return[];let e=this.media;if(!("audioTracks"in e))return[];let t=e.audioTracks,i=[];for(let n=0;n<t.length;n++){let s=t[n];i.push({id:s.id||String(n),label:s.label||`Track ${n+1}`,language:s.language||"",kind:s.kind||"",selected:s.enabled})}return i}setAudioTrack(e){if(!this.media||this.isAudio)return;let t=this.media;if(!("audioTracks"in t))return;let i=t.audioTracks;for(let n=0;n<i.length;n++){let s=i[n].id===e||String(n)===e;i[n].enabled=s}this.events.emit("audiotrackchange",this.getAudioTracks().find((n)=>n.selected)||null)}addTextTrack(e){if(!this.media)return;let t=document.createElement("track");if(e.src)t.src=e.src;if(t.kind=e.kind||"subtitles",t.label=e.label||"",t.srclang=e.language||"",e.default)t.default=!0;this.media.appendChild(t)}}var ye={name:"html5",type:"video",canPlay(e){return ve(e)},mediaType(e){if(typeof e==="string"){let t=ge(e);if(["mp3","wav","flac","m4a","aac","oga","opus"].includes(t))return"audio";return"video"}if(typeof e==="object"&&"type"in e){if((e.type?.toLowerCase()||"").startsWith("audio/"))return"audio"}return"video"},async load(e,t){let i=new L;return await i.setup(e,t),i}};var Vt=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,/youtube\.com\/v\/([a-zA-Z0-9_-]{11})/,/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/];function E(e){for(let t of Vt){let i=e.match(t);if(i)return i[1]}return null}function fe(e){if(typeof e==="string")return E(e)!==null;if(typeof e==="object"&&"type"in e)return e.type==="youtube";return!1}function Dt(e){if(typeof e==="string"){let t=E(e);if(!t)return null;let i=new URL(e,"https://youtube.com"),n=i.searchParams.get("t")||i.searchParams.get("start"),s=i.searchParams.get("end");return{videoId:t,startTime:n?st(n):void 0,endTime:s?st(s):void 0}}if(typeof e==="object"&&"type"in e&&e.type==="youtube"){let t=e;return{videoId:t.videoId||E(t.src)||"",startTime:t.startTime,endTime:t.endTime}}return null}function st(e){if(/^\d+$/.test(e))return parseInt(e,10);let t=e.match(/(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?/);if(t){let n=parseInt(t[1]||"0",10),s=parseInt(t[2]||"0",10),r=parseInt(t[3]||"0",10);return n*3600+s*60+r}let i=e.split(":").map((n)=>parseInt(n,10));if(i.length===2)return i[0]*60+i[1];if(i.length===3)return i[0]*3600+i[1]*60+i[2];return 0}class C extends b{name="youtube";type="youtube";player=null;iframe=null;pendingVideoId=null;playerReady=!1;startTime;endTime;timeUpdateInterval=null;lastState=-1;pendingPlay=!1;get mediaElement(){return this.iframe}async initialize(){if(!this.container)throw Error("Container element is required");await this.loadYouTubeAPI();let e=document.createElement("div");e.id=`ts-video-player-yt-${Date.now()}`,e.className="ts-video-player__youtube",this.container.appendChild(e);let t={autoplay:this.options.autoplay?1:0,controls:0,disablekb:1,enablejsapi:1,iv_load_policy:3,modestbranding:1,playsinline:this.options.playsinline?1:0,rel:0,origin:window.location.origin};if(this.options.youtubeParams)Object.assign(t,this.options.youtubeParams);if(this.player=new window.YT.Player(e,{host:"https://www.youtube-nocookie.com",width:"100%",height:"100%",playerVars:t,events:{onReady:()=>this.onReady(),onStateChange:(i)=>this.onStateChange(i),onError:(i)=>this.onError(i),onPlaybackQualityChange:()=>this.onQualityChange(),onPlaybackRateChange:()=>this.onRateChange()}}),this.iframe=this.player.getIframe(),this.iframe.className="ts-video-player__media",this.iframe.style.cssText="position:absolute;left:0;top:-100%;width:100%;height:300%;border:0",this.iframe.parentElement)this.iframe.parentElement.style.overflow="hidden"}async loadYouTubeAPI(){if(window.YT?.Player)return;return new Promise((e)=>{if(document.querySelector('script[src*="youtube.com/iframe_api"]')){let i=()=>{if(window.YT?.Player)e();else setTimeout(i,100)};i();return}let t=document.createElement("script");t.src="https://www.youtube.com/iframe_api",t.async=!0,window.onYouTubeIframeAPIReady=()=>{e()},document.head.appendChild(t)})}cleanup(){if(this.timeUpdateInterval)clearInterval(this.timeUpdateInterval),this.timeUpdateInterval=null;this.player?.destroy(),this.player=null,this.playerReady=!1,this.pendingPlay=!1,this.iframe=null}onReady(){if(this.playerReady=!0,this.timeUpdateInterval=setInterval(()=>{if(this.player&&this.lastState===1)this.events.emit("timeupdate",this.getCurrentTime())},250),this.events.emit("loadedmetadata"),this.events.emit("canplay"),this.pendingVideoId){let e=this.pendingVideoId;this.pendingVideoId=null,this.loadVideo(e,this.startTime,this.endTime)}else if(this.pendingPlay)this.pendingPlay=!1,this.player?.playVideo()}onStateChange(e){let t=e.data;this.lastState=t;let i=window.YT.PlayerState;switch(t){case i.UNSTARTED:this.events.emit("loadstart");break;case i.PLAYING:if(this.getDuration()>0)this.events.emit("durationchange",this.getDuration());this.events.emit("play"),this.events.emit("playing"),this.events.emit("statechange",{paused:!1,playing:!0,waiting:!1});break;case i.PAUSED:this.events.emit("pause"),this.events.emit("statechange",{paused:!0,playing:!1});break;case i.BUFFERING:this.events.emit("waiting"),this.events.emit("statechange",{waiting:!0});break;case i.ENDED:this.events.emit("ended"),this.events.emit("statechange",{ended:!0,playing:!1});break;case i.CUED:this.events.emit("loadeddata"),this.events.emit("durationchange",this.getDuration());break}}onError(e){let t={2:"Invalid video ID",5:"HTML5 player error",100:"Video not found or removed",101:"Video cannot be embedded",150:"Video cannot be embedded"};this.emitError(e.data,t[e.data]||"Unknown YouTube error")}onQualityChange(){let e=this.player?.getPlaybackQuality()||"auto",t=this.getQualities();this.events.emit("qualitychange",t.find((i)=>i.id===e)||null)}onRateChange(){this.events.emit("ratechange",this.getPlaybackRate())}canPlay(e){return fe(e)}async load(e){let t=Dt(e);if(!t){this.emitError(2,"Invalid YouTube source");return}if(this.startTime=t.startTime,this.endTime=t.endTime,!this.player||!this._ready||!this.playerReady){this.pendingVideoId=t.videoId;return}this.loadVideo(t.videoId,t.startTime,t.endTime)}loadVideo(e,t,i){if(!this.player)return;if(this.options.autoplay||this.pendingPlay)this.pendingPlay=!1,this.player.loadVideoById({videoId:e,startSeconds:t,endSeconds:i});else this.player.cueVideoById({videoId:e,startSeconds:t,endSeconds:i})}async play(){if(!this.player||!this.playerReady||this.pendingVideoId){this.pendingPlay=!0;return}this.player.playVideo()}pause(){if(this.pendingPlay=!1,this.playerReady)this.player?.pauseVideo()}stop(){if(this.pendingPlay=!1,this.playerReady)this.player?.stopVideo()}seekTo(e){this.player?.seekTo(e,!0),this.events.emit("seeking"),setTimeout(()=>this.events.emit("seeked"),100)}getCurrentTime(){return this.player?.getCurrentTime()||0}getDuration(){return this.player?.getDuration()||0}setVolume(e){this.player?.setVolume(Math.round(e*100)),this.events.emit("volumechange",e,this.getMuted())}getVolume(){return(this.player?.getVolume()||100)/100}setMuted(e){if(e)this.player?.mute();else this.player?.unMute();this.events.emit("volumechange",this.getVolume(),e)}getMuted(){return this.player?.isMuted()||!1}setPlaybackRate(e){this.player?.setPlaybackRate(e)}getPlaybackRate(){return this.player?.getPlaybackRate()||1}getQualities(){let e=this.player?.getAvailableQualityLevels()||[],t={highres:2160,hd2160:2160,hd1440:1440,hd1080:1080,hd720:720,large:480,medium:360,small:240,tiny:144},i=this.player?.getPlaybackQuality();return e.map((n)=>({id:n,width:Math.round((t[n]||480)*1.7777777777777777),height:t[n]||480,bitrate:0,selected:n===i}))}setQuality(e){if(e==="auto")this.player?.setPlaybackQuality("default");else this.player?.setPlaybackQuality(e.id)}}var be={name:"youtube",type:"youtube",canPlay(e){return fe(e)},mediaType(){return"video"},preconnect(){return["https://www.youtube-nocookie.com","https://www.youtube.com","https://i.ytimg.com","https://s.ytimg.com"]},async load(e,t){let i=new C;return await i.setup(e,t),i}};var Bt=[/vimeo\.com\/(\d+)/,/vimeo\.com\/video\/(\d+)/,/player\.vimeo\.com\/video\/(\d+)/,/vimeo\.com\/channels\/[\w]+\/(\d+)/,/vimeo\.com\/groups\/[\w]+\/videos\/(\d+)/];function Q(e){for(let t of Bt){let i=e.match(t);if(i)return i[1]}return null}function at(e){let t=e.match(/vimeo\.com\/\d+\/([a-f0-9]+)/);return t?t[1]:null}function ke(e){if(typeof e==="string")return Q(e)!==null;if(typeof e==="object"&&"type"in e)return e.type==="vimeo";return!1}function $t(e){if(typeof e==="string"){let t=Q(e);if(!t)return null;return{videoId:t,hash:at(e)||void 0}}if(typeof e==="object"&&"type"in e&&e.type==="vimeo"){let t=e;return{videoId:t.videoId||Q(t.src)||"",hash:t.hash}}return null}var rt="https://player.vimeo.com/api/player.js";class Te extends b{name="vimeo";type="vimeo";container_el=null;player=null;iframe=null;timeUpdateInterval=null;_qualities=[];_duration=0;get mediaElement(){return this.iframe}async initialize(){if(!this.container)throw Error("Container element is required");await this.loadVimeoSDK(),this.container_el=document.createElement("div"),this.container_el.className="ts-video-player__vimeo",this.container.appendChild(this.container_el)}async loadVimeoSDK(){if(window.Vimeo)return;return new Promise((e,t)=>{if(document.querySelector(`script[src="${rt}"]`)){let n=()=>{if(window.Vimeo)e();else setTimeout(n,100)};n();return}let i=document.createElement("script");i.src=rt,i.async=!0,i.onload=()=>e(),i.onerror=()=>t(Error("Failed to load Vimeo SDK")),document.head.appendChild(i)})}cleanup(){if(this.timeUpdateInterval)clearInterval(this.timeUpdateInterval),this.timeUpdateInterval=null;this.player?.destroy(),this.player=null,this.iframe=null,this.container_el?.remove(),this.container_el=null}canPlay(e){return ke(e)}async load(e){let t=$t(e);if(!t||!this.container_el){this.emitError(2,"Invalid Vimeo source");return}if(this.player)await this.player.destroy(),this.player=null;let i={id:parseInt(t.videoId,10),autopause:!1,autoplay:this.options.autoplay||!1,controls:!1,loop:this.options.loop||!1,muted:this.options.muted||!1,playsinline:this.options.playsinline!==!1,responsive:!0,dnt:!0};if(this.options.vimeoParams)Object.assign(i,this.options.vimeoParams);if(this.player=new window.Vimeo.Player(this.container_el,i),await this.player.ready(),this.iframe=this.container_el.querySelector("iframe"),this.iframe)this.iframe.className="ts-video-player__media",this.iframe.style.cssText="position:absolute;inset:0;width:100%;height:100%;border:0";this.attachVimeoEvents(),this.events.emit("loadedmetadata"),this.events.emit("canplay"),this._duration=await this.player.getDuration(),this.events.emit("durationchange",this._duration),await this.updateQualities();let[n,s]=await Promise.all([this.player.getVideoWidth(),this.player.getVideoHeight()]);this.events.emit("statechange",{videoWidth:n,videoHeight:s,aspectRatio:n/s||1.7777777777777777,canFullscreen:!0,canPictureInPicture:!1})}attachVimeoEvents(){if(!this.player)return;this.player.on("play",()=>{this.events.emit("play"),this.events.emit("playing"),this.events.emit("statechange",{paused:!1,playing:!0})}),this.player.on("pause",()=>{this.events.emit("pause"),this.events.emit("statechange",{paused:!0,playing:!1})}),this.player.on("ended",()=>{this.events.emit("ended"),this.events.emit("statechange",{ended:!0,playing:!1})}),this.player.on("timeupdate",(e)=>{this.events.emit("timeupdate",e.seconds)}),this.player.on("seeking",()=>{this.events.emit("seeking")}),this.player.on("seeked",()=>{this.events.emit("seeked")}),this.player.on("bufferstart",()=>{this.events.emit("waiting"),this.events.emit("statechange",{waiting:!0})}),this.player.on("bufferend",()=>{this.events.emit("statechange",{waiting:!1})}),this.player.on("progress",(e)=>{let t=[{start:0,end:e.percent*this._duration}];this.events.emit("progress",t)}),this.player.on("volumechange",async()=>{let[e,t]=await Promise.all([this.player.getVolume(),this.player.getMuted()]);this.events.emit("volumechange",e,t)}),this.player.on("playbackratechange",(e)=>{this.events.emit("ratechange",e.playbackRate)}),this.player.on("qualitychange",async()=>{await this.updateQualities();let e=this._qualities.find((t)=>t.selected);this.events.emit("qualitychange",e||null)}),this.player.on("error",(e)=>{this.emitError(5,e.message,e)})}async updateQualities(){if(!this.player)return;try{let e=await this.player.getQualities();this._qualities=e.map((t)=>{let i=t.label.match(/(\d+)p/),n=i?parseInt(i[1],10):0;return{id:t.id,width:Math.round(n*1.7777777777777777),height:n,bitrate:0,selected:t.active}}),this.events.emit("statechange",{qualities:this._qualities})}catch{}}async play(){try{await this.player?.play()}catch(e){if(e.name==="NotAllowedError")this.emitError(1,"Playback was blocked. User interaction required.",e);else throw e}}pause(){this.player?.pause()}stop(){this.pause(),this.seekTo(0)}seekTo(e){this.player?.setCurrentTime(e)}getCurrentTime(){return 0}getDuration(){return this._duration}setVolume(e){this.player?.setVolume(Math.max(0,Math.min(1,e)))}getVolume(){return 1}setMuted(e){this.player?.setMuted(e)}getMuted(){return!1}setPlaybackRate(e){this.player?.setPlaybackRate(e)}getPlaybackRate(){return 1}getQualities(){return this._qualities}setQuality(e){if(!this.player)return;if(e==="auto")this.player.setQuality("auto");else this.player.setQuality(e.id)}async enableTextTrack(e){await this.player?.enableTextTrack(e)}async disableTextTrack(){await this.player?.disableTextTrack()}async getChapters(){if(!this.player)return[];try{return await this.player.getChapters()}catch{return[]}}}var we={name:"vimeo",type:"vimeo",canPlay(e){return ke(e)},mediaType(){return"video"},preconnect(){return["https://player.vimeo.com","https://i.vimeocdn.com","https://f.vimeocdn.com"]},async load(e,t){let i=new Te;return await i.setup(e,t),i}};function xe(e){if(typeof e==="string"){let t=e.toLowerCase();return t.endsWith(".m3u8")||t.includes("application/x-mpegurl")||t.includes("application/vnd.apple.mpegurl")}if(typeof e==="object"&&"type"in e){let t=e.type?.toLowerCase()||"";return t==="application/x-mpegurl"||t==="application/vnd.apple.mpegurl"}return!1}function ot(){return document.createElement("video").canPlayType("application/vnd.apple.mpegurl")!==""}var Ft="https://cdn.jsdelivr.net/npm/hls.js@latest/dist/hls.min.js";class R extends b{name="hls";type="hls";video=null;hls=null;eventsNormalizer=null;cleanupFullscreen=null;cleanupPiP=null;useNativeHLS=!1;_qualities=[];_audioTracks=[];_textTracks=[];currentQualityIndex=-1;get mediaElement(){return this.video}get canLiveSync(){return!this.useNativeHLS&&this.hls!==null}get hlsConfig(){return this.hls?.config||{}}async initialize(){if(!this.container)throw Error("Container element is required");if(this.video=document.createElement("video"),this.video.className="ts-video-player__media",this.options.autoplay)this.video.autoplay=!0;if(this.options.loop)this.video.loop=!0;if(this.options.muted)this.video.muted=!0;if(this.options.playsinline)this.video.playsInline=!0;if(this.options.preload)this.video.preload=this.options.preload;if(this.options.crossorigin)this.video.crossOrigin=this.options.crossorigin;if(this.options.poster)this.video.poster=this.options.poster;if(this.options.volume!==void 0)this.video.volume=this.options.volume;if(this.container.appendChild(this.video),this.eventsNormalizer=new M(this.video,this.events),this.cleanupFullscreen=N((e)=>{this.events.emit("fullscreenchange",e)}),this.cleanupPiP=z(this.video,(e)=>{this.events.emit("pipchange",e)}),this.useNativeHLS=ot(),!this.useNativeHLS)await this.loadHLSLibrary();this.video.addEventListener("loadedmetadata",()=>{let e=this.getFeatureAvailability("fullscreen"),t=this.getFeatureAvailability("pip"),i=this.getFeatureAvailability("volume");this.events.emit("statechange",{videoWidth:this.video.videoWidth,videoHeight:this.video.videoHeight,aspectRatio:(this.video.videoHeight>0?this.video.videoWidth/this.video.videoHeight:0)||1.7777777777777777,canFullscreen:e==="available",canPictureInPicture:t==="available",fullscreenAvailability:e,pipAvailability:t,volumeAvailability:i}),this.events.emit("availabilitychange","fullscreen",e),this.events.emit("availabilitychange","pip",t),this.events.emit("availabilitychange","volume",i)})}async loadHLSLibrary(){if(window.Hls)return;return new Promise((e,t)=>{let i=document.createElement("script");i.src=this.options.hlsCdnUrl||Ft,i.async=!0,i.onload=()=>e(),i.onerror=()=>t(Error("Failed to load HLS.js")),document.head.appendChild(i)})}cleanup(){if(this.eventsNormalizer?.destroy(),this.cleanupFullscreen?.(),this.cleanupPiP?.(),this.hls)this.hls.destroy(),this.hls=null;if(this.video)this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video=null;this._qualities=[],this._audioTracks=[],this._textTracks=[]}canPlay(e){return xe(e)}async load(e){if(!this.video)return;let t=typeof e==="string"?e:e.src;if(this.useNativeHLS){this.video.src=t,this.video.load();return}if(!window.Hls)await this.loadHLSLibrary();if(!window.Hls?.isSupported()){this.emitError(4,"HLS is not supported in this browser");return}if(this.hls)this.hls.destroy();let i={enableWorker:!0,lowLatencyMode:!1,...this.options.hlsConfig};this.hls=new window.Hls(i),this.attachHLSEvents(),this.hls.attachMedia(this.video),this.hls.loadSource(t)}attachHLSEvents(){if(!this.hls||!window.Hls)return;let e=window.Hls;this.hls.on(e.Events.MANIFEST_PARSED,(t,i)=>{if(this.updateQualities(i.levels),this.options.autoplay)this.video?.play().catch(()=>{})}),this.hls.on(e.Events.LEVEL_SWITCHED,(t,i)=>{this.currentQualityIndex=i.level,this.updateQualitySelection(),this.events.emit("qualitychange",this._qualities[i.level]||null)}),this.hls.on(e.Events.AUDIO_TRACK_LOADED,()=>{this.updateAudioTracks()}),this.hls.on(e.Events.AUDIO_TRACK_SWITCHED,()=>{this.updateAudioTracks();let t=this._audioTracks.find((i)=>i.selected);this.events.emit("audiotrackchange",t||null)}),this.hls.on(e.Events.SUBTITLE_TRACK_LOADED,()=>{this.updateTextTracks()}),this.hls.on(e.Events.ERROR,(t,i)=>{if(i.fatal)switch(i.type){case e.ErrorTypes.NETWORK_ERROR:this.hls?.startLoad();break;case e.ErrorTypes.MEDIA_ERROR:this.hls?.recoverMediaError();break;default:this.emitError(5,`HLS fatal error: ${i.details}`,i),this.hls?.destroy();break}})}updateQualities(e){this._qualities=e.map((t,i)=>({id:String(i),width:t.width,height:t.height,bitrate:t.bitrate,codec:t.codecSet||t.videoCodec||void 0,selected:i===this.currentQualityIndex})),this.events.emit("statechange",{qualities:this._qualities})}updateQualitySelection(){this._qualities=this._qualities.map((e,t)=>({...e,selected:t===this.currentQualityIndex}))}updateAudioTracks(){if(!this.hls)return;this._audioTracks=this.hls.audioTracks.map((e,t)=>({id:String(e.id),label:e.name||`Track ${t+1}`,language:e.lang||"",kind:e.default?"main":"alternative",selected:t===this.hls.audioTrack})),this.events.emit("statechange",{audioTracks:this._audioTracks})}updateTextTracks(){if(!this.hls)return;this._textTracks=this.hls.subtitleTracks.map((e,t)=>({id:String(e.id),kind:"subtitles",label:e.name||`Subtitle ${t+1}`,language:e.lang||"",mode:t===this.hls.subtitleTrack?"showing":"disabled",cues:[]})),this.events.emit("statechange",{textTracks:this._textTracks})}async play(){if(!this.video)return;try{await this.video.play()}catch(e){if(e.name==="NotAllowedError")this.emitError(1,"Playback was blocked. User interaction required.",e);else throw e}}pause(){this.video?.pause()}seekTo(e){if(this.video)this.video.currentTime=Math.max(0,Math.min(e,this.getDuration()))}getCurrentTime(){return this.video?.currentTime||0}getDuration(){return this.video?.duration||0}syncToLive(){if(this.hls?.liveSyncPosition!=null)this.seekTo(this.hls.liveSyncPosition)}setVolume(e){if(this.video)this.video.volume=Math.max(0,Math.min(1,e))}getVolume(){return this.video?.volume||1}setMuted(e){if(this.video)this.video.muted=e}getMuted(){return this.video?.muted||!1}setPlaybackRate(e){if(this.video)this.video.playbackRate=Math.max(0.25,Math.min(4,e))}getPlaybackRate(){return this.video?.playbackRate||1}getQualities(){return this._qualities}setQuality(e){if(!this.hls)return;if(e==="auto")this.hls.currentLevel=-1,this.currentQualityIndex=-1,this.events.emit("statechange",{autoQuality:!0});else{let t=parseInt(e.id,10);if(!isNaN(t)&&t>=0&&t<this._qualities.length)this.hls.currentLevel=t,this.currentQualityIndex=t,this.events.emit("statechange",{autoQuality:!1})}}getAudioTracks(){return this._audioTracks}setAudioTrack(e){if(!this.hls)return;let t=parseInt(e,10);if(!isNaN(t)&&t>=0&&t<this.hls.audioTracks.length)this.hls.audioTrack=t}getTextTracks(){return this._textTracks}setTextTrackMode(e,t){if(!this.hls)return;if(t==="showing"){let n=parseInt(e,10);if(!isNaN(n))this.hls.subtitleTrack=n}else this.hls.subtitleTrack=-1;this.updateTextTracks();let i=this._textTracks.find((n)=>n.mode==="showing");this.events.emit("texttrackchange",i||null)}}var Se={name:"hls",type:"hls",canPlay(e){return xe(e)},mediaType(){return"video"},preconnect(){return["https://cdn.jsdelivr.net"]},async load(e,t){let i=new R;return await i.setup(e,t),i}};var T=null,K=null,qt="https://cdn.dashjs.org/latest/dash.all.min.js";async function Ot(e){if(T)return T;if(K)return K;return K=new Promise((t,i)=>{if(typeof window<"u"&&window.dashjs){T=window.dashjs,t(T);return}let n=document.createElement("script");n.src=e||qt,n.async=!0,n.onload=()=>{T=window.dashjs,t(T)},n.onerror=()=>{i(Error("Failed to load dash.js"))},document.head.appendChild(n)}),K}function W(e){if(typeof e==="object"&&"type"in e&&e.type==="dash")return!0;if(typeof e==="string")return e.includes(".mpd")||e.includes("manifest(format=mpd");return!1}class I extends b{name="dash";type="dash";dash=null;video=null;source=null;config={};_volume=1;_muted=!1;_playbackRate=1;get mediaElement(){return this.video}async initialize(){if(this.video=document.createElement("video"),this.video.style.width="100%",this.video.style.height="100%",this.video.style.display="block",await Ot(this.options.dashCdnUrl),this.dash=T.MediaPlayer().create(),this.options.dashConfig)this.config.dashConfig=this.options.dashConfig;if(this.config.dashConfig)Object.entries(this.config.dashConfig).forEach(([e,t])=>{this.dash.updateSettings({[e]:t})});if(this.config.lowLatency)this.dash.updateSettings({streaming:{lowLatencyEnabled:!0,liveDelay:3,liveCatchUpMinDrift:0.05,liveCatchUpPlaybackRate:0.5}});if(this.attachDashEvents(),this.container)this.container.appendChild(this.video);this.attachVideoEvents()}attachVideoEvents(){if(!this.video)return;this.video.addEventListener("play",()=>this.events.emit("play")),this.video.addEventListener("pause",()=>this.events.emit("pause")),this.video.addEventListener("ended",()=>this.events.emit("ended")),this.video.addEventListener("timeupdate",()=>this.events.emit("timeupdate",this.getCurrentTime())),this.video.addEventListener("durationchange",()=>this.events.emit("durationchange",this.getDuration())),this.video.addEventListener("volumechange",()=>{this.events.emit("volumechange",this.getVolume(),this.getMuted())}),this.video.addEventListener("waiting",()=>this.events.emit("waiting")),this.video.addEventListener("playing",()=>this.events.emit("playing")),this.video.addEventListener("seeking",()=>this.events.emit("seeking")),this.video.addEventListener("seeked",()=>this.events.emit("seeked")),this.video.addEventListener("progress",()=>{let e=[];for(let t=0;t<this.video.buffered.length;t++)e.push({start:this.video.buffered.start(t),end:this.video.buffered.end(t)});this.events.emit("progress",e)}),this.video.addEventListener("loadedmetadata",()=>{this.events.emit("loadedmetadata");let e=this.getFeatureAvailability("fullscreen"),t=this.getFeatureAvailability("pip"),i=this.getFeatureAvailability("volume");this.events.emit("statechange",{videoWidth:this.video.videoWidth,videoHeight:this.video.videoHeight,aspectRatio:(this.video.videoHeight>0?this.video.videoWidth/this.video.videoHeight:0)||1.7777777777777777,canFullscreen:e==="available",canPictureInPicture:t==="available",fullscreenAvailability:e,pipAvailability:t,volumeAvailability:i}),this.events.emit("availabilitychange","fullscreen",e),this.events.emit("availabilitychange","pip",t),this.events.emit("availabilitychange","volume",i)}),this.video.addEventListener("loadeddata",()=>this.events.emit("loadeddata")),this.video.addEventListener("canplay",()=>this.events.emit("canplay")),this.video.addEventListener("canplaythrough",()=>this.events.emit("canplaythrough")),this.video.addEventListener("ratechange",()=>this.events.emit("ratechange",this.getPlaybackRate()))}attachDashEvents(){if(!T)return;let e=T.MediaPlayer;this.dash.on(e.events.QUALITY_CHANGE_RENDERED,()=>{this.events.emit("qualitychange",this.getQualities().find((t)=>t.selected)||null)}),this.dash.on(e.events.MANIFEST_LOADED,()=>{}),this.dash.on(e.events.ERROR,(t)=>{this.emitError(t.error?.code||0,t.error?.message||"DASH playback error",t.error)})}configureDRM(e){let t={};if(e.widevine)t["com.widevine.alpha"]={serverURL:e.widevine.url,httpRequestHeaders:e.widevine.headers};if(e.playready)t["com.microsoft.playready"]={serverURL:e.playready.url,httpRequestHeaders:e.playready.headers};if(e.fairplay)t["com.apple.fps.1_0"]={serverURL:e.fairplay.url,serverCertificateURL:e.fairplay.certificateUrl,httpRequestHeaders:e.fairplay.headers};this.dash.setProtectionData(t)}async load(e){if(!this.video||!this.dash)return;if(typeof e==="string")this.source={src:e,type:"dash"};else if(W(e))this.source=e;else{this.emitError(4,"Invalid DASH source");return}if(this.source.drm)this.configureDRM(this.source.drm);this.dash.initialize(this.video,this.source.src,!1)}canPlay(e){return W(e)}cleanup(){if(this.dash)this.dash.reset(),this.dash=null;if(this.video)this.video.remove(),this.video=null;this.source=null}async play(){if(!this.video)return;try{await this.video.play()}catch(e){if(e.name==="NotAllowedError")this.emitError(1,"Playback was blocked. User interaction required.",e);else throw e}}pause(){if(this.video)this.video.pause()}seekTo(e){if(this.video)this.video.currentTime=e}getCurrentTime(){return this.video?.currentTime||0}getDuration(){return this.video?.duration||0}setVolume(e){if(this._volume=Math.max(0,Math.min(1,e)),this.video)this.video.volume=this._volume}getVolume(){return this.video?.volume??this._volume}setMuted(e){if(this._muted=e,this.video)this.video.muted=e}getMuted(){return this.video?.muted??this._muted}setPlaybackRate(e){if(this._playbackRate=e,this.video)this.video.playbackRate=e}getPlaybackRate(){return this.video?.playbackRate??this._playbackRate}get isLive(){return this.dash?.isDynamic()??!1}get liveLatency(){return this.dash?.getCurrentLiveLatency()??0}get canLiveSync(){return this.isLive}syncToLive(){if(this.dash&&this.isLive)this.dash.seekToOriginalLive()}getQualities(){if(!this.dash)return[];let e=this.dash.getBitrateInfoListFor("video");if(!e)return[];let t=this.dash.getQualityFor("video");return e.map((i,n)=>({id:`${n}`,label:`${i.height}p`,width:i.width,height:i.height,bitrate:i.bitrate,selected:n===t}))}setQuality(e){if(!this.dash)return;if(e==="auto")this.dash.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:!0}}}});else{let t=Number.parseInt(e.id,10);if(!Number.isNaN(t))this.dash.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:!1}}}}),this.dash.setQualityFor("video",t)}}get isAutoQuality(){if(!this.dash)return!0;return this.dash.getSettings()?.streaming?.abr?.autoSwitchBitrate?.video??!0}getAudioTracks(){if(!this.dash)return[];let e=this.dash.getTracksFor("audio");if(!e)return[];let t=this.dash.getCurrentTrackFor("audio");return e.map((i,n)=>({id:i.id||`${n}`,label:i.labels?.[0]?.text||i.lang||`Track ${n+1}`,language:i.lang||"",kind:"main",selected:i===t}))}setAudioTrack(e){if(!this.dash)return;let i=this.dash.getTracksFor("audio").find((n,s)=>(n.id||`${s}`)===e);if(i)this.dash.setCurrentTrack(i)}getTextTracks(){if(!this.dash)return[];let e=this.dash.getTracksFor("text");if(!e)return[];let t=this.dash.getCurrentTrackFor("text");return e.map((i,n)=>({id:i.id||`${n}`,label:i.labels?.[0]?.text||i.lang||`Subtitle ${n+1}`,language:i.lang||"",kind:i.kind||"subtitles",mode:i===t?"showing":"disabled",cues:[]}))}setTextTrackMode(e,t){if(!this.dash)return;if(t==="disabled"){this.dash.enableText(!1);return}let n=this.dash.getTracksFor("text").find((s,r)=>(s.id||`${r}`)===e);if(n)this.dash.setCurrentTrack(n),this.dash.enableText(t==="showing")}}var Ee={name:"dash",type:"dash",canPlay(e){return W(e)},mediaType(){return"video"},async load(e,t){let i=new I;return await i.setup(e,t),i},preconnect(){return["https://cdn.dashjs.org"]}};var j=[Se,Ee,be,we,ye];function lt(e){if(!e||typeof e!=="object"||typeof e.src!=="string")return null;return"type"in e&&e.type?null:e.src}var Nt={youtube:()=>"youtube",vimeo:()=>"vimeo",hls:()=>"application/x-mpegurl",dash:()=>"dash",video:(e)=>U(e)};function zt(e,t){let i=lt(e),n=i&&Nt[t.type];return i&&n?{...e,type:n(i)}:e}function Ut(e,t=j){for(let n of t)if(n.canPlay(e))return n;let i=lt(e);if(i){for(let n of t)if(n.canPlay(i))return n}return null}function dt(e,t=j){let i=[];return e.forEach((n,s)=>{let r=Ut(n,t);if(r)i.push({src:zt(n,r),index:s,loader:r})}),i}function ct(e,t){let i=e.providerType==="youtube"||e.providerType==="vimeo",n=!e.started||e.ended;if(!i||!n||e.error||t)return{show:!1,image:""};if(e.poster)return{show:!0,image:e.poster};let s=e.src,r=typeof s==="string"?s:s?.src||"",a=e.providerType==="youtube"?E(r):null;return{show:!0,image:a?`https://i.ytimg.com/vi/${a}/hqdefault.jpg`:""}}class P{_el;_options;_store;_events=new S;_provider=null;_loaders;_cleanupFns=[];_destroyed=!1;_sourceLoadId=0;_announcer=null;_cover=null;_coverDismissed=!1;_coverTimer=null;_playRequested=!1;constructor(e,t={}){if(typeof e==="string"){let i=document.querySelector(e);if(!i)throw Error(`Container element not found: ${e}`);this._el=i}else this._el=e;if(this._options={...Qt,...t},this._loaders=j,this._store=new _,this.setupElement(),this.setupState(),this.setupKeyboard(),this.setupActivity(),this.setupStorage(),this.setupMediaSession(),this.setupEvents(),this._options.src)this.setSrc(this._options.src);this._events.emit("init")}get el(){return this._el}get state(){return this._store.getState()}get provider(){return this._provider}get ready(){return this._provider?.ready||!1}setupElement(){this._el.classList.add("ts-video-player"),this._el.setAttribute("tabindex","0"),this._el.setAttribute("role","region"),this._el.setAttribute("aria-roledescription","video player"),this._el.setAttribute("aria-label",this._options.title||"Video player"),this._el.setAttribute("aria-keyshortcuts","Space K M F I C ArrowLeft ArrowRight J L ArrowUp ArrowDown Home End 0 1 2 3 4 5 6 7 8 9");let e=document.createElement("div");if(e.className="ts-video-player__container",e.style.cssText="position:relative;width:100%;height:100%",this._el.appendChild(e),this.setupCover(),this._options.announcements!==!1){let i=document.createElement("div");i.className="ts-video-player__announcer",i.setAttribute("role","status"),i.setAttribute("aria-live","polite"),i.setAttribute("aria-atomic","true"),i.style.cssText="position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0",this._el.appendChild(i),this._announcer=i}let t=this._el;t.__videoPlayer=this}setupCover(){let e=document.createElement("button");e.type="button",e.className="ts-video-player__cover",e.setAttribute("aria-label",`Play ${this._options.title||"video"}`),e.hidden=!0,e.style.cssText="position:absolute;inset:0;z-index:2;display:none;align-items:center;justify-content:center;width:100%;height:100%;margin:0;padding:0;border:0;border-radius:inherit;background:#000 center/cover no-repeat;cursor:pointer;-webkit-tap-highlight-color:transparent";let t=document.createElement("span");t.setAttribute("aria-hidden","true"),t.style.cssText="display:flex;align-items:center;justify-content:center;width:64px;height:64px;border-radius:50%;background:rgba(255,255,255,0.92);box-shadow:0 4px 18px rgba(0,0,0,0.35)";let i=document.createElement("span");i.className="ts-video-player__cover-play",i.style.cssText="width:22px;height:24px;margin-left:5px;background:#0f172a;clip-path:polygon(0 0,100% 50%,0 100%)",t.appendChild(i),e.appendChild(t),e.addEventListener("click",(n)=>{if(n.stopPropagation(),!e.dataset.loading){e.dataset.loading="",i.style.display="none";let a=document.createElement("span");a.className="ts-video-player__cover-spinner",a.style.cssText="width:26px;height:26px;border-radius:50%;border:3px solid rgba(15,23,42,0.2);border-top-color:#0f172a",t.appendChild(a),a.animate?.([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:800,iterations:1/0})}if(this.play().catch(()=>{}),this._coverTimer)clearTimeout(this._coverTimer);let s=0,r=()=>{this._coverTimer=setTimeout(()=>{if(this.state.started)return;if(!this.state.canPlay&&++s<10)return r();this._coverDismissed=!0,this.updateCover(this.state)},2000)};r()}),this._el.appendChild(e),this._cover=e,this._cleanupFns.push(()=>{if(this._coverTimer)clearTimeout(this._coverTimer);e.remove()})}updateCover(e){let t=this._cover;if(!t)return;let{show:i,image:n}=ct(e,this._coverDismissed);if(i){let s=n?`url("${n.replace(/["\\]/g,"")}")`:"none";if(t.style.backgroundImage!==s)t.style.backgroundImage=s}if(!i&&t.dataset.loading!==void 0){delete t.dataset.loading,t.querySelector(".ts-video-player__cover-spinner")?.remove();let s=t.querySelector(".ts-video-player__cover-play");if(s)s.style.display=""}t.hidden=!i,t.style.display=i?"flex":"none"}setupState(){this._store.batch({volume:this._options.volume??1,muted:this._options.muted??!1,loop:this._options.loop??!1,autoplay:this._options.autoplay??!1,playsinline:this._options.playsinline??!0,playbackRate:this._options.playbackRate??1,poster:this._options.poster||"",title:this._options.title||"",preload:this._options.preload||"metadata"});let e=this._store.subscribe((t)=>{this.updateAttributes(t),this.updateCover(t)});this._cleanupFns.push(e)}setupKeyboard(){if(this._options.keyboard===!1)return;let e={togglePlay:()=>this.togglePlay(),toggleMute:()=>this.toggleMute(),toggleFullscreen:()=>this.toggleFullscreen(),togglePiP:()=>this.togglePiP(),toggleCaptions:()=>this.toggleCaptions(),seekBackward:()=>this.seekBy(-5),seekForward:()=>this.seekBy(5),volumeUp:()=>this.setVolume(Math.min(1,this.state.volume+0.1)),volumeDown:()=>this.setVolume(Math.max(0,this.state.volume-0.1)),speedUp:()=>this.setPlaybackRate(Math.min(4,this.state.playbackRate+0.25)),speedDown:()=>this.setPlaybackRate(Math.max(0.25,this.state.playbackRate-0.25)),seekStart:()=>this.seekTo(0),seekEnd:()=>this.seekTo(this.state.duration),seekPercent:(s)=>this.seekTo(s/100*this.state.duration)},t=typeof this._options.keyboard==="object"?this._options.keyboard:{},i=Ne(e,{seekStep:t.seekStep,volumeStep:t.volumeStep}),n=t.global?document:this._el;n.addEventListener("keydown",i),this._cleanupFns.push(()=>n.removeEventListener("keydown",i))}setupActivity(){let e=ze(this._el,{timeout:this._options.controlsTimeout||3000,onActive:()=>{this._store.batch({userActive:!0,controlsVisible:!0}),this._events.emit("useractivitychange",!0),this._events.emit("controlschange",!0)},onInactive:()=>{if(this.state.playing)this._store.batch({userActive:!1,controlsVisible:!1}),this._events.emit("useractivitychange",!1),this._events.emit("controlschange",!1)}});this._cleanupFns.push(e);let t=()=>this._store.set("pointerOver",!0),i=()=>this._store.set("pointerOver",!1);this._el.addEventListener("mouseenter",t),this._el.addEventListener("mouseleave",i),this._cleanupFns.push(()=>this._el.removeEventListener("mouseenter",t),()=>this._el.removeEventListener("mouseleave",i))}setupStorage(){if(!this._options.storage)return;let e=typeof this._options.storage==="object"?this._options.storage:{},t=e.type==="session"?sessionStorage:localStorage,i=Oe(this._store,e.persist||["volume","muted","playbackRate"],t);this._cleanupFns.push(i)}setupMediaSession(){if(this._options.mediaSession===!1)return;let e=typeof this._options.mediaSession==="object"?this._options.mediaSession:this._options.title?{title:this._options.title}:void 0,t=Qe(this._store,{play:()=>this.play(),pause:()=>this.pause(),seekTo:(i)=>this.seekTo(i),seekBy:(i)=>this.seekBy(i),stop:()=>this.stop()},e);this._cleanupFns.push(t)}setupEvents(){if(this._options.on){for(let[e,t]of Object.entries(this._options.on))if(t)this.on(e,t)}}updateAttributes(e){let t=this._el;t.dataset.paused=String(e.paused),t.dataset.playing=String(e.playing),t.dataset.started=String(e.started),t.dataset.ended=String(e.ended),t.dataset.seeking=String(e.seeking),t.dataset.waiting=String(e.waiting),t.dataset.loop=String(e.loop),t.dataset.autoplay=String(e.autoplay),t.dataset.loading=String(e.waiting||e.loadingState==="loading"),t.dataset.canPlay=String(e.canPlay),t.dataset.loadingState=e.loadingState,t.setAttribute("aria-busy",String(e.waiting||e.loadingState==="loading")),t.dataset.muted=String(e.muted),t.dataset.volumeLevel=e.muted||e.volume===0?"silent":e.volume<0.5?"low":"high",t.dataset.fullscreen=String(e.fullscreen),t.dataset.pip=String(e.pictureInPicture),t.dataset.controlsVisible=String(e.controlsVisible),t.dataset.userActive=String(e.userActive),t.dataset.mediaType=e.mediaType,t.dataset.streamType=e.streamType;let i=e.textTracks.some((n)=>n.mode==="showing");t.dataset.captions=String(i),t.dataset.error=String(!!e.error)}announce(e){if(!this._announcer)return;this._announcer.textContent="",requestAnimationFrame(()=>{if(this._announcer)this._announcer.textContent=e})}destroy(){if(this._destroyed)return;this._destroyed=!0,this._sourceLoadId++,this._events.emit("destroy"),this._cleanupFns.forEach((e)=>e()),this._cleanupFns=[],this._provider?.destroy(),this._provider=null,this._events.removeAllListeners(),this._store.reset(),this._el.classList.remove("ts-video-player"),this._el.innerHTML="",delete this._el.__videoPlayer}async setSrc(e){if(this._destroyed)return;let t=++this._sourceLoadId,i=Array.isArray(e)?e:[e];if(i.length===0)return;this._coverDismissed=!1,this._playRequested=!1,this._store.batch({sources:i,src:i[0],loadingState:"loading",error:null,started:!1}),this._events.emit("sourceschange",i);let n=dt(i,this._loaders);if(n.length===0){this._store.batch({loadingState:"error",error:{code:4,message:"No compatible provider found for source"}});return}let s;for(let r of n){if(this._destroyed||t!==this._sourceLoadId)return;let{loader:a}=r;if(this._provider&&this._provider.type!==a.type)this._provider.destroy(),this._provider=null,this._events.emit("providerchange",null);if(!this._provider){let o=this._el.querySelector(".ts-video-player__container");try{if(this._provider=await a.load(o,{...this._options,mediaType:a.mediaType(r.src)}),this._destroyed||t!==this._sourceLoadId){this._provider.destroy(),this._provider=null;return}this._events.emit("providerchange",this._provider),this.attachProviderEvents(this._provider)}catch(l){s=l,this._provider=null;continue}}try{let o=a.type==="video"?n.filter((l)=>l.loader.type===a.type).map((l)=>l.src):[r.src];if(await this._provider.load(o.length>1?o:r.src),this._destroyed||t!==this._sourceLoadId)return;if(this._store.batch({src:r.src,currentSourceIndex:r.index,mediaType:a.mediaType(r.src),providerType:a.type}),this._playRequested)this._playRequested=!1,this._provider.play().catch(()=>{});return}catch(o){if(s=o,this._provider)this._provider.destroy(),this._provider=null;this._events.emit("providerchange",null)}}if(this._destroyed||t!==this._sourceLoadId)return;this._store.batch({loadingState:"error",error:{code:4,message:"Failed to load all compatible sources",details:s}})}setPoster(e){this._store.set("poster",e)}getSrc(){return this.state.src}attachProviderEvents(e){e.on("loadstart",()=>{this._store.set("loadingState","loading"),this._events.emit("loadstart")}),e.on("loadedmetadata",()=>{this._events.emit("loadedmetadata")}),e.on("loadeddata",()=>{this._events.emit("loadeddata")}),e.on("canplay",()=>{this._store.batch({canPlay:!0,loadingState:"loaded"}),this._events.emit("canplay")}),e.on("canplaythrough",()=>{this._store.set("canPlayThrough",!0),this._events.emit("canplaythrough")}),e.on("play",()=>{this._store.batch({paused:!1,ended:!1}),this._events.emit("play"),this.announce("Playing")}),e.on("pause",()=>{this._store.set("paused",!0),this._events.emit("pause"),this.announce("Paused")}),e.on("playing",()=>{this._store.batch({playing:!0,started:!0,waiting:!1,playbackState:"playing"}),this._events.emit("playing")}),e.on("waiting",()=>{this._store.batch({waiting:!0,playbackState:"buffering"}),this._events.emit("waiting")}),e.on("seeking",()=>{this._store.set("seeking",!0),this._events.emit("seeking")}),e.on("seeked",()=>{this._store.set("seeking",!1),this._events.emit("seeked")}),e.on("timeupdate",(t)=>{this._store.set("currentTime",t),this._events.emit("timeupdate",t)}),e.on("durationchange",(t)=>{this._store.set("duration",t),this._events.emit("durationchange",t)}),e.on("volumechange",(t,i)=>{if(this._store.batch({volume:t,muted:i}),this._events.emit("volumechange",t,i),i)this.announce("Muted");else this.announce(`Volume ${Math.round(t*100)}%`)}),e.on("ratechange",(t)=>{this._store.set("playbackRate",t),this._events.emit("ratechange",t)}),e.on("progress",(t)=>{this._store.batch({buffered:t,bufferedAmount:$e({...this.state,buffered:t})}),this._events.emit("progress",t)}),e.on("ended",()=>{if(this._store.batch({ended:!0,playing:!1,playbackState:"ended"}),this._events.emit("ended"),this.announce("Playback ended"),this.state.loop)this.seekTo(0),this.play()}),e.on("error",(t)=>{this._store.batch({loadingState:"error",error:t}),this._events.emit("error",t),this.announce(`Error: ${t.message}`)}),e.on("statechange",(t)=>{this._store.batch(t),this._events.emit("statechange",t)}),e.on("qualitychange",(t)=>{this._store.set("qualities",e.getQualities()),this._events.emit("qualitychange",t)}),e.on("fullscreenchange",(t)=>{this._store.set("fullscreen",t),this._events.emit("fullscreenchange",t),this.announce(t?"Entered fullscreen":"Exited fullscreen")}),e.on("pipchange",(t)=>{this._store.set("pictureInPicture",t),this._events.emit("pipchange",t)}),e.on("availabilitychange",(t,i)=>{if(t==="volume")this._store.set("volumeAvailability",i);else if(t==="fullscreen")this._store.set("fullscreenAvailability",i);else if(t==="pip")this._store.set("pipAvailability",i);this._events.emit("availabilitychange",t,i)})}async play(){if(!this._provider){this._playRequested=!0;return}await this._provider.play()}pause(){this._playRequested=!1,this._provider?.pause()}togglePlay(){if(this.state.paused)this.play().catch(()=>{});else this.pause()}stop(){this._provider?.stop(),this._store.batch({playing:!1,paused:!0,currentTime:0,playbackState:"idle"})}seekTo(e){this._provider?.seekTo(e)}seekBy(e){let t=Math.max(0,Math.min(this.state.currentTime+e,this.state.duration));this.seekTo(t)}setVolume(e){if(this.state.volumeAvailability==="unsupported")return;let t=Math.max(0,Math.min(1,e));this._provider?.setVolume(t),this._store.set("volume",t)}setMuted(e){this._provider?.setMuted(e),this._store.set("muted",e)}toggleMute(){this.setMuted(!this.state.muted)}setPlaybackRate(e){let t=Math.max(0.25,Math.min(4,e));this._provider?.setPlaybackRate(t),this._store.set("playbackRate",t)}async enterFullscreen(){if(this.state.fullscreenAvailability==="unsupported")return;if(this.state.pictureInPicture)await this.exitPiP();if(await this._provider?.enterFullscreen(),this._options.fullscreenOrientationLock!==!1)We("landscape")}async exitFullscreen(){if(await this._provider?.exitFullscreen(),this._options.fullscreenOrientationLock!==!1)je()}async toggleFullscreen(){if(this.state.fullscreen)await this.exitFullscreen();else await this.enterFullscreen()}async enterPiP(){if(this.state.pipAvailability==="unsupported")return;if(this.state.fullscreen)await this.exitFullscreen();await this._provider?.enterPiP()}async exitPiP(){await this._provider?.exitPiP()}async togglePiP(){if(this.state.pictureInPicture)await this.exitPiP();else await this.enterPiP()}setQuality(e){if(this._provider?.setQuality(e),e==="auto")this._store.set("autoQuality",!0);else this._store.set("autoQuality",!1)}setTextTrack(e,t){this._provider?.setTextTrackMode(e,t),this._store.set("textTracks",this._provider?.getTextTracks()||[])}setAudioTrack(e){this._provider?.setAudioTrack(e),this._store.set("audioTracks",this._provider?.getAudioTracks()||[])}toggleCaptions(){let e=this.state.textTracks,t=e.find((i)=>i.mode==="showing");if(t)this.setTextTrack(t.id,"disabled");else{let i=e.find((n)=>n.kind==="subtitles"||n.kind==="captions");if(i)this.setTextTrack(i.id,"showing")}}on(e,t){this._events.on(e,t)}off(e,t){this._events.off(e,t)}once(e,t){this._events.once(e,t)}subscribe(e,t){return this._store.subscribe(e,t)}}var Qt={autoplay:!1,loop:!1,muted:!1,volume:1,playbackRate:1,playsinline:!0,preload:"metadata",controls:!0,keyboard:!0,controlsTimeout:3000,storage:!0};function ut(e,t){return new P(e,t)}var Kt={colors:{primary:"#00a8ff",secondary:"#6c5ce7",background:"rgba(0, 0, 0, 0.85)",text:"#ffffff",textOnPrimary:"#ffffff",border:"rgba(255, 255, 255, 0.1)",focus:"#00a8ff",error:"#ff4757",success:"#2ed573",warning:"#ffa502"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',fontSize:"14px",fontSizeSmall:"12px",fontSizeLarge:"16px",fontWeight:"400",fontWeightBold:"600",lineHeight:"1.5"},spacing:{xs:"4px",sm:"8px",md:"12px",lg:"16px",xl:"24px"},borderRadius:{sm:"4px",md:"8px",lg:"12px",full:"9999px"},shadows:{sm:"0 1px 2px rgba(0, 0, 0, 0.2)",md:"0 4px 6px rgba(0, 0, 0, 0.3)",lg:"0 10px 15px rgba(0, 0, 0, 0.4)"},transitions:{fast:"100ms",normal:"200ms",slow:"300ms",easing:"cubic-bezier(0.4, 0, 0.2, 1)"},slider:{trackHeight:"4px",thumbSize:"14px",trackBg:"rgba(255, 255, 255, 0.2)",trackFillBg:"var(--tsvp-color-primary)",bufferedBg:"rgba(255, 255, 255, 0.4)",thumbBg:"#ffffff",thumbBorder:"none"},controls:{height:"48px",background:"linear-gradient(transparent, rgba(0, 0, 0, 0.7))",padding:"0 12px",buttonSize:"40px",iconSize:"24px",tooltipBg:"rgba(0, 0, 0, 0.9)",tooltipText:"#ffffff"},menu:{background:"rgba(20, 20, 20, 0.95)",borderRadius:"8px",shadow:"0 4px 20px rgba(0, 0, 0, 0.5)",itemHeight:"40px",itemHoverBg:"rgba(255, 255, 255, 0.1)",itemActiveBg:"rgba(0, 168, 255, 0.2)"},captions:{fontFamily:"inherit",fontSize:"1.5em",textColor:"#ffffff",background:"rgba(0, 0, 0, 0.75)",textShadow:"0 1px 2px rgba(0, 0, 0, 0.5)",borderRadius:"4px",padding:"4px 8px"},thumbnails:{width:"160px",height:"90px",borderRadius:"4px",border:"2px solid rgba(255, 255, 255, 0.2)",shadow:"0 4px 12px rgba(0, 0, 0, 0.4)"},live:{indicatorColor:"#ff0000",indicatorSize:"8px",badgeBg:"#ff0000",badgeText:"#ffffff"}},Wt={colors:{primary:"#00a8ff",background:"rgba(0, 0, 0, 0.9)",text:"#ffffff"}},jt={colors:{primary:"#0070f3",background:"rgba(255, 255, 255, 0.95)",text:"#1a1a1a",textOnPrimary:"#ffffff",border:"rgba(0, 0, 0, 0.1)"},controls:{background:"linear-gradient(transparent, rgba(255, 255, 255, 0.9))",tooltipBg:"rgba(0, 0, 0, 0.8)"},menu:{background:"rgba(255, 255, 255, 0.98)",shadow:"0 4px 20px rgba(0, 0, 0, 0.15)",itemHoverBg:"rgba(0, 0, 0, 0.05)",itemActiveBg:"rgba(0, 112, 243, 0.1)"},captions:{background:"rgba(255, 255, 255, 0.9)",textColor:"#1a1a1a"}},Yt={colors:{primary:"#ffffff",background:"transparent"},controls:{height:"40px",background:"transparent"},slider:{trackHeight:"2px",thumbSize:"10px"}},Xt={colors:{primary:"#e50914",background:"rgba(0, 0, 0, 0.85)"},slider:{trackFillBg:"#e50914"},live:{indicatorColor:"#e50914",badgeBg:"#e50914"}},Gt={colors:{primary:"#ff0000",background:"rgba(0, 0, 0, 0.85)"},slider:{trackHeight:"3px",thumbSize:"13px",trackFillBg:"#ff0000"},controls:{height:"48px"},live:{indicatorColor:"#ff0000",badgeBg:"#ff0000"}},Jt={colors:{primary:"#00adef",background:"rgba(0, 0, 0, 0.85)"},slider:{trackFillBg:"#00adef"}},Pe={dark:Wt,light:jt,minimal:Yt,netflix:Xt,youtube:Gt,vimeo:Jt};function Zt(e,t){let i={...e};for(let n of Object.keys(t)){let s=e[n],r=t[n];if(r&&typeof r==="object")i[n]={...s||{},...r};else if(r!==void 0)i[n]=r}return i}function ei(e,t="tsvp"){let i=Zt(Kt,e),n=[];if(i.colors)n.push(`--${t}-color-primary: ${i.colors.primary};`),n.push(`--${t}-color-secondary: ${i.colors.secondary};`),n.push(`--${t}-color-background: ${i.colors.background};`),n.push(`--${t}-color-text: ${i.colors.text};`),n.push(`--${t}-color-text-on-primary: ${i.colors.textOnPrimary};`),n.push(`--${t}-color-border: ${i.colors.border};`),n.push(`--${t}-color-focus: ${i.colors.focus};`),n.push(`--${t}-color-error: ${i.colors.error};`),n.push(`--${t}-color-success: ${i.colors.success};`),n.push(`--${t}-color-warning: ${i.colors.warning};`);if(i.typography)n.push(`--${t}-font-family: ${i.typography.fontFamily};`),n.push(`--${t}-font-size: ${i.typography.fontSize};`),n.push(`--${t}-font-size-sm: ${i.typography.fontSizeSmall};`),n.push(`--${t}-font-size-lg: ${i.typography.fontSizeLarge};`),n.push(`--${t}-font-weight: ${i.typography.fontWeight};`),n.push(`--${t}-font-weight-bold: ${i.typography.fontWeightBold};`),n.push(`--${t}-line-height: ${i.typography.lineHeight};`);if(i.spacing)n.push(`--${t}-spacing-xs: ${i.spacing.xs};`),n.push(`--${t}-spacing-sm: ${i.spacing.sm};`),n.push(`--${t}-spacing-md: ${i.spacing.md};`),n.push(`--${t}-spacing-lg: ${i.spacing.lg};`),n.push(`--${t}-spacing-xl: ${i.spacing.xl};`);if(i.borderRadius)n.push(`--${t}-radius-sm: ${i.borderRadius.sm};`),n.push(`--${t}-radius-md: ${i.borderRadius.md};`),n.push(`--${t}-radius-lg: ${i.borderRadius.lg};`),n.push(`--${t}-radius-full: ${i.borderRadius.full};`);if(i.shadows)n.push(`--${t}-shadow-sm: ${i.shadows.sm};`),n.push(`--${t}-shadow-md: ${i.shadows.md};`),n.push(`--${t}-shadow-lg: ${i.shadows.lg};`);if(i.transitions)n.push(`--${t}-transition-fast: ${i.transitions.fast};`),n.push(`--${t}-transition-normal: ${i.transitions.normal};`),n.push(`--${t}-transition-slow: ${i.transitions.slow};`),n.push(`--${t}-transition-easing: ${i.transitions.easing};`);if(i.slider)n.push(`--${t}-slider-track-height: ${i.slider.trackHeight};`),n.push(`--${t}-slider-thumb-size: ${i.slider.thumbSize};`),n.push(`--${t}-slider-track-bg: ${i.slider.trackBg};`),n.push(`--${t}-slider-track-fill-bg: ${i.slider.trackFillBg};`),n.push(`--${t}-slider-buffered-bg: ${i.slider.bufferedBg};`),n.push(`--${t}-slider-thumb-bg: ${i.slider.thumbBg};`),n.push(`--${t}-slider-thumb-border: ${i.slider.thumbBorder};`);if(i.controls)n.push(`--${t}-controls-height: ${i.controls.height};`),n.push(`--${t}-controls-bg: ${i.controls.background};`),n.push(`--${t}-controls-padding: ${i.controls.padding};`),n.push(`--${t}-controls-button-size: ${i.controls.buttonSize};`),n.push(`--${t}-controls-icon-size: ${i.controls.iconSize};`),n.push(`--${t}-controls-tooltip-bg: ${i.controls.tooltipBg};`),n.push(`--${t}-controls-tooltip-text: ${i.controls.tooltipText};`);if(i.menu)n.push(`--${t}-menu-bg: ${i.menu.background};`),n.push(`--${t}-menu-radius: ${i.menu.borderRadius};`),n.push(`--${t}-menu-shadow: ${i.menu.shadow};`),n.push(`--${t}-menu-item-height: ${i.menu.itemHeight};`),n.push(`--${t}-menu-item-hover-bg: ${i.menu.itemHoverBg};`),n.push(`--${t}-menu-item-active-bg: ${i.menu.itemActiveBg};`);if(i.captions)n.push(`--${t}-captions-font-family: ${i.captions.fontFamily};`),n.push(`--${t}-captions-font-size: ${i.captions.fontSize};`),n.push(`--${t}-captions-text-color: ${i.captions.textColor};`),n.push(`--${t}-captions-bg: ${i.captions.background};`),n.push(`--${t}-captions-text-shadow: ${i.captions.textShadow};`),n.push(`--${t}-captions-radius: ${i.captions.borderRadius};`),n.push(`--${t}-captions-padding: ${i.captions.padding};`);if(i.thumbnails)n.push(`--${t}-thumbnail-width: ${i.thumbnails.width};`),n.push(`--${t}-thumbnail-height: ${i.thumbnails.height};`),n.push(`--${t}-thumbnail-radius: ${i.thumbnails.borderRadius};`),n.push(`--${t}-thumbnail-border: ${i.thumbnails.border};`),n.push(`--${t}-thumbnail-shadow: ${i.thumbnails.shadow};`);if(i.live)n.push(`--${t}-live-indicator-color: ${i.live.indicatorColor};`),n.push(`--${t}-live-indicator-size: ${i.live.indicatorSize};`),n.push(`--${t}-live-badge-bg: ${i.live.badgeBg};`),n.push(`--${t}-live-badge-text: ${i.live.badgeText};`);return n.join(`
2
- `)}function pt(e,t){let i=typeof t==="string"?Pe[t]:t;e.querySelectorAll("style[data-tsvp-theme]").forEach((s)=>s.remove());let n=ei(i);e.style.cssText+=n.split(`
3
- `).map((s)=>s.trim().replace(";","")).join("; ")}var ti={play:"Play",pause:"Pause",replay:"Replay",mute:"Mute",unmute:"Unmute",volume:"Volume",seekBackward:"Seek backward {seconds} seconds",seekForward:"Seek forward {seconds} seconds",seekTo:"Seek to {time}",duration:"Duration",currentTime:"Current time",played:"Played",buffered:"Buffered",enterFullscreen:"Enter fullscreen",exitFullscreen:"Exit fullscreen",enterPiP:"Enter picture-in-picture",exitPiP:"Exit picture-in-picture",enableCaptions:"Enable captions",disableCaptions:"Disable captions",captions:"Captions",captionsOff:"Off",settings:"Settings",quality:"Quality",auto:"Auto",speed:"Speed",normal:"Normal",loop:"Loop",loopEnabled:"Loop enabled",loopDisabled:"Loop disabled",audioBoost:"Audio boost",audioTrack:"Audio track",live:"LIVE",liveEdge:"At live edge",seekToLive:"Seek to live edge",behindLive:"{seconds}s behind",networkError:"A network error occurred",mediaError:"The media could not be loaded",unknownError:"An unknown error occurred",loading:"Loading",buffering:"Buffering",chapters:"Chapters",airPlay:"AirPlay",googleCast:"Cast",casting:"Casting to {device}",download:"Download",share:"Share",close:"Close",menu:"Menu",back:"Back"},ii={play:"Reproducir",pause:"Pausar",replay:"Repetir",mute:"Silenciar",unmute:"Activar sonido",volume:"Volumen",seekBackward:"Retroceder {seconds} segundos",seekForward:"Avanzar {seconds} segundos",seekTo:"Ir a {time}",duration:"Duración",currentTime:"Tiempo actual",played:"Reproducido",buffered:"Almacenado",enterFullscreen:"Pantalla completa",exitFullscreen:"Salir de pantalla completa",enterPiP:"Imagen en imagen",exitPiP:"Salir de imagen en imagen",enableCaptions:"Activar subtítulos",disableCaptions:"Desactivar subtítulos",captions:"Subtítulos",captionsOff:"Desactivados",settings:"Ajustes",quality:"Calidad",auto:"Automático",speed:"Velocidad",normal:"Normal",loop:"Bucle",loopEnabled:"Bucle activado",loopDisabled:"Bucle desactivado",audioBoost:"Aumento de audio",audioTrack:"Pista de audio",live:"EN VIVO",liveEdge:"En vivo",seekToLive:"Ir al directo",behindLive:"{seconds}s de retraso",networkError:"Error de red",mediaError:"No se pudo cargar el medio",unknownError:"Error desconocido",loading:"Cargando",buffering:"Almacenando",chapters:"Capítulos",airPlay:"AirPlay",googleCast:"Enviar",casting:"Enviando a {device}",download:"Descargar",share:"Compartir",close:"Cerrar",menu:"Menú",back:"Volver"},ni={play:"Lecture",pause:"Pause",replay:"Relire",mute:"Muet",unmute:"Son activé",volume:"Volume",seekBackward:"Reculer de {seconds} secondes",seekForward:"Avancer de {seconds} secondes",seekTo:"Aller à {time}",duration:"Durée",currentTime:"Temps actuel",played:"Joué",buffered:"Mis en mémoire tampon",enterFullscreen:"Plein écran",exitFullscreen:"Quitter le plein écran",enterPiP:"Image dans l'image",exitPiP:"Quitter l'image dans l'image",enableCaptions:"Activer les sous-titres",disableCaptions:"Désactiver les sous-titres",captions:"Sous-titres",captionsOff:"Désactivés",settings:"Paramètres",quality:"Qualité",auto:"Auto",speed:"Vitesse",normal:"Normal",loop:"Boucle",loopEnabled:"Boucle activée",loopDisabled:"Boucle désactivée",audioBoost:"Amplification audio",audioTrack:"Piste audio",live:"EN DIRECT",liveEdge:"En direct",seekToLive:"Aller au direct",behindLive:"{seconds}s de retard",networkError:"Erreur réseau",mediaError:"Le média n'a pas pu être chargé",unknownError:"Erreur inconnue",loading:"Chargement",buffering:"Mise en mémoire tampon",chapters:"Chapitres",airPlay:"AirPlay",googleCast:"Caster",casting:"Diffusion sur {device}",download:"Télécharger",share:"Partager",close:"Fermer",menu:"Menu",back:"Retour"},si={play:"Abspielen",pause:"Pause",replay:"Wiederholen",mute:"Stumm",unmute:"Ton an",volume:"Lautstärke",seekBackward:"{seconds} Sekunden zurück",seekForward:"{seconds} Sekunden vor",seekTo:"Zu {time} springen",duration:"Dauer",currentTime:"Aktuelle Zeit",played:"Abgespielt",buffered:"Gepuffert",enterFullscreen:"Vollbild",exitFullscreen:"Vollbild beenden",enterPiP:"Bild-in-Bild",exitPiP:"Bild-in-Bild beenden",enableCaptions:"Untertitel aktivieren",disableCaptions:"Untertitel deaktivieren",captions:"Untertitel",captionsOff:"Aus",settings:"Einstellungen",quality:"Qualität",auto:"Auto",speed:"Geschwindigkeit",normal:"Normal",loop:"Schleife",loopEnabled:"Schleife aktiviert",loopDisabled:"Schleife deaktiviert",audioBoost:"Audio-Verstärkung",audioTrack:"Audiospur",live:"LIVE",liveEdge:"Am Live-Punkt",seekToLive:"Zum Live-Punkt",behindLive:"{seconds}s hinter Live",networkError:"Netzwerkfehler",mediaError:"Medium konnte nicht geladen werden",unknownError:"Unbekannter Fehler",loading:"Wird geladen",buffering:"Puffern",chapters:"Kapitel",airPlay:"AirPlay",googleCast:"Streamen",casting:"Streame zu {device}",download:"Herunterladen",share:"Teilen",close:"Schließen",menu:"Menü",back:"Zurück"},ri={play:"再生",pause:"一時停止",replay:"リプレイ",mute:"ミュート",unmute:"ミュート解除",volume:"音量",seekBackward:"{seconds}秒戻る",seekForward:"{seconds}秒進む",seekTo:"{time}にシーク",duration:"長さ",currentTime:"現在の時間",played:"再生済み",buffered:"バッファ済み",enterFullscreen:"フルスクリーン",exitFullscreen:"フルスクリーン終了",enterPiP:"ピクチャーインピクチャー",exitPiP:"ピクチャーインピクチャー終了",enableCaptions:"字幕を有効化",disableCaptions:"字幕を無効化",captions:"字幕",captionsOff:"オフ",settings:"設定",quality:"画質",auto:"自動",speed:"再生速度",normal:"通常",loop:"ループ",loopEnabled:"ループ有効",loopDisabled:"ループ無効",audioBoost:"オーディオブースト",audioTrack:"オーディオトラック",live:"ライブ",liveEdge:"ライブ中",seekToLive:"ライブに移動",behindLive:"{seconds}秒遅れ",networkError:"ネットワークエラー",mediaError:"メディアを読み込めません",unknownError:"不明なエラー",loading:"読み込み中",buffering:"バッファリング",chapters:"チャプター",airPlay:"AirPlay",googleCast:"キャスト",casting:"{device}にキャスト中",download:"ダウンロード",share:"共有",close:"閉じる",menu:"メニュー",back:"戻る"},ai={play:"播放",pause:"暂停",replay:"重播",mute:"静音",unmute:"取消静音",volume:"音量",seekBackward:"后退{seconds}秒",seekForward:"前进{seconds}秒",seekTo:"跳转到{time}",duration:"时长",currentTime:"当前时间",played:"已播放",buffered:"已缓冲",enterFullscreen:"全屏",exitFullscreen:"退出全屏",enterPiP:"画中画",exitPiP:"退出画中画",enableCaptions:"开启字幕",disableCaptions:"关闭字幕",captions:"字幕",captionsOff:"关闭",settings:"设置",quality:"画质",auto:"自动",speed:"播放速度",normal:"正常",loop:"循环",loopEnabled:"循环已开启",loopDisabled:"循环已关闭",audioBoost:"音频增强",audioTrack:"音轨",live:"直播",liveEdge:"直播中",seekToLive:"跳转到直播",behindLive:"落后{seconds}秒",networkError:"网络错误",mediaError:"无法加载媒体",unknownError:"未知错误",loading:"加载中",buffering:"缓冲中",chapters:"章节",airPlay:"AirPlay",googleCast:"投射",casting:"正在投射到{device}",download:"下载",share:"分享",close:"关闭",menu:"菜单",back:"返回"},oi={en:ti,es:ii,fr:ni,de:si,ja:ri,zh:ai};class Y{language;fallbackLanguage;translations;interpolationPattern;constructor(e={}){if(this.language=e.language||this.detectLanguage()||"en",this.fallbackLanguage=e.fallbackLanguage||"en",this.translations={...oi},e.translations){for(let[t,i]of Object.entries(e.translations))if(i)this.translations[t]={...this.translations[t],...i}}this.interpolationPattern=e.interpolationPattern||/\{(\w+)\}/g}detectLanguage(){if(typeof navigator>"u")return null;let e=navigator.language||navigator.userLanguage;if(!e)return null;if(this.translations[e])return e;let t=e.split("-")[0];if(this.translations[t])return t;return null}getLanguage(){return this.language}setLanguage(e){this.language=e}t(e,t){let i=this.translations[this.language]?.[e];if(!i)i=this.translations[this.fallbackLanguage]?.[e];if(!i)return e;if(t)i=i.replace(this.interpolationPattern,(n,s)=>{let r=t[s];return r!==void 0?String(r):n});return i}addTranslations(e,t){this.translations[e]={...this.translations[e],...t}}getTranslations(e){return this.translations[e]}getAvailableLanguages(){return Object.keys(this.translations)}hasLanguage(e){return e in this.translations}}var Ae=null;function li(e){return new Y(e)}function di(e){if(!Ae)Ae=li(e);return Ae}function ht(e,t){return di().t(e,t)}var ci={name:"default",description:"Full-featured default layout with all controls",styles:`
1
+ function Oe(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown",streamType:"unknown",providerType:"unknown",loadingState:"idle",preload:"metadata",canPlay:!1,canPlayThrough:!1,error:null,playbackState:"idle",paused:!0,playing:!1,started:!1,ended:!1,seeking:!1,waiting:!1,currentTime:0,duration:0,playbackRate:1,loop:!1,autoplay:!1,playsinline:!0,muted:!1,volume:1,buffered:[],bufferedAmount:0,seekable:[],videoWidth:0,videoHeight:0,aspectRatio:1.7777777777777777,qualities:[],autoQuality:!0,audioTracks:[],textTracks:[],fullscreen:!1,pictureInPicture:!1,canFullscreen:!1,canPictureInPicture:!1,volumeAvailability:"unavailable",fullscreenAvailability:"unavailable",pipAvailability:"unavailable",controlsVisible:!0,userActive:!0,pointerOver:!1,title:"",poster:""}}class L{state;listeners=new Map;_pendingKeys=null;_flushScheduled=!1;constructor(e){this.state={...Oe(),...e}}getState(){return this.state}get(e){return this.state[e]}set(e,t){if(this.state[e]===t)return;this.state={...this.state,[e]:t},this.scheduleNotify(e)}batch(e){for(let[t,i]of Object.entries(e))if(this.state[t]!==i)this.state[t]=i,this.scheduleNotify(t)}subscribe(e,t){if(typeof e==="function"){if(!this.listeners.has("*"))this.listeners.set("*",new Set);return this.listeners.get("*").add(e),()=>this.listeners.get("*")?.delete(e)}let i=e;if(!t)return()=>{};if(!this.listeners.has(i))this.listeners.set(i,new Set);return this.listeners.get(i).add(t),()=>this.listeners.get(i)?.delete(t)}reset(){this.state=Oe(),this._pendingKeys=null,this._flushScheduled=!1,this.notifyAll()}flush(){if(this._pendingKeys){let e=this._pendingKeys;this._pendingKeys=null,this._flushScheduled=!1;for(let t of e)this.notifyKey(t);this.notifyAll()}}scheduleNotify(e){if(!this._pendingKeys)this._pendingKeys=new Set;if(this._pendingKeys.add(e),!this._flushScheduled)this._flushScheduled=!0,queueMicrotask(()=>this.flush())}notifyKey(e){this.listeners.get(e)?.forEach((t)=>t(this.state,e))}notifyAll(){this.listeners.get("*")?.forEach((e)=>e(this.state))}}function qe(e){if(e.duration===0||e.buffered.length===0)return 0;let t=0;for(let i of e.buffered)t+=i.end-i.start;return Math.min(t/e.duration,1)}var Ne="ts-video-player";function ze(e=localStorage){try{let t=e.getItem(Ne);if(t)return JSON.parse(t)}catch{}return{}}function It(e,t=localStorage){try{let i=ze(t);t.setItem(Ne,JSON.stringify({...i,...e}))}catch{}}function Ue(e,t=["volume","muted","playbackRate"],i=localStorage){let n=ze(i);if(n.volume!==void 0)e.set("volume",n.volume);if(n.muted!==void 0)e.set("muted",n.muted);if(n.playbackRate!==void 0)e.set("playbackRate",n.playbackRate);let s=t.map((r)=>e.subscribe(r,(a)=>{let o=a[r];It({[r]:o},i)}));return()=>s.forEach((r)=>r())}class E{listeners=new Map;onceListeners=new Map;on(e,t){if(!this.listeners.has(e))this.listeners.set(e,new Set);return this.listeners.get(e).add(t),()=>this.off(e,t)}once(e,t){if(!this.onceListeners.has(e))this.onceListeners.set(e,new Set);return this.onceListeners.get(e).add(t),()=>this.onceListeners.get(e)?.delete(t)}off(e,t){this.listeners.get(e)?.delete(t),this.onceListeners.get(e)?.delete(t)}emit(e,...t){this.listeners.get(e)?.forEach((n)=>{try{n(...t)}catch(s){console.error(`[ts-video-player] Error in event handler for "${String(e)}":`,s)}});let i=this.onceListeners.get(e);if(i)i.forEach((n)=>{try{n(...t)}catch(s){console.error(`[ts-video-player] Error in once handler for "${String(e)}":`,s)}}),i.clear()}removeAllListeners(e){if(e)this.listeners.delete(e),this.onceListeners.delete(e);else this.listeners.clear(),this.onceListeners.clear()}listenerCount(e){return(this.listeners.get(e)?.size||0)+(this.onceListeners.get(e)?.size||0)}}class M{media;emitter;listeners=[];constructor(e,t){this.media=e,this.emitter=t,this.attachListeners()}attachListeners(){let e=(t,i)=>{this.media.addEventListener(t,i),this.listeners.push(()=>this.media.removeEventListener(t,i))};e("loadstart",()=>this.emitter.emit("loadstart")),e("loadedmetadata",()=>this.emitter.emit("loadedmetadata")),e("loadeddata",()=>this.emitter.emit("loadeddata")),e("canplay",()=>this.emitter.emit("canplay")),e("canplaythrough",()=>this.emitter.emit("canplaythrough")),e("play",()=>this.emitter.emit("play")),e("pause",()=>this.emitter.emit("pause")),e("playing",()=>this.emitter.emit("playing")),e("waiting",()=>this.emitter.emit("waiting")),e("ended",()=>this.emitter.emit("ended")),e("seeking",()=>this.emitter.emit("seeking")),e("seeked",()=>this.emitter.emit("seeked")),e("timeupdate",()=>this.emitter.emit("timeupdate",this.media.currentTime)),e("durationchange",()=>this.emitter.emit("durationchange",this.media.duration)),e("volumechange",()=>this.emitter.emit("volumechange",this.media.volume,this.media.muted)),e("ratechange",()=>this.emitter.emit("ratechange",this.media.playbackRate)),e("progress",()=>{let t=this.getTimeRanges(this.media.buffered);this.emitter.emit("progress",t)}),e("error",()=>{let t=this.normalizeError(this.media.error);this.emitter.emit("error",t)})}getTimeRanges(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}normalizeError(e){if(!e)return{code:0,message:"Unknown error"};let t={1:"The fetching of the media resource was aborted by the user agent.",2:"A network error occurred while fetching the media resource.",3:"An error occurred while decoding the media resource.",4:"The media resource is not supported."};return{code:e.code,message:t[e.code]||e.message||"Unknown error"}}destroy(){this.listeners.forEach((e)=>e()),this.listeners=[]}}function z(e){let t=["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],i=(n)=>{if(n&&typeof CustomEvent<"u"&&n instanceof CustomEvent)return;let s=!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement);e(s)};return t.forEach((n)=>document.addEventListener(n,i)),()=>{t.forEach((n)=>document.removeEventListener(n,i))}}function U(e,t){let i=()=>t(!0),n=()=>t(!1);return e.addEventListener("enterpictureinpicture",i),e.addEventListener("leavepictureinpicture",n),()=>{e.removeEventListener("enterpictureinpicture",i),e.removeEventListener("leavepictureinpicture",n)}}var Ht={" ":"togglePlay",k:"togglePlay",m:"toggleMute",f:"toggleFullscreen",i:"togglePiP",c:"toggleCaptions",ArrowLeft:"seekBackward",ArrowRight:"seekForward",j:"seekBackwardLong",l:"seekForwardLong",ArrowUp:"volumeUp",ArrowDown:"volumeDown",">":"speedUp","<":"speedDown",Home:"seekStart",End:"seekEnd","0":"seek0","1":"seek10","2":"seek20","3":"seek30","4":"seek40","5":"seek50","6":"seek60","7":"seek70","8":"seek80","9":"seek90"};function Ke(e,t={}){let{seekStep:i=5,volumeStep:n=0.1,speedStep:s=0.25}=t;return(r)=>{if(r.target instanceof HTMLInputElement||r.target instanceof HTMLTextAreaElement||r.target instanceof HTMLSelectElement||r.target?.isContentEditable)return;let a=r.key,o=Ht[a];if(!o)return;switch(r.preventDefault(),o){case"togglePlay":e.togglePlay();break;case"toggleMute":e.toggleMute();break;case"toggleFullscreen":e.toggleFullscreen();break;case"togglePiP":e.togglePiP();break;case"toggleCaptions":e.toggleCaptions();break;case"seekBackward":e.seekBackward();break;case"seekForward":e.seekForward();break;case"seekBackwardLong":if(e.seekBackwardLong)e.seekBackwardLong();else e.seekBackward();break;case"seekForwardLong":if(e.seekForwardLong)e.seekForwardLong();else e.seekForward();break;case"volumeUp":e.volumeUp();break;case"volumeDown":e.volumeDown();break;case"speedUp":e.speedUp();break;case"speedDown":e.speedDown();break;case"seekStart":e.seekStart();break;case"seekEnd":e.seekEnd();break;default:if(o.startsWith("seek")){let d=parseInt(o.replace("seek",""),10);if(!isNaN(d))e.seekPercent(d)}}}}function Qe(e,t={}){let{timeout:i=3000,onActive:n,onInactive:s}=t,r=null,a=!0,o=()=>{if(!a)a=!0,n?.();c()},d=()=>{if(a)a=!1,s?.()},c=()=>{if(r)clearTimeout(r);r=setTimeout(d,i)},u=["mousemove","mouseenter","mouseleave","mousedown","keydown","touchstart","touchmove"];return u.forEach((p)=>e.addEventListener(p,o)),c(),()=>{if(r)clearTimeout(r);u.forEach((p)=>e.removeEventListener(p,o))}}function We(){return typeof navigator<"u"&&"mediaSession"in navigator}function je(e,t,i){if(!We())return()=>{};let n=navigator.mediaSession;if(i)Vt(i);let s=[["play",()=>t.play()],["pause",()=>t.pause()],["stop",()=>t.stop()],["seekbackward",(c)=>{let u=c.seekOffset||-10;t.seekBy(u)}],["seekforward",(c)=>{let u=c.seekOffset||10;t.seekBy(u)}],["seekto",(c)=>{let u=c.seekTime;if(u!==void 0)t.seekTo(u)}]];for(let[c,u]of s)try{n.setActionHandler(c,u)}catch{}let r=e.subscribe("paused",(c)=>{n.playbackState=c.paused?"paused":"playing"}),a=null,o=()=>{let c=e.getState();if(!isFinite(c.duration)||c.duration<=0)return;try{n.setPositionState({duration:c.duration,playbackRate:c.playbackRate,position:Math.min(c.currentTime,c.duration)})}catch{}},d=e.subscribe("playing",(c)=>{if(c.playing){if(o(),!a)a=setInterval(o,1000)}else{if(a)clearInterval(a),a=null;o()}});return()=>{if(a)clearInterval(a);r(),d();for(let[c]of s)try{n.setActionHandler(c,null)}catch{}}}function Vt(e){if(!We())return;navigator.mediaSession.metadata=new MediaMetadata({title:e.title||"",artist:e.artist||"",album:e.album||"",artwork:e.artwork||[]})}function Ye(){return typeof screen<"u"&&"orientation"in screen&&typeof screen.orientation.lock==="function"}function Xe(e){if(!Ye())return;let t={landscape:"landscape",portrait:"portrait",any:"any"};screen.orientation.lock(t[e]).catch(()=>{})}function Ge(){if(!Ye())return;try{screen.orientation.unlock()}catch{}}function Bt(){if(typeof navigator>"u")return!1;let e=navigator.userAgent;if(/iPad|iPhone|iPod/.test(e)&&!window.MSStream)return!0;if(navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1)return!0;return!1}function Dt(){if(typeof navigator>"u")return!1;return/^(?:(?!chrome|android).)*safari/i.test(navigator.userAgent)}function Je(){if(typeof window>"u")return!1;return navigator.standalone===!0||window.matchMedia("(display-mode: standalone)").matches}function Ze(e){if(Bt())return"unsupported";if(!e)return"unavailable";return"available"}async function et(e){let t=e.volume;try{let i=t===1?0.5:1;e.volume=i,await new Promise((s)=>setTimeout(s,0));let n=e.volume!==t;return e.volume=t,n?"available":"unsupported"}catch{try{e.volume=t}catch{}return"unsupported"}}function tt(e,t){let i=typeof document<"u"?document:null;if(!i)return"unsupported";if(i.fullscreenEnabled||i.webkitFullscreenEnabled)return"available";if(i.mozFullScreenEnabled||i.msFullscreenEnabled)return"available";if(t){let n=t;if(n.webkitSupportsFullscreen===!0)return"available";if(typeof n.webkitEnterFullscreen==="function")return"available"}if(!e&&!t)return"unavailable";return"unsupported"}async function it(e,t){let i=t;if(e){let n=e;if(typeof n.requestFullscreen==="function")return n.requestFullscreen();if(typeof n.webkitRequestFullscreen==="function")return n.webkitRequestFullscreen();if(typeof n.webkitRequestFullScreen==="function")return n.webkitRequestFullScreen()}if(i&&typeof i.webkitEnterFullscreen==="function"){i.webkitEnterFullscreen();return}if(t&&typeof t.requestFullscreen==="function")return t.requestFullscreen()}async function nt(e){let t=document,i=e;if(typeof t.exitFullscreen==="function")return t.exitFullscreen();if(typeof t.webkitExitFullscreen==="function")return t.webkitExitFullscreen();if(typeof t.webkitCancelFullScreen==="function")return t.webkitCancelFullScreen();if(i&&typeof i.webkitExitFullscreen==="function")i.webkitExitFullscreen()}function st(e){if(!e)return"unavailable";if("requestPictureInPicture"in e){if(typeof document<"u"&&document.pictureInPictureEnabled===!1)return"unavailable";if(Dt()&&Je())return"unavailable";return"available"}let t=e;if(typeof t.webkitSetPresentationMode==="function"){if(Je())return"unavailable";if(typeof t.webkitSupportsPresentationMode==="function")return t.webkitSupportsPresentationMode("picture-in-picture")?"available":"unsupported";return"available"}return"unsupported"}async function rt(e){let t=e;if(typeof t.requestPictureInPicture==="function"){await t.requestPictureInPicture();return}if(typeof t.webkitSetPresentationMode==="function")t.webkitSetPresentationMode("picture-in-picture")}async function at(e){if(document.pictureInPictureElement&&typeof document.exitPictureInPicture==="function"){await document.exitPictureInPicture();return}if(e){let t=e;if(t.webkitPresentationMode==="picture-in-picture"&&typeof t.webkitSetPresentationMode==="function")t.webkitSetPresentationMode("inline")}}class k{container=null;options={};events=new E;_ready=!1;get mediaElement(){return null}get ready(){return this._ready}async setup(e,t){this.container=e,this.options=t,await this.initialize(),this._ready=!0,this.events.emit("ready")}destroy(){this._ready=!1,this.cleanup(),this.events.removeAllListeners()}stop(){this.pause(),this.seekTo(0)}getQualities(){return[]}setQuality(e){}getTextTracks(){return[]}setTextTrackMode(e,t){}getAudioTracks(){return[]}setAudioTrack(e){}getFeatureAvailability(e){let t=this.mediaElement,i=t instanceof HTMLMediaElement?t:null,n=t instanceof HTMLVideoElement?t:null;switch(e){case"volume":return t&&!(t instanceof HTMLMediaElement)?"available":Ze(i);case"fullscreen":return tt(this.container,n);case"pip":return t&&!(t instanceof HTMLMediaElement)?"unsupported":st(n);default:return"unsupported"}}async enterFullscreen(){await it(this.container,this.mediaElement)}async exitFullscreen(){await nt(this.mediaElement)}getFullscreenElement(){return this.container}async enterPiP(){let e=this.mediaElement;if(!e)return;await rt(e)}async exitPiP(){await at(this.mediaElement)}on(e,t){this.events.on(e,t)}off(e,t){this.events.off(e,t)}emitError(e,t,i){let n={code:e,message:t,details:i};this.events.emit("error",n)}}function ge(e){if(typeof e==="string"){let t=ye(e);if(t==="mp4"||t==="webm"||t==="ogg"||t==="ogv"||t==="mov"||t==="mp3"||t==="wav"||t==="flac"||t==="m4a"||t==="aac"||t==="oga"||t==="opus")return!0;return!1}if(typeof e==="object"&&"type"in e){let t=e.type?.toLowerCase()||"";return t.startsWith("video/")||t.startsWith("audio/")||t==="application/ogg"}return!1}function ye(e){let t=e.split(/[?#]/,1)[0];return t.slice(t.lastIndexOf(".")+1).toLowerCase()}function K(e){let t=ye(e);return{mp4:"video/mp4",webm:"video/webm",ogg:"video/ogg",ogv:"video/ogg",mov:"video/quicktime",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",m4a:"audio/mp4",aac:"audio/aac",oga:"audio/ogg",opus:"audio/ogg; codecs=opus"}[t||""]||"video/mp4"}class C extends k{name="html5";type="video";media=null;eventsNormalizer=null;cleanupFullscreen=null;cleanupPiP=null;isAudio=!1;get mediaElement(){return this.media}async initialize(){if(!this.container)throw Error("Container element is required");if(this.isAudio=this.options.mediaType==="audio",this.media=document.createElement(this.isAudio?"audio":"video"),this.media.className="ts-video-player__media",this.options.autoplay)this.media.autoplay=!0;if(this.options.loop)this.media.loop=!0;if(this.options.muted)this.media.muted=!0;if(this.options.playsinline&&!this.isAudio)this.media.playsInline=!0;if(this.options.preload)this.media.preload=this.options.preload;if(this.options.crossorigin)this.media.crossOrigin=this.options.crossorigin;if(this.options.controlsList?.length)this.media.setAttribute("controlslist",this.options.controlsList.join(" "));if(!this.isAudio&&this.options.disablePictureInPicture)this.media.disablePictureInPicture=!0;if(this.options.poster&&!this.isAudio)this.media.poster=this.options.poster;if(this.options.volume!==void 0)this.media.volume=this.options.volume;this.container.appendChild(this.media);for(let e of this.options.tracks??[])this.addTextTrack(e);if(this.eventsNormalizer=new M(this.media,this.events),this.cleanupFullscreen=z((e)=>{this.events.emit("fullscreenchange",e)}),!this.isAudio&&this.media instanceof HTMLVideoElement)this.cleanupPiP=U(this.media,(e)=>{this.events.emit("pipchange",e)});if(!this.isAudio)this.media.addEventListener("loadedmetadata",()=>{let e=this.media,t=this.getFeatureAvailability("fullscreen"),i=this.getFeatureAvailability("pip"),n=this.getFeatureAvailability("volume");this.events.emit("statechange",{videoWidth:e.videoWidth,videoHeight:e.videoHeight,aspectRatio:(e.videoHeight>0?e.videoWidth/e.videoHeight:0)||1.7777777777777777,canFullscreen:t==="available",canPictureInPicture:i==="available",fullscreenAvailability:t,pipAvailability:i,volumeAvailability:n}),this.events.emit("availabilitychange","fullscreen",t),this.events.emit("availabilitychange","pip",i),this.events.emit("availabilitychange","volume",n)});if(this.media.addEventListener("loadeddata",()=>{if(!this.media)return;et(this.media).then((e)=>{this.events.emit("statechange",{volumeAvailability:e}),this.events.emit("availabilitychange","volume",e)}).catch(()=>{})}),!this.isAudio&&this.media instanceof HTMLVideoElement)this.media.addEventListener("webkitpresentationmodechanged",()=>{let e=this.media;if(e?.webkitPresentationMode){let t=e.webkitPresentationMode==="picture-in-picture";this.events.emit("pipchange",t)}})}cleanup(){if(this.eventsNormalizer?.destroy(),this.cleanupFullscreen?.(),this.cleanupPiP?.(),this.media)this.media.pause(),this.media.removeAttribute("src"),this.media.load(),this.media.remove(),this.media=null}canPlay(e){return ge(e)}async load(e){if(!this.media)return;this.media.innerHTML="",this.media.removeAttribute("src");let t=Array.isArray(e)?e:[e];for(let i of t)if(typeof i==="string"){let n=document.createElement("source");n.src=i,n.type=K(i),this.media.appendChild(n)}else if("src"in i&&typeof i.src==="string"){let n=i,s=document.createElement("source");s.src=n.src,s.type=n.type||K(n.src),this.media.appendChild(s)}this.media.load()}async play(){if(!this.media)return;try{await this.media.play()}catch(e){if(e.name==="NotAllowedError")this.emitError(1,"Playback was blocked. User interaction required.",e);else throw e}}pause(){this.media?.pause()}seekTo(e){if(this.media)this.media.currentTime=Math.max(0,Math.min(e,this.getDuration()))}getCurrentTime(){return this.media?.currentTime||0}getDuration(){return this.media?.duration||0}setVolume(e){if(this.media)this.media.volume=Math.max(0,Math.min(1,e))}getVolume(){return this.media?.volume||1}setMuted(e){if(this.media)this.media.muted=e}getMuted(){return this.media?.muted||!1}setPlaybackRate(e){if(this.media)this.media.playbackRate=Math.max(0.25,Math.min(4,e))}getPlaybackRate(){return this.media?.playbackRate||1}getTextTracks(){if(!this.media)return[];let e=[],t=this.media.textTracks;for(let i=0;i<t.length;i++){let n=t[i];e.push({id:String(i),kind:n.kind,label:n.label||`Track ${i+1}`,language:n.language||"",mode:n.mode,cues:this.getTrackCues(n)})}return e}getTrackCues(e){if(!e.cues)return[];let t=[];for(let i=0;i<e.cues.length;i++){let n=e.cues[i];t.push({id:n.id||String(i),startTime:n.startTime,endTime:n.endTime,text:n.text})}return t}setTextTrackMode(e,t){if(!this.media)return;let i=parseInt(e,10),n=this.media.textTracks[i];if(n)n.mode=t,this.events.emit("texttrackchange",t==="showing"?this.getTextTracks()[i]:null)}getAudioTracks(){if(!this.media||this.isAudio)return[];let e=this.media;if(!("audioTracks"in e))return[];let t=e.audioTracks,i=[];for(let n=0;n<t.length;n++){let s=t[n];i.push({id:s.id||String(n),label:s.label||`Track ${n+1}`,language:s.language||"",kind:s.kind||"",selected:s.enabled})}return i}setAudioTrack(e){if(!this.media||this.isAudio)return;let t=this.media;if(!("audioTracks"in t))return;let i=t.audioTracks;for(let n=0;n<i.length;n++){let s=i[n].id===e||String(n)===e;i[n].enabled=s}this.events.emit("audiotrackchange",this.getAudioTracks().find((n)=>n.selected)||null)}addTextTrack(e){if(!this.media)return;let t=document.createElement("track");if(e.src)t.src=e.src;if(t.kind=e.kind||"subtitles",t.label=e.label||"",t.srclang=e.language||"",e.default)t.default=!0;this.media.appendChild(t)}}var fe={name:"html5",type:"video",canPlay(e){return ge(e)},mediaType(e){if(typeof e==="string"){let t=ye(e);if(["mp3","wav","flac","m4a","aac","oga","opus"].includes(t))return"audio";return"video"}if(typeof e==="object"&&"type"in e){if((e.type?.toLowerCase()||"").startsWith("audio/"))return"audio"}return"video"},async load(e,t){let i=new C;return await i.setup(e,t),i}};var Ft=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,/youtube\.com\/v\/([a-zA-Z0-9_-]{11})/,/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/];function A(e){for(let t of Ft){let i=e.match(t);if(i)return i[1]}return null}function be(e){if(typeof e==="string")return A(e)!==null;if(typeof e==="object"&&"type"in e)return e.type==="youtube";return!1}function $t(e){if(typeof e==="string"){let t=A(e);if(!t)return null;let i=new URL(e,"https://youtube.com"),n=i.searchParams.get("t")||i.searchParams.get("start"),s=i.searchParams.get("end");return{videoId:t,startTime:n?ot(n):void 0,endTime:s?ot(s):void 0}}if(typeof e==="object"&&"type"in e&&e.type==="youtube"){let t=e;return{videoId:t.videoId||A(t.src)||"",startTime:t.startTime,endTime:t.endTime}}return null}function ot(e){if(/^\d+$/.test(e))return parseInt(e,10);let t=e.match(/(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?/);if(t){let n=parseInt(t[1]||"0",10),s=parseInt(t[2]||"0",10),r=parseInt(t[3]||"0",10);return n*3600+s*60+r}let i=e.split(":").map((n)=>parseInt(n,10));if(i.length===2)return i[0]*60+i[1];if(i.length===3)return i[0]*3600+i[1]*60+i[2];return 0}class R extends k{name="youtube";type="youtube";player=null;iframe=null;pendingVideoId=null;playerReady=!1;startTime;endTime;timeUpdateInterval=null;lastState=-1;pendingPlay=!1;get mediaElement(){return this.iframe}async initialize(){if(!this.container)throw Error("Container element is required");await this.loadYouTubeAPI();let e=document.createElement("div");e.id=`ts-video-player-yt-${Date.now()}`,e.className="ts-video-player__youtube",this.container.appendChild(e);let t={autoplay:this.options.autoplay?1:0,controls:0,disablekb:1,enablejsapi:1,iv_load_policy:3,modestbranding:1,playsinline:this.options.playsinline?1:0,rel:0,origin:window.location.origin};if(this.options.youtubeParams)Object.assign(t,this.options.youtubeParams);if(this.player=new window.YT.Player(e,{host:"https://www.youtube-nocookie.com",width:"100%",height:"100%",playerVars:t,events:{onReady:()=>this.onReady(),onStateChange:(i)=>this.onStateChange(i),onError:(i)=>this.onError(i),onPlaybackQualityChange:()=>this.onQualityChange(),onPlaybackRateChange:()=>this.onRateChange()}}),this.iframe=this.player.getIframe(),this.iframe.className="ts-video-player__media",this.iframe.style.cssText="position:absolute;left:0;top:-100%;width:100%;height:300%;border:0",this.iframe.parentElement)this.iframe.parentElement.style.overflow="hidden"}async loadYouTubeAPI(){if(window.YT?.Player)return;return new Promise((e)=>{if(document.querySelector('script[src*="youtube.com/iframe_api"]')){let i=()=>{if(window.YT?.Player)e();else setTimeout(i,100)};i();return}let t=document.createElement("script");t.src="https://www.youtube.com/iframe_api",t.async=!0,window.onYouTubeIframeAPIReady=()=>{e()},document.head.appendChild(t)})}cleanup(){if(this.timeUpdateInterval)clearInterval(this.timeUpdateInterval),this.timeUpdateInterval=null;this.player?.destroy(),this.player=null,this.playerReady=!1,this.pendingPlay=!1,this.iframe=null}onReady(){if(this.playerReady=!0,this.timeUpdateInterval=setInterval(()=>{if(this.player&&this.lastState===1)this.events.emit("timeupdate",this.getCurrentTime())},250),this.events.emit("loadedmetadata"),this.events.emit("canplay"),this.pendingVideoId){let e=this.pendingVideoId;this.pendingVideoId=null,this.loadVideo(e,this.startTime,this.endTime)}else if(this.pendingPlay)this.pendingPlay=!1,this.player?.playVideo()}onStateChange(e){let t=e.data;this.lastState=t;let i=window.YT.PlayerState;switch(t){case i.UNSTARTED:this.events.emit("loadstart");break;case i.PLAYING:if(this.getDuration()>0)this.events.emit("durationchange",this.getDuration());this.events.emit("play"),this.events.emit("playing"),this.events.emit("statechange",{paused:!1,playing:!0,waiting:!1});break;case i.PAUSED:this.events.emit("pause"),this.events.emit("statechange",{paused:!0,playing:!1});break;case i.BUFFERING:this.events.emit("waiting"),this.events.emit("statechange",{waiting:!0});break;case i.ENDED:this.events.emit("ended"),this.events.emit("statechange",{ended:!0,playing:!1});break;case i.CUED:this.events.emit("loadeddata"),this.events.emit("durationchange",this.getDuration());break}}onError(e){let t={2:"Invalid video ID",5:"HTML5 player error",100:"Video not found or removed",101:"Video cannot be embedded",150:"Video cannot be embedded"};this.emitError(e.data,t[e.data]||"Unknown YouTube error")}onQualityChange(){let e=this.player?.getPlaybackQuality()||"auto",t=this.getQualities();this.events.emit("qualitychange",t.find((i)=>i.id===e)||null)}onRateChange(){this.events.emit("ratechange",this.getPlaybackRate())}canPlay(e){return be(e)}async load(e){let t=$t(e);if(!t){this.emitError(2,"Invalid YouTube source");return}if(this.startTime=t.startTime,this.endTime=t.endTime,!this.player||!this._ready||!this.playerReady){this.pendingVideoId=t.videoId;return}this.loadVideo(t.videoId,t.startTime,t.endTime)}loadVideo(e,t,i){if(!this.player)return;if(this.options.autoplay||this.pendingPlay)this.pendingPlay=!1,this.player.loadVideoById({videoId:e,startSeconds:t,endSeconds:i});else this.player.cueVideoById({videoId:e,startSeconds:t,endSeconds:i})}async play(){if(!this.player||!this.playerReady||this.pendingVideoId){this.pendingPlay=!0;return}this.player.playVideo()}pause(){if(this.pendingPlay=!1,this.playerReady)this.player?.pauseVideo()}stop(){if(this.pendingPlay=!1,this.playerReady)this.player?.stopVideo()}seekTo(e){this.player?.seekTo(e,!0),this.events.emit("seeking"),setTimeout(()=>this.events.emit("seeked"),100)}getCurrentTime(){return this.player?.getCurrentTime()||0}getDuration(){return this.player?.getDuration()||0}setVolume(e){this.player?.setVolume(Math.round(e*100)),this.events.emit("volumechange",e,this.getMuted())}getVolume(){return(this.player?.getVolume()||100)/100}setMuted(e){if(e)this.player?.mute();else this.player?.unMute();this.events.emit("volumechange",this.getVolume(),e)}getMuted(){return this.player?.isMuted()||!1}setPlaybackRate(e){this.player?.setPlaybackRate(e)}getPlaybackRate(){return this.player?.getPlaybackRate()||1}getQualities(){let e=this.player?.getAvailableQualityLevels()||[],t={highres:2160,hd2160:2160,hd1440:1440,hd1080:1080,hd720:720,large:480,medium:360,small:240,tiny:144},i=this.player?.getPlaybackQuality();return e.map((n)=>({id:n,width:Math.round((t[n]||480)*1.7777777777777777),height:t[n]||480,bitrate:0,selected:n===i}))}setQuality(e){if(e==="auto")this.player?.setPlaybackQuality("default");else this.player?.setPlaybackQuality(e.id)}}var ke={name:"youtube",type:"youtube",canPlay(e){return be(e)},mediaType(){return"video"},preconnect(){return["https://www.youtube-nocookie.com","https://www.youtube.com","https://i.ytimg.com","https://s.ytimg.com"]},async load(e,t){let i=new R;return await i.setup(e,t),i}};var Ot=[/vimeo\.com\/(\d+)/,/vimeo\.com\/video\/(\d+)/,/player\.vimeo\.com\/video\/(\d+)/,/vimeo\.com\/channels\/[\w]+\/(\d+)/,/vimeo\.com\/groups\/[\w]+\/videos\/(\d+)/];function Q(e){for(let t of Ot){let i=e.match(t);if(i)return i[1]}return null}function dt(e){let t=e.match(/vimeo\.com\/\d+\/([a-f0-9]+)/);return t?t[1]:null}function Te(e){if(typeof e==="string")return Q(e)!==null;if(typeof e==="object"&&"type"in e)return e.type==="vimeo";return!1}function qt(e){if(typeof e==="string"){let t=Q(e);if(!t)return null;return{videoId:t,hash:dt(e)||void 0}}if(typeof e==="object"&&"type"in e&&e.type==="vimeo"){let t=e;return{videoId:t.videoId||Q(t.src)||"",hash:t.hash}}return null}var lt="https://player.vimeo.com/api/player.js";class we extends k{name="vimeo";type="vimeo";container_el=null;player=null;iframe=null;timeUpdateInterval=null;_qualities=[];_duration=0;get mediaElement(){return this.iframe}async initialize(){if(!this.container)throw Error("Container element is required");await this.loadVimeoSDK(),this.container_el=document.createElement("div"),this.container_el.className="ts-video-player__vimeo",this.container.appendChild(this.container_el)}async loadVimeoSDK(){if(window.Vimeo)return;return new Promise((e,t)=>{if(document.querySelector(`script[src="${lt}"]`)){let n=()=>{if(window.Vimeo)e();else setTimeout(n,100)};n();return}let i=document.createElement("script");i.src=lt,i.async=!0,i.onload=()=>e(),i.onerror=()=>t(Error("Failed to load Vimeo SDK")),document.head.appendChild(i)})}cleanup(){if(this.timeUpdateInterval)clearInterval(this.timeUpdateInterval),this.timeUpdateInterval=null;this.player?.destroy(),this.player=null,this.iframe=null,this.container_el?.remove(),this.container_el=null}canPlay(e){return Te(e)}async load(e){let t=qt(e);if(!t||!this.container_el){this.emitError(2,"Invalid Vimeo source");return}if(this.player){await this.player.loadVideo(parseInt(t.videoId,10)),await this.announceLoaded();return}let i={id:parseInt(t.videoId,10),autopause:!1,autoplay:this.options.autoplay||!1,controls:!1,loop:this.options.loop||!1,muted:this.options.muted||!1,playsinline:this.options.playsinline!==!1,responsive:!0,dnt:!0};if(this.options.vimeoParams)Object.assign(i,this.options.vimeoParams);if(this.player=new window.Vimeo.Player(this.container_el,i),await this.player.ready(),this.iframe=this.container_el.querySelector("iframe"),this.iframe)this.iframe.className="ts-video-player__media",this.iframe.style.cssText="position:absolute;inset:0;width:100%;height:100%;border:0";this.attachVimeoEvents(),await this.announceLoaded()}async announceLoaded(){if(!this.player)return;this.events.emit("loadedmetadata"),this.events.emit("canplay"),this._duration=await this.player.getDuration(),this.events.emit("durationchange",this._duration),await this.updateQualities();let[e,t]=await Promise.all([this.player.getVideoWidth(),this.player.getVideoHeight()]);this.events.emit("statechange",{videoWidth:e,videoHeight:t,aspectRatio:e/t||1.7777777777777777,canFullscreen:!0,canPictureInPicture:!1})}attachVimeoEvents(){if(!this.player)return;this.player.on("play",()=>{this.events.emit("play"),this.events.emit("playing"),this.events.emit("statechange",{paused:!1,playing:!0})}),this.player.on("pause",()=>{this.events.emit("pause"),this.events.emit("statechange",{paused:!0,playing:!1})}),this.player.on("ended",()=>{this.events.emit("ended"),this.events.emit("statechange",{ended:!0,playing:!1})}),this.player.on("timeupdate",(e)=>{this.events.emit("timeupdate",e.seconds)}),this.player.on("seeking",()=>{this.events.emit("seeking")}),this.player.on("seeked",()=>{this.events.emit("seeked")}),this.player.on("bufferstart",()=>{this.events.emit("waiting"),this.events.emit("statechange",{waiting:!0})}),this.player.on("bufferend",()=>{this.events.emit("statechange",{waiting:!1})}),this.player.on("progress",(e)=>{let t=[{start:0,end:e.percent*this._duration}];this.events.emit("progress",t)}),this.player.on("volumechange",async()=>{let[e,t]=await Promise.all([this.player.getVolume(),this.player.getMuted()]);this.events.emit("volumechange",e,t)}),this.player.on("playbackratechange",(e)=>{this.events.emit("ratechange",e.playbackRate)}),this.player.on("qualitychange",async()=>{await this.updateQualities();let e=this._qualities.find((t)=>t.selected);this.events.emit("qualitychange",e||null)}),this.player.on("error",(e)=>{this.emitError(5,e.message,e)})}async updateQualities(){if(!this.player)return;try{let e=await this.player.getQualities();this._qualities=e.map((t)=>{let i=t.label.match(/(\d+)p/),n=i?parseInt(i[1],10):0;return{id:t.id,width:Math.round(n*1.7777777777777777),height:n,bitrate:0,selected:t.active}}),this.events.emit("statechange",{qualities:this._qualities})}catch{}}async play(){try{await this.player?.play()}catch(e){if(e.name==="NotAllowedError")this.emitError(1,"Playback was blocked. User interaction required.",e);else throw e}}pause(){this.player?.pause()}stop(){this.pause(),this.seekTo(0)}seekTo(e){this.player?.setCurrentTime(e)}getCurrentTime(){return 0}getDuration(){return this._duration}setVolume(e){this.player?.setVolume(Math.max(0,Math.min(1,e)))}getVolume(){return 1}setMuted(e){this.player?.setMuted(e)}getMuted(){return!1}setPlaybackRate(e){this.player?.setPlaybackRate(e)}getPlaybackRate(){return 1}getQualities(){return this._qualities}setQuality(e){if(!this.player)return;if(e==="auto")this.player.setQuality("auto");else this.player.setQuality(e.id)}async enableTextTrack(e){await this.player?.enableTextTrack(e)}async disableTextTrack(){await this.player?.disableTextTrack()}async getChapters(){if(!this.player)return[];try{return await this.player.getChapters()}catch{return[]}}}var xe={name:"vimeo",type:"vimeo",canPlay(e){return Te(e)},mediaType(){return"video"},preconnect(){return["https://player.vimeo.com","https://i.vimeocdn.com","https://f.vimeocdn.com"]},async load(e,t){let i=new we;return await i.setup(e,t),i}};function Se(e){if(typeof e==="string"){let t=e.toLowerCase();return t.endsWith(".m3u8")||t.includes("application/x-mpegurl")||t.includes("application/vnd.apple.mpegurl")}if(typeof e==="object"&&"type"in e){let t=e.type?.toLowerCase()||"";return t==="application/x-mpegurl"||t==="application/vnd.apple.mpegurl"}return!1}function ct(){return document.createElement("video").canPlayType("application/vnd.apple.mpegurl")!==""}var Nt="https://cdn.jsdelivr.net/npm/hls.js@latest/dist/hls.min.js";class I extends k{name="hls";type="hls";video=null;hls=null;eventsNormalizer=null;cleanupFullscreen=null;cleanupPiP=null;useNativeHLS=!1;_qualities=[];_audioTracks=[];_textTracks=[];currentQualityIndex=-1;get mediaElement(){return this.video}get canLiveSync(){return!this.useNativeHLS&&this.hls!==null}get hlsConfig(){return this.hls?.config||{}}async initialize(){if(!this.container)throw Error("Container element is required");if(this.video=document.createElement("video"),this.video.className="ts-video-player__media",this.options.autoplay)this.video.autoplay=!0;if(this.options.loop)this.video.loop=!0;if(this.options.muted)this.video.muted=!0;if(this.options.playsinline)this.video.playsInline=!0;if(this.options.preload)this.video.preload=this.options.preload;if(this.options.crossorigin)this.video.crossOrigin=this.options.crossorigin;if(this.options.poster)this.video.poster=this.options.poster;if(this.options.volume!==void 0)this.video.volume=this.options.volume;if(this.container.appendChild(this.video),this.eventsNormalizer=new M(this.video,this.events),this.cleanupFullscreen=z((e)=>{this.events.emit("fullscreenchange",e)}),this.cleanupPiP=U(this.video,(e)=>{this.events.emit("pipchange",e)}),this.useNativeHLS=ct(),!this.useNativeHLS)await this.loadHLSLibrary();this.video.addEventListener("loadedmetadata",()=>{let e=this.getFeatureAvailability("fullscreen"),t=this.getFeatureAvailability("pip"),i=this.getFeatureAvailability("volume");this.events.emit("statechange",{videoWidth:this.video.videoWidth,videoHeight:this.video.videoHeight,aspectRatio:(this.video.videoHeight>0?this.video.videoWidth/this.video.videoHeight:0)||1.7777777777777777,canFullscreen:e==="available",canPictureInPicture:t==="available",fullscreenAvailability:e,pipAvailability:t,volumeAvailability:i}),this.events.emit("availabilitychange","fullscreen",e),this.events.emit("availabilitychange","pip",t),this.events.emit("availabilitychange","volume",i)})}async loadHLSLibrary(){if(window.Hls)return;return new Promise((e,t)=>{let i=document.createElement("script");i.src=this.options.hlsCdnUrl||Nt,i.async=!0,i.onload=()=>e(),i.onerror=()=>t(Error("Failed to load HLS.js")),document.head.appendChild(i)})}cleanup(){if(this.eventsNormalizer?.destroy(),this.cleanupFullscreen?.(),this.cleanupPiP?.(),this.hls)this.hls.destroy(),this.hls=null;if(this.video)this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video=null;this._qualities=[],this._audioTracks=[],this._textTracks=[]}canPlay(e){return Se(e)}async load(e){if(!this.video)return;let t=typeof e==="string"?e:e.src;if(this.useNativeHLS){this.video.src=t,this.video.load();return}if(!window.Hls)await this.loadHLSLibrary();if(!window.Hls?.isSupported()){this.emitError(4,"HLS is not supported in this browser");return}if(this.hls)this.hls.destroy();let i={enableWorker:!0,lowLatencyMode:!1,...this.options.hlsConfig};this.hls=new window.Hls(i),this.attachHLSEvents(),this.hls.attachMedia(this.video),this.hls.loadSource(t)}attachHLSEvents(){if(!this.hls||!window.Hls)return;let e=window.Hls;this.hls.on(e.Events.MANIFEST_PARSED,(t,i)=>{if(this.updateQualities(i.levels),this.options.autoplay)this.video?.play().catch(()=>{})}),this.hls.on(e.Events.LEVEL_SWITCHED,(t,i)=>{this.currentQualityIndex=i.level,this.updateQualitySelection(),this.events.emit("qualitychange",this._qualities[i.level]||null)}),this.hls.on(e.Events.AUDIO_TRACK_LOADED,()=>{this.updateAudioTracks()}),this.hls.on(e.Events.AUDIO_TRACK_SWITCHED,()=>{this.updateAudioTracks();let t=this._audioTracks.find((i)=>i.selected);this.events.emit("audiotrackchange",t||null)}),this.hls.on(e.Events.SUBTITLE_TRACK_LOADED,()=>{this.updateTextTracks()}),this.hls.on(e.Events.ERROR,(t,i)=>{if(i.fatal)switch(i.type){case e.ErrorTypes.NETWORK_ERROR:this.hls?.startLoad();break;case e.ErrorTypes.MEDIA_ERROR:this.hls?.recoverMediaError();break;default:this.emitError(5,`HLS fatal error: ${i.details}`,i),this.hls?.destroy();break}})}updateQualities(e){this._qualities=e.map((t,i)=>({id:String(i),width:t.width,height:t.height,bitrate:t.bitrate,codec:t.codecSet||t.videoCodec||void 0,selected:i===this.currentQualityIndex})),this.events.emit("statechange",{qualities:this._qualities})}updateQualitySelection(){this._qualities=this._qualities.map((e,t)=>({...e,selected:t===this.currentQualityIndex}))}updateAudioTracks(){if(!this.hls)return;this._audioTracks=this.hls.audioTracks.map((e,t)=>({id:String(e.id),label:e.name||`Track ${t+1}`,language:e.lang||"",kind:e.default?"main":"alternative",selected:t===this.hls.audioTrack})),this.events.emit("statechange",{audioTracks:this._audioTracks})}updateTextTracks(){if(!this.hls)return;this._textTracks=this.hls.subtitleTracks.map((e,t)=>({id:String(e.id),kind:"subtitles",label:e.name||`Subtitle ${t+1}`,language:e.lang||"",mode:t===this.hls.subtitleTrack?"showing":"disabled",cues:[]})),this.events.emit("statechange",{textTracks:this._textTracks})}async play(){if(!this.video)return;try{await this.video.play()}catch(e){if(e.name==="NotAllowedError")this.emitError(1,"Playback was blocked. User interaction required.",e);else throw e}}pause(){this.video?.pause()}seekTo(e){if(this.video)this.video.currentTime=Math.max(0,Math.min(e,this.getDuration()))}getCurrentTime(){return this.video?.currentTime||0}getDuration(){return this.video?.duration||0}syncToLive(){if(this.hls?.liveSyncPosition!=null)this.seekTo(this.hls.liveSyncPosition)}setVolume(e){if(this.video)this.video.volume=Math.max(0,Math.min(1,e))}getVolume(){return this.video?.volume||1}setMuted(e){if(this.video)this.video.muted=e}getMuted(){return this.video?.muted||!1}setPlaybackRate(e){if(this.video)this.video.playbackRate=Math.max(0.25,Math.min(4,e))}getPlaybackRate(){return this.video?.playbackRate||1}getQualities(){return this._qualities}setQuality(e){if(!this.hls)return;if(e==="auto")this.hls.currentLevel=-1,this.currentQualityIndex=-1,this.events.emit("statechange",{autoQuality:!0});else{let t=parseInt(e.id,10);if(!isNaN(t)&&t>=0&&t<this._qualities.length)this.hls.currentLevel=t,this.currentQualityIndex=t,this.events.emit("statechange",{autoQuality:!1})}}getAudioTracks(){return this._audioTracks}setAudioTrack(e){if(!this.hls)return;let t=parseInt(e,10);if(!isNaN(t)&&t>=0&&t<this.hls.audioTracks.length)this.hls.audioTrack=t}getTextTracks(){return this._textTracks}setTextTrackMode(e,t){if(!this.hls)return;if(t==="showing"){let n=parseInt(e,10);if(!isNaN(n))this.hls.subtitleTrack=n}else this.hls.subtitleTrack=-1;this.updateTextTracks();let i=this._textTracks.find((n)=>n.mode==="showing");this.events.emit("texttrackchange",i||null)}}var Ee={name:"hls",type:"hls",canPlay(e){return Se(e)},mediaType(){return"video"},preconnect(){return["https://cdn.jsdelivr.net"]},async load(e,t){let i=new I;return await i.setup(e,t),i}};var w=null,W=null,zt="https://cdn.dashjs.org/latest/dash.all.min.js";async function Ut(e){if(w)return w;if(W)return W;return W=new Promise((t,i)=>{if(typeof window<"u"&&window.dashjs){w=window.dashjs,t(w);return}let n=document.createElement("script");n.src=e||zt,n.async=!0,n.onload=()=>{w=window.dashjs,t(w)},n.onerror=()=>{i(Error("Failed to load dash.js"))},document.head.appendChild(n)}),W}function j(e){if(typeof e==="object"&&"type"in e&&e.type==="dash")return!0;if(typeof e==="string")return e.includes(".mpd")||e.includes("manifest(format=mpd");return!1}class H extends k{name="dash";type="dash";dash=null;video=null;source=null;config={};_volume=1;_muted=!1;_playbackRate=1;get mediaElement(){return this.video}async initialize(){if(this.video=document.createElement("video"),this.video.style.width="100%",this.video.style.height="100%",this.video.style.display="block",await Ut(this.options.dashCdnUrl),this.dash=w.MediaPlayer().create(),this.options.dashConfig)this.config.dashConfig=this.options.dashConfig;if(this.config.dashConfig)Object.entries(this.config.dashConfig).forEach(([e,t])=>{this.dash.updateSettings({[e]:t})});if(this.config.lowLatency)this.dash.updateSettings({streaming:{lowLatencyEnabled:!0,liveDelay:3,liveCatchUpMinDrift:0.05,liveCatchUpPlaybackRate:0.5}});if(this.attachDashEvents(),this.container)this.container.appendChild(this.video);this.attachVideoEvents()}attachVideoEvents(){if(!this.video)return;this.video.addEventListener("play",()=>this.events.emit("play")),this.video.addEventListener("pause",()=>this.events.emit("pause")),this.video.addEventListener("ended",()=>this.events.emit("ended")),this.video.addEventListener("timeupdate",()=>this.events.emit("timeupdate",this.getCurrentTime())),this.video.addEventListener("durationchange",()=>this.events.emit("durationchange",this.getDuration())),this.video.addEventListener("volumechange",()=>{this.events.emit("volumechange",this.getVolume(),this.getMuted())}),this.video.addEventListener("waiting",()=>this.events.emit("waiting")),this.video.addEventListener("playing",()=>this.events.emit("playing")),this.video.addEventListener("seeking",()=>this.events.emit("seeking")),this.video.addEventListener("seeked",()=>this.events.emit("seeked")),this.video.addEventListener("progress",()=>{let e=[];for(let t=0;t<this.video.buffered.length;t++)e.push({start:this.video.buffered.start(t),end:this.video.buffered.end(t)});this.events.emit("progress",e)}),this.video.addEventListener("loadedmetadata",()=>{this.events.emit("loadedmetadata");let e=this.getFeatureAvailability("fullscreen"),t=this.getFeatureAvailability("pip"),i=this.getFeatureAvailability("volume");this.events.emit("statechange",{videoWidth:this.video.videoWidth,videoHeight:this.video.videoHeight,aspectRatio:(this.video.videoHeight>0?this.video.videoWidth/this.video.videoHeight:0)||1.7777777777777777,canFullscreen:e==="available",canPictureInPicture:t==="available",fullscreenAvailability:e,pipAvailability:t,volumeAvailability:i}),this.events.emit("availabilitychange","fullscreen",e),this.events.emit("availabilitychange","pip",t),this.events.emit("availabilitychange","volume",i)}),this.video.addEventListener("loadeddata",()=>this.events.emit("loadeddata")),this.video.addEventListener("canplay",()=>this.events.emit("canplay")),this.video.addEventListener("canplaythrough",()=>this.events.emit("canplaythrough")),this.video.addEventListener("ratechange",()=>this.events.emit("ratechange",this.getPlaybackRate()))}attachDashEvents(){if(!w)return;let e=w.MediaPlayer;this.dash.on(e.events.QUALITY_CHANGE_RENDERED,()=>{this.events.emit("qualitychange",this.getQualities().find((t)=>t.selected)||null)}),this.dash.on(e.events.MANIFEST_LOADED,()=>{}),this.dash.on(e.events.ERROR,(t)=>{this.emitError(t.error?.code||0,t.error?.message||"DASH playback error",t.error)})}configureDRM(e){let t={};if(e.widevine)t["com.widevine.alpha"]={serverURL:e.widevine.url,httpRequestHeaders:e.widevine.headers};if(e.playready)t["com.microsoft.playready"]={serverURL:e.playready.url,httpRequestHeaders:e.playready.headers};if(e.fairplay)t["com.apple.fps.1_0"]={serverURL:e.fairplay.url,serverCertificateURL:e.fairplay.certificateUrl,httpRequestHeaders:e.fairplay.headers};this.dash.setProtectionData(t)}async load(e){if(!this.video||!this.dash)return;if(typeof e==="string")this.source={src:e,type:"dash"};else if(j(e))this.source=e;else{this.emitError(4,"Invalid DASH source");return}if(this.source.drm)this.configureDRM(this.source.drm);this.dash.initialize(this.video,this.source.src,!1)}canPlay(e){return j(e)}cleanup(){if(this.dash)this.dash.reset(),this.dash=null;if(this.video)this.video.remove(),this.video=null;this.source=null}async play(){if(!this.video)return;try{await this.video.play()}catch(e){if(e.name==="NotAllowedError")this.emitError(1,"Playback was blocked. User interaction required.",e);else throw e}}pause(){if(this.video)this.video.pause()}seekTo(e){if(this.video)this.video.currentTime=e}getCurrentTime(){return this.video?.currentTime||0}getDuration(){return this.video?.duration||0}setVolume(e){if(this._volume=Math.max(0,Math.min(1,e)),this.video)this.video.volume=this._volume}getVolume(){return this.video?.volume??this._volume}setMuted(e){if(this._muted=e,this.video)this.video.muted=e}getMuted(){return this.video?.muted??this._muted}setPlaybackRate(e){if(this._playbackRate=e,this.video)this.video.playbackRate=e}getPlaybackRate(){return this.video?.playbackRate??this._playbackRate}get isLive(){return this.dash?.isDynamic()??!1}get liveLatency(){return this.dash?.getCurrentLiveLatency()??0}get canLiveSync(){return this.isLive}syncToLive(){if(this.dash&&this.isLive)this.dash.seekToOriginalLive()}getQualities(){if(!this.dash)return[];let e=this.dash.getBitrateInfoListFor("video");if(!e)return[];let t=this.dash.getQualityFor("video");return e.map((i,n)=>({id:`${n}`,label:`${i.height}p`,width:i.width,height:i.height,bitrate:i.bitrate,selected:n===t}))}setQuality(e){if(!this.dash)return;if(e==="auto")this.dash.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:!0}}}});else{let t=Number.parseInt(e.id,10);if(!Number.isNaN(t))this.dash.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:!1}}}}),this.dash.setQualityFor("video",t)}}get isAutoQuality(){if(!this.dash)return!0;return this.dash.getSettings()?.streaming?.abr?.autoSwitchBitrate?.video??!0}getAudioTracks(){if(!this.dash)return[];let e=this.dash.getTracksFor("audio");if(!e)return[];let t=this.dash.getCurrentTrackFor("audio");return e.map((i,n)=>({id:i.id||`${n}`,label:i.labels?.[0]?.text||i.lang||`Track ${n+1}`,language:i.lang||"",kind:"main",selected:i===t}))}setAudioTrack(e){if(!this.dash)return;let i=this.dash.getTracksFor("audio").find((n,s)=>(n.id||`${s}`)===e);if(i)this.dash.setCurrentTrack(i)}getTextTracks(){if(!this.dash)return[];let e=this.dash.getTracksFor("text");if(!e)return[];let t=this.dash.getCurrentTrackFor("text");return e.map((i,n)=>({id:i.id||`${n}`,label:i.labels?.[0]?.text||i.lang||`Subtitle ${n+1}`,language:i.lang||"",kind:i.kind||"subtitles",mode:i===t?"showing":"disabled",cues:[]}))}setTextTrackMode(e,t){if(!this.dash)return;if(t==="disabled"){this.dash.enableText(!1);return}let n=this.dash.getTracksFor("text").find((s,r)=>(s.id||`${r}`)===e);if(n)this.dash.setCurrentTrack(n),this.dash.enableText(t==="showing")}}var Pe={name:"dash",type:"dash",canPlay(e){return j(e)},mediaType(){return"video"},async load(e,t){let i=new H;return await i.setup(e,t),i},preconnect(){return["https://cdn.dashjs.org"]}};var Y=[Ee,Pe,ke,xe,fe];function ut(e){if(!e||typeof e!=="object"||typeof e.src!=="string")return null;return"type"in e&&e.type?null:e.src}var Kt={youtube:()=>"youtube",vimeo:()=>"vimeo",hls:()=>"application/x-mpegurl",dash:()=>"dash",video:(e)=>K(e)};function Qt(e,t){let i=ut(e),n=i&&Kt[t.type];return i&&n?{...e,type:n(i)}:e}function Wt(e,t=Y){for(let n of t)if(n.canPlay(e))return n;let i=ut(e);if(i){for(let n of t)if(n.canPlay(i))return n}return null}function pt(e,t=Y){let i=[];return e.forEach((n,s)=>{let r=Wt(n,t);if(r)i.push({src:Qt(n,r),index:s,loader:r})}),i}function ht(e,t){let i=e.providerType==="youtube"||e.providerType==="vimeo",n=!e.started||e.ended;if(!i||!n||e.error||t)return{show:!1,image:""};if(e.poster)return{show:!0,image:e.poster};let s=e.src,r=typeof s==="string"?s:s?.src||"",a=e.providerType==="youtube"?A(r):null;return{show:!0,image:a?`https://i.ytimg.com/vi/${a}/hqdefault.jpg`:""}}var _e={play:"Play",pause:"Pause",replay:"Replay",mute:"Mute",unmute:"Unmute",volume:"Volume",seekBackward:"Seek backward {seconds} seconds",seekForward:"Seek forward {seconds} seconds",seekTo:"Seek to {time}",duration:"Duration",currentTime:"Current time",played:"Played",buffered:"Buffered",enterFullscreen:"Enter fullscreen",exitFullscreen:"Exit fullscreen",enterPiP:"Enter picture-in-picture",exitPiP:"Exit picture-in-picture",enableCaptions:"Enable captions",disableCaptions:"Disable captions",captions:"Captions",captionsOff:"Off",settings:"Settings",quality:"Quality",auto:"Auto",speed:"Speed",normal:"Normal",loop:"Loop",loopEnabled:"Loop enabled",loopDisabled:"Loop disabled",audioBoost:"Audio boost",audioTrack:"Audio track",live:"LIVE",liveEdge:"At live edge",seekToLive:"Seek to live edge",behindLive:"{seconds}s behind",networkError:"A network error occurred",mediaError:"The media could not be loaded",unknownError:"An unknown error occurred",loading:"Loading",buffering:"Buffering",chapters:"Chapters",airPlay:"AirPlay",googleCast:"Cast",casting:"Casting to {device}",download:"Download",share:"Share",close:"Close",menu:"Menu",back:"Back",seek:"Seek",playbackRate:"Playback speed {rate}x",airPlayPlay:"Play on AirPlay",remotePlayback:"Play on another device",videoPlayer:"Video player",videoRole:"video player",playTitle:"Play {title}",audio:"Audio",defaultTrack:"Default",playing:"Playing",paused:"Paused",muted:"Muted",volumeLevel:"Volume {percent}%",ended:"Playback ended",enteredFullscreen:"Entered fullscreen",exitedFullscreen:"Exited fullscreen",errorMessage:"Error: {message}",timeOf:"{current} of {duration}",hourOne:"{n} hour",hourOther:"{n} hours",minuteOne:"{n} minute",minuteOther:"{n} minutes",secondOne:"{n} second",secondOther:"{n} seconds"},jt={play:"Reproducir",pause:"Pausar",replay:"Repetir",mute:"Silenciar",unmute:"Activar sonido",volume:"Volumen",seekBackward:"Retroceder {seconds} segundos",seekForward:"Avanzar {seconds} segundos",seekTo:"Ir a {time}",duration:"Duración",currentTime:"Tiempo actual",played:"Reproducido",buffered:"Almacenado",enterFullscreen:"Pantalla completa",exitFullscreen:"Salir de pantalla completa",enterPiP:"Imagen en imagen",exitPiP:"Salir de imagen en imagen",enableCaptions:"Activar subtítulos",disableCaptions:"Desactivar subtítulos",captions:"Subtítulos",captionsOff:"Desactivados",settings:"Ajustes",quality:"Calidad",auto:"Automático",speed:"Velocidad",normal:"Normal",loop:"Bucle",loopEnabled:"Bucle activado",loopDisabled:"Bucle desactivado",audioBoost:"Aumento de audio",audioTrack:"Pista de audio",live:"EN VIVO",liveEdge:"En vivo",seekToLive:"Ir al directo",behindLive:"{seconds}s de retraso",networkError:"Error de red",mediaError:"No se pudo cargar el medio",unknownError:"Error desconocido",loading:"Cargando",buffering:"Almacenando",chapters:"Capítulos",airPlay:"AirPlay",googleCast:"Enviar",casting:"Enviando a {device}",download:"Descargar",share:"Compartir",close:"Cerrar",menu:"Menú",back:"Volver",seek:"Buscar",playbackRate:"Velocidad de reproducción {rate}x",airPlayPlay:"Reproducir con AirPlay",remotePlayback:"Reproducir en otro dispositivo",videoPlayer:"Reproductor de vídeo",videoRole:"reproductor de vídeo",playTitle:"Reproducir {title}",audio:"Audio",defaultTrack:"Predeterminado",playing:"Reproduciendo",paused:"En pausa",muted:"Silenciado",volumeLevel:"Volumen {percent}%",ended:"Reproducción finalizada",enteredFullscreen:"Pantalla completa activada",exitedFullscreen:"Pantalla completa desactivada",errorMessage:"Error: {message}",timeOf:"{current} de {duration}",hourOne:"{n} hora",hourOther:"{n} horas",minuteOne:"{n} minuto",minuteOther:"{n} minutos",secondOne:"{n} segundo",secondOther:"{n} segundos"},Yt={play:"Lecture",pause:"Pause",replay:"Relire",mute:"Muet",unmute:"Son activé",volume:"Volume",seekBackward:"Reculer de {seconds} secondes",seekForward:"Avancer de {seconds} secondes",seekTo:"Aller à {time}",duration:"Durée",currentTime:"Temps actuel",played:"Joué",buffered:"Mis en mémoire tampon",enterFullscreen:"Plein écran",exitFullscreen:"Quitter le plein écran",enterPiP:"Image dans l'image",exitPiP:"Quitter l'image dans l'image",enableCaptions:"Activer les sous-titres",disableCaptions:"Désactiver les sous-titres",captions:"Sous-titres",captionsOff:"Désactivés",settings:"Paramètres",quality:"Qualité",auto:"Auto",speed:"Vitesse",normal:"Normal",loop:"Boucle",loopEnabled:"Boucle activée",loopDisabled:"Boucle désactivée",audioBoost:"Amplification audio",audioTrack:"Piste audio",live:"EN DIRECT",liveEdge:"En direct",seekToLive:"Aller au direct",behindLive:"{seconds}s de retard",networkError:"Erreur réseau",mediaError:"Le média n'a pas pu être chargé",unknownError:"Erreur inconnue",loading:"Chargement",buffering:"Mise en mémoire tampon",chapters:"Chapitres",airPlay:"AirPlay",googleCast:"Caster",casting:"Diffusion sur {device}",download:"Télécharger",share:"Partager",close:"Fermer",menu:"Menu",back:"Retour",seek:"Rechercher",playbackRate:"Vitesse de lecture {rate}x",airPlayPlay:"Lire avec AirPlay",remotePlayback:"Lire sur un autre appareil",videoPlayer:"Lecteur vidéo",videoRole:"lecteur vidéo",playTitle:"Lire {title}",audio:"Audio",defaultTrack:"Par défaut",playing:"Lecture",paused:"En pause",muted:"Son coupé",volumeLevel:"Volume {percent} %",ended:"Lecture terminée",enteredFullscreen:"Plein écran activé",exitedFullscreen:"Plein écran désactivé",errorMessage:"Erreur : {message}",timeOf:"{current} sur {duration}",hourOne:"{n} heure",hourOther:"{n} heures",minuteOne:"{n} minute",minuteOther:"{n} minutes",secondOne:"{n} seconde",secondOther:"{n} secondes"},Xt={play:"Abspielen",pause:"Pause",replay:"Wiederholen",mute:"Stumm",unmute:"Ton an",volume:"Lautstärke",seekBackward:"{seconds} Sekunden zurück",seekForward:"{seconds} Sekunden vor",seekTo:"Zu {time} springen",duration:"Dauer",currentTime:"Aktuelle Zeit",played:"Abgespielt",buffered:"Gepuffert",enterFullscreen:"Vollbild",exitFullscreen:"Vollbild beenden",enterPiP:"Bild-in-Bild",exitPiP:"Bild-in-Bild beenden",enableCaptions:"Untertitel aktivieren",disableCaptions:"Untertitel deaktivieren",captions:"Untertitel",captionsOff:"Aus",settings:"Einstellungen",quality:"Qualität",auto:"Auto",speed:"Geschwindigkeit",normal:"Normal",loop:"Schleife",loopEnabled:"Schleife aktiviert",loopDisabled:"Schleife deaktiviert",audioBoost:"Audio-Verstärkung",audioTrack:"Audiospur",live:"LIVE",liveEdge:"Am Live-Punkt",seekToLive:"Zum Live-Punkt",behindLive:"{seconds}s hinter Live",networkError:"Netzwerkfehler",mediaError:"Medium konnte nicht geladen werden",unknownError:"Unbekannter Fehler",loading:"Wird geladen",buffering:"Puffern",chapters:"Kapitel",airPlay:"AirPlay",googleCast:"Streamen",casting:"Streame zu {device}",download:"Herunterladen",share:"Teilen",close:"Schließen",menu:"Menü",back:"Zurück",seek:"Spulen",playbackRate:"Wiedergabegeschwindigkeit {rate}x",airPlayPlay:"Über AirPlay abspielen",remotePlayback:"Auf einem anderen Gerät abspielen",videoPlayer:"Videoplayer",videoRole:"Videoplayer",playTitle:"{title} abspielen",audio:"Audio",defaultTrack:"Standard",playing:"Wird abgespielt",paused:"Pausiert",muted:"Stumm",volumeLevel:"Lautstärke {percent} %",ended:"Wiedergabe beendet",enteredFullscreen:"Vollbild an",exitedFullscreen:"Vollbild aus",errorMessage:"Fehler: {message}",timeOf:"{current} von {duration}",hourOne:"{n} Stunde",hourOther:"{n} Stunden",minuteOne:"{n} Minute",minuteOther:"{n} Minuten",secondOne:"{n} Sekunde",secondOther:"{n} Sekunden"},Gt={play:"再生",pause:"一時停止",replay:"リプレイ",mute:"ミュート",unmute:"ミュート解除",volume:"音量",seekBackward:"{seconds}秒戻る",seekForward:"{seconds}秒進む",seekTo:"{time}にシーク",duration:"長さ",currentTime:"現在の時間",played:"再生済み",buffered:"バッファ済み",enterFullscreen:"フルスクリーン",exitFullscreen:"フルスクリーン終了",enterPiP:"ピクチャーインピクチャー",exitPiP:"ピクチャーインピクチャー終了",enableCaptions:"字幕を有効化",disableCaptions:"字幕を無効化",captions:"字幕",captionsOff:"オフ",settings:"設定",quality:"画質",auto:"自動",speed:"再生速度",normal:"通常",loop:"ループ",loopEnabled:"ループ有効",loopDisabled:"ループ無効",audioBoost:"オーディオブースト",audioTrack:"オーディオトラック",live:"ライブ",liveEdge:"ライブ中",seekToLive:"ライブに移動",behindLive:"{seconds}秒遅れ",networkError:"ネットワークエラー",mediaError:"メディアを読み込めません",unknownError:"不明なエラー",loading:"読み込み中",buffering:"バッファリング",chapters:"チャプター",airPlay:"AirPlay",googleCast:"キャスト",casting:"{device}にキャスト中",download:"ダウンロード",share:"共有",close:"閉じる",menu:"メニュー",back:"戻る",seek:"シーク",playbackRate:"再生速度 {rate}x",airPlayPlay:"AirPlayで再生",remotePlayback:"別のデバイスで再生",videoPlayer:"動画プレーヤー",videoRole:"動画プレーヤー",playTitle:"{title}を再生",audio:"音声",defaultTrack:"デフォルト",playing:"再生中",paused:"一時停止中",muted:"ミュート",volumeLevel:"音量 {percent}%",ended:"再生終了",enteredFullscreen:"全画面表示",exitedFullscreen:"全画面表示を終了",errorMessage:"エラー: {message}",timeOf:"{current} / {duration}",hourOne:"{n}時間",hourOther:"{n}時間",minuteOne:"{n}分",minuteOther:"{n}分",secondOne:"{n}秒",secondOther:"{n}秒"},Jt={play:"播放",pause:"暂停",replay:"重播",mute:"静音",unmute:"取消静音",volume:"音量",seekBackward:"后退{seconds}秒",seekForward:"前进{seconds}秒",seekTo:"跳转到{time}",duration:"时长",currentTime:"当前时间",played:"已播放",buffered:"已缓冲",enterFullscreen:"全屏",exitFullscreen:"退出全屏",enterPiP:"画中画",exitPiP:"退出画中画",enableCaptions:"开启字幕",disableCaptions:"关闭字幕",captions:"字幕",captionsOff:"关闭",settings:"设置",quality:"画质",auto:"自动",speed:"播放速度",normal:"正常",loop:"循环",loopEnabled:"循环已开启",loopDisabled:"循环已关闭",audioBoost:"音频增强",audioTrack:"音轨",live:"直播",liveEdge:"直播中",seekToLive:"跳转到直播",behindLive:"落后{seconds}秒",networkError:"网络错误",mediaError:"无法加载媒体",unknownError:"未知错误",loading:"加载中",buffering:"缓冲中",chapters:"章节",airPlay:"AirPlay",googleCast:"投射",casting:"正在投射到{device}",download:"下载",share:"分享",close:"关闭",menu:"菜单",back:"返回",seek:"跳转",playbackRate:"播放速度 {rate}x",airPlayPlay:"通过 AirPlay 播放",remotePlayback:"在其他设备上播放",videoPlayer:"视频播放器",videoRole:"视频播放器",playTitle:"播放{title}",audio:"音频",defaultTrack:"默认",playing:"正在播放",paused:"已暂停",muted:"已静音",volumeLevel:"音量 {percent}%",ended:"播放结束",enteredFullscreen:"已进入全屏",exitedFullscreen:"已退出全屏",errorMessage:"错误:{message}",timeOf:"{current} / {duration}",hourOne:"{n}小时",hourOther:"{n}小时",minuteOne:"{n}分钟",minuteOther:"{n}分钟",secondOne:"{n}秒",secondOther:"{n}秒"},Zt={en:_e,es:jt,fr:Yt,de:Xt,ja:Gt,zh:Jt};class X{language;fallbackLanguage;translations;interpolationPattern;constructor(e={}){if(this.translations={...Zt},this.language=e.language||this.detectLanguage()||"en",this.fallbackLanguage=e.fallbackLanguage||"en",e.translations){for(let[t,i]of Object.entries(e.translations))if(i)this.translations[t]={...this.translations[t],...i}}this.interpolationPattern=e.interpolationPattern||/\{(\w+)\}/g}detectLanguage(){if(typeof navigator>"u")return null;let e=navigator.language||navigator.userLanguage;if(!e)return null;if(this.translations[e])return e;let t=e.split("-")[0];if(this.translations[t])return t;return null}getLanguage(){return this.language}setLanguage(e){this.language=e}t(e,t){let i=this.translations[this.language]?.[e];if(!i)i=this.translations[this.fallbackLanguage]?.[e];if(!i)return e;if(t)i=i.replace(this.interpolationPattern,(n,s)=>{let r=t[s];return r!==void 0?String(r):n});return i}addTranslations(e,t){this.translations[e]={...this.translations[e],...t}}getTranslations(e){return this.translations[e]}getAvailableLanguages(){return Object.keys(this.translations)}hasLanguage(e){return e in this.translations}}var Ae=null;function ei(e){return new X(e)}function Le(e){if(!Ae)Ae=ei(e);return Ae}function mt(e,t){return Le().t(e,t)}function ti(e){let t=e;while(t){let i=t.closest?.("[lang]")?.getAttribute("lang");if(i)return i.toLowerCase();let n=t.getRootNode?.();t=n&&n.host?n.host:null}if(typeof navigator<"u"&&navigator.language)return navigator.language.toLowerCase();return"en"}function l(e,t,i){let n=ti(e),s=Le(),r=s.getTranslations(n)?.[t]||s.getTranslations(n.split("-")[0])?.[t]||_e[t]||t;return i?r.replace(/\{(\w+)\}/g,(a,o)=>i[o]!==void 0?String(i[o]):a):r}function x(e,t=0){if(!isFinite(e)||isNaN(e))return"0:00";let i=Math.floor(e),n=Math.floor(i/3600),s=Math.floor(i%3600/60),r=i%60;if(n>0||t>=3600)return`${n}:${s.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`;return`${s}:${r.toString().padStart(2,"0")}`}function P(e,t){let i=(d,c,u)=>l(t,d===1?c:u,{n:d});if(!isFinite(e)||isNaN(e))return i(0,"secondOne","secondOther");let n=Math.floor(e),s=Math.floor(n/3600),r=Math.floor(n%3600/60),a=n%60,o=[];if(s>0)o.push(i(s,"hourOne","hourOther"));if(r>0)o.push(i(r,"minuteOne","minuteOther"));if(a>0||o.length===0)o.push(i(a,"secondOne","secondOther"));return o.join(", ")}function Me(e){if(!isFinite(e)||isNaN(e))return"PT0S";let t=Math.floor(e),i=Math.floor(t/3600),n=Math.floor(t%3600/60),s=t%60,r="PT";if(i>0)r+=`${i}H`;if(n>0)r+=`${n}M`;if(s>0||r==="PT")r+=`${s}S`;return r}function m(e){let t=e.getAttribute("for");if(t)return document.getElementById(t)?.player??null;return e.closest("video-player")?.player??null}class _{_el;_options;_store;_events=new E;_provider=null;_loaders;_cleanupFns=[];_destroyed=!1;_sourceLoadId=0;_announcer=null;_cover=null;_coverDismissed=!1;_coverTimer=null;_playRequested=!1;constructor(e,t={}){if(typeof e==="string"){let i=document.querySelector(e);if(!i)throw Error(`Container element not found: ${e}`);this._el=i}else this._el=e;if(this._options={...ii,...t},this._loaders=Y,this._store=new L,this.setupElement(),this.setupState(),this.setupKeyboard(),this.setupActivity(),this.setupStorage(),this.setupMediaSession(),this.setupEvents(),this._options.src)this.setSrc(this._options.src);this._events.emit("init")}get el(){return this._el}get state(){return this._store.getState()}get provider(){return this._provider}get ready(){return this._provider?.ready||!1}setupElement(){this._el.classList.add("ts-video-player"),this._el.setAttribute("tabindex","0"),this._el.setAttribute("role","region"),this._el.setAttribute("aria-roledescription",l(this._el,"videoRole")),this._el.setAttribute("aria-label",this._options.title||l(this._el,"videoPlayer")),this._el.setAttribute("aria-keyshortcuts","Space K M F I C ArrowLeft ArrowRight J L ArrowUp ArrowDown Home End 0 1 2 3 4 5 6 7 8 9");let e=document.createElement("div");if(e.className="ts-video-player__container",e.style.cssText="position:relative;width:100%;height:100%",this._el.appendChild(e),this.setupCover(),this._options.announcements!==!1){let i=document.createElement("div");i.className="ts-video-player__announcer",i.setAttribute("role","status"),i.setAttribute("aria-live","polite"),i.setAttribute("aria-atomic","true"),i.style.cssText="position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0",this._el.appendChild(i),this._announcer=i}let t=this._el;t.__videoPlayer=this}setupCover(){let e=document.createElement("button");e.type="button",e.className="ts-video-player__cover",e.setAttribute("aria-label",this._options.title?l(this._el,"playTitle",{title:this._options.title}):l(this._el,"play")),e.hidden=!0,e.style.cssText="position:absolute;inset:0;z-index:2;display:none;align-items:center;justify-content:center;width:100%;height:100%;margin:0;padding:0;border:0;border-radius:inherit;background:#000 center/cover no-repeat;cursor:pointer;-webkit-tap-highlight-color:transparent";let t=document.createElement("span");t.setAttribute("aria-hidden","true"),t.style.cssText="display:flex;align-items:center;justify-content:center;width:64px;height:64px;border-radius:50%;background:rgba(255,255,255,0.92);box-shadow:0 4px 18px rgba(0,0,0,0.35)";let i=document.createElement("span");i.className="ts-video-player__cover-play",i.style.cssText="width:22px;height:24px;margin-left:5px;background:#0f172a;clip-path:polygon(0 0,100% 50%,0 100%)",t.appendChild(i),e.appendChild(t),e.addEventListener("click",(n)=>{if(n.stopPropagation(),!e.dataset.loading){e.dataset.loading="",i.style.display="none";let a=document.createElement("span");a.className="ts-video-player__cover-spinner",a.style.cssText="width:26px;height:26px;border-radius:50%;border:3px solid rgba(15,23,42,0.2);border-top-color:#0f172a",t.appendChild(a),a.animate?.([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:800,iterations:1/0})}if(this.play().catch(()=>{}),this._coverTimer)clearTimeout(this._coverTimer);let s=0,r=()=>{this._coverTimer=setTimeout(()=>{if(this.state.started)return;if(!this.state.canPlay&&++s<10)return r();this._coverDismissed=!0,this.updateCover(this.state)},2000)};r()}),this._el.appendChild(e),this._cover=e,this._cleanupFns.push(()=>{if(this._coverTimer)clearTimeout(this._coverTimer);e.remove()})}updateCover(e){let t=this._cover;if(!t)return;let{show:i,image:n}=ht(e,this._coverDismissed);if(i){let s=n?`url("${n.replace(/["\\]/g,"")}")`:"none";if(t.style.backgroundImage!==s)t.style.backgroundImage=s}if(!i&&t.dataset.loading!==void 0){delete t.dataset.loading,t.querySelector(".ts-video-player__cover-spinner")?.remove();let s=t.querySelector(".ts-video-player__cover-play");if(s)s.style.display=""}t.hidden=!i,t.style.display=i?"flex":"none"}setupState(){this._store.batch({volume:this._options.volume??1,muted:this._options.muted??!1,loop:this._options.loop??!1,autoplay:this._options.autoplay??!1,playsinline:this._options.playsinline??!0,playbackRate:this._options.playbackRate??1,poster:this._options.poster||"",title:this._options.title||"",preload:this._options.preload||"metadata"});let e=this._store.subscribe((t)=>{this.updateAttributes(t),this.updateCover(t)});this._cleanupFns.push(e)}setupKeyboard(){if(this._options.keyboard===!1)return;let e={togglePlay:()=>this.togglePlay(),toggleMute:()=>this.toggleMute(),toggleFullscreen:()=>this.toggleFullscreen(),togglePiP:()=>this.togglePiP(),toggleCaptions:()=>this.toggleCaptions(),seekBackward:()=>this.seekBy(-5),seekForward:()=>this.seekBy(5),seekBackwardLong:()=>this.seekBy(-10),seekForwardLong:()=>this.seekBy(10),volumeUp:()=>this.setVolume(Math.min(1,this.state.volume+0.1)),volumeDown:()=>this.setVolume(Math.max(0,this.state.volume-0.1)),speedUp:()=>this.setPlaybackRate(Math.min(4,this.state.playbackRate+0.25)),speedDown:()=>this.setPlaybackRate(Math.max(0.25,this.state.playbackRate-0.25)),seekStart:()=>this.seekTo(0),seekEnd:()=>this.seekTo(this.state.duration),seekPercent:(s)=>this.seekTo(s/100*this.state.duration)},t=typeof this._options.keyboard==="object"?this._options.keyboard:{},i=Ke(e,{seekStep:t.seekStep,volumeStep:t.volumeStep}),n=t.global?document:this._el;n.addEventListener("keydown",i),this._cleanupFns.push(()=>n.removeEventListener("keydown",i))}setupActivity(){let e=Qe(this._el,{timeout:this._options.controlsTimeout||3000,onActive:()=>{this._store.batch({userActive:!0,controlsVisible:!0}),this._events.emit("useractivitychange",!0),this._events.emit("controlschange",!0)},onInactive:()=>{if(this.state.playing)this._store.batch({userActive:!1,controlsVisible:!1}),this._events.emit("useractivitychange",!1),this._events.emit("controlschange",!1)}});this._cleanupFns.push(e);let t=()=>this._store.set("pointerOver",!0),i=()=>this._store.set("pointerOver",!1);this._el.addEventListener("mouseenter",t),this._el.addEventListener("mouseleave",i),this._cleanupFns.push(()=>this._el.removeEventListener("mouseenter",t),()=>this._el.removeEventListener("mouseleave",i))}setupStorage(){if(!this._options.storage)return;let e=typeof this._options.storage==="object"?this._options.storage:{},t=e.type==="session"?sessionStorage:localStorage,i=Ue(this._store,e.persist||["volume","muted","playbackRate"],t);this._cleanupFns.push(i)}setupMediaSession(){if(this._options.mediaSession===!1)return;let e=typeof this._options.mediaSession==="object"?this._options.mediaSession:this._options.title?{title:this._options.title}:void 0,t=je(this._store,{play:()=>this.play(),pause:()=>this.pause(),seekTo:(i)=>this.seekTo(i),seekBy:(i)=>this.seekBy(i),stop:()=>this.stop()},e);this._cleanupFns.push(t)}setupEvents(){if(this._options.on){for(let[e,t]of Object.entries(this._options.on))if(t)this.on(e,t)}}updateAttributes(e){let t=this._el;t.dataset.paused=String(e.paused),t.dataset.playing=String(e.playing),t.dataset.started=String(e.started),t.dataset.ended=String(e.ended),t.dataset.seeking=String(e.seeking),t.dataset.waiting=String(e.waiting),t.dataset.loop=String(e.loop),t.dataset.autoplay=String(e.autoplay),t.dataset.loading=String(e.waiting||e.loadingState==="loading"),t.dataset.canPlay=String(e.canPlay),t.dataset.loadingState=e.loadingState,t.setAttribute("aria-busy",String(e.waiting||e.loadingState==="loading")),t.dataset.muted=String(e.muted),t.dataset.volumeLevel=e.muted||e.volume===0?"silent":e.volume<0.5?"low":"high",t.dataset.fullscreen=String(e.fullscreen),t.dataset.pip=String(e.pictureInPicture),t.dataset.controlsVisible=String(e.controlsVisible),t.dataset.userActive=String(e.userActive),t.dataset.mediaType=e.mediaType,t.dataset.streamType=e.streamType;let i=e.textTracks.some((n)=>n.mode==="showing");t.dataset.captions=String(i),t.dataset.error=String(!!e.error)}announce(e){if(!this._announcer)return;this._announcer.textContent="",requestAnimationFrame(()=>{if(this._announcer)this._announcer.textContent=e})}destroy(){if(this._destroyed)return;this._destroyed=!0,this._sourceLoadId++,this._events.emit("destroy"),this._cleanupFns.forEach((e)=>e()),this._cleanupFns=[],this._provider?.destroy(),this._provider=null,this._events.removeAllListeners(),this._store.reset(),this._el.classList.remove("ts-video-player"),this._el.innerHTML="",delete this._el.__videoPlayer}async setSrc(e){if(this._destroyed)return;let t=++this._sourceLoadId,i=Array.isArray(e)?e:[e];if(i.length===0)return;this._coverDismissed=!1,this._playRequested=!!this._options.autoplay,this._store.batch({sources:i,src:i[0],loadingState:"loading",error:null,started:!1}),this._events.emit("sourceschange",i);let n=pt(i,this._loaders);if(n.length===0){this._store.batch({loadingState:"error",error:{code:4,message:"No compatible provider found for source"}});return}let s;for(let r of n){if(this._destroyed||t!==this._sourceLoadId)return;let{loader:a}=r;if(this._provider&&this._provider.type!==a.type)this._provider.destroy(),this._provider=null,this._events.emit("providerchange",null);if(!this._provider){let o=this._el.querySelector(".ts-video-player__container");try{if(this._provider=await a.load(o,{...this._options,mediaType:a.mediaType(r.src)}),this._destroyed||t!==this._sourceLoadId){this._provider.destroy(),this._provider=null;return}this._events.emit("providerchange",this._provider),this.attachProviderEvents(this._provider)}catch(d){s=d,this._provider=null;continue}}try{let o=a.type==="video"?n.filter((d)=>d.loader.type===a.type).map((d)=>d.src):[r.src];if(await this._provider.load(o.length>1?o:r.src),this._destroyed||t!==this._sourceLoadId)return;if(this._store.batch({src:r.src,currentSourceIndex:r.index,mediaType:a.mediaType(r.src),providerType:a.type}),this._playRequested)this._playRequested=!1,this.startRequestedPlay(this._provider);return}catch(o){if(s=o,this._provider)this._provider.destroy(),this._provider=null;this._events.emit("providerchange",null)}}if(this._destroyed||t!==this._sourceLoadId)return;this._store.batch({loadingState:"error",error:{code:4,message:"Failed to load all compatible sources",details:s}})}setPoster(e){this._store.set("poster",e)}getSrc(){return this.state.src}attachProviderEvents(e){e.on("loadstart",()=>{this._store.set("loadingState","loading"),this._events.emit("loadstart")}),e.on("loadedmetadata",()=>{this._events.emit("loadedmetadata")}),e.on("loadeddata",()=>{this._events.emit("loadeddata")}),e.on("canplay",()=>{this._store.batch({canPlay:!0,loadingState:"loaded"}),this._events.emit("canplay")}),e.on("canplaythrough",()=>{this._store.set("canPlayThrough",!0),this._events.emit("canplaythrough")}),e.on("play",()=>{this._store.batch({paused:!1,ended:!1}),this._events.emit("play"),this.announce(l(this._el,"playing"))}),e.on("pause",()=>{this._store.batch({paused:!0,playing:!1,playbackState:"paused"}),this._events.emit("pause"),this.announce(l(this._el,"paused"))}),e.on("playing",()=>{this._store.batch({playing:!0,started:!0,waiting:!1,playbackState:"playing"}),this._events.emit("playing")}),e.on("waiting",()=>{this._store.batch({waiting:!0,playbackState:"buffering"}),this._events.emit("waiting")}),e.on("seeking",()=>{this._store.set("seeking",!0),this._events.emit("seeking")}),e.on("seeked",()=>{this._store.set("seeking",!1),this._events.emit("seeked")}),e.on("timeupdate",(t)=>{this._store.set("currentTime",t),this._events.emit("timeupdate",t)}),e.on("durationchange",(t)=>{this._store.set("duration",t),this._events.emit("durationchange",t)}),e.on("volumechange",(t,i)=>{if(this._store.batch({volume:t,muted:i}),this._events.emit("volumechange",t,i),i)this.announce(l(this._el,"muted"));else this.announce(l(this._el,"volumeLevel",{percent:Math.round(t*100)}))}),e.on("ratechange",(t)=>{this._store.set("playbackRate",t),this._events.emit("ratechange",t)}),e.on("progress",(t)=>{this._store.batch({buffered:t,bufferedAmount:qe({...this.state,buffered:t})}),this._events.emit("progress",t)}),e.on("ended",()=>{if(this._store.batch({ended:!0,playing:!1,playbackState:"ended"}),this._events.emit("ended"),this.announce(l(this._el,"ended")),this.state.loop)this.seekTo(0),this.play()}),e.on("error",(t)=>{this._store.batch({loadingState:"error",error:t}),this._events.emit("error",t),this.announce(l(this._el,"errorMessage",{message:t.message}))}),e.on("statechange",(t)=>{this._store.batch(t),this._events.emit("statechange",t)}),e.on("qualitychange",(t)=>{this._store.set("qualities",e.getQualities()),this._events.emit("qualitychange",t)}),e.on("fullscreenchange",(t)=>{this._store.set("fullscreen",t),this._events.emit("fullscreenchange",t),this.announce(l(this._el,t?"enteredFullscreen":"exitedFullscreen"))}),e.on("pipchange",(t)=>{this._store.set("pictureInPicture",t),this._events.emit("pipchange",t)}),e.on("availabilitychange",(t,i)=>{if(t==="volume")this._store.set("volumeAvailability",i);else if(t==="fullscreen")this._store.set("fullscreenAvailability",i);else if(t==="pip")this._store.set("pipAvailability",i);this._events.emit("availabilitychange",t,i)})}async startRequestedPlay(e){if(await e.play().catch(()=>{}),this._provider!==e||this.state.error?.code!==1||this.state.muted)return;this._store.set("error",null),this.setMuted(!0),await e.play().catch(()=>{})}async play(){if(!this._provider){this._playRequested=!0;return}await this._provider.play()}pause(){this._playRequested=!1,this._provider?.pause()}togglePlay(){if(this.state.paused)this.play().catch(()=>{});else this.pause()}stop(){this._provider?.stop(),this._store.batch({playing:!1,paused:!0,currentTime:0,playbackState:"idle"})}seekTo(e){this._provider?.seekTo(e)}seekBy(e){let t=Math.max(0,Math.min(this.state.currentTime+e,this.state.duration));this.seekTo(t)}setVolume(e){if(this.state.volumeAvailability==="unsupported")return;let t=Math.max(0,Math.min(1,e));this._provider?.setVolume(t),this._store.set("volume",t)}setMuted(e){this._provider?.setMuted(e),this._store.set("muted",e)}toggleMute(){this.setMuted(!this.state.muted)}setPlaybackRate(e){let t=Math.max(0.25,Math.min(4,e));this._provider?.setPlaybackRate(t),this._store.set("playbackRate",t)}async enterFullscreen(){if(this.state.fullscreenAvailability==="unsupported")return;if(this.state.pictureInPicture)await this.exitPiP();if(await this._provider?.enterFullscreen(),this._options.fullscreenOrientationLock!==!1)Xe("landscape")}async exitFullscreen(){if(await this._provider?.exitFullscreen(),this._options.fullscreenOrientationLock!==!1)Ge()}async toggleFullscreen(){if(this.state.fullscreen)await this.exitFullscreen();else await this.enterFullscreen()}async enterPiP(){if(this.state.pipAvailability==="unsupported")return;if(this.state.fullscreen)await this.exitFullscreen();await this._provider?.enterPiP()}async exitPiP(){await this._provider?.exitPiP()}async togglePiP(){if(this.state.pictureInPicture)await this.exitPiP();else await this.enterPiP()}setQuality(e){if(this._provider?.setQuality(e),e==="auto")this._store.set("autoQuality",!0);else this._store.set("autoQuality",!1)}setTextTrack(e,t){this._provider?.setTextTrackMode(e,t),this._store.set("textTracks",this._provider?.getTextTracks()||[])}setAudioTrack(e){this._provider?.setAudioTrack(e),this._store.set("audioTracks",this._provider?.getAudioTracks()||[])}toggleCaptions(){let e=this.state.textTracks,t=e.find((i)=>i.mode==="showing");if(t)this.setTextTrack(t.id,"disabled");else{let i=e.find((n)=>n.kind==="subtitles"||n.kind==="captions");if(i)this.setTextTrack(i.id,"showing")}}on(e,t){this._events.on(e,t)}off(e,t){this._events.off(e,t)}once(e,t){this._events.once(e,t)}subscribe(e,t){return this._store.subscribe(e,t)}}var ii={autoplay:!1,loop:!1,muted:!1,volume:1,playbackRate:1,playsinline:!0,preload:"metadata",controls:!0,keyboard:!0,controlsTimeout:3000,storage:!0};function vt(e,t){return new _(e,t)}var ni={colors:{primary:"#00a8ff",secondary:"#6c5ce7",background:"rgba(0, 0, 0, 0.85)",text:"#ffffff",textOnPrimary:"#ffffff",border:"rgba(255, 255, 255, 0.1)",focus:"#00a8ff",error:"#ff4757",success:"#2ed573",warning:"#ffa502"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',fontSize:"14px",fontSizeSmall:"12px",fontSizeLarge:"16px",fontWeight:"400",fontWeightBold:"600",lineHeight:"1.5"},spacing:{xs:"4px",sm:"8px",md:"12px",lg:"16px",xl:"24px"},borderRadius:{sm:"4px",md:"8px",lg:"12px",full:"9999px"},shadows:{sm:"0 1px 2px rgba(0, 0, 0, 0.2)",md:"0 4px 6px rgba(0, 0, 0, 0.3)",lg:"0 10px 15px rgba(0, 0, 0, 0.4)"},transitions:{fast:"100ms",normal:"200ms",slow:"300ms",easing:"cubic-bezier(0.4, 0, 0.2, 1)"},slider:{trackHeight:"4px",thumbSize:"14px",trackBg:"rgba(255, 255, 255, 0.2)",trackFillBg:"var(--tsvp-color-primary)",bufferedBg:"rgba(255, 255, 255, 0.4)",thumbBg:"#ffffff",thumbBorder:"none"},controls:{height:"48px",background:"linear-gradient(transparent, rgba(0, 0, 0, 0.7))",padding:"0 12px",buttonSize:"40px",iconSize:"24px",tooltipBg:"rgba(0, 0, 0, 0.9)",tooltipText:"#ffffff"},menu:{background:"rgba(20, 20, 20, 0.95)",borderRadius:"8px",shadow:"0 4px 20px rgba(0, 0, 0, 0.5)",itemHeight:"40px",itemHoverBg:"rgba(255, 255, 255, 0.1)",itemActiveBg:"rgba(0, 168, 255, 0.2)"},captions:{fontFamily:"inherit",fontSize:"1.5em",textColor:"#ffffff",background:"rgba(0, 0, 0, 0.75)",textShadow:"0 1px 2px rgba(0, 0, 0, 0.5)",borderRadius:"4px",padding:"4px 8px"},thumbnails:{width:"160px",height:"90px",borderRadius:"4px",border:"2px solid rgba(255, 255, 255, 0.2)",shadow:"0 4px 12px rgba(0, 0, 0, 0.4)"},live:{indicatorColor:"#ff0000",indicatorSize:"8px",badgeBg:"#ff0000",badgeText:"#ffffff"}},si={colors:{primary:"#00a8ff",background:"rgba(0, 0, 0, 0.9)",text:"#ffffff"}},ri={colors:{primary:"#0070f3",background:"rgba(255, 255, 255, 0.95)",text:"#1a1a1a",textOnPrimary:"#ffffff",border:"rgba(0, 0, 0, 0.1)"},controls:{background:"linear-gradient(transparent, rgba(255, 255, 255, 0.9))",tooltipBg:"rgba(0, 0, 0, 0.8)"},menu:{background:"rgba(255, 255, 255, 0.98)",shadow:"0 4px 20px rgba(0, 0, 0, 0.15)",itemHoverBg:"rgba(0, 0, 0, 0.05)",itemActiveBg:"rgba(0, 112, 243, 0.1)"},captions:{background:"rgba(255, 255, 255, 0.9)",textColor:"#1a1a1a"}},ai={colors:{primary:"#ffffff",background:"transparent"},controls:{height:"40px",background:"transparent"},slider:{trackHeight:"2px",thumbSize:"10px"}},oi={colors:{primary:"#e50914",background:"rgba(0, 0, 0, 0.85)"},slider:{trackFillBg:"#e50914"},live:{indicatorColor:"#e50914",badgeBg:"#e50914"}},li={colors:{primary:"#ff0000",background:"rgba(0, 0, 0, 0.85)"},slider:{trackHeight:"3px",thumbSize:"13px",trackFillBg:"#ff0000"},controls:{height:"48px"},live:{indicatorColor:"#ff0000",badgeBg:"#ff0000"}},di={colors:{primary:"#00adef",background:"rgba(0, 0, 0, 0.85)"},slider:{trackFillBg:"#00adef"}},Ce={dark:si,light:ri,minimal:ai,netflix:oi,youtube:li,vimeo:di};function ci(e,t){let i={...e};for(let n of Object.keys(t)){let s=e[n],r=t[n];if(r&&typeof r==="object")i[n]={...s||{},...r};else if(r!==void 0)i[n]=r}return i}function ui(e,t="tsvp"){let i=ci(ni,e),n=[];if(i.colors)n.push(`--${t}-color-primary: ${i.colors.primary};`),n.push(`--${t}-color-secondary: ${i.colors.secondary};`),n.push(`--${t}-color-background: ${i.colors.background};`),n.push(`--${t}-color-text: ${i.colors.text};`),n.push(`--${t}-color-text-on-primary: ${i.colors.textOnPrimary};`),n.push(`--${t}-color-border: ${i.colors.border};`),n.push(`--${t}-color-focus: ${i.colors.focus};`),n.push(`--${t}-color-error: ${i.colors.error};`),n.push(`--${t}-color-success: ${i.colors.success};`),n.push(`--${t}-color-warning: ${i.colors.warning};`);if(i.typography)n.push(`--${t}-font-family: ${i.typography.fontFamily};`),n.push(`--${t}-font-size: ${i.typography.fontSize};`),n.push(`--${t}-font-size-sm: ${i.typography.fontSizeSmall};`),n.push(`--${t}-font-size-lg: ${i.typography.fontSizeLarge};`),n.push(`--${t}-font-weight: ${i.typography.fontWeight};`),n.push(`--${t}-font-weight-bold: ${i.typography.fontWeightBold};`),n.push(`--${t}-line-height: ${i.typography.lineHeight};`);if(i.spacing)n.push(`--${t}-spacing-xs: ${i.spacing.xs};`),n.push(`--${t}-spacing-sm: ${i.spacing.sm};`),n.push(`--${t}-spacing-md: ${i.spacing.md};`),n.push(`--${t}-spacing-lg: ${i.spacing.lg};`),n.push(`--${t}-spacing-xl: ${i.spacing.xl};`);if(i.borderRadius)n.push(`--${t}-radius-sm: ${i.borderRadius.sm};`),n.push(`--${t}-radius-md: ${i.borderRadius.md};`),n.push(`--${t}-radius-lg: ${i.borderRadius.lg};`),n.push(`--${t}-radius-full: ${i.borderRadius.full};`);if(i.shadows)n.push(`--${t}-shadow-sm: ${i.shadows.sm};`),n.push(`--${t}-shadow-md: ${i.shadows.md};`),n.push(`--${t}-shadow-lg: ${i.shadows.lg};`);if(i.transitions)n.push(`--${t}-transition-fast: ${i.transitions.fast};`),n.push(`--${t}-transition-normal: ${i.transitions.normal};`),n.push(`--${t}-transition-slow: ${i.transitions.slow};`),n.push(`--${t}-transition-easing: ${i.transitions.easing};`);if(i.slider)n.push(`--${t}-slider-track-height: ${i.slider.trackHeight};`),n.push(`--${t}-slider-thumb-size: ${i.slider.thumbSize};`),n.push(`--${t}-slider-track-bg: ${i.slider.trackBg};`),n.push(`--${t}-slider-track-fill-bg: ${i.slider.trackFillBg};`),n.push(`--${t}-slider-buffered-bg: ${i.slider.bufferedBg};`),n.push(`--${t}-slider-thumb-bg: ${i.slider.thumbBg};`),n.push(`--${t}-slider-thumb-border: ${i.slider.thumbBorder};`);if(i.controls)n.push(`--${t}-controls-height: ${i.controls.height};`),n.push(`--${t}-controls-bg: ${i.controls.background};`),n.push(`--${t}-controls-padding: ${i.controls.padding};`),n.push(`--${t}-controls-button-size: ${i.controls.buttonSize};`),n.push(`--${t}-controls-icon-size: ${i.controls.iconSize};`),n.push(`--${t}-controls-tooltip-bg: ${i.controls.tooltipBg};`),n.push(`--${t}-controls-tooltip-text: ${i.controls.tooltipText};`);if(i.menu)n.push(`--${t}-menu-bg: ${i.menu.background};`),n.push(`--${t}-menu-radius: ${i.menu.borderRadius};`),n.push(`--${t}-menu-shadow: ${i.menu.shadow};`),n.push(`--${t}-menu-item-height: ${i.menu.itemHeight};`),n.push(`--${t}-menu-item-hover-bg: ${i.menu.itemHoverBg};`),n.push(`--${t}-menu-item-active-bg: ${i.menu.itemActiveBg};`);if(i.captions)n.push(`--${t}-captions-font-family: ${i.captions.fontFamily};`),n.push(`--${t}-captions-font-size: ${i.captions.fontSize};`),n.push(`--${t}-captions-text-color: ${i.captions.textColor};`),n.push(`--${t}-captions-bg: ${i.captions.background};`),n.push(`--${t}-captions-text-shadow: ${i.captions.textShadow};`),n.push(`--${t}-captions-radius: ${i.captions.borderRadius};`),n.push(`--${t}-captions-padding: ${i.captions.padding};`);if(i.thumbnails)n.push(`--${t}-thumbnail-width: ${i.thumbnails.width};`),n.push(`--${t}-thumbnail-height: ${i.thumbnails.height};`),n.push(`--${t}-thumbnail-radius: ${i.thumbnails.borderRadius};`),n.push(`--${t}-thumbnail-border: ${i.thumbnails.border};`),n.push(`--${t}-thumbnail-shadow: ${i.thumbnails.shadow};`);if(i.live)n.push(`--${t}-live-indicator-color: ${i.live.indicatorColor};`),n.push(`--${t}-live-indicator-size: ${i.live.indicatorSize};`),n.push(`--${t}-live-badge-bg: ${i.live.badgeBg};`),n.push(`--${t}-live-badge-text: ${i.live.badgeText};`);return n.join(`
2
+ `)}function gt(e,t){let i=typeof t==="string"?Ce[t]:t;e.querySelectorAll("style[data-tsvp-theme]").forEach((s)=>s.remove());let n=ui(i);e.style.cssText+=n.split(`
3
+ `).map((s)=>s.trim().replace(";","")).join("; ")}var pi={name:"default",description:"Full-featured default layout with all controls",styles:`
4
4
  .tsvp-layout-default {
5
5
  --tsvp-controls-height: 48px;
6
6
  }
@@ -84,7 +84,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
84
84
  </div>
85
85
  </div>
86
86
  </div>
87
- `},ui={name:"minimal",description:"Clean, minimal layout with essential controls only",styles:`
87
+ `},hi={name:"minimal",description:"Clean, minimal layout with essential controls only",styles:`
88
88
  .tsvp-layout-minimal {
89
89
  --tsvp-controls-height: 36px;
90
90
  --tsvp-slider-track-height: 2px;
@@ -123,7 +123,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
123
123
  <slot name="time"></slot>
124
124
  <slot name="fullscreen-button"></slot>
125
125
  </div>
126
- `},pi={name:"cinema",description:"Immersive cinema-style layout with center play button",styles:`
126
+ `},mi={name:"cinema",description:"Immersive cinema-style layout with center play button",styles:`
127
127
  .tsvp-layout-cinema {
128
128
  --tsvp-controls-height: 60px;
129
129
  }
@@ -208,7 +208,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
208
208
  <slot name="fullscreen-button"></slot>
209
209
  </div>
210
210
  </div>
211
- `,init:(e)=>{let t=e.querySelector(".tsvp-center-play");if(t)t.addEventListener("click",()=>{e.dispatchEvent(new CustomEvent("tsvp:toggleplay"))})}},hi={name:"youtube",description:"YouTube-inspired layout with familiar controls",styles:`
211
+ `,init:(e)=>{let t=e.querySelector(".tsvp-center-play");if(t)t.addEventListener("click",()=>{e.dispatchEvent(new CustomEvent("tsvp:toggleplay"))})}},vi={name:"youtube",description:"YouTube-inspired layout with familiar controls",styles:`
212
212
  .tsvp-layout-youtube {
213
213
  --tsvp-color-primary: #ff0000;
214
214
  --tsvp-slider-track-height: 3px;
@@ -294,7 +294,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
294
294
  <div class="tsvp-end-screen">
295
295
  <slot name="end-screen"></slot>
296
296
  </div>
297
- `},mi={name:"vimeo",description:"Vimeo-inspired clean layout",styles:`
297
+ `},gi={name:"vimeo",description:"Vimeo-inspired clean layout",styles:`
298
298
  .tsvp-layout-vimeo {
299
299
  --tsvp-color-primary: #00adef;
300
300
  --tsvp-controls-height: 44px;
@@ -375,7 +375,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
375
375
  <slot name="fullscreen-button"></slot>
376
376
  </div>
377
377
  </div>
378
- `},vi={name:"audio",description:"Compact layout for audio-only playback",styles:`
378
+ `},yi={name:"audio",description:"Compact layout for audio-only playback",styles:`
379
379
  .tsvp-layout-audio {
380
380
  --tsvp-controls-height: 64px;
381
381
  height: var(--tsvp-controls-height);
@@ -457,7 +457,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
457
457
  </div>
458
458
  <slot name="volume"></slot>
459
459
  </div>
460
- `},_e={default:ci,minimal:ui,cinema:pi,youtube:hi,vimeo:mi,audio:vi};class mt{container;currentLayout=null;styleElement=null;constructor(e){this.container=e}apply(e){let t=typeof e==="string"?_e[e]:e;if(this.cleanup(),this.container.classList.add(`tsvp-layout-${t.name}`),this.styleElement=document.createElement("style"),this.styleElement.textContent=t.styles,document.head.appendChild(this.styleElement),this.container.innerHTML=t.template,t.init)t.init(this.container);this.currentLayout=t}getLayout(){return this.currentLayout}cleanup(){if(this.currentLayout){if(this.container.classList.remove(`tsvp-layout-${this.currentLayout.name}`),this.currentLayout.destroy)this.currentLayout.destroy(this.container);if(this.styleElement)this.styleElement.remove(),this.styleElement=null;this.currentLayout=null}}destroy(){this.cleanup()}}function vt(e){return new mt(e)}var gi=[10,25,50,75,90,100];class H{player=null;config;state;heartbeatTimer=null;eventQueue=[];flushTimer=null;sessionId;visitorId;unsubscribers=[];constructor(e){this.config={milestones:gi,heartbeatInterval:30,trackQualityChanges:!0,trackSeeking:!0,trackBuffering:!0,trackErrors:!0,trackEngagement:!0,...e},this.sessionId=e.sessionId||this.generateId(),this.visitorId=e.visitorId||this.getOrCreateVisitorId(),this.state=this.createInitialState()}createInitialState(){return{hasStarted:!1,hasCompleted:!1,watchTime:0,pauseCount:0,seekCount:0,bufferCount:0,bufferTime:0,qualityChangeCount:0,reachedMilestones:[],reachedQuartiles:[],playbackStartTime:null,lastHeartbeat:0,isBuffering:!1,bufferStartTime:null}}attach(e){if(this.config.disabled)return;this.player=e,this.attachEventListeners(),this.startHeartbeat()}detach(){this.stopHeartbeat(),this.unsubscribers.forEach((e)=>e()),this.unsubscribers=[],this.flush(),this.player=null}attachEventListeners(){if(!this.player)return;if(this.on("play",()=>{if(!this.state.hasStarted)this.state.hasStarted=!0,this.state.playbackStartTime=Date.now(),this.trackEvent("video_start");else this.trackEvent("video_resume");this.trackEvent("video_play")}),this.on("pause",()=>{this.state.pauseCount++,this.updateWatchTime(),this.trackEvent("video_pause")}),this.config.trackSeeking)this.on("seeking",()=>{this.state.seekCount++}),this.on("seeked",()=>{let e=this.player?.state;this.trackEvent("video_seek",{seekTo:e?.currentTime||0})});if(this.config.trackBuffering)this.on("waiting",()=>{if(!this.state.isBuffering)this.state.isBuffering=!0,this.state.bufferStartTime=Date.now(),this.state.bufferCount++,this.trackEvent("video_buffer_start")}),this.on("playing",()=>{if(this.state.isBuffering){if(this.state.isBuffering=!1,this.state.bufferStartTime)this.state.bufferTime+=(Date.now()-this.state.bufferStartTime)/1000;this.trackEvent("video_buffer_end",{bufferDuration:this.state.bufferStartTime?(Date.now()-this.state.bufferStartTime)/1000:0}),this.state.bufferStartTime=null}});if(this.on("timeupdate",()=>{this.checkMilestones()}),this.config.trackQualityChanges)this.on("qualitychange",(e)=>{this.state.qualityChangeCount++,this.trackEvent("video_quality_change",{quality:e?`${e.height}p`:"auto",bitrate:e?.bitrate})});if(this.on("volumechange",()=>{let e=this.player?.state;if(e?.muted)this.trackEvent("video_mute");else this.trackEvent("video_volume_change",{volume:e?.volume})}),this.on("fullscreenchange",(e)=>{this.trackEvent(e?"video_fullscreen_enter":"video_fullscreen_exit")}),this.on("pipchange",(e)=>{this.trackEvent(e?"video_pip_enter":"video_pip_exit")}),this.on("texttrackchange",(e)=>{if(e)this.trackEvent("video_caption_change",{language:e.language,label:e.label});else this.trackEvent("video_caption_disable")}),this.on("audiotrackchange",(e)=>{if(e)this.trackEvent("video_audio_track_change",{language:e.language,label:e.label})}),this.on("ratechange",(e)=>{this.trackEvent("video_speed_change",{speed:e})}),this.on("ended",()=>{if(!this.state.hasCompleted)this.state.hasCompleted=!0,this.updateWatchTime(),this.trackEvent("video_complete",{watchTime:this.state.watchTime,pauseCount:this.state.pauseCount,seekCount:this.state.seekCount,bufferCount:this.state.bufferCount,bufferTime:this.state.bufferTime})}),this.config.trackErrors)this.on("error",(e)=>{this.trackEvent("video_error",{code:e?.code,message:e?.message})})}on(e,t){if(!this.player)return;this.player.on(e,t),this.unsubscribers.push(()=>this.player?.off(e,t))}checkMilestones(){let e=this.player?.state;if(!e||!e.duration)return;let t=e.currentTime/e.duration*100;for(let n of this.config.milestones||[])if(t>=n&&!this.state.reachedMilestones.includes(n))this.state.reachedMilestones.push(n),this.trackEvent("video_milestone",{milestone:n});let i=[25,50,75,100];for(let n of i)if(t>=n&&!this.state.reachedQuartiles.includes(n))this.state.reachedQuartiles.push(n),this.trackEvent("video_quartile",{quartile:n})}updateWatchTime(){if(this.state.playbackStartTime)this.state.watchTime+=(Date.now()-this.state.playbackStartTime)/1000,this.state.playbackStartTime=Date.now()}startHeartbeat(){if(this.heartbeatTimer)return;let e=(this.config.heartbeatInterval||30)*1000;this.heartbeatTimer=setInterval(()=>{let t=this.player?.state;if(t?.playbackState==="playing")this.updateWatchTime(),this.trackEvent("video_heartbeat",{watchTime:this.state.watchTime,currentTime:t.currentTime})},e)}stopHeartbeat(){if(this.heartbeatTimer)clearInterval(this.heartbeatTimer),this.heartbeatTimer=null}trackEvent(e,t){if(this.config.disabled)return;let i=this.player?.state,n={name:e,timestamp:new Date,currentTime:i?.currentTime||0,duration:i?.duration||this.config.duration||0,properties:t};this.eventQueue.push(n),this.scheduleFlush()}scheduleFlush(){if(this.flushTimer)return;this.flushTimer=setTimeout(()=>{this.flush(),this.flushTimer=null},1000)}async flush(){if(this.eventQueue.length===0)return;let e=[...this.eventQueue];this.eventQueue=[];try{await this.sendEvents(e)}catch(t){console.error("Failed to send analytics events:",t),this.eventQueue.unshift(...e)}}async sendEvents(e){let t=e.map((i)=>this.buildEventPayload(i));for(let i of t)await fetch(this.config.apiEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),keepalive:!0})}buildEventPayload(e){return{s:this.config.siteId,sid:this.sessionId,vid:this.visitorId,e:"event",u:typeof window<"u"?window.location.href:"",p:{eventName:e.name,videoId:this.config.videoId,videoTitle:this.config.videoTitle,contentType:this.config.contentType,category:this.config.category,creatorId:this.config.creatorId,seriesId:this.config.seriesId,episode:this.config.episode,season:this.config.season,currentTime:e.currentTime,duration:e.duration,progress:e.duration>0?e.currentTime/e.duration*100:0,watchTime:this.state.watchTime,...this.config.customProperties,...e.properties}}}generateId(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}getOrCreateVisitorId(){if(typeof localStorage>"u")return this.generateId();let e="tsvp_visitor_id",t=localStorage.getItem(e);if(!t)t=this.generateId(),localStorage.setItem(e,t);return t}getState(){return{...this.state}}getSummary(){return{videoId:this.config.videoId,sessionId:this.sessionId,hasStarted:this.state.hasStarted,hasCompleted:this.state.hasCompleted,watchTime:this.state.watchTime,pauseCount:this.state.pauseCount,seekCount:this.state.seekCount,bufferCount:this.state.bufferCount,bufferTime:this.state.bufferTime,qualityChangeCount:this.state.qualityChangeCount,reachedMilestones:this.state.reachedMilestones,completionRate:this.state.reachedQuartiles.length>0?Math.max(...this.state.reachedQuartiles):0}}reset(){this.flush(),this.state=this.createInitialState(),this.sessionId=this.generateId()}destroy(){if(this.detach(),this.flushTimer)clearTimeout(this.flushTimer)}}function gt(e){return new H(e)}function Me(e){return{name:"analytics",install(t,i){let n=gt({...e,...i});return n.attach(t),t.analytics=n,()=>{n.destroy(),delete t.analytics}}}}class Le{maxRedirects;timeout;redirectCount=0;constructor(e={}){this.maxRedirects=e.maxRedirects??5,this.timeout=e.timeout??1e4}async parseFromUrl(e){return this.redirectCount=0,this.fetchAndParse(e)}parseFromXml(e){let i=new DOMParser().parseFromString(e,"text/xml");return this.parseDocument(i)}async fetchAndParse(e){if(this.redirectCount>=this.maxRedirects)throw Error("Too many VAST redirects");let t=new AbortController,i=setTimeout(()=>t.abort(),this.timeout);try{let s=await(await fetch(e,{signal:t.signal})).text(),a=new DOMParser().parseFromString(s,"text/xml"),o=a.querySelector("Wrapper");if(o){let l=o.querySelector("VASTAdTagURI")?.textContent?.trim();if(l)return this.redirectCount++,this.fetchAndParse(l)}return this.parseDocument(a)}finally{clearTimeout(i)}}parseDocument(e){let t=[];return e.querySelectorAll("Ad").forEach((n)=>{let s=n.querySelector("InLine");if(!s)return;let r={id:n.getAttribute("id")||this.generateId(),type:"linear",adSystem:s.querySelector("AdSystem")?.textContent?.trim(),title:s.querySelector("AdTitle")?.textContent?.trim(),description:s.querySelector("Description")?.textContent?.trim(),duration:0,mediaFiles:[],trackingEvents:[]},a=s.querySelector("Linear");if(a){let o=a.querySelector("Duration")?.textContent?.trim();if(o)r.duration=this.parseDuration(o);let l=a.getAttribute("skipoffset");if(l)r.skipOffset=this.parseOffset(l,r.duration);a.querySelectorAll("MediaFile").forEach((c)=>{let u=c.textContent?.trim();if(u)r.mediaFiles.push({url:u,type:c.getAttribute("type")||"video/mp4",width:Number.parseInt(c.getAttribute("width")||"0",10),height:Number.parseInt(c.getAttribute("height")||"0",10),bitrate:c.getAttribute("bitrate")?Number.parseInt(c.getAttribute("bitrate"),10):void 0,delivery:c.getAttribute("delivery")||"progressive"})});let d=a.querySelector("VideoClicks > ClickThrough");if(d)r.clickThroughUrl=d.textContent?.trim();a.querySelectorAll("TrackingEvents > Tracking").forEach((c)=>{let u=c.getAttribute("event"),v=c.textContent?.trim();if(u&&v){let g={event:u,url:v};if(u==="progress"){let k=c.getAttribute("offset");if(k)g.offset=this.parseOffset(k,r.duration)}r.trackingEvents.push(g)}}),a.querySelectorAll("Icons > Icon").forEach((c)=>{let u=c.querySelector("StaticResource");if(u?.textContent)r.icons=r.icons||[],r.icons.push({url:u.textContent.trim(),width:Number.parseInt(c.getAttribute("width")||"0",10),height:Number.parseInt(c.getAttribute("height")||"0",10),xPosition:c.getAttribute("xPosition")||"right",yPosition:c.getAttribute("yPosition")||"top",clickUrl:c.querySelector("IconClicks > IconClickThrough")?.textContent?.trim()})})}if(s.querySelectorAll("CompanionAds > Companion").forEach((o)=>{r.companions=r.companions||[];let l=o.querySelector("StaticResource"),d=o.querySelector("IFrameResource"),c=o.querySelector("HTMLResource"),u="",v="static";if(l?.textContent)u=l.textContent.trim(),v="static";else if(d?.textContent)u=d.textContent.trim(),v="iframe";else if(c?.textContent)u=c.textContent.trim(),v="html";if(u)r.companions.push({width:Number.parseInt(o.getAttribute("width")||"0",10),height:Number.parseInt(o.getAttribute("height")||"0",10),resourceUrl:u,resourceType:v,clickThroughUrl:o.querySelector("CompanionClickThrough")?.textContent?.trim(),altText:o.getAttribute("altText")||void 0,trackingUrl:o.querySelector("TrackingEvents > Tracking")?.textContent?.trim()})}),r.mediaFiles.length>0)t.push(r)}),t}parseDuration(e){let t=e.split(":");if(t.length!==3)return 0;let i=Number.parseFloat(t[0]),n=Number.parseFloat(t[1]),s=Number.parseFloat(t[2]);return i*3600+n*60+s}parseOffset(e,t){if(e.endsWith("%")){let i=Number.parseFloat(e)/100;return t*i}return this.parseDuration(e)}generateId(){return`ad-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}}class V{player=null;config;parser;state;container=null;adVideo=null;adContainer=null;skipButton=null;adBreaks=[];currentAds=[];currentAdIndex=0;skipTimer=null;contentPaused=!1;onAdStart=null;onAdComplete=null;onAdSkip=null;onAdClick=null;onAdErrorCallback=null;onAllAdsComplete=null;constructor(e={}){if(this.config={skipDelay:5,maxRedirects:5,timeout:1e4,vpaidEnabled:!1,preloadAds:!0,debug:!1,...e},this.parser=new Le({maxRedirects:this.config.maxRedirects,timeout:this.config.timeout}),this.state={isPlaying:!1,currentAd:null,currentBreak:null,timeRemaining:0,canSkip:!1,skipCountdown:0,isLoading:!1,error:null},this.config.schedule)this.adBreaks=this.config.schedule;else if(this.config.vastUrl||this.config.vastXml)this.adBreaks=[{type:"preroll",vastUrl:this.config.vastUrl,vastXml:this.config.vastXml}]}attach(e,t){if(this.player=e,this.container=t,this.createAdContainer(),this.attachPlayerEvents(),this.config.preloadAds)this.preloadAds()}createAdContainer(){if(!this.container)return;this.adContainer=document.createElement("div"),this.adContainer.className="tsvp-ad-container",this.adContainer.style.cssText=`
460
+ `},Re={default:pi,minimal:hi,cinema:mi,youtube:vi,vimeo:gi,audio:yi};class yt{container;currentLayout=null;styleElement=null;constructor(e){this.container=e}apply(e){let t=typeof e==="string"?Re[e]:e;if(this.cleanup(),this.container.classList.add(`tsvp-layout-${t.name}`),this.styleElement=document.createElement("style"),this.styleElement.textContent=t.styles,document.head.appendChild(this.styleElement),this.container.innerHTML=t.template,t.init)t.init(this.container);this.currentLayout=t}getLayout(){return this.currentLayout}cleanup(){if(this.currentLayout){if(this.container.classList.remove(`tsvp-layout-${this.currentLayout.name}`),this.currentLayout.destroy)this.currentLayout.destroy(this.container);if(this.styleElement)this.styleElement.remove(),this.styleElement=null;this.currentLayout=null}}destroy(){this.cleanup()}}function ft(e){return new yt(e)}var fi=[10,25,50,75,90,100];class V{player=null;config;state;heartbeatTimer=null;eventQueue=[];flushTimer=null;sessionId;visitorId;unsubscribers=[];constructor(e){this.config={milestones:fi,heartbeatInterval:30,trackQualityChanges:!0,trackSeeking:!0,trackBuffering:!0,trackErrors:!0,trackEngagement:!0,...e},this.sessionId=e.sessionId||this.generateId(),this.visitorId=e.visitorId||this.getOrCreateVisitorId(),this.state=this.createInitialState()}createInitialState(){return{hasStarted:!1,hasCompleted:!1,watchTime:0,pauseCount:0,seekCount:0,bufferCount:0,bufferTime:0,qualityChangeCount:0,reachedMilestones:[],reachedQuartiles:[],playbackStartTime:null,lastHeartbeat:0,isBuffering:!1,bufferStartTime:null}}attach(e){if(this.config.disabled)return;this.player=e,this.attachEventListeners(),this.startHeartbeat()}detach(){this.stopHeartbeat(),this.unsubscribers.forEach((e)=>e()),this.unsubscribers=[],this.flush(),this.player=null}attachEventListeners(){if(!this.player)return;if(this.on("play",()=>{if(!this.state.hasStarted)this.state.hasStarted=!0,this.state.playbackStartTime=Date.now(),this.trackEvent("video_start");else this.trackEvent("video_resume");this.trackEvent("video_play")}),this.on("pause",()=>{this.state.pauseCount++,this.updateWatchTime(),this.trackEvent("video_pause")}),this.config.trackSeeking)this.on("seeking",()=>{this.state.seekCount++}),this.on("seeked",()=>{let e=this.player?.state;this.trackEvent("video_seek",{seekTo:e?.currentTime||0})});if(this.config.trackBuffering)this.on("waiting",()=>{if(!this.state.isBuffering)this.state.isBuffering=!0,this.state.bufferStartTime=Date.now(),this.state.bufferCount++,this.trackEvent("video_buffer_start")}),this.on("playing",()=>{if(this.state.isBuffering){if(this.state.isBuffering=!1,this.state.bufferStartTime)this.state.bufferTime+=(Date.now()-this.state.bufferStartTime)/1000;this.trackEvent("video_buffer_end",{bufferDuration:this.state.bufferStartTime?(Date.now()-this.state.bufferStartTime)/1000:0}),this.state.bufferStartTime=null}});if(this.on("timeupdate",()=>{this.checkMilestones()}),this.config.trackQualityChanges)this.on("qualitychange",(e)=>{this.state.qualityChangeCount++,this.trackEvent("video_quality_change",{quality:e?`${e.height}p`:"auto",bitrate:e?.bitrate})});if(this.on("volumechange",()=>{let e=this.player?.state;if(e?.muted)this.trackEvent("video_mute");else this.trackEvent("video_volume_change",{volume:e?.volume})}),this.on("fullscreenchange",(e)=>{this.trackEvent(e?"video_fullscreen_enter":"video_fullscreen_exit")}),this.on("pipchange",(e)=>{this.trackEvent(e?"video_pip_enter":"video_pip_exit")}),this.on("texttrackchange",(e)=>{if(e)this.trackEvent("video_caption_change",{language:e.language,label:e.label});else this.trackEvent("video_caption_disable")}),this.on("audiotrackchange",(e)=>{if(e)this.trackEvent("video_audio_track_change",{language:e.language,label:e.label})}),this.on("ratechange",(e)=>{this.trackEvent("video_speed_change",{speed:e})}),this.on("ended",()=>{if(!this.state.hasCompleted)this.state.hasCompleted=!0,this.updateWatchTime(),this.trackEvent("video_complete",{watchTime:this.state.watchTime,pauseCount:this.state.pauseCount,seekCount:this.state.seekCount,bufferCount:this.state.bufferCount,bufferTime:this.state.bufferTime})}),this.config.trackErrors)this.on("error",(e)=>{this.trackEvent("video_error",{code:e?.code,message:e?.message})})}on(e,t){if(!this.player)return;this.player.on(e,t),this.unsubscribers.push(()=>this.player?.off(e,t))}checkMilestones(){let e=this.player?.state;if(!e||!e.duration)return;let t=e.currentTime/e.duration*100;for(let n of this.config.milestones||[])if(t>=n&&!this.state.reachedMilestones.includes(n))this.state.reachedMilestones.push(n),this.trackEvent("video_milestone",{milestone:n});let i=[25,50,75,100];for(let n of i)if(t>=n&&!this.state.reachedQuartiles.includes(n))this.state.reachedQuartiles.push(n),this.trackEvent("video_quartile",{quartile:n})}updateWatchTime(){if(this.state.playbackStartTime)this.state.watchTime+=(Date.now()-this.state.playbackStartTime)/1000,this.state.playbackStartTime=Date.now()}startHeartbeat(){if(this.heartbeatTimer)return;let e=(this.config.heartbeatInterval||30)*1000;this.heartbeatTimer=setInterval(()=>{let t=this.player?.state;if(t?.playbackState==="playing")this.updateWatchTime(),this.trackEvent("video_heartbeat",{watchTime:this.state.watchTime,currentTime:t.currentTime})},e)}stopHeartbeat(){if(this.heartbeatTimer)clearInterval(this.heartbeatTimer),this.heartbeatTimer=null}trackEvent(e,t){if(this.config.disabled)return;let i=this.player?.state,n={name:e,timestamp:new Date,currentTime:i?.currentTime||0,duration:i?.duration||this.config.duration||0,properties:t};this.eventQueue.push(n),this.scheduleFlush()}scheduleFlush(){if(this.flushTimer)return;this.flushTimer=setTimeout(()=>{this.flush(),this.flushTimer=null},1000)}async flush(){if(this.eventQueue.length===0)return;let e=[...this.eventQueue];this.eventQueue=[];try{await this.sendEvents(e)}catch(t){console.error("Failed to send analytics events:",t),this.eventQueue.unshift(...e)}}async sendEvents(e){let t=e.map((i)=>this.buildEventPayload(i));for(let i of t)await fetch(this.config.apiEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),keepalive:!0})}buildEventPayload(e){return{s:this.config.siteId,sid:this.sessionId,vid:this.visitorId,e:"event",u:typeof window<"u"?window.location.href:"",p:{eventName:e.name,videoId:this.config.videoId,videoTitle:this.config.videoTitle,contentType:this.config.contentType,category:this.config.category,creatorId:this.config.creatorId,seriesId:this.config.seriesId,episode:this.config.episode,season:this.config.season,currentTime:e.currentTime,duration:e.duration,progress:e.duration>0?e.currentTime/e.duration*100:0,watchTime:this.state.watchTime,...this.config.customProperties,...e.properties}}}generateId(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}getOrCreateVisitorId(){if(typeof localStorage>"u")return this.generateId();let e="tsvp_visitor_id",t=localStorage.getItem(e);if(!t)t=this.generateId(),localStorage.setItem(e,t);return t}getState(){return{...this.state}}getSummary(){return{videoId:this.config.videoId,sessionId:this.sessionId,hasStarted:this.state.hasStarted,hasCompleted:this.state.hasCompleted,watchTime:this.state.watchTime,pauseCount:this.state.pauseCount,seekCount:this.state.seekCount,bufferCount:this.state.bufferCount,bufferTime:this.state.bufferTime,qualityChangeCount:this.state.qualityChangeCount,reachedMilestones:this.state.reachedMilestones,completionRate:this.state.reachedQuartiles.length>0?Math.max(...this.state.reachedQuartiles):0}}reset(){this.flush(),this.state=this.createInitialState(),this.sessionId=this.generateId()}destroy(){if(this.detach(),this.flushTimer)clearTimeout(this.flushTimer)}}function bt(e){return new V(e)}function Ie(e){return{name:"analytics",install(t,i){let n=bt({...e,...i});return n.attach(t),t.analytics=n,()=>{n.destroy(),delete t.analytics}}}}class He{maxRedirects;timeout;redirectCount=0;constructor(e={}){this.maxRedirects=e.maxRedirects??5,this.timeout=e.timeout??1e4}async parseFromUrl(e){return this.redirectCount=0,this.fetchAndParse(e)}parseFromXml(e){let i=new DOMParser().parseFromString(e,"text/xml");return this.parseDocument(i)}async fetchAndParse(e){if(this.redirectCount>=this.maxRedirects)throw Error("Too many VAST redirects");let t=new AbortController,i=setTimeout(()=>t.abort(),this.timeout);try{let s=await(await fetch(e,{signal:t.signal})).text(),a=new DOMParser().parseFromString(s,"text/xml"),o=a.querySelector("Wrapper");if(o){let d=o.querySelector("VASTAdTagURI")?.textContent?.trim();if(d)return this.redirectCount++,this.fetchAndParse(d)}return this.parseDocument(a)}finally{clearTimeout(i)}}parseDocument(e){let t=[];return e.querySelectorAll("Ad").forEach((n)=>{let s=n.querySelector("InLine");if(!s)return;let r={id:n.getAttribute("id")||this.generateId(),type:"linear",adSystem:s.querySelector("AdSystem")?.textContent?.trim(),title:s.querySelector("AdTitle")?.textContent?.trim(),description:s.querySelector("Description")?.textContent?.trim(),duration:0,mediaFiles:[],trackingEvents:[]},a=s.querySelector("Linear");if(a){let o=a.querySelector("Duration")?.textContent?.trim();if(o)r.duration=this.parseDuration(o);let d=a.getAttribute("skipoffset");if(d)r.skipOffset=this.parseOffset(d,r.duration);a.querySelectorAll("MediaFile").forEach((u)=>{let p=u.textContent?.trim();if(p)r.mediaFiles.push({url:p,type:u.getAttribute("type")||"video/mp4",width:Number.parseInt(u.getAttribute("width")||"0",10),height:Number.parseInt(u.getAttribute("height")||"0",10),bitrate:u.getAttribute("bitrate")?Number.parseInt(u.getAttribute("bitrate"),10):void 0,delivery:u.getAttribute("delivery")||"progressive"})});let c=a.querySelector("VideoClicks > ClickThrough");if(c)r.clickThroughUrl=c.textContent?.trim();a.querySelectorAll("TrackingEvents > Tracking").forEach((u)=>{let p=u.getAttribute("event"),g=u.textContent?.trim();if(p&&g){let y={event:p,url:g};if(p==="progress"){let T=u.getAttribute("offset");if(T)y.offset=this.parseOffset(T,r.duration)}r.trackingEvents.push(y)}}),a.querySelectorAll("Icons > Icon").forEach((u)=>{let p=u.querySelector("StaticResource");if(p?.textContent)r.icons=r.icons||[],r.icons.push({url:p.textContent.trim(),width:Number.parseInt(u.getAttribute("width")||"0",10),height:Number.parseInt(u.getAttribute("height")||"0",10),xPosition:u.getAttribute("xPosition")||"right",yPosition:u.getAttribute("yPosition")||"top",clickUrl:u.querySelector("IconClicks > IconClickThrough")?.textContent?.trim()})})}if(s.querySelectorAll("CompanionAds > Companion").forEach((o)=>{r.companions=r.companions||[];let d=o.querySelector("StaticResource"),c=o.querySelector("IFrameResource"),u=o.querySelector("HTMLResource"),p="",g="static";if(d?.textContent)p=d.textContent.trim(),g="static";else if(c?.textContent)p=c.textContent.trim(),g="iframe";else if(u?.textContent)p=u.textContent.trim(),g="html";if(p)r.companions.push({width:Number.parseInt(o.getAttribute("width")||"0",10),height:Number.parseInt(o.getAttribute("height")||"0",10),resourceUrl:p,resourceType:g,clickThroughUrl:o.querySelector("CompanionClickThrough")?.textContent?.trim(),altText:o.getAttribute("altText")||void 0,trackingUrl:o.querySelector("TrackingEvents > Tracking")?.textContent?.trim()})}),r.mediaFiles.length>0)t.push(r)}),t}parseDuration(e){let t=e.split(":");if(t.length!==3)return 0;let i=Number.parseFloat(t[0]),n=Number.parseFloat(t[1]),s=Number.parseFloat(t[2]);return i*3600+n*60+s}parseOffset(e,t){if(e.endsWith("%")){let i=Number.parseFloat(e)/100;return t*i}return this.parseDuration(e)}generateId(){return`ad-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}}class B{player=null;config;parser;state;container=null;adVideo=null;adContainer=null;skipButton=null;adBreaks=[];currentAds=[];currentAdIndex=0;skipTimer=null;contentPaused=!1;onAdStart=null;onAdComplete=null;onAdSkip=null;onAdClick=null;onAdErrorCallback=null;onAllAdsComplete=null;constructor(e={}){if(this.config={skipDelay:5,maxRedirects:5,timeout:1e4,vpaidEnabled:!1,preloadAds:!0,debug:!1,...e},this.parser=new He({maxRedirects:this.config.maxRedirects,timeout:this.config.timeout}),this.state={isPlaying:!1,currentAd:null,currentBreak:null,timeRemaining:0,canSkip:!1,skipCountdown:0,isLoading:!1,error:null},this.config.schedule)this.adBreaks=this.config.schedule;else if(this.config.vastUrl||this.config.vastXml)this.adBreaks=[{type:"preroll",vastUrl:this.config.vastUrl,vastXml:this.config.vastXml}]}attach(e,t){if(this.player=e,this.container=t,this.createAdContainer(),this.attachPlayerEvents(),this.config.preloadAds)this.preloadAds()}createAdContainer(){if(!this.container)return;this.adContainer=document.createElement("div"),this.adContainer.className="tsvp-ad-container",this.adContainer.style.cssText=`
461
461
  position: absolute;
462
462
  inset: 0;
463
463
  z-index: 50;
@@ -511,7 +511,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
511
511
  cursor: pointer;
512
512
  pointer-events: auto;
513
513
  display: none;
514
- `,i.textContent="Learn More",i.addEventListener("click",()=>this.handleAdClick()),e.appendChild(t),e.appendChild(this.skipButton),e.appendChild(i),this.adContainer.appendChild(this.adVideo),this.adContainer.appendChild(e),this.container.appendChild(this.adContainer),this.adVideo.addEventListener("timeupdate",()=>this.onAdTimeUpdate()),this.adVideo.addEventListener("ended",()=>this.onAdEnded()),this.adVideo.addEventListener("error",()=>this.handleAdError())}attachPlayerEvents(){if(!this.player)return;let e=!0;this.player.on("play",async()=>{if(e){e=!1;let t=this.adBreaks.find((i)=>i.type==="preroll"&&!i.played);if(t)await this.playAdBreak(t)}}),this.player.on("timeupdate",()=>{let t=this.player?.state;if(!t)return;for(let i of this.adBreaks)if(i.type==="midroll"&&!i.played&&i.timeOffset&&t.currentTime>=i.timeOffset){this.playAdBreak(i);break}}),this.player.on("ended",async()=>{let t=this.adBreaks.find((i)=>i.type==="postroll"&&!i.played);if(t)await this.playAdBreak(t)})}async preloadAds(){for(let e of this.adBreaks)if(e.vastUrl)try{await this.parser.parseFromUrl(e.vastUrl)}catch(t){this.log("Failed to preload ad:",t)}}async playAdBreak(e){if(this.state.isPlaying)return;this.state.currentBreak=e,this.state.isLoading=!0,this.pauseContent();try{if(e.vastUrl)this.currentAds=await this.parser.parseFromUrl(e.vastUrl);else if(e.vastXml)this.currentAds=this.parser.parseFromXml(e.vastXml);if(this.currentAds.length===0)throw Error("No ads found in VAST response");this.currentAdIndex=0,e.played=!0,await this.playAd(this.currentAds[0])}catch(t){this.state.error=t.message,this.state.isLoading=!1,this.onAdErrorCallback?.(t.message),this.resumeContent()}}async playAd(e){if(!this.adVideo||!this.adContainer)return;this.state.currentAd=e,this.state.isPlaying=!0,this.state.isLoading=!1,this.state.timeRemaining=e.duration,this.state.canSkip=!1,this.state.skipCountdown=this.config.skipDelay||0;let t=this.selectMediaFile(e.mediaFiles);if(!t)throw Error("No suitable media file found");this.adContainer.style.display="block",this.adVideo.src=t.url,await this.adVideo.play(),this.trackEvent(e,"impression"),this.trackEvent(e,"start"),this.startSkipTimer(e),this.onAdStart?.(e)}selectMediaFile(e){return[...e].sort((i,n)=>{if(i.type.includes("mp4")&&!n.type.includes("mp4"))return-1;if(!i.type.includes("mp4")&&n.type.includes("mp4"))return 1;return(n.bitrate||0)-(i.bitrate||0)})[0]||null}startSkipTimer(e){let t=this.config.skipDelay===-1?e.skipOffset||5:this.config.skipDelay||0;if(t<=0){this.state.canSkip=!0,this.updateSkipButton();return}this.state.skipCountdown=t,this.skipTimer=setInterval(()=>{if(this.state.skipCountdown--,this.state.skipCountdown<=0){if(this.state.canSkip=!0,this.skipTimer)clearInterval(this.skipTimer),this.skipTimer=null}this.updateSkipButton()},1000)}updateSkipButton(){if(!this.skipButton)return;if(this.state.canSkip)this.skipButton.textContent="Skip Ad",this.skipButton.style.display="block";else if(this.state.skipCountdown>0)this.skipButton.textContent=`Skip in ${this.state.skipCountdown}s`,this.skipButton.style.display="block",this.skipButton.style.cursor="default";else this.skipButton.style.display="none"}skipAd(){if(!this.state.canSkip||!this.state.currentAd)return;this.trackEvent(this.state.currentAd,"skip"),this.onAdSkip?.(this.state.currentAd),this.onAdEnded()}handleAdClick(){if(!this.state.currentAd?.clickThroughUrl)return;this.adVideo?.pause(),this.trackEvent(this.state.currentAd,"clickThrough"),this.onAdClick?.(this.state.currentAd),window.open(this.state.currentAd.clickThroughUrl,"_blank")}onAdTimeUpdate(){if(!this.adVideo||!this.state.currentAd)return;let e=this.adVideo.currentTime,t=this.state.currentAd.duration;this.state.timeRemaining=Math.max(0,t-e);let i=e/t;if(i>=0.25)this.trackEvent(this.state.currentAd,"firstQuartile");if(i>=0.5)this.trackEvent(this.state.currentAd,"midpoint");if(i>=0.75)this.trackEvent(this.state.currentAd,"thirdQuartile");for(let n of this.state.currentAd.trackingEvents)if(n.event==="progress"&&n.offset&&e>=n.offset)this.trackUrl(n.url)}onAdEnded(){if(this.state.currentAd)this.trackEvent(this.state.currentAd,"complete"),this.onAdComplete?.(this.state.currentAd);if(this.skipTimer)clearInterval(this.skipTimer),this.skipTimer=null;if(this.currentAdIndex++,this.currentAdIndex<this.currentAds.length)this.playAd(this.currentAds[this.currentAdIndex]);else this.finishAdBreak()}handleAdError(){this.state.error="Ad playback failed",this.onAdErrorCallback?.("Ad playback failed"),this.trackEvent(this.state.currentAd,"error"),this.finishAdBreak()}finishAdBreak(){if(this.state.isPlaying=!1,this.state.currentAd=null,this.state.currentBreak=null,this.currentAds=[],this.currentAdIndex=0,this.adContainer)this.adContainer.style.display="none";this.onAllAdsComplete?.(),this.resumeContent()}pauseContent(){if(!this.player)return;if(this.player.state.playbackState==="playing")this.contentPaused=!0,this.player.pause()}resumeContent(){if(!this.player)return;if(this.contentPaused)this.contentPaused=!1,this.player.play()}trackEvent(e,t){let i=e.trackingEvents.filter((n)=>n.event===t);for(let n of i)this.trackUrl(n.url)}trackUrl(e){let t=new Image;t.src=e}log(...e){if(this.config.debug)console.log("[VideoAds]",...e)}getState(){return{...this.state}}on(e,t){switch(e){case"adStart":this.onAdStart=t;break;case"adComplete":this.onAdComplete=t;break;case"adSkip":this.onAdSkip=t;break;case"adClick":this.onAdClick=t;break;case"adError":this.onAdErrorCallback=t;break;case"allAdsComplete":this.onAllAdsComplete=t;break}}destroy(){if(this.skipTimer)clearInterval(this.skipTimer);if(this.adContainer)this.adContainer.remove();this.player=null,this.container=null,this.adVideo=null,this.adContainer=null}}function yt(e){return new V(e)}function Ce(e){return{name:"ads",install(t,i){let n=yt(e);return n.attach(t,i),t.ads=n,()=>{n.destroy(),delete t.ads}}}}var ft={intro:"Skip Intro",outro:"Skip Outro",recap:"Skip Recap",preview:"Skip Preview",credits:"Skip Credits",sponsor:"Skip",custom:"Skip"};class D{player=null;config;state;container=null;button=null;markersContainer=null;countdownTimer=null;hideTimer=null;unsubscribers=[];onSkip=null;onSegmentEnter=null;onSegmentExit=null;constructor(e){this.config={segments:e.segments||[],buttonVisibleDuration:e.buttonVisibleDuration??1e4,defaultAutoSkipDelay:e.defaultAutoSkipDelay??0,buttonPosition:e.buttonPosition||"bottom-right",showMarkers:e.showMarkers??!0,markerColor:e.markerColor||"rgba(255, 255, 0, 0.8)",keyboardShortcut:e.keyboardShortcut??!0},this.state={activeSegment:null,buttonVisible:!1,countdown:0,isAutoSkipping:!1}}attach(e,t){if(this.player=e,this.container=t,this.createButton(),this.attachEventListeners(),this.config.showMarkers)this.createMarkers()}createButton(){if(!this.container)return;this.button=document.createElement("button"),this.button.className="tsvp-skip-button",this.button.type="button";let e=this.getPositionStyles();this.button.style.cssText=`
514
+ `,i.textContent="Learn More",i.addEventListener("click",()=>this.handleAdClick()),e.appendChild(t),e.appendChild(this.skipButton),e.appendChild(i),this.adContainer.appendChild(this.adVideo),this.adContainer.appendChild(e),this.container.appendChild(this.adContainer),this.adVideo.addEventListener("timeupdate",()=>this.onAdTimeUpdate()),this.adVideo.addEventListener("ended",()=>this.onAdEnded()),this.adVideo.addEventListener("error",()=>this.handleAdError())}attachPlayerEvents(){if(!this.player)return;let e=!0;this.player.on("play",async()=>{if(e){e=!1;let t=this.adBreaks.find((i)=>i.type==="preroll"&&!i.played);if(t)await this.playAdBreak(t)}}),this.player.on("timeupdate",()=>{let t=this.player?.state;if(!t)return;for(let i of this.adBreaks)if(i.type==="midroll"&&!i.played&&i.timeOffset&&t.currentTime>=i.timeOffset){this.playAdBreak(i);break}}),this.player.on("ended",async()=>{let t=this.adBreaks.find((i)=>i.type==="postroll"&&!i.played);if(t)await this.playAdBreak(t)})}async preloadAds(){for(let e of this.adBreaks)if(e.vastUrl)try{await this.parser.parseFromUrl(e.vastUrl)}catch(t){this.log("Failed to preload ad:",t)}}async playAdBreak(e){if(this.state.isPlaying)return;this.state.currentBreak=e,this.state.isLoading=!0,this.pauseContent();try{if(e.vastUrl)this.currentAds=await this.parser.parseFromUrl(e.vastUrl);else if(e.vastXml)this.currentAds=this.parser.parseFromXml(e.vastXml);if(this.currentAds.length===0)throw Error("No ads found in VAST response");this.currentAdIndex=0,e.played=!0,await this.playAd(this.currentAds[0])}catch(t){this.state.error=t.message,this.state.isLoading=!1,this.onAdErrorCallback?.(t.message),this.resumeContent()}}async playAd(e){if(!this.adVideo||!this.adContainer)return;this.state.currentAd=e,this.state.isPlaying=!0,this.state.isLoading=!1,this.state.timeRemaining=e.duration,this.state.canSkip=!1,this.state.skipCountdown=this.config.skipDelay||0;let t=this.selectMediaFile(e.mediaFiles);if(!t)throw Error("No suitable media file found");this.adContainer.style.display="block",this.adVideo.src=t.url,await this.adVideo.play(),this.trackEvent(e,"impression"),this.trackEvent(e,"start"),this.startSkipTimer(e),this.onAdStart?.(e)}selectMediaFile(e){return[...e].sort((i,n)=>{if(i.type.includes("mp4")&&!n.type.includes("mp4"))return-1;if(!i.type.includes("mp4")&&n.type.includes("mp4"))return 1;return(n.bitrate||0)-(i.bitrate||0)})[0]||null}startSkipTimer(e){let t=this.config.skipDelay===-1?e.skipOffset||5:this.config.skipDelay||0;if(t<=0){this.state.canSkip=!0,this.updateSkipButton();return}this.state.skipCountdown=t,this.skipTimer=setInterval(()=>{if(this.state.skipCountdown--,this.state.skipCountdown<=0){if(this.state.canSkip=!0,this.skipTimer)clearInterval(this.skipTimer),this.skipTimer=null}this.updateSkipButton()},1000)}updateSkipButton(){if(!this.skipButton)return;if(this.state.canSkip)this.skipButton.textContent="Skip Ad",this.skipButton.style.display="block";else if(this.state.skipCountdown>0)this.skipButton.textContent=`Skip in ${this.state.skipCountdown}s`,this.skipButton.style.display="block",this.skipButton.style.cursor="default";else this.skipButton.style.display="none"}skipAd(){if(!this.state.canSkip||!this.state.currentAd)return;this.trackEvent(this.state.currentAd,"skip"),this.onAdSkip?.(this.state.currentAd),this.onAdEnded()}handleAdClick(){if(!this.state.currentAd?.clickThroughUrl)return;this.adVideo?.pause(),this.trackEvent(this.state.currentAd,"clickThrough"),this.onAdClick?.(this.state.currentAd),window.open(this.state.currentAd.clickThroughUrl,"_blank")}onAdTimeUpdate(){if(!this.adVideo||!this.state.currentAd)return;let e=this.adVideo.currentTime,t=this.state.currentAd.duration;this.state.timeRemaining=Math.max(0,t-e);let i=e/t;if(i>=0.25)this.trackEvent(this.state.currentAd,"firstQuartile");if(i>=0.5)this.trackEvent(this.state.currentAd,"midpoint");if(i>=0.75)this.trackEvent(this.state.currentAd,"thirdQuartile");for(let n of this.state.currentAd.trackingEvents)if(n.event==="progress"&&n.offset&&e>=n.offset)this.trackUrl(n.url)}onAdEnded(){if(this.state.currentAd)this.trackEvent(this.state.currentAd,"complete"),this.onAdComplete?.(this.state.currentAd);if(this.skipTimer)clearInterval(this.skipTimer),this.skipTimer=null;if(this.currentAdIndex++,this.currentAdIndex<this.currentAds.length)this.playAd(this.currentAds[this.currentAdIndex]);else this.finishAdBreak()}handleAdError(){this.state.error="Ad playback failed",this.onAdErrorCallback?.("Ad playback failed"),this.trackEvent(this.state.currentAd,"error"),this.finishAdBreak()}finishAdBreak(){if(this.state.isPlaying=!1,this.state.currentAd=null,this.state.currentBreak=null,this.currentAds=[],this.currentAdIndex=0,this.adContainer)this.adContainer.style.display="none";this.onAllAdsComplete?.(),this.resumeContent()}pauseContent(){if(!this.player)return;if(this.player.state.playbackState==="playing")this.contentPaused=!0,this.player.pause()}resumeContent(){if(!this.player)return;if(this.contentPaused)this.contentPaused=!1,this.player.play()}trackEvent(e,t){let i=e.trackingEvents.filter((n)=>n.event===t);for(let n of i)this.trackUrl(n.url)}trackUrl(e){let t=new Image;t.src=e}log(...e){if(this.config.debug)console.log("[VideoAds]",...e)}getState(){return{...this.state}}on(e,t){switch(e){case"adStart":this.onAdStart=t;break;case"adComplete":this.onAdComplete=t;break;case"adSkip":this.onAdSkip=t;break;case"adClick":this.onAdClick=t;break;case"adError":this.onAdErrorCallback=t;break;case"allAdsComplete":this.onAllAdsComplete=t;break}}destroy(){if(this.skipTimer)clearInterval(this.skipTimer);if(this.adContainer)this.adContainer.remove();this.player=null,this.container=null,this.adVideo=null,this.adContainer=null}}function kt(e){return new B(e)}function Ve(e){return{name:"ads",install(t,i){let n=kt(e);return n.attach(t,i),t.ads=n,()=>{n.destroy(),delete t.ads}}}}var Tt={intro:"Skip Intro",outro:"Skip Outro",recap:"Skip Recap",preview:"Skip Preview",credits:"Skip Credits",sponsor:"Skip",custom:"Skip"};class D{player=null;config;state;container=null;button=null;markersContainer=null;countdownTimer=null;hideTimer=null;unsubscribers=[];onSkip=null;onSegmentEnter=null;onSegmentExit=null;constructor(e){this.config={segments:e.segments||[],buttonVisibleDuration:e.buttonVisibleDuration??1e4,defaultAutoSkipDelay:e.defaultAutoSkipDelay??0,buttonPosition:e.buttonPosition||"bottom-right",showMarkers:e.showMarkers??!0,markerColor:e.markerColor||"rgba(255, 255, 0, 0.8)",keyboardShortcut:e.keyboardShortcut??!0},this.state={activeSegment:null,buttonVisible:!1,countdown:0,isAutoSkipping:!1}}attach(e,t){if(this.player=e,this.container=t,this.createButton(),this.attachEventListeners(),this.config.showMarkers)this.createMarkers()}createButton(){if(!this.container)return;this.button=document.createElement("button"),this.button.className="tsvp-skip-button",this.button.type="button";let e=this.getPositionStyles();this.button.style.cssText=`
515
515
  position: absolute;
516
516
  ${e}
517
517
  padding: 12px 24px;
@@ -541,7 +541,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
541
541
  bottom: 0;
542
542
  background: ${this.config.markerColor};
543
543
  opacity: 0.6;
544
- `,this.markersContainer.appendChild(i)}return this.markersContainer}attachEventListeners(){if(!this.player)return;let e=()=>{let t=this.player?.state;if(!t)return;this.checkSegments(t.currentTime)};if(this.player.on("timeupdate",e),this.unsubscribers.push(()=>this.player?.off("timeupdate",e)),this.config.keyboardShortcut){let t=(i)=>{if(i.key==="Enter"&&this.state.activeSegment&&this.state.buttonVisible)i.preventDefault(),this.skip()};document.addEventListener("keydown",t),this.unsubscribers.push(()=>document.removeEventListener("keydown",t))}}checkSegments(e){let t=this.state.activeSegment,i=null;for(let n of this.config.segments)if(e>=n.startTime&&e<n.endTime){i=n;break}if(i!==t){if(t)this.onSegmentExit?.(t),this.hideButton();if(i)this.state.activeSegment=i,this.onSegmentEnter?.(i),this.showButton(i);else this.state.activeSegment=null}}showButton(e){if(!this.button)return;let t=e.buttonText||ft[e.type];this.button.textContent=t,this.state.buttonVisible=!0,this.button.style.display="block",this.button.style.opacity="0",this.button.style.transform="translateX(20px)",requestAnimationFrame(()=>{this.button.style.transition="opacity 200ms ease, transform 200ms ease",this.button.style.opacity="1",this.button.style.transform="translateX(0)"});let i=e.autoSkipDelay??this.config.defaultAutoSkipDelay;if(i>0)this.startAutoSkip(i,e);if(this.config.buttonVisibleDuration>0&&!i)this.hideTimer=setTimeout(()=>{this.hideButton()},this.config.buttonVisibleDuration)}hideButton(){if(!this.button)return;if(this.state.buttonVisible=!1,this.state.isAutoSkipping=!1,this.state.countdown=0,this.countdownTimer)clearInterval(this.countdownTimer),this.countdownTimer=null;if(this.hideTimer)clearTimeout(this.hideTimer),this.hideTimer=null;this.button.style.opacity="0",this.button.style.transform="translateX(20px)",setTimeout(()=>{if(this.button&&!this.state.buttonVisible)this.button.style.display="none"},200)}startAutoSkip(e,t){this.state.isAutoSkipping=!0,this.state.countdown=e,this.updateButtonText(t),this.countdownTimer=setInterval(()=>{if(this.state.countdown--,this.updateButtonText(t),this.state.countdown<=0){if(this.countdownTimer)clearInterval(this.countdownTimer),this.countdownTimer=null;this.skip()}},1000)}updateButtonText(e){if(!this.button)return;let t=e.buttonText||ft[e.type];if(this.state.isAutoSkipping&&this.state.countdown>0&&e.showCountdown!==!1)this.button.textContent=`${t} (${this.state.countdown})`;else this.button.textContent=t}skip(){if(!this.state.activeSegment||!this.player)return;let e=this.state.activeSegment,t=e.skipTo??e.endTime;this.player.seekTo(t),this.onSkip?.(e),this.hideButton()}addSegment(e){this.config.segments.push(e)}removeSegment(e){this.config.segments=this.config.segments.filter((t)=>t.type!==e)}clearSegments(){this.config.segments=[],this.hideButton()}setSegments(e){this.config.segments=e}getSegments(){return[...this.config.segments]}getState(){return{...this.state}}on(e,t){switch(e){case"skip":this.onSkip=t;break;case"segmentEnter":this.onSegmentEnter=t;break;case"segmentExit":this.onSegmentExit=t;break}}destroy(){if(this.countdownTimer)clearInterval(this.countdownTimer);if(this.hideTimer)clearTimeout(this.hideTimer);this.unsubscribers.forEach((e)=>e()),this.button?.remove(),this.markersContainer?.remove(),this.player=null,this.container=null}}function bt(e){return new D(e)}function Re(e){return{name:"skipSegments",install(t,i){let n=bt(e);return n.attach(t,i),t.skipSegments=n,()=>{n.destroy(),delete t.skipSegments}}}}class B{player=null;config;state;container=null;element=null;countdownTimer=null;showTimer=null;unsubscribers=[];onRecommendationClick=null;onReplay=null;onAutoplay=null;onShow=null;onHide=null;constructor(e={}){this.config={enabled:e.enabled??!0,showDelay:e.showDelay??0,recommendations:e.recommendations||[],actions:e.actions||[],showReplay:e.showReplay??!0,showShare:e.showShare??!1,autoplayCountdown:e.autoplayCountdown??0,title:e.title||"",template:e.template||"",backgroundStyle:e.backgroundStyle||"blur"},this.state={visible:!1,countdown:0,isCountingDown:!1,selectedIndex:0}}attach(e,t){this.player=e,this.container=t,this.createElement(),this.attachEventListeners()}createElement(){if(!this.container)return;this.element=document.createElement("div"),this.element.className="tsvp-end-screen",this.element.style.cssText=`
544
+ `,this.markersContainer.appendChild(i)}return this.markersContainer}attachEventListeners(){if(!this.player)return;let e=()=>{let t=this.player?.state;if(!t)return;this.checkSegments(t.currentTime)};if(this.player.on("timeupdate",e),this.unsubscribers.push(()=>this.player?.off("timeupdate",e)),this.config.keyboardShortcut){let t=(i)=>{if(i.key==="Enter"&&this.state.activeSegment&&this.state.buttonVisible)i.preventDefault(),this.skip()};document.addEventListener("keydown",t),this.unsubscribers.push(()=>document.removeEventListener("keydown",t))}}checkSegments(e){let t=this.state.activeSegment,i=null;for(let n of this.config.segments)if(e>=n.startTime&&e<n.endTime){i=n;break}if(i!==t){if(t)this.onSegmentExit?.(t),this.hideButton();if(i)this.state.activeSegment=i,this.onSegmentEnter?.(i),this.showButton(i);else this.state.activeSegment=null}}showButton(e){if(!this.button)return;let t=e.buttonText||Tt[e.type];this.button.textContent=t,this.state.buttonVisible=!0,this.button.style.display="block",this.button.style.opacity="0",this.button.style.transform="translateX(20px)",requestAnimationFrame(()=>{this.button.style.transition="opacity 200ms ease, transform 200ms ease",this.button.style.opacity="1",this.button.style.transform="translateX(0)"});let i=e.autoSkipDelay??this.config.defaultAutoSkipDelay;if(i>0)this.startAutoSkip(i,e);if(this.config.buttonVisibleDuration>0&&!i)this.hideTimer=setTimeout(()=>{this.hideButton()},this.config.buttonVisibleDuration)}hideButton(){if(!this.button)return;if(this.state.buttonVisible=!1,this.state.isAutoSkipping=!1,this.state.countdown=0,this.countdownTimer)clearInterval(this.countdownTimer),this.countdownTimer=null;if(this.hideTimer)clearTimeout(this.hideTimer),this.hideTimer=null;this.button.style.opacity="0",this.button.style.transform="translateX(20px)",setTimeout(()=>{if(this.button&&!this.state.buttonVisible)this.button.style.display="none"},200)}startAutoSkip(e,t){this.state.isAutoSkipping=!0,this.state.countdown=e,this.updateButtonText(t),this.countdownTimer=setInterval(()=>{if(this.state.countdown--,this.updateButtonText(t),this.state.countdown<=0){if(this.countdownTimer)clearInterval(this.countdownTimer),this.countdownTimer=null;this.skip()}},1000)}updateButtonText(e){if(!this.button)return;let t=e.buttonText||Tt[e.type];if(this.state.isAutoSkipping&&this.state.countdown>0&&e.showCountdown!==!1)this.button.textContent=`${t} (${this.state.countdown})`;else this.button.textContent=t}skip(){if(!this.state.activeSegment||!this.player)return;let e=this.state.activeSegment,t=e.skipTo??e.endTime;this.player.seekTo(t),this.onSkip?.(e),this.hideButton()}addSegment(e){this.config.segments.push(e)}removeSegment(e){this.config.segments=this.config.segments.filter((t)=>t.type!==e)}clearSegments(){this.config.segments=[],this.hideButton()}setSegments(e){this.config.segments=e}getSegments(){return[...this.config.segments]}getState(){return{...this.state}}on(e,t){switch(e){case"skip":this.onSkip=t;break;case"segmentEnter":this.onSegmentEnter=t;break;case"segmentExit":this.onSegmentExit=t;break}}destroy(){if(this.countdownTimer)clearInterval(this.countdownTimer);if(this.hideTimer)clearTimeout(this.hideTimer);this.unsubscribers.forEach((e)=>e()),this.button?.remove(),this.markersContainer?.remove(),this.player=null,this.container=null}}function wt(e){return new D(e)}function Be(e){return{name:"skipSegments",install(t,i){let n=wt(e);return n.attach(t,i),t.skipSegments=n,()=>{n.destroy(),delete t.skipSegments}}}}class F{player=null;config;state;container=null;element=null;countdownTimer=null;showTimer=null;unsubscribers=[];onRecommendationClick=null;onReplay=null;onAutoplay=null;onShow=null;onHide=null;constructor(e={}){this.config={enabled:e.enabled??!0,showDelay:e.showDelay??0,recommendations:e.recommendations||[],actions:e.actions||[],showReplay:e.showReplay??!0,showShare:e.showShare??!1,autoplayCountdown:e.autoplayCountdown??0,title:e.title||"",template:e.template||"",backgroundStyle:e.backgroundStyle||"blur"},this.state={visible:!1,countdown:0,isCountingDown:!1,selectedIndex:0}}attach(e,t){this.player=e,this.container=t,this.createElement(),this.attachEventListeners()}createElement(){if(!this.container)return;this.element=document.createElement("div"),this.element.className="tsvp-end-screen",this.element.style.cssText=`
545
545
  position: absolute;
546
546
  inset: 0;
547
547
  display: none;
@@ -643,7 +643,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
643
643
  font-family: inherit;
644
644
  cursor: pointer;
645
645
  transition: transform 150ms ease, opacity 150ms ease;
646
- `,e.icon){let r=document.createElement("span");r.innerHTML=e.icon,r.style.display="flex",t.appendChild(r)}let s=document.createElement("span");return s.textContent=e.label,t.appendChild(s),t.addEventListener("mouseenter",()=>{t.style.transform="scale(1.05)"}),t.addEventListener("mouseleave",()=>{t.style.transform="scale(1)"}),t.addEventListener("click",e.onClick),t}attachEventListeners(){if(!this.player)return;let e=()=>{if(this.config.enabled)this.showTimer=setTimeout(()=>{this.show()},this.config.showDelay)};this.player.on("ended",e),this.unsubscribers.push(()=>this.player?.off("ended",e));let t=()=>{if(this.state.visible)this.hide()};this.player.on("play",t),this.unsubscribers.push(()=>this.player?.off("play",t));let i=(n)=>{if(!this.state.visible)return;switch(n.key){case"Escape":this.hide();break;case"ArrowLeft":this.selectPrevious();break;case"ArrowRight":this.selectNext();break;case"Enter":this.selectCurrent();break}};document.addEventListener("keydown",i),this.unsubscribers.push(()=>document.removeEventListener("keydown",i))}show(){if(!this.element||this.state.visible)return;if(this.state.visible=!0,this.state.selectedIndex=0,this.config.autoplayCountdown>0&&this.config.recommendations.length>0)this.startAutoplayCountdown();this.render(),this.element.style.display="flex",this.element.style.opacity="0",requestAnimationFrame(()=>{this.element.style.transition="opacity 300ms ease",this.element.style.opacity="1"}),this.onShow?.()}hide(){if(!this.element||!this.state.visible)return;this.state.visible=!1,this.cancelAutoplay(),this.element.style.opacity="0",setTimeout(()=>{if(this.element&&!this.state.visible)this.element.style.display="none"},300),this.onHide?.()}startAutoplayCountdown(){this.state.isCountingDown=!0,this.state.countdown=this.config.autoplayCountdown,this.countdownTimer=setInterval(()=>{if(this.state.countdown--,this.render(),this.state.countdown<=0)this.playNextVideo()},1000)}cancelAutoplay(){if(this.state.isCountingDown=!1,this.state.countdown=0,this.countdownTimer)clearInterval(this.countdownTimer),this.countdownTimer=null;if(this.state.visible)this.render()}playNextVideo(){let e=this.config.recommendations[this.state.selectedIndex];if(e){if(this.onAutoplay?.(e),e.onClick)e.onClick();else if(e.url)window.location.href=e.url}}selectPrevious(){if(this.config.recommendations.length===0)return;this.state.selectedIndex=(this.state.selectedIndex-1+this.config.recommendations.length)%this.config.recommendations.length,this.render()}selectNext(){if(this.config.recommendations.length===0)return;this.state.selectedIndex=(this.state.selectedIndex+1)%this.config.recommendations.length,this.render()}selectCurrent(){let e=this.config.recommendations[this.state.selectedIndex];if(e){if(this.onRecommendationClick?.(e),e.onClick)e.onClick();else if(e.url)window.location.href=e.url}}replay(){this.hide(),this.player?.seekTo(0),this.player?.play(),this.onReplay?.()}share(){if(navigator.share)navigator.share({title:document.title,url:window.location.href});else navigator.clipboard?.writeText(window.location.href)}setRecommendations(e){if(this.config.recommendations=e,this.state.visible)this.render()}getState(){return{...this.state}}on(e,t){switch(e){case"recommendationClick":this.onRecommendationClick=t;break;case"replay":this.onReplay=t;break;case"autoplay":this.onAutoplay=t;break;case"show":this.onShow=t;break;case"hide":this.onHide=t;break}}destroy(){if(this.countdownTimer)clearInterval(this.countdownTimer);if(this.showTimer)clearTimeout(this.showTimer);this.unsubscribers.forEach((e)=>e()),this.element?.remove(),this.player=null,this.container=null}}function kt(e){return new B(e)}function Ie(e){return{name:"endScreen",install(t,i){let n=kt(e);return n.attach(t,i),t.endScreen=n,()=>{n.destroy(),delete t.endScreen}}}}class F{player=null;container=null;elements=new Map;dynamicTimers=new Map;unsubscribers=[];constructor(){}attach(e,t){this.player=e,this.container=t}add(e,t){if(!this.container)throw Error("Watermark manager not attached to container");this.remove(e);let i=this.createElement(t);if(i.dataset.watermarkId=e,this.elements.set(e,i),this.container.appendChild(i),t.showOnlyDuringPlayback&&this.player)this.setupPlaybackVisibility(e,i);if(t.animation&&t.animation.type!=="none")this.applyAnimation(i,t.animation);return i}createElement(e){let t=document.createElement("div");t.className="tsvp-watermark";let i=this.getPositionStyles(e.position||"bottom-right",e.offset);if(t.style.cssText=`
646
+ `,e.icon){let r=document.createElement("span");r.innerHTML=e.icon,r.style.display="flex",t.appendChild(r)}let s=document.createElement("span");return s.textContent=e.label,t.appendChild(s),t.addEventListener("mouseenter",()=>{t.style.transform="scale(1.05)"}),t.addEventListener("mouseleave",()=>{t.style.transform="scale(1)"}),t.addEventListener("click",e.onClick),t}attachEventListeners(){if(!this.player)return;let e=()=>{if(this.config.enabled)this.showTimer=setTimeout(()=>{this.show()},this.config.showDelay)};this.player.on("ended",e),this.unsubscribers.push(()=>this.player?.off("ended",e));let t=()=>{if(this.state.visible)this.hide()};this.player.on("play",t),this.unsubscribers.push(()=>this.player?.off("play",t));let i=(n)=>{if(!this.state.visible)return;switch(n.key){case"Escape":this.hide();break;case"ArrowLeft":this.selectPrevious();break;case"ArrowRight":this.selectNext();break;case"Enter":this.selectCurrent();break}};document.addEventListener("keydown",i),this.unsubscribers.push(()=>document.removeEventListener("keydown",i))}show(){if(!this.element||this.state.visible)return;if(this.state.visible=!0,this.state.selectedIndex=0,this.config.autoplayCountdown>0&&this.config.recommendations.length>0)this.startAutoplayCountdown();this.render(),this.element.style.display="flex",this.element.style.opacity="0",requestAnimationFrame(()=>{this.element.style.transition="opacity 300ms ease",this.element.style.opacity="1"}),this.onShow?.()}hide(){if(!this.element||!this.state.visible)return;this.state.visible=!1,this.cancelAutoplay(),this.element.style.opacity="0",setTimeout(()=>{if(this.element&&!this.state.visible)this.element.style.display="none"},300),this.onHide?.()}startAutoplayCountdown(){this.state.isCountingDown=!0,this.state.countdown=this.config.autoplayCountdown,this.countdownTimer=setInterval(()=>{if(this.state.countdown--,this.render(),this.state.countdown<=0)this.playNextVideo()},1000)}cancelAutoplay(){if(this.state.isCountingDown=!1,this.state.countdown=0,this.countdownTimer)clearInterval(this.countdownTimer),this.countdownTimer=null;if(this.state.visible)this.render()}playNextVideo(){let e=this.config.recommendations[this.state.selectedIndex];if(e){if(this.onAutoplay?.(e),e.onClick)e.onClick();else if(e.url)window.location.href=e.url}}selectPrevious(){if(this.config.recommendations.length===0)return;this.state.selectedIndex=(this.state.selectedIndex-1+this.config.recommendations.length)%this.config.recommendations.length,this.render()}selectNext(){if(this.config.recommendations.length===0)return;this.state.selectedIndex=(this.state.selectedIndex+1)%this.config.recommendations.length,this.render()}selectCurrent(){let e=this.config.recommendations[this.state.selectedIndex];if(e){if(this.onRecommendationClick?.(e),e.onClick)e.onClick();else if(e.url)window.location.href=e.url}}replay(){this.hide(),this.player?.seekTo(0),this.player?.play(),this.onReplay?.()}share(){if(navigator.share)navigator.share({title:document.title,url:window.location.href});else navigator.clipboard?.writeText(window.location.href)}setRecommendations(e){if(this.config.recommendations=e,this.state.visible)this.render()}getState(){return{...this.state}}on(e,t){switch(e){case"recommendationClick":this.onRecommendationClick=t;break;case"replay":this.onReplay=t;break;case"autoplay":this.onAutoplay=t;break;case"show":this.onShow=t;break;case"hide":this.onHide=t;break}}destroy(){if(this.countdownTimer)clearInterval(this.countdownTimer);if(this.showTimer)clearTimeout(this.showTimer);this.unsubscribers.forEach((e)=>e()),this.element?.remove(),this.player=null,this.container=null}}function xt(e){return new F(e)}function De(e){return{name:"endScreen",install(t,i){let n=xt(e);return n.attach(t,i),t.endScreen=n,()=>{n.destroy(),delete t.endScreen}}}}class O{player=null;container=null;elements=new Map;dynamicTimers=new Map;unsubscribers=[];constructor(){}attach(e,t){this.player=e,this.container=t}add(e,t){if(!this.container)throw Error("Watermark manager not attached to container");this.remove(e);let i=this.createElement(t);if(i.dataset.watermarkId=e,this.elements.set(e,i),this.container.appendChild(i),t.showOnlyDuringPlayback&&this.player)this.setupPlaybackVisibility(e,i);if(t.animation&&t.animation.type!=="none")this.applyAnimation(i,t.animation);return i}createElement(e){let t=document.createElement("div");t.className="tsvp-watermark";let i=this.getPositionStyles(e.position||"bottom-right",e.offset);if(t.style.cssText=`
647
647
  position: absolute;
648
648
  ${i}
649
649
  z-index: 25;
@@ -679,7 +679,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
679
679
  0%, 100% { transform: scale(1); }
680
680
  50% { transform: scale(1.1); }
681
681
  }
682
- `,document.head.appendChild(a)}let r=`tsvp-watermark-${t.type}`;e.style.animation=`${r} ${i}ms ease ${n}ms ${s}`}addDynamic(e,t,i={}){let n=()=>{let o=[];if(t.userId)o.push(t.userId);if(t.showTimestamp)o.push(new Date().toISOString());if(t.customText)o.push(t.customText);return o.join(" | ")},s=["top-left","top-right","bottom-left","bottom-right","center-left","center-right"],r=i.position||"bottom-right",a=this.add(e,{...i,text:n(),position:r,opacity:i.opacity??0.3});if(t.updateInterval&&t.updateInterval>0){let o=setInterval(()=>{let l=a.querySelector("span");if(l)l.textContent=n()},t.updateInterval);this.dynamicTimers.set(`${e}-text`,o)}if(t.randomizePosition&&t.moveInterval&&t.moveInterval>0){let o=setInterval(()=>{let l=Math.floor(Math.random()*s.length);r=s[l];let d=this.getPositionStyles(r,i.offset);a.style.cssText=a.style.cssText.replace(/top:.*?;|bottom:.*?;|left:.*?;|right:.*?;|transform:.*?;/g,""),a.style.cssText+=d},t.moveInterval);this.dynamicTimers.set(`${e}-move`,o)}return a}remove(e){let t=this.elements.get(e);if(t)t.remove(),this.elements.delete(e);let i=this.dynamicTimers.get(`${e}-text`);if(i)clearInterval(i),this.dynamicTimers.delete(`${e}-text`);let n=this.dynamicTimers.get(`${e}-move`);if(n)clearInterval(n),this.dynamicTimers.delete(`${e}-move`)}removeAll(){for(let e of this.elements.keys())this.remove(e)}update(e,t){let i=this.elements.get(e);if(!i)return;if(t.opacity!==void 0)i.style.opacity=String(t.opacity);if(t.position){let n=this.getPositionStyles(t.position,t.offset);i.style.cssText=i.style.cssText.replace(/top:.*?;|bottom:.*?;|left:.*?;|right:.*?;|transform:.*?;/g,""),i.style.cssText+=n}if(t.text){let n=i.querySelector("span");if(n)n.textContent=t.text}if(t.image){let n=i.querySelector("img");if(n)n.src=t.image}}show(e){let t=this.elements.get(e);if(t)t.style.display=""}hide(e){let t=this.elements.get(e);if(t)t.style.display="none"}showAll(){for(let e of this.elements.keys())this.show(e)}hideAll(){for(let e of this.elements.keys())this.hide(e)}get(e){return this.elements.get(e)}getAll(){return Array.from(this.elements.keys())}destroy(){this.removeAll(),this.unsubscribers.forEach((e)=>e()),this.player=null,this.container=null}}function Tt(){return new F}function He(e){return{name:"watermark",install(t,i){let n=Tt();n.attach(t,i);for(let{id:s,...r}of e)n.add(s,r);return t.watermark=n,()=>{n.destroy(),delete t.watermark}}}}var p=globalThis.HTMLElement??class{};var yi=["src","poster","autoplay","loop","muted","controls","volume","playback-rate","preload","playsinline","crossorigin","controlslist","disable-picture-in-picture"];class X extends p{_player=null;_container=null;_disconnectId=0;static get observedAttributes(){return[...yi]}get player(){return this._player}connectedCallback(){if(this._disconnectId++,this._player)return;let e=this.shadowRoot??this.attachShadow({mode:"open"});this._container=document.createElement("div"),this._container.setAttribute("part","container"),this._container.style.cssText="position:relative;width:100%;height:100%;";let t=document.createElement("slot");this._container.appendChild(t),e.appendChild(this._container);let i=this.buildOptions();this._player=new P(this._container,i),this.forwardEvents()}disconnectedCallback(){if(this.hasAttribute("keep-alive"))return;let e=++this._disconnectId;queueMicrotask(()=>{if(this.isConnected||e!==this._disconnectId)return;this._player?.destroy(),this._player=null,this._container=null,this.shadowRoot?.replaceChildren()})}attributeChangedCallback(e,t,i){if(!this._player)return;switch(e){case"src":if(i)this._player.setSrc(i);break;case"poster":this._player.setPoster(i||"");break;case"muted":this._player.setMuted(i!==null);break;case"volume":if(i!==null)this._player.setVolume(parseFloat(i));break;case"playback-rate":if(i!==null)this._player.setPlaybackRate(parseFloat(i));break}}buildOptions(){let e={},t=this.readSourceConfig();if(t.sources?.length)e.src=t.sources;if(t.tracks?.length)e.tracks=t.tracks;let i=this.getAttribute("src");if(i&&!e.src)e.src=t.drm?{src:i,type:"application/dash+xml",drm:t.drm}:i;let n=this.getAttribute("poster");if(n)e.poster=n;let s=this.getAttribute("title");if(s)e.title=s;if(this.hasAttribute("autoplay"))e.autoplay=!0;if(this.hasAttribute("loop"))e.loop=!0;if(this.hasAttribute("muted"))e.muted=!0;let r=this.getAttribute("volume");if(r)e.volume=parseFloat(r);let a=this.getAttribute("playback-rate");if(a)e.playbackRate=parseFloat(a);let o=this.getAttribute("preload");if(o)e.preload=o;if(this.hasAttribute("controls"))e.controls=!0;e.playsinline=this.getAttribute("playsinline")!=="false";let l=this.getAttribute("crossorigin");if(l!==null)e.crossorigin=l;let d=this.getAttribute("controlslist");if(d)e.controlsList=d.split(/\s+/);return e.disablePictureInPicture=this.hasAttribute("disable-picture-in-picture"),e}readSourceConfig(){let e=this.querySelector('script[type="application/json"][data-media-config]'),t=this.getAttribute("data-media-config")?.trim()||e?.textContent?.trim();if(!t)return{};if(t.length>65536)throw TypeError("Media player configuration is too large");try{let i=JSON.parse(t);if(i.sources!==void 0&&(!Array.isArray(i.sources)||i.sources.some((s)=>!s||typeof s!=="object"||typeof s.src!=="string")))throw TypeError("Media player sources are invalid");let n=new Set(["subtitles","captions","descriptions","chapters","metadata"]);if(i.tracks!==void 0&&(!Array.isArray(i.tracks)||i.tracks.some((s)=>!s||typeof s!=="object"||typeof s.src!=="string"||!n.has(String(s.kind)))))throw TypeError("Media player tracks are invalid");return{sources:i.sources,drm:i.drm,tracks:i.tracks}}catch(i){if(i instanceof TypeError)throw i;throw TypeError("Media player configuration is invalid JSON")}}forwardEvents(){if(!this._player)return;let e=["play","pause","playing","waiting","ended","timeupdate","durationchange","volumechange","fullscreenchange","pipchange","error","loadstart","loadeddata","loadedmetadata","canplay","canplaythrough","seeking","seeked","ratechange","qualitychange","statechange","availabilitychange"];for(let t of e)this._player.on(t,(...i)=>{this.dispatchEvent(new CustomEvent(t,{detail:i.length===1?i[0]:i,bubbles:!0,composed:!0}))})}}function w(e,t=0){if(!isFinite(e)||isNaN(e))return"0:00";let i=Math.floor(e),n=Math.floor(i/3600),s=Math.floor(i%3600/60),r=i%60;if(n>0||t>=3600)return`${n}:${s.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`;return`${s}:${r.toString().padStart(2,"0")}`}function A(e){if(!isFinite(e)||isNaN(e))return"0 seconds";let t=Math.floor(e),i=Math.floor(t/3600),n=Math.floor(t%3600/60),s=t%60,r=[];if(i>0)r.push(`${i} ${i===1?"hour":"hours"}`);if(n>0)r.push(`${n} ${n===1?"minute":"minutes"}`);if(s>0||r.length===0)r.push(`${s} ${s===1?"second":"seconds"}`);return r.join(", ")}function Ve(e){if(!isFinite(e)||isNaN(e))return"PT0S";let t=Math.floor(e),i=Math.floor(t/3600),n=Math.floor(t%3600/60),s=t%60,r="PT";if(i>0)r+=`${i}H`;if(n>0)r+=`${n}M`;if(s>0||r==="PT")r+=`${s}S`;return r}function h(e){let t=e.getAttribute("for");if(t)return document.getElementById(t)?.player??null;return e.closest("video-player")?.player??null}class G extends p{_cleanups=[];connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
682
+ `,document.head.appendChild(a)}let r=`tsvp-watermark-${t.type}`;e.style.animation=`${r} ${i}ms ease ${n}ms ${s}`}addDynamic(e,t,i={}){let n=()=>{let o=[];if(t.userId)o.push(t.userId);if(t.showTimestamp)o.push(new Date().toISOString());if(t.customText)o.push(t.customText);return o.join(" | ")},s=["top-left","top-right","bottom-left","bottom-right","center-left","center-right"],r=i.position||"bottom-right",a=this.add(e,{...i,text:n(),position:r,opacity:i.opacity??0.3});if(t.updateInterval&&t.updateInterval>0){let o=setInterval(()=>{let d=a.querySelector("span");if(d)d.textContent=n()},t.updateInterval);this.dynamicTimers.set(`${e}-text`,o)}if(t.randomizePosition&&t.moveInterval&&t.moveInterval>0){let o=setInterval(()=>{let d=Math.floor(Math.random()*s.length);r=s[d];let c=this.getPositionStyles(r,i.offset);a.style.cssText=a.style.cssText.replace(/top:.*?;|bottom:.*?;|left:.*?;|right:.*?;|transform:.*?;/g,""),a.style.cssText+=c},t.moveInterval);this.dynamicTimers.set(`${e}-move`,o)}return a}remove(e){let t=this.elements.get(e);if(t)t.remove(),this.elements.delete(e);let i=this.dynamicTimers.get(`${e}-text`);if(i)clearInterval(i),this.dynamicTimers.delete(`${e}-text`);let n=this.dynamicTimers.get(`${e}-move`);if(n)clearInterval(n),this.dynamicTimers.delete(`${e}-move`)}removeAll(){for(let e of this.elements.keys())this.remove(e)}update(e,t){let i=this.elements.get(e);if(!i)return;if(t.opacity!==void 0)i.style.opacity=String(t.opacity);if(t.position){let n=this.getPositionStyles(t.position,t.offset);i.style.cssText=i.style.cssText.replace(/top:.*?;|bottom:.*?;|left:.*?;|right:.*?;|transform:.*?;/g,""),i.style.cssText+=n}if(t.text){let n=i.querySelector("span");if(n)n.textContent=t.text}if(t.image){let n=i.querySelector("img");if(n)n.src=t.image}}show(e){let t=this.elements.get(e);if(t)t.style.display=""}hide(e){let t=this.elements.get(e);if(t)t.style.display="none"}showAll(){for(let e of this.elements.keys())this.show(e)}hideAll(){for(let e of this.elements.keys())this.hide(e)}get(e){return this.elements.get(e)}getAll(){return Array.from(this.elements.keys())}destroy(){this.removeAll(),this.unsubscribers.forEach((e)=>e()),this.player=null,this.container=null}}function St(){return new O}function Fe(e){return{name:"watermark",install(t,i){let n=St();n.attach(t,i);for(let{id:s,...r}of e)n.add(s,r);return t.watermark=n,()=>{n.destroy(),delete t.watermark}}}}var h=globalThis.HTMLElement??class{};var bi=["src","poster","autoplay","loop","muted","controls","volume","playback-rate","preload","playsinline","crossorigin","controlslist","disable-picture-in-picture"];class G extends h{_player=null;_container=null;_disconnectId=0;static get observedAttributes(){return[...bi]}get player(){return this._player}connectedCallback(){if(this._disconnectId++,this._player)return;let e=this.shadowRoot??this.attachShadow({mode:"open",delegatesFocus:!0});this._container=document.createElement("div"),this._container.setAttribute("part","container"),this._container.style.cssText="position:relative;width:100%;height:100%;";let t=document.createElement("slot");this._container.appendChild(t),e.appendChild(this._container);let i=this.buildOptions();this._player=new _(this._container,i),this.forwardEvents()}disconnectedCallback(){if(this.hasAttribute("keep-alive"))return;let e=++this._disconnectId;queueMicrotask(()=>{if(this.isConnected||e!==this._disconnectId)return;this._player?.destroy(),this._player=null,this._container=null,this.shadowRoot?.replaceChildren()})}attributeChangedCallback(e,t,i){if(!this._player)return;switch(e){case"src":if(i)this._player.setSrc(i);break;case"poster":this._player.setPoster(i||"");break;case"muted":this._player.setMuted(i!==null);break;case"volume":if(i!==null)this._player.setVolume(parseFloat(i));break;case"playback-rate":if(i!==null)this._player.setPlaybackRate(parseFloat(i));break}}buildOptions(){let e={},t=this.readSourceConfig();if(t.sources?.length)e.src=t.sources;if(t.tracks?.length)e.tracks=t.tracks;let i=this.getAttribute("src");if(i&&!e.src)e.src=t.drm?{src:i,type:"application/dash+xml",drm:t.drm}:i;let n=this.getAttribute("poster");if(n)e.poster=n;let s=this.getAttribute("title");if(s)e.title=s;if(this.hasAttribute("autoplay"))e.autoplay=!0;if(this.hasAttribute("loop"))e.loop=!0;if(this.hasAttribute("muted"))e.muted=!0;let r=this.getAttribute("volume");if(r)e.volume=parseFloat(r);let a=this.getAttribute("playback-rate");if(a)e.playbackRate=parseFloat(a);let o=this.getAttribute("preload");if(o)e.preload=o;if(this.hasAttribute("controls"))e.controls=!0;e.playsinline=this.getAttribute("playsinline")!=="false";let d=this.getAttribute("crossorigin");if(d!==null)e.crossorigin=d;let c=this.getAttribute("controlslist");if(c)e.controlsList=c.split(/\s+/);return e.disablePictureInPicture=this.hasAttribute("disable-picture-in-picture"),e}readSourceConfig(){let e=this.querySelector('script[type="application/json"][data-media-config]'),t=this.getAttribute("data-media-config")?.trim()||e?.textContent?.trim();if(!t)return{};if(t.length>65536)throw TypeError("Media player configuration is too large");try{let i=JSON.parse(t);if(i.sources!==void 0&&(!Array.isArray(i.sources)||i.sources.some((s)=>!s||typeof s!=="object"||typeof s.src!=="string")))throw TypeError("Media player sources are invalid");let n=new Set(["subtitles","captions","descriptions","chapters","metadata"]);if(i.tracks!==void 0&&(!Array.isArray(i.tracks)||i.tracks.some((s)=>!s||typeof s!=="object"||typeof s.src!=="string"||!n.has(String(s.kind)))))throw TypeError("Media player tracks are invalid");return{sources:i.sources,drm:i.drm,tracks:i.tracks}}catch(i){if(i instanceof TypeError)throw i;throw TypeError("Media player configuration is invalid JSON")}}forwardEvents(){if(!this._player)return;let e=["play","pause","playing","waiting","ended","timeupdate","durationchange","volumechange","fullscreenchange","pipchange","error","loadstart","loadeddata","loadedmetadata","canplay","canplaythrough","seeking","seeked","ratechange","qualitychange","statechange","availabilitychange"];for(let t of e)this._player.on(t,(...i)=>{this.dispatchEvent(new CustomEvent(t,{detail:i.length===1?i[0]:i,bubbles:!0,composed:!0}))})}}class J extends h{_cleanups=[];connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
683
683
  <style>
684
684
  :host {
685
685
  display: flex;
@@ -758,7 +758,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
758
758
  <slot name="right"></slot>
759
759
  <slot></slot>
760
760
  </div>
761
- `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanups.forEach((e)=>e()),this._cleanups=[]}attach(){let e=h(this);if(!e)return;let t=e.subscribe((s)=>{if(s.controlsVisible)this.removeAttribute("controls-hidden");else this.setAttribute("controls-hidden","");this.dataset.fullscreen=s.fullscreenAvailability,this.dataset.pip=s.pipAvailability,this.dataset.volume=s.volumeAvailability,this.dataset.captions=String(s.textTracks.length>0),this.dataset.qualities=String(s.qualities.length>0)}),i=this.shadowRoot.querySelector(".overlay"),n=()=>e.togglePlay();i.addEventListener("click",n),this._cleanups.push(t,()=>i.removeEventListener("click",n))}}var wt="M8 5v14l11-7z",fi="M6 19h4V5H6v14zm8-14v14h4V5h-4z";class J extends p{_cleanup=null;_onClick=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
761
+ `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanups.forEach((e)=>e()),this._cleanups=[]}attach(){let e=m(this);if(!e)return;let t=e.subscribe((s)=>{if(s.controlsVisible)this.removeAttribute("controls-hidden");else this.setAttribute("controls-hidden","");this.dataset.fullscreen=s.fullscreenAvailability,this.dataset.pip=s.pipAvailability,this.dataset.volume=s.volumeAvailability,this.dataset.captions=String(s.textTracks.length>0),this.dataset.qualities=String(s.qualities.length>0)}),i=this.shadowRoot.querySelector(".overlay"),n=()=>e.togglePlay();i.addEventListener("click",n),this._cleanups.push(t,()=>i.removeEventListener("click",n))}}var Et="M8 5v14l11-7z",ki="M6 19h4V5H6v14zm8-14v14h4V5h-4z";class Z extends h{_cleanup=null;_onClick=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
762
762
  <style>
763
763
  :host { display: inline-flex; }
764
764
  button {
@@ -767,13 +767,15 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
767
767
  background: transparent; border: none; color: inherit; cursor: pointer;
768
768
  }
769
769
  button:hover { opacity: 0.8; }
770
+ /* 44px, the smallest a finger hits reliably, on a touch screen. */
771
+ @media (pointer: coarse) { button { min-width: 44px; min-height: 44px; } }
770
772
  </style>
771
- <button part="button" type="button" aria-label="Play">
773
+ <button part="button" type="button" aria-label="${l(this,"play")}">
772
774
  <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" part="icon">
773
- <path d="${wt}"/>
775
+ <path d="${Et}"/>
774
776
  </svg>
775
777
  </button>
776
- `}queueMicrotask(()=>this.attach())}disconnectedCallback(){let e=this.shadowRoot?.querySelector("button");if(e&&this._onClick)e.removeEventListener("click",this._onClick);this._cleanup?.(),this._cleanup=null,this._onClick=null}attach(){let e=h(this);if(!e)return;let t=this.shadowRoot.querySelector("button");this._onClick=()=>e.togglePlay(),t.addEventListener("click",this._onClick);let i=e.subscribe("paused",(n)=>{let s=n.paused;t.setAttribute("aria-label",s?"Play":"Pause"),t.setAttribute("aria-pressed",String(!s)),this.shadowRoot.querySelector("path").setAttribute("d",s?wt:fi)});this._cleanup=i}}var bi="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51A8.796 8.796 0 0 0 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3 3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06a8.99 8.99 0 0 0 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4 9.91 6.09 12 8.18V4z",ki="M18.5 12A4.5 4.5 0 0 0 16 7.97v8.05c1.48-.73 2.5-2.25 2.5-4.02zM5 9v6h4l5 5V4L9 9H5z",xt="M3 9v6h4l5 5V4L7 9H3zm13.5 3A4.5 4.5 0 0 0 14 7.97v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z";function Ti(e,t){if(e||t===0)return bi;if(t<0.5)return ki;return xt}class Z extends p{_cleanup=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
778
+ `}queueMicrotask(()=>this.attach())}disconnectedCallback(){let e=this.shadowRoot?.querySelector("button");if(e&&this._onClick)e.removeEventListener("click",this._onClick);this._cleanup?.(),this._cleanup=null,this._onClick=null}attach(){let e=m(this);if(!e)return;let t=this.shadowRoot.querySelector("button");this._onClick=()=>e.togglePlay(),t.addEventListener("click",this._onClick);let i=e.subscribe("paused",(n)=>{let s=n.paused;t.setAttribute("aria-label",l(this,s?"play":"pause")),t.setAttribute("aria-pressed",String(!s)),this.shadowRoot.querySelector("path").setAttribute("d",s?Et:ki)});this._cleanup=i}}var Ti="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51A8.796 8.796 0 0 0 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3 3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06a8.99 8.99 0 0 0 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4 9.91 6.09 12 8.18V4z",wi="M18.5 12A4.5 4.5 0 0 0 16 7.97v8.05c1.48-.73 2.5-2.25 2.5-4.02zM5 9v6h4l5 5V4L9 9H5z",Pt="M3 9v6h4l5 5V4L7 9H3zm13.5 3A4.5 4.5 0 0 0 14 7.97v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z";function xi(e,t){if(e||t===0)return Ti;if(t<0.5)return wi;return Pt}class ee extends h{_cleanup=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
777
779
  <style>
778
780
  :host { display: inline-flex; }
779
781
  button {
@@ -782,13 +784,15 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
782
784
  background: transparent; border: none; color: inherit; cursor: pointer;
783
785
  }
784
786
  button:hover { opacity: 0.8; }
787
+ /* 44px, the smallest a finger hits reliably, on a touch screen. */
788
+ @media (pointer: coarse) { button { min-width: 44px; min-height: 44px; } }
785
789
  </style>
786
- <button part="button" type="button" aria-label="Mute">
790
+ <button part="button" type="button" aria-label="${l(this,"mute")}">
787
791
  <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" part="icon">
788
- <path d="${xt}"/>
792
+ <path d="${Pt}"/>
789
793
  </svg>
790
794
  </button>
791
- `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanup?.(),this._cleanup=null}attach(){let e=h(this);if(!e)return;let t=this.shadowRoot.querySelector("button");t.addEventListener("click",()=>e.toggleMute());let i=e.subscribe((n)=>{let s=Ti(n.muted,n.volume);t.setAttribute("aria-label",n.muted?"Unmute":"Mute"),this.shadowRoot.querySelector("path").setAttribute("d",s)});this._cleanup=i}}var St="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z",wi="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z";class ee extends p{_cleanup=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
795
+ `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanup?.(),this._cleanup=null}attach(){let e=m(this);if(!e)return;let t=this.shadowRoot.querySelector("button");t.addEventListener("click",()=>e.toggleMute());let i=e.subscribe((n)=>{let s=xi(n.muted,n.volume);t.setAttribute("aria-label",l(this,n.muted?"unmute":"mute")),this.shadowRoot.querySelector("path").setAttribute("d",s)});this._cleanup=i}}var At="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z",Si="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z";class te extends h{_cleanup=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
792
796
  <style>
793
797
  :host { display: inline-flex; }
794
798
  :host([hidden]) { display: none; }
@@ -799,13 +803,15 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
799
803
  }
800
804
  button:hover { opacity: 0.8; }
801
805
  button:disabled { opacity: 0.4; cursor: not-allowed; }
806
+ /* 44px, the smallest a finger hits reliably, on a touch screen. */
807
+ @media (pointer: coarse) { button { min-width: 44px; min-height: 44px; } }
802
808
  </style>
803
- <button part="button" type="button" aria-label="Enter fullscreen">
809
+ <button part="button" type="button" aria-label="${l(this,"enterFullscreen")}">
804
810
  <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" part="icon">
805
- <path d="${St}"/>
811
+ <path d="${At}"/>
806
812
  </svg>
807
813
  </button>
808
- `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanup?.(),this._cleanup=null}attach(){let e=h(this);if(!e)return;let t=this.shadowRoot.querySelector("button");t.addEventListener("click",()=>e.toggleFullscreen());let i=e.subscribe((n)=>{let s=n.fullscreenAvailability;if(s==="unsupported")this.setAttribute("hidden","");else this.removeAttribute("hidden");t.disabled=s!=="available";let r=n.fullscreen;t.setAttribute("aria-label",r?"Exit fullscreen":"Enter fullscreen"),this.shadowRoot.querySelector("path").setAttribute("d",r?wi:St)});this._cleanup=i}}var xi="M19 7h-8v6h8V7zm2-4H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14z";class te extends p{_cleanup=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
814
+ `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanup?.(),this._cleanup=null}attach(){let e=m(this);if(!e)return;let t=this.shadowRoot.querySelector("button");t.addEventListener("click",()=>e.toggleFullscreen());let i=e.subscribe((n)=>{let s=n.fullscreenAvailability;if(s==="unsupported")this.setAttribute("hidden","");else this.removeAttribute("hidden");t.disabled=s!=="available";let r=n.fullscreen;t.setAttribute("aria-label",l(this,r?"exitFullscreen":"enterFullscreen")),this.shadowRoot.querySelector("path").setAttribute("d",r?Si:At)});this._cleanup=i}}var Ei="M19 7h-8v6h8V7zm2-4H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14z";class ie extends h{_cleanup=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
809
815
  <style>
810
816
  :host { display: inline-flex; }
811
817
  :host([hidden]) { display: none; }
@@ -816,13 +822,15 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
816
822
  }
817
823
  button:hover { opacity: 0.8; }
818
824
  button:disabled { opacity: 0.4; cursor: not-allowed; }
825
+ /* 44px, the smallest a finger hits reliably, on a touch screen. */
826
+ @media (pointer: coarse) { button { min-width: 44px; min-height: 44px; } }
819
827
  </style>
820
- <button part="button" type="button" aria-label="Picture in picture">
828
+ <button part="button" type="button" aria-label="${l(this,"enterPiP")}">
821
829
  <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" part="icon">
822
- <path d="${xi}"/>
830
+ <path d="${Ei}"/>
823
831
  </svg>
824
832
  </button>
825
- `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanup?.(),this._cleanup=null}attach(){let e=h(this);if(!e)return;let t=this.shadowRoot.querySelector("button");t.addEventListener("click",()=>e.togglePiP());let i=e.subscribe((n)=>{let s=n.pipAvailability;if(s==="unsupported")this.setAttribute("hidden","");else this.removeAttribute("hidden");t.disabled=s!=="available"});this._cleanup=i}}class ie extends p{_cleanup=null;_showRemaining=!1;static get observedAttributes(){return["type"]}get type(){return this.getAttribute("type")||"current"}connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
833
+ `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanup?.(),this._cleanup=null}attach(){let e=m(this);if(!e)return;let t=this.shadowRoot.querySelector("button");t.addEventListener("click",()=>e.togglePiP());let i=e.subscribe((n)=>{let s=n.pipAvailability;if(s==="unsupported")this.setAttribute("hidden","");else this.removeAttribute("hidden");t.disabled=s!=="available",t.setAttribute("aria-label",l(this,n.pictureInPicture?"exitPiP":"enterPiP"))});this._cleanup=i}}class ne extends h{_cleanup=null;_showRemaining=!1;static get observedAttributes(){return["type"]}get type(){return this.getAttribute("type")||"current"}connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
826
834
  <style>
827
835
  :host {
828
836
  display: inline-flex;
@@ -835,8 +843,8 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
835
843
  time { color: inherit; }
836
844
  .separator { margin: 0 2px; }
837
845
  </style>
838
- <time part="time" datetime="PT0S" aria-valuetext="0 seconds">0:00</time>
839
- `}this.addEventListener("click",this.handleClick),queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanup?.(),this._cleanup=null,this.removeEventListener("click",this.handleClick)}handleClick=()=>{if(this.type==="duration"){this._showRemaining=!this._showRemaining;let e=h(this);if(e)this.render(e.state)}};attach(){let e=h(this);if(!e)return;let t=e.subscribe((i)=>{this.render(i)});this._cleanup=t}render(e){let t=this.shadowRoot?.querySelector("time");if(!t)return;let i=this.type,n;if(i==="remaining"||i==="duration"&&this._showRemaining){n=Math.max(e.duration-e.currentTime,0);let s=`-${w(n,e.duration)}`;t.textContent=s}else if(i==="duration")n=e.duration,t.textContent=w(n);else n=e.currentTime,t.textContent=w(n,e.duration);t.setAttribute("datetime",Ve(n)),t.setAttribute("aria-valuetext",A(n))}}class ne extends p{connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
846
+ <time part="time" datetime="PT0S" aria-valuetext="${P(0,this)}">0:00</time>
847
+ `}this.addEventListener("click",this.handleClick),queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanup?.(),this._cleanup=null,this.removeEventListener("click",this.handleClick)}handleClick=()=>{if(this.type==="duration"){this._showRemaining=!this._showRemaining;let e=m(this);if(e)this.render(e.state)}};attach(){let e=m(this);if(!e)return;let t=e.subscribe((i)=>{this.render(i)});this._cleanup=t}render(e){let t=this.shadowRoot?.querySelector("time");if(!t)return;let i=this.type,n;if(i==="remaining"||i==="duration"&&this._showRemaining){n=Math.max(e.duration-e.currentTime,0);let s=`-${x(n,e.duration)}`;t.textContent=s}else if(i==="duration")n=e.duration,t.textContent=x(n);else n=e.currentTime,t.textContent=x(n,e.duration);t.setAttribute("datetime",Me(n)),t.setAttribute("aria-valuetext",P(n,this))}}class se extends h{connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
840
848
  <style>
841
849
  :host {
842
850
  display: inline-flex;
@@ -849,7 +857,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
849
857
  }
850
858
  </style>
851
859
  <slot></slot>
852
- `}}}class se extends p{connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
860
+ `}}}class re extends h{connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
853
861
  <style>
854
862
  :host {
855
863
  display: inline-flex;
@@ -862,7 +870,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
862
870
  }
863
871
  </style>
864
872
  <span aria-hidden="true" part="separator"><slot>/</slot></span>
865
- `}this.setAttribute("role","separator"),this.setAttribute("aria-hidden","true")}}class re extends p{_cleanups=[];connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
873
+ `}this.setAttribute("role","separator"),this.setAttribute("aria-hidden","true")}}class ae extends h{_cleanups=[];connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
866
874
  <style>
867
875
  :host {
868
876
  display: inline-block;
@@ -874,7 +882,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
874
882
  }
875
883
  </style>
876
884
  <span part="value">0:00</span>
877
- `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanups.forEach((e)=>e()),this._cleanups=[]}attach(){let e=h(this);if(!e)return;let t=this.closest("media-progress-bar")||this.parentElement?.querySelector("media-progress-bar");if(t){let i=(n)=>{let s=n,a=(t.shadowRoot?.querySelector(".track")||t).getBoundingClientRect(),l=Math.max(0,Math.min(1,(s.clientX-a.left)/a.width))*(e.state.duration||0);this.updateTime(l,e.state.duration)};t.addEventListener("pointermove",i),this._cleanups.push(()=>t.removeEventListener("pointermove",i))}}updateTime(e,t){let i=this.shadowRoot?.querySelector("span");if(i)i.textContent=w(e,t)}}class ae extends p{_cleanups=[];_isDragging=!1;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
885
+ `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanups.forEach((e)=>e()),this._cleanups=[]}attach(){let e=m(this);if(!e)return;let t=this.closest("media-progress-bar")||this.parentElement?.querySelector("media-progress-bar");if(t){let i=(n)=>{let s=n,a=(t.shadowRoot?.querySelector(".track")||t).getBoundingClientRect(),d=Math.max(0,Math.min(1,(s.clientX-a.left)/a.width))*(e.state.duration||0);this.updateTime(d,e.state.duration)};t.addEventListener("pointermove",i),this._cleanups.push(()=>t.removeEventListener("pointermove",i))}}updateTime(e,t){let i=this.shadowRoot?.querySelector("span");if(i)i.textContent=x(e,t)}}class oe extends h{_cleanups=[];_isDragging=!1;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
878
886
  <style>
879
887
  :host { display: flex; flex: 1; align-items: center; }
880
888
  .container {
@@ -922,10 +930,12 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
922
930
  border-top-color: rgba(0,0,0,0.85);
923
931
  }
924
932
  .container:hover .tooltip { opacity: 1; }
933
+ /* A finger needs more than the 20px a mouse does. */
934
+ @media (pointer: coarse) { .container { height: 36px; } .thumb { width: 18px; height: 18px; } }
925
935
  </style>
926
936
  <div class="container" part="container" role="slider"
927
937
  aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"
928
- aria-label="Seek" tabindex="0">
938
+ aria-label="${l(this,"seek")}" tabindex="0">
929
939
  <div class="tooltip" part="tooltip">0:00</div>
930
940
  <div class="track" part="track">
931
941
  <div class="waveform" part="waveform" aria-hidden="true"></div>
@@ -934,7 +944,7 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
934
944
  <div class="thumb" part="thumb"></div>
935
945
  </div>
936
946
  </div>
937
- `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanups.forEach((e)=>e()),this._cleanups=[]}attach(){let e=h(this);if(!e)return;let t=this.shadowRoot.querySelector(".container"),i=this.shadowRoot.querySelector(".track"),n=this.shadowRoot.querySelector(".fill"),s=this.shadowRoot.querySelector(".thumb"),r=this.shadowRoot.querySelector(".buffered"),a=this.shadowRoot.querySelector(".tooltip"),o=this.getAttribute("waveform");if(o){let m=new URL(o,document.baseURI);if(["http:","https:","blob:"].includes(m.protocol)||m.href.startsWith("data:image/")){let f=this.shadowRoot.querySelector(".waveform");f.style.backgroundImage=`url(${JSON.stringify(m.href)})`}}let l=(m)=>{let f=i.getBoundingClientRect(),x=Math.max(0,Math.min(1,(m.clientX-f.left)/f.width))*(e.state.duration||0);a.textContent=w(x,e.state.duration);let q=t.getBoundingClientRect(),O=a.offsetWidth,Pt=m.clientX-q.left,At=O/2,_t=q.width-O/2,Mt=Math.max(At,Math.min(_t,Pt));a.style.left=`${Mt}px`},d=(m)=>{let f=i.getBoundingClientRect(),x=Math.max(0,Math.min(1,(m.clientX-f.left)/f.width))*(e.state.duration||0);e.seekTo(x)},c=(m)=>{this._isDragging=!0,t.setPointerCapture(m.pointerId),d(m)},u=(m)=>{if(l(m),!this._isDragging)return;d(m)},v=(m)=>{if(!this._isDragging)return;this._isDragging=!1,t.releasePointerCapture(m.pointerId)},g=(m)=>{let y=e.state.currentTime;switch(m.key){case"ArrowRight":y=Math.min(e.state.duration,y+5);break;case"ArrowLeft":y=Math.max(0,y-5);break;case"Home":y=0;break;case"End":y=e.state.duration;break;default:return}m.preventDefault(),e.seekTo(y)};t.addEventListener("pointerdown",c),t.addEventListener("pointermove",u),t.addEventListener("pointerup",v),t.addEventListener("keydown",g),this._cleanups.push(()=>t.removeEventListener("pointerdown",c),()=>t.removeEventListener("pointermove",u),()=>t.removeEventListener("pointerup",v),()=>t.removeEventListener("keydown",g));let k=e.subscribe((m)=>{if(this._isDragging)return;let f=m.duration||0,y=f>0?m.currentTime/f*100:0;n.style.width=`${y}%`,s.style.left=`${y}%`,t.setAttribute("aria-valuenow",String(Math.round(y))),t.setAttribute("aria-valuetext",`${A(m.currentTime)} of ${A(f)}`);let x=(m.bufferedAmount||0)*100;r.style.width=`${x}%`});this._cleanups.push(k)}}class oe extends p{_cleanups=[];_isDragging=!1;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
947
+ `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanups.forEach((e)=>e()),this._cleanups=[]}attach(){let e=m(this);if(!e)return;let t=this.shadowRoot.querySelector(".container"),i=this.shadowRoot.querySelector(".track"),n=this.shadowRoot.querySelector(".fill"),s=this.shadowRoot.querySelector(".thumb"),r=this.shadowRoot.querySelector(".buffered"),a=this.shadowRoot.querySelector(".tooltip"),o=this.getAttribute("waveform");if(o){let v=new URL(o,document.baseURI);if(["http:","https:","blob:"].includes(v.protocol)||v.href.startsWith("data:image/")){let b=this.shadowRoot.querySelector(".waveform");b.style.backgroundImage=`url(${JSON.stringify(v.href)})`}}let d=(v)=>{let b=i.getBoundingClientRect(),S=Math.max(0,Math.min(1,(v.clientX-b.left)/b.width))*(e.state.duration||0);a.textContent=x(S,e.state.duration);let q=t.getBoundingClientRect(),N=a.offsetWidth,Lt=v.clientX-q.left,Mt=N/2,Ct=q.width-N/2,Rt=Math.max(Mt,Math.min(Ct,Lt));a.style.left=`${Rt}px`},c=(v)=>{let b=i.getBoundingClientRect(),S=Math.max(0,Math.min(1,(v.clientX-b.left)/b.width))*(e.state.duration||0);e.seekTo(S)},u=(v)=>{this._isDragging=!0,t.setPointerCapture(v.pointerId),c(v)},p=(v)=>{if(d(v),!this._isDragging)return;c(v)},g=(v)=>{if(!this._isDragging)return;this._isDragging=!1,t.releasePointerCapture(v.pointerId)},y=(v)=>{let f=e.state.currentTime;switch(v.key){case"ArrowRight":f=Math.min(e.state.duration,f+5);break;case"ArrowLeft":f=Math.max(0,f-5);break;case"Home":f=0;break;case"End":f=e.state.duration;break;default:return}v.preventDefault(),e.seekTo(f)};t.addEventListener("pointerdown",u),t.addEventListener("pointermove",p),t.addEventListener("pointerup",g),t.addEventListener("keydown",y),this._cleanups.push(()=>t.removeEventListener("pointerdown",u),()=>t.removeEventListener("pointermove",p),()=>t.removeEventListener("pointerup",g),()=>t.removeEventListener("keydown",y));let T=e.subscribe((v)=>{if(this._isDragging)return;let b=v.duration||0,f=b>0?v.currentTime/b*100:0;n.style.width=`${f}%`,s.style.left=`${f}%`,t.setAttribute("aria-valuenow",String(Math.round(f))),t.setAttribute("aria-valuetext",l(this,"timeOf",{current:P(v.currentTime,this),duration:P(b,this)}));let S=(v.bufferedAmount||0)*100;r.style.width=`${S}%`});this._cleanups.push(T)}}class le extends h{_cleanups=[];_isDragging=!1;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
938
948
  <style>
939
949
  :host { display: inline-flex; align-items: center; width: 80px; }
940
950
  :host([hidden]) { display: none; }
@@ -959,16 +969,18 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
959
969
  transition: transform 0.1s;
960
970
  }
961
971
  .container:hover .thumb { transform: translate(-50%, -50%) scale(1.2); }
972
+ /* A finger needs more than the 20px a mouse does. */
973
+ @media (pointer: coarse) { .container { height: 36px; } .thumb { width: 18px; height: 18px; } }
962
974
  </style>
963
975
  <div class="container" part="container" role="slider"
964
976
  aria-valuemin="0" aria-valuemax="100" aria-valuenow="100"
965
- aria-label="Volume" tabindex="0">
977
+ aria-label="${l(this,"volume")}" tabindex="0">
966
978
  <div class="track" part="track">
967
979
  <div class="fill" part="fill"></div>
968
980
  <div class="thumb" part="thumb"></div>
969
981
  </div>
970
982
  </div>
971
- `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanups.forEach((e)=>e()),this._cleanups=[]}attach(){let e=h(this);if(!e)return;let t=this.shadowRoot.querySelector(".container"),i=this.shadowRoot.querySelector(".track"),n=this.shadowRoot.querySelector(".fill"),s=this.shadowRoot.querySelector(".thumb"),r=(u)=>{let v=i.getBoundingClientRect(),g=Math.max(0,Math.min(1,(u.clientX-v.left)/v.width));if(e.setVolume(g),g>0&&e.state.muted)e.setMuted(!1)},a=(u)=>{this._isDragging=!0,t.setPointerCapture(u.pointerId),r(u)},o=(u)=>{if(!this._isDragging)return;r(u)},l=(u)=>{if(!this._isDragging)return;this._isDragging=!1,t.releasePointerCapture(u.pointerId)},d=(u)=>{let v=e.state.volume,g=0.05;switch(u.key){case"ArrowRight":case"ArrowUp":v=Math.min(1,v+g);break;case"ArrowLeft":case"ArrowDown":v=Math.max(0,v-g);break;default:return}u.preventDefault(),e.setVolume(v)};t.addEventListener("pointerdown",a),t.addEventListener("pointermove",o),t.addEventListener("pointerup",l),t.addEventListener("keydown",d),this._cleanups.push(()=>t.removeEventListener("pointerdown",a),()=>t.removeEventListener("pointermove",o),()=>t.removeEventListener("pointerup",l),()=>t.removeEventListener("keydown",d));let c=e.subscribe((u)=>{if(u.volumeAvailability==="unsupported"){this.setAttribute("hidden","");return}this.removeAttribute("hidden");let g=(u.muted?0:u.volume)*100;n.style.width=`${g}%`,s.style.left=`${g}%`,t.setAttribute("aria-valuenow",String(Math.round(g)))});this._cleanups.push(c)}}function Et(e,t,i={}){let{placement:n="top",offset:s=4,boundary:r=null,padding:a=8}=i,o=e.getBoundingClientRect(),l=t.getBoundingClientRect(),d=r?r.getBoundingClientRect():{top:0,left:0,bottom:window.innerHeight,right:window.innerWidth,width:window.innerWidth,height:window.innerHeight},c=o.top-d.top-a,u=d.bottom-o.bottom-a,v;if(n.startsWith("top"))v=l.height+s<=c?"top":"bottom";else v=l.height+s<=u?"bottom":"top";let g;if(v==="top")g=o.top-l.height-s;else g=o.bottom+s;let k="";if(n.endsWith("-start"))k="-start";else if(n.endsWith("-end"))k="-end";let m;switch(k){case"-start":m=o.left;break;case"-end":m=o.right-l.width;break;default:m=o.left+(o.width-l.width)/2;break}let f=d.left+a,y=d.right-l.width-a;m=Math.max(f,Math.min(y,m));let x=d.top+a,q=d.bottom-l.height-a;g=Math.max(x,Math.min(q,g));let O=`${v}${k}`;return{top:g,left:m,placement:O}}var Si="M19.14 12.94c.04-.31.06-.63.06-.94 0-.31-.02-.63-.06-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.488.488 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 0 0-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.04.31-.06.63-.06.94s.02.63.06.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z",Ei=[0.25,0.5,0.75,1,1.25,1.5,1.75,2];class le extends p{_cleanup=null;_isOpen=!1;_currentPanel="main";connectedCallback(){if(!this.shadowRoot){let t=this.attachShadow({mode:"open"});t.innerHTML=`
983
+ `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this._cleanups.forEach((e)=>e()),this._cleanups=[]}attach(){let e=m(this);if(!e)return;let t=this.shadowRoot.querySelector(".container"),i=this.shadowRoot.querySelector(".track"),n=this.shadowRoot.querySelector(".fill"),s=this.shadowRoot.querySelector(".thumb"),r=(p)=>{let g=i.getBoundingClientRect(),y=Math.max(0,Math.min(1,(p.clientX-g.left)/g.width));if(e.setVolume(y),y>0&&e.state.muted)e.setMuted(!1)},a=(p)=>{this._isDragging=!0,t.setPointerCapture(p.pointerId),r(p)},o=(p)=>{if(!this._isDragging)return;r(p)},d=(p)=>{if(!this._isDragging)return;this._isDragging=!1,t.releasePointerCapture(p.pointerId)},c=(p)=>{let g=e.state.volume,y=0.05;switch(p.key){case"ArrowRight":case"ArrowUp":g=Math.min(1,g+y);break;case"ArrowLeft":case"ArrowDown":g=Math.max(0,g-y);break;default:return}p.preventDefault(),e.setVolume(g)};t.addEventListener("pointerdown",a),t.addEventListener("pointermove",o),t.addEventListener("pointerup",d),t.addEventListener("keydown",c),this._cleanups.push(()=>t.removeEventListener("pointerdown",a),()=>t.removeEventListener("pointermove",o),()=>t.removeEventListener("pointerup",d),()=>t.removeEventListener("keydown",c));let u=e.subscribe((p)=>{if(p.volumeAvailability==="unsupported"){this.setAttribute("hidden","");return}this.removeAttribute("hidden");let y=(p.muted?0:p.volume)*100;n.style.width=`${y}%`,s.style.left=`${y}%`,t.setAttribute("aria-valuenow",String(Math.round(y)))});this._cleanups.push(u)}}function _t(e,t,i={}){let{placement:n="top",offset:s=4,boundary:r=null,padding:a=8}=i,o=e.getBoundingClientRect(),d=t.getBoundingClientRect(),c=r?r.getBoundingClientRect():{top:0,left:0,bottom:window.innerHeight,right:window.innerWidth,width:window.innerWidth,height:window.innerHeight},u=o.top-c.top-a,p=c.bottom-o.bottom-a,g;if(n.startsWith("top"))g=d.height+s<=u?"top":"bottom";else g=d.height+s<=p?"bottom":"top";let y;if(g==="top")y=o.top-d.height-s;else y=o.bottom+s;let T="";if(n.endsWith("-start"))T="-start";else if(n.endsWith("-end"))T="-end";let v;switch(T){case"-start":v=o.left;break;case"-end":v=o.right-d.width;break;default:v=o.left+(o.width-d.width)/2;break}let b=c.left+a,f=c.right-d.width-a;v=Math.max(b,Math.min(f,v));let S=c.top+a,q=c.bottom-d.height-a;y=Math.max(S,Math.min(q,y));let N=`${g}${T}`;return{top:y,left:v,placement:N}}var Pi="M19.14 12.94c.04-.31.06-.63.06-.94 0-.31-.02-.63-.06-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.488.488 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 0 0-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.04.31-.06.63-.06.94s.02.63.06.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z",Ai=[0.25,0.5,0.75,1,1.25,1.5,1.75,2];class de extends h{_cleanup=null;_isOpen=!1;_currentPanel="main";connectedCallback(){if(!this.shadowRoot){let t=this.attachShadow({mode:"open"});t.innerHTML=`
972
984
  <style>
973
985
  :host { display: inline-flex; position: relative; }
974
986
  button.trigger {
@@ -998,67 +1010,79 @@ function Be(){return{src:null,sources:[],currentSourceIndex:0,mediaType:"unknown
998
1010
  .item[aria-checked="true"]::before { content: '\\2713'; }
999
1011
  .item[aria-checked="false"]::before { content: ''; min-width: 12px; display: inline-block; }
1000
1012
  .back { font-weight: bold; border-bottom: 1px solid rgba(255,255,255,0.2); }
1013
+ /* 44px, the smallest a finger hits reliably, on a touch screen. */
1014
+ @media (pointer: coarse) { button { min-width: 44px; min-height: 44px; } }
1001
1015
  </style>
1002
1016
  <button class="trigger" part="trigger" type="button"
1003
- aria-label="Settings" aria-haspopup="true" aria-expanded="false">
1017
+ aria-label="${l(this,"settings")}" aria-haspopup="true" aria-expanded="false">
1004
1018
  <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" part="icon">
1005
- <path d="${Si}"/>
1019
+ <path d="${Pi}"/>
1006
1020
  </svg>
1007
1021
  </button>
1008
1022
  <div class="menu" part="menu" role="menu" aria-hidden="true"></div>
1009
- `}let e=this.shadowRoot.querySelector(".trigger");this._onTriggerClick=()=>this.toggle(),e.addEventListener("click",this._onTriggerClick),this._onDocClick=(t)=>{if(this._isOpen&&!this.contains(t.target))this.close()},document.addEventListener("click",this._onDocClick),this._onDocKeydown=(t)=>{if(t.key==="Escape"&&this._isOpen)this.close()},document.addEventListener("keydown",this._onDocKeydown),queueMicrotask(()=>this.attach())}_onTriggerClick=null;_onDocClick=null;_onDocKeydown=null;disconnectedCallback(){if(this._cleanup?.(),this._cleanup=null,this._onTriggerClick)this.shadowRoot?.querySelector(".trigger")?.removeEventListener("click",this._onTriggerClick);if(this._onDocClick)document.removeEventListener("click",this._onDocClick);if(this._onDocKeydown)document.removeEventListener("keydown",this._onDocKeydown)}toggle(){if(this._isOpen)this.close();else this.open()}open(){this._isOpen=!0,this._currentPanel="main",this.setAttribute("open",""),this.shadowRoot.querySelector(".trigger").setAttribute("aria-expanded","true"),this.shadowRoot.querySelector(".menu").setAttribute("aria-hidden","false"),this.renderPanel(),this.positionMenu()}close(){this._isOpen=!1,this.removeAttribute("open"),this.shadowRoot.querySelector(".trigger").setAttribute("aria-expanded","false"),this.shadowRoot.querySelector(".menu").setAttribute("aria-hidden","true")}positionMenu(){let e=this.shadowRoot.querySelector(".trigger"),t=this.shadowRoot.querySelector(".menu");if(!e||!t)return;let i=this.closest("video-player, .ts-video-player"),n=Et(e,t,{placement:"top-end",offset:4,boundary:i,padding:8});t.style.top=`${n.top}px`,t.style.left=`${n.left}px`}attach(){let e=h(this);if(!e)return;let t=e.subscribe(()=>{if(this._isOpen)this.renderPanel()});this._cleanup=t}renderPanel(){let e=h(this);if(!e)return;let t=this.shadowRoot.querySelector(".menu");switch(t.innerHTML="",this._currentPanel){case"main":this.renderMain(t,e);break;case"speed":this.renderSpeed(t,e);break;case"quality":this.renderQuality(t,e);break;case"captions":this.renderCaptions(t,e);break;case"audio":this.renderAudio(t,e);break}if(this._isOpen)queueMicrotask(()=>this.positionMenu())}renderMain(e,t){let i=t.state;if(this.addItem(e,`Speed: ${i.playbackRate}x`,()=>{this._currentPanel="speed",this.renderPanel()}),i.qualities.length>0){let n=i.qualities.find((r)=>r.selected),s=i.autoQuality?"Auto":n?`${n.height}p`:"Auto";this.addItem(e,`Quality: ${s}`,()=>{this._currentPanel="quality",this.renderPanel()})}if(i.textTracks.length>0){let n=i.textTracks.find((s)=>s.mode==="showing");this.addItem(e,`Captions: ${n?.label||"Off"}`,()=>{this._currentPanel="captions",this.renderPanel()})}if(i.audioTracks.length>1){let n=i.audioTracks.find((s)=>s.selected);this.addItem(e,`Audio: ${n?.label||"Default"}`,()=>{this._currentPanel="audio",this.renderPanel()})}}renderSpeed(e,t){this.addItem(e,"Back",()=>{this._currentPanel="main",this.renderPanel()},!1,!0);for(let i of Ei){let n=t.state.playbackRate===i;this.addItem(e,`${i}x`,()=>{t.setPlaybackRate(i),this.close()},n)}}renderQuality(e,t){this.addItem(e,"Back",()=>{this._currentPanel="main",this.renderPanel()},!1,!0),this.addItem(e,"Auto",()=>{t.setQuality("auto"),this.close()},t.state.autoQuality);for(let i of t.state.qualities)this.addItem(e,`${i.height}p`,()=>{t.setQuality(i),this.close()},i.selected&&!t.state.autoQuality)}renderCaptions(e,t){this.addItem(e,"Back",()=>{this._currentPanel="main",this.renderPanel()},!1,!0);let i=t.state.textTracks.some((n)=>n.mode==="showing");this.addItem(e,"Off",()=>{for(let n of t.state.textTracks)if(n.mode==="showing")t.setTextTrack(n.id,"disabled");this.close()},!i);for(let n of t.state.textTracks)if(n.kind==="subtitles"||n.kind==="captions")this.addItem(e,n.label,()=>{t.setTextTrack(n.id,"showing"),this.close()},n.mode==="showing")}renderAudio(e,t){this.addItem(e,"Back",()=>{this._currentPanel="main",this.renderPanel()},!1,!0);for(let i of t.state.audioTracks)this.addItem(e,i.label||i.language||"Audio track",()=>{t.setAudioTrack(i.id),this.close()},i.selected)}addItem(e,t,i,n=!1,s=!1){let r=document.createElement("button");if(r.className=`item${s?" back":""}`,r.setAttribute("role","menuitem"),!s)r.setAttribute("aria-checked",String(n));r.textContent=t,r.addEventListener("click",i),e.appendChild(r)}}class de extends p{cleanup=null;onClick=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
1023
+ `}let e=this.shadowRoot.querySelector(".trigger");this._onTriggerClick=()=>this.toggle(),e.addEventListener("click",this._onTriggerClick),this._onDocClick=(t)=>{if(this._isOpen&&!this.contains(t.target))this.close()},document.addEventListener("click",this._onDocClick),this._onDocKeydown=(t)=>{if(t.key==="Escape"&&this._isOpen)this.close()},document.addEventListener("keydown",this._onDocKeydown),queueMicrotask(()=>this.attach())}_onTriggerClick=null;_onDocClick=null;_onDocKeydown=null;disconnectedCallback(){if(this._cleanup?.(),this._cleanup=null,this._onTriggerClick)this.shadowRoot?.querySelector(".trigger")?.removeEventListener("click",this._onTriggerClick);if(this._onDocClick)document.removeEventListener("click",this._onDocClick);if(this._onDocKeydown)document.removeEventListener("keydown",this._onDocKeydown)}toggle(){if(this._isOpen)this.close();else this.open()}open(){this._isOpen=!0,this._currentPanel="main",this.setAttribute("open",""),this.shadowRoot.querySelector(".trigger").setAttribute("aria-expanded","true"),this.shadowRoot.querySelector(".menu").setAttribute("aria-hidden","false"),this.renderPanel(),this.positionMenu()}close(){this._isOpen=!1,this.removeAttribute("open"),this.shadowRoot.querySelector(".trigger").setAttribute("aria-expanded","false"),this.shadowRoot.querySelector(".menu").setAttribute("aria-hidden","true")}positionMenu(){let e=this.shadowRoot.querySelector(".trigger"),t=this.shadowRoot.querySelector(".menu");if(!e||!t)return;let i=this.closest("video-player, .ts-video-player"),n=_t(e,t,{placement:"top-end",offset:4,boundary:i,padding:8});t.style.top=`${n.top}px`,t.style.left=`${n.left}px`}attach(){let e=m(this);if(!e)return;let t=e.subscribe(()=>{if(this._isOpen)this.renderPanel()});this._cleanup=t}renderPanel(){let e=m(this);if(!e)return;let t=this.shadowRoot.querySelector(".menu");switch(t.innerHTML="",this._currentPanel){case"main":this.renderMain(t,e);break;case"speed":this.renderSpeed(t,e);break;case"quality":this.renderQuality(t,e);break;case"captions":this.renderCaptions(t,e);break;case"audio":this.renderAudio(t,e);break}if(this._isOpen)queueMicrotask(()=>this.positionMenu())}renderMain(e,t){let i=t.state;if(this.addItem(e,`${l(this,"speed")}: ${i.playbackRate}x`,()=>{this._currentPanel="speed",this.renderPanel()}),i.qualities.length>0){let n=i.qualities.find((r)=>r.selected),s=i.autoQuality?l(this,"auto"):n?`${n.height}p`:l(this,"auto");this.addItem(e,`${l(this,"quality")}: ${s}`,()=>{this._currentPanel="quality",this.renderPanel()})}if(i.textTracks.length>0){let n=i.textTracks.find((s)=>s.mode==="showing");this.addItem(e,`${l(this,"captions")}: ${n?.label||l(this,"captionsOff")}`,()=>{this._currentPanel="captions",this.renderPanel()})}if(i.audioTracks.length>1){let n=i.audioTracks.find((s)=>s.selected);this.addItem(e,`${l(this,"audio")}: ${n?.label||l(this,"defaultTrack")}`,()=>{this._currentPanel="audio",this.renderPanel()})}}renderSpeed(e,t){this.addItem(e,l(this,"back"),()=>{this._currentPanel="main",this.renderPanel()},!1,!0);for(let i of Ai){let n=t.state.playbackRate===i;this.addItem(e,`${i}x`,()=>{t.setPlaybackRate(i),this.close()},n)}}renderQuality(e,t){this.addItem(e,l(this,"back"),()=>{this._currentPanel="main",this.renderPanel()},!1,!0),this.addItem(e,l(this,"auto"),()=>{t.setQuality("auto"),this.close()},t.state.autoQuality);for(let i of t.state.qualities)this.addItem(e,`${i.height}p`,()=>{t.setQuality(i),this.close()},i.selected&&!t.state.autoQuality)}renderCaptions(e,t){this.addItem(e,l(this,"back"),()=>{this._currentPanel="main",this.renderPanel()},!1,!0);let i=t.state.textTracks.some((n)=>n.mode==="showing");this.addItem(e,l(this,"captionsOff"),()=>{for(let n of t.state.textTracks)if(n.mode==="showing")t.setTextTrack(n.id,"disabled");this.close()},!i);for(let n of t.state.textTracks)if(n.kind==="subtitles"||n.kind==="captions")this.addItem(e,n.label,()=>{t.setTextTrack(n.id,"showing"),this.close()},n.mode==="showing")}renderAudio(e,t){this.addItem(e,l(this,"back"),()=>{this._currentPanel="main",this.renderPanel()},!1,!0);for(let i of t.state.audioTracks)this.addItem(e,i.label||i.language||l(this,"audioTrack"),()=>{t.setAudioTrack(i.id),this.close()},i.selected)}addItem(e,t,i,n=!1,s=!1){let r=document.createElement("button");if(r.className=`item${s?" back":""}`,r.setAttribute("role","menuitem"),!s)r.setAttribute("aria-checked",String(n));r.textContent=t,r.addEventListener("click",i),e.appendChild(r)}}class ce extends h{cleanup=null;onClick=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
1010
1024
  <style>
1011
1025
  :host { display: inline-flex; }
1012
1026
  button { min-width: 40px; height: 40px; padding: 0 8px; border: 0; background: transparent; color: inherit; cursor: pointer; font: inherit; }
1013
1027
  button:hover { opacity: .8; }
1014
1028
  button:focus-visible { outline: 2px solid currentColor; outline-offset: -2px; }
1015
1029
  button:disabled { cursor: default; opacity: .45; }
1030
+ /* 44px, the smallest a finger hits reliably, on a touch screen. */
1031
+ @media (pointer: coarse) { button { min-width: 44px; min-height: 44px; } }
1016
1032
  </style>
1017
1033
  <button part="button" type="button"></button>
1018
- `}queueMicrotask(()=>this.attach())}disconnectedCallback(){let e=this.shadowRoot?.querySelector("button");if(e&&this.onClick)e.removeEventListener("click",this.onClick);this.cleanup?.(),this.cleanup=null,this.onClick=null}attach(){let e=h(this),t=this.shadowRoot?.querySelector("button");if(!e||!t)return;let i=Number.parseFloat(this.getAttribute("seconds")??"10"),n=Number.isFinite(i)&&i!==0?i:10,s=n>0?`Forward ${n} seconds`:`Back ${Math.abs(n)} seconds`;t.textContent=n>0?`+${n}`:String(n),t.setAttribute("aria-label",s),this.onClick=()=>e.seekBy(n),t.addEventListener("click",this.onClick),this.cleanup=e.subscribe((r)=>{t.disabled=n<0?r.currentTime<=0:r.duration>0&&r.currentTime>=r.duration})}}var Pi=[0.5,0.75,1,1.25,1.5,2];class ce extends p{cleanup=null;onClick=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
1034
+ `}queueMicrotask(()=>this.attach())}disconnectedCallback(){let e=this.shadowRoot?.querySelector("button");if(e&&this.onClick)e.removeEventListener("click",this.onClick);this.cleanup?.(),this.cleanup=null,this.onClick=null}attach(){let e=m(this),t=this.shadowRoot?.querySelector("button");if(!e||!t)return;let i=Number.parseFloat(this.getAttribute("seconds")??"10"),n=Number.isFinite(i)&&i!==0?i:10;t.textContent=n>0?`+${n}`:String(n),t.setAttribute("aria-label",l(this,n>0?"seekForward":"seekBackward",{seconds:Math.abs(n)})),this.onClick=()=>e.seekBy(n),t.addEventListener("click",this.onClick),this.cleanup=e.subscribe((s)=>{t.disabled=n<0?s.currentTime<=0:s.duration>0&&s.currentTime>=s.duration})}}var _i=[0.5,0.75,1,1.25,1.5,2];class ue extends h{cleanup=null;onClick=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
1019
1035
  <style>
1020
1036
  :host { display: inline-flex; }
1021
1037
  button { min-width: 42px; height: 40px; padding: 0 8px; border: 0; background: transparent; color: inherit; cursor: pointer; font: inherit; font-variant-numeric: tabular-nums; }
1022
1038
  button:hover { opacity: .8; }
1023
1039
  button:focus-visible { outline: 2px solid currentColor; outline-offset: -2px; }
1040
+ /* 44px, the smallest a finger hits reliably, on a touch screen. */
1041
+ @media (pointer: coarse) { button { min-width: 44px; min-height: 44px; } }
1024
1042
  </style>
1025
- <button part="button" type="button" aria-label="Playback speed"></button>
1026
- `}queueMicrotask(()=>this.attach())}disconnectedCallback(){let e=this.shadowRoot?.querySelector("button");if(e&&this.onClick)e.removeEventListener("click",this.onClick);this.cleanup?.(),this.cleanup=null,this.onClick=null}getRates(){let e=(this.getAttribute("rates")??"").split(",").map((t)=>Number.parseFloat(t.trim())).filter((t)=>Number.isFinite(t)&&t>=0.25&&t<=4);return[...new Set(e.length>0?e:Pi)].sort((t,i)=>t-i)}attach(){let e=h(this),t=this.shadowRoot?.querySelector("button");if(!e||!t)return;let i=this.getRates();this.onClick=()=>{let n=i.findIndex((s)=>s>e.state.playbackRate+0.001);e.setPlaybackRate(i[n<0?0:n])},t.addEventListener("click",this.onClick),this.cleanup=e.subscribe("playbackRate",(n)=>{t.textContent=`${n.playbackRate}x`,t.setAttribute("aria-label",`Playback speed ${n.playbackRate}x`)})}}var Ai="M6.2 19h11.6L12 13.2 6.2 19zM19 3H5a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h2v-2H5V5h14v10h-2v2h2a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2z";class ue extends p{cleanup=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
1043
+ <button part="button" type="button" aria-label="${l(this,"speed")}"></button>
1044
+ `}queueMicrotask(()=>this.attach())}disconnectedCallback(){let e=this.shadowRoot?.querySelector("button");if(e&&this.onClick)e.removeEventListener("click",this.onClick);this.cleanup?.(),this.cleanup=null,this.onClick=null}getRates(){let e=(this.getAttribute("rates")??"").split(",").map((t)=>Number.parseFloat(t.trim())).filter((t)=>Number.isFinite(t)&&t>=0.25&&t<=4);return[...new Set(e.length>0?e:_i)].sort((t,i)=>t-i)}attach(){let e=m(this),t=this.shadowRoot?.querySelector("button");if(!e||!t)return;let i=this.getRates();this.onClick=()=>{let n=i.findIndex((s)=>s>e.state.playbackRate+0.001);e.setPlaybackRate(i[n<0?0:n])},t.addEventListener("click",this.onClick),this.cleanup=e.subscribe("playbackRate",(n)=>{t.textContent=`${n.playbackRate}x`,t.setAttribute("aria-label",l(this,"playbackRate",{rate:n.playbackRate}))})}}var Li="M6.2 19h11.6L12 13.2 6.2 19zM19 3H5a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h2v-2H5V5h14v10h-2v2h2a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2z";class pe extends h{cleanup=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
1027
1045
  <style>
1028
1046
  :host { display: none; }
1029
1047
  :host([available]) { display: inline-flex; }
1030
1048
  button { display: inline-flex; align-items: center; justify-content: center; width: 40px; height: 40px; padding: 8px; background: transparent; border: 0; color: inherit; cursor: pointer; }
1031
1049
  button:hover { opacity: 0.8; }
1032
1050
  :host([connected]) button { color: var(--media-airplay-active-color, #38bdf8); }
1051
+ /* 44px, the smallest a finger hits reliably, on a touch screen. */
1052
+ @media (pointer: coarse) { button { min-width: 44px; min-height: 44px; } }
1033
1053
  </style>
1034
- <button part="button" type="button" aria-label="Play on AirPlay">
1035
- <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" part="icon"><path d="${Ai}"/></svg>
1054
+ <button part="button" type="button" aria-label="${l(this,"airPlayPlay")}">
1055
+ <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" part="icon"><path d="${Li}"/></svg>
1036
1056
  </button>
1037
- `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this.cleanup?.(),this.cleanup=null}attach(){let e=h(this),t=this.shadowRoot?.querySelector("button");if(!e||!t)return;let i=null,n=()=>s(),s=()=>{let o=e.provider?.mediaElement,l=o instanceof HTMLVideoElement?o:null;if(l!==i)i?.removeEventListener("webkitplaybacktargetavailabilitychanged",n),i?.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",n),l?.addEventListener("webkitplaybacktargetavailabilitychanged",n),l?.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",n),i=l;let d=typeof i?.webkitShowPlaybackTargetPicker==="function";this.toggleAttribute("available",d),this.toggleAttribute("connected",i?.webkitCurrentPlaybackTargetIsWireless===!0),t.setAttribute("aria-pressed",String(i?.webkitCurrentPlaybackTargetIsWireless===!0))},r=()=>i?.webkitShowPlaybackTargetPicker?.();t.addEventListener("click",r);let a=e.subscribe(s);s(),this.cleanup=()=>{a(),t.removeEventListener("click",r),i?.removeEventListener("webkitplaybacktargetavailabilitychanged",n),i?.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",n)}}}class pe extends p{cleanup=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
1057
+ `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this.cleanup?.(),this.cleanup=null}attach(){let e=m(this),t=this.shadowRoot?.querySelector("button");if(!e||!t)return;let i=null,n=()=>s(),s=()=>{let o=e.provider?.mediaElement,d=o instanceof HTMLVideoElement?o:null;if(d!==i)i?.removeEventListener("webkitplaybacktargetavailabilitychanged",n),i?.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",n),d?.addEventListener("webkitplaybacktargetavailabilitychanged",n),d?.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",n),i=d;let c=typeof i?.webkitShowPlaybackTargetPicker==="function";this.toggleAttribute("available",c),this.toggleAttribute("connected",i?.webkitCurrentPlaybackTargetIsWireless===!0),t.setAttribute("aria-pressed",String(i?.webkitCurrentPlaybackTargetIsWireless===!0))},r=()=>i?.webkitShowPlaybackTargetPicker?.();t.addEventListener("click",r);let a=e.subscribe(s);s(),this.cleanup=()=>{a(),t.removeEventListener("click",r),i?.removeEventListener("webkitplaybacktargetavailabilitychanged",n),i?.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",n)}}}class he extends h{cleanup=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
1038
1058
  <style>
1039
1059
  :host { display: none; }
1040
1060
  :host([available]) { display: inline-flex; }
1041
1061
  button { display: inline-flex; align-items: center; gap: 6px; min-height: 40px; padding: 8px; background: transparent; border: 0; color: inherit; cursor: pointer; font: inherit; font-size: 12px; font-weight: 700; }
1042
1062
  i { width: 8px; height: 8px; border-radius: 9999px; background: #ef4444; }
1043
1063
  :host(:not([at-live-edge])) button { opacity: 0.72; }
1064
+ /* 44px, the smallest a finger hits reliably, on a touch screen. */
1065
+ @media (pointer: coarse) { button { min-width: 44px; min-height: 44px; } }
1044
1066
  </style>
1045
- <button part="button" type="button" aria-label="Go to live edge"><i aria-hidden="true"></i><span>LIVE</span></button>
1046
- `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this.cleanup?.(),this.cleanup=null}attach(){let e=h(this),t=this.shadowRoot?.querySelector("button");if(!e||!t)return;let i=Math.max(0,Number(this.getAttribute("threshold")||10)),n=()=>{let a=e.state,o=a.seekable.at(-1)?.end,l=e.provider?.isLive===!0,d=o!==void 0&&(l||!Number.isFinite(a.duration)),c=d&&o-a.currentTime<=i;this.toggleAttribute("available",d),this.toggleAttribute("at-live-edge",c),t.setAttribute("aria-pressed",String(c))},s=()=>{let a=e.state.seekable.at(-1)?.end;if(a!==void 0)e.seekTo(a),e.play()};t.addEventListener("click",s);let r=e.subscribe(n);n(),this.cleanup=()=>{r(),t.removeEventListener("click",s)}}}class he extends p{cleanup=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
1067
+ <button part="button" type="button" aria-label="${l(this,"seekToLive")}"><i aria-hidden="true"></i><span>${l(this,"live")}</span></button>
1068
+ `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this.cleanup?.(),this.cleanup=null}attach(){let e=m(this),t=this.shadowRoot?.querySelector("button");if(!e||!t)return;let i=Math.max(0,Number(this.getAttribute("threshold")||10)),n=()=>{let a=e.state,o=a.seekable.at(-1)?.end,d=e.provider?.isLive===!0,c=o!==void 0&&(d||!Number.isFinite(a.duration)),u=c&&o-a.currentTime<=i;this.toggleAttribute("available",c),this.toggleAttribute("at-live-edge",u),t.setAttribute("aria-pressed",String(u))},s=()=>{let a=e.state.seekable.at(-1)?.end;if(a!==void 0)e.seekTo(a),e.play()};t.addEventListener("click",s);let r=e.subscribe(n);n(),this.cleanup=()=>{r(),t.removeEventListener("click",s)}}}class me extends h{cleanup=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
1047
1069
  <style>
1048
1070
  :host { display: none; position: absolute; inset: 0; z-index: 5; place-items: center; padding: 24px; background: rgba(0, 0, 0, 0.76); color: white; text-align: center; }
1049
1071
  :host([open]) { display: grid; }
1050
1072
  p { max-width: 42rem; margin: 0; font: 500 14px/1.5 system-ui, sans-serif; }
1051
1073
  </style>
1052
1074
  <p part="message" role="alert" aria-live="assertive"></p>
1053
- `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this.cleanup?.(),this.cleanup=null}attach(){let e=h(this),t=this.shadowRoot?.querySelector("p");if(!e||!t)return;let i=()=>{let n=e.state.error;if(this.toggleAttribute("open",!!n),t.textContent=n?.message||"",n?.code!==void 0)this.setAttribute("data-code",String(n.code));else this.removeAttribute("data-code")};this.cleanup=e.subscribe(i),i()}}var _i="M1 18v3h3a3 3 0 0 0-3-3zm0-4v2a5 5 0 0 1 5 5h2a7 7 0 0 0-7-7zm0-4v2c5 0 9 4 9 9h2c0-6.1-4.9-11-11-11zm18-7H5a2 2 0 0 0-2 2v3h2V5h14v10h-5v2h5a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2z";class me extends p{cleanup=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
1075
+ `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this.cleanup?.(),this.cleanup=null}attach(){let e=m(this),t=this.shadowRoot?.querySelector("p");if(!e||!t)return;let i=()=>{let n=e.state.error;if(this.toggleAttribute("open",!!n),t.textContent=n?.message||"",n?.code!==void 0)this.setAttribute("data-code",String(n.code));else this.removeAttribute("data-code")};this.cleanup=e.subscribe(i),i()}}var Mi="M1 18v3h3a3 3 0 0 0-3-3zm0-4v2a5 5 0 0 1 5 5h2a7 7 0 0 0-7-7zm0-4v2c5 0 9 4 9 9h2c0-6.1-4.9-11-11-11zm18-7H5a2 2 0 0 0-2 2v3h2V5h14v10h-5v2h5a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2z";class ve extends h{cleanup=null;connectedCallback(){if(!this.shadowRoot){let e=this.attachShadow({mode:"open"});e.innerHTML=`
1054
1076
  <style>
1055
1077
  :host { display: none; }
1056
1078
  :host([available]) { display: inline-flex; }
1057
1079
  button { display: inline-flex; align-items: center; justify-content: center; width: 40px; height: 40px; padding: 8px; background: transparent; border: 0; color: inherit; cursor: pointer; }
1058
1080
  button:hover { opacity: 0.8; }
1059
1081
  :host([connected]) button { color: var(--media-remote-active-color, #38bdf8); }
1082
+ /* 44px, the smallest a finger hits reliably, on a touch screen. */
1083
+ @media (pointer: coarse) { button { min-width: 44px; min-height: 44px; } }
1060
1084
  </style>
1061
- <button part="button" type="button" aria-label="Play on another device">
1062
- <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" part="icon"><path d="${_i}"/></svg>
1085
+ <button part="button" type="button" aria-label="${l(this,"remotePlayback")}">
1086
+ <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" part="icon"><path d="${Mi}"/></svg>
1063
1087
  </button>
1064
- `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this.cleanup?.(),this.cleanup=null}attach(){let e=h(this),t=this.shadowRoot?.querySelector("button");if(!e||!t)return;let i=null,n=null,s=0,r=()=>{let c=i?.state==="connected";this.toggleAttribute("connected",c),t.setAttribute("aria-pressed",String(c))},a=()=>{if(s++,i?.removeEventListener("connecting",r),i?.removeEventListener("connect",r),i?.removeEventListener("disconnect",r),i&&n!==null)i.cancelWatchAvailability(n).catch(()=>{});i=null,n=null,this.removeAttribute("available"),this.removeAttribute("connected")},o=()=>{let c=e.provider?.mediaElement,u=c instanceof HTMLMediaElement?c.remote??null:null;if(u===i)return;if(a(),!u)return;i=u;let v=s;i.addEventListener("connecting",r),i.addEventListener("connect",r),i.addEventListener("disconnect",r),r(),i.watchAvailability((g)=>{if(s===v&&i===u)this.toggleAttribute("available",g)}).then((g)=>{if(s===v&&i===u)n=g;else u.cancelWatchAvailability(g).catch(()=>{})}).catch(()=>this.removeAttribute("available"))},l=()=>{i?.prompt().catch(()=>{})};t.addEventListener("click",l);let d=e.subscribe(o);o(),this.cleanup=()=>{d(),t.removeEventListener("click",l),a()}}}var Mi=[["video-player",X],["video-skin",G],["media-play-button",J],["media-mute-button",Z],["media-fullscreen-button",ee],["media-pip-button",te],["media-time-display",ie],["media-time-group",ne],["media-time-separator",se],["media-preview-time",re],["media-progress-bar",ae],["media-volume-slider",oe],["media-settings-menu",le],["media-seek-button",de],["media-playback-rate-button",ce],["media-airplay-button",ue],["media-live-button",pe],["media-error-display",he],["media-remote-playback-button",me]];function De(){for(let[e,t]of Mi)if(!customElements.get(e))customElements.define(e,t)}if(typeof window<"u")De(),window.VideoPlayer={createPlayer:ut,Player:P,EventEmitter:S,StateStore:_,HTML5Provider:L,YouTubeProvider:C,HLSProvider:R,DASHProvider:I,applyTheme:pt,presetThemes:Pe,I18n:Y,t:ht,layouts:_e,createLayoutManager:vt,registerElements:De,plugins:{VideoAnalytics:H,analyticsPlugin:Me,AdsManager:V,adsPlugin:Ce,SkipSegmentsManager:D,skipSegmentsPlugin:Re,EndScreenManager:B,endScreenPlugin:Ie,WatermarkManager:F,watermarkPlugin:He}};
1088
+ `}queueMicrotask(()=>this.attach())}disconnectedCallback(){this.cleanup?.(),this.cleanup=null}attach(){let e=m(this),t=this.shadowRoot?.querySelector("button");if(!e||!t)return;let i=null,n=null,s=0,r=()=>{let u=i?.state==="connected";this.toggleAttribute("connected",u),t.setAttribute("aria-pressed",String(u))},a=()=>{if(s++,i?.removeEventListener("connecting",r),i?.removeEventListener("connect",r),i?.removeEventListener("disconnect",r),i&&n!==null)i.cancelWatchAvailability(n).catch(()=>{});i=null,n=null,this.removeAttribute("available"),this.removeAttribute("connected")},o=()=>{let u=e.provider?.mediaElement,p=u instanceof HTMLMediaElement?u.remote??null:null;if(p===i)return;if(a(),!p)return;i=p;let g=s;i.addEventListener("connecting",r),i.addEventListener("connect",r),i.addEventListener("disconnect",r),r(),i.watchAvailability((y)=>{if(s===g&&i===p)this.toggleAttribute("available",y)}).then((y)=>{if(s===g&&i===p)n=y;else p.cancelWatchAvailability(y).catch(()=>{})}).catch(()=>this.removeAttribute("available"))},d=()=>{i?.prompt().catch(()=>{})};t.addEventListener("click",d);let c=e.subscribe(o);o(),this.cleanup=()=>{c(),t.removeEventListener("click",d),a()}}}var Ci=[["video-player",G],["video-skin",J],["media-play-button",Z],["media-mute-button",ee],["media-fullscreen-button",te],["media-pip-button",ie],["media-time-display",ne],["media-time-group",se],["media-time-separator",re],["media-preview-time",ae],["media-progress-bar",oe],["media-volume-slider",le],["media-settings-menu",de],["media-seek-button",ce],["media-playback-rate-button",ue],["media-airplay-button",pe],["media-live-button",he],["media-error-display",me],["media-remote-playback-button",ve]];function $e(){for(let[e,t]of Ci)if(!customElements.get(e))customElements.define(e,t)}if(typeof window<"u")$e(),window.VideoPlayer={createPlayer:vt,Player:_,EventEmitter:E,StateStore:L,HTML5Provider:C,YouTubeProvider:R,HLSProvider:I,DASHProvider:H,applyTheme:gt,presetThemes:Ce,I18n:X,t:mt,layouts:Re,createLayoutManager:ft,registerElements:$e,plugins:{VideoAnalytics:V,analyticsPlugin:Ie,AdsManager:B,adsPlugin:Ve,SkipSegmentsManager:D,skipSegmentsPlugin:Be,EndScreenManager:F,endScreenPlugin:De,WatermarkManager:O,watermarkPlugin:Fe}};